@cloudflare/realtimekit 2.0.3-staging.8 → 2.0.3
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/ClientMock.cjs.js +1 -1
- package/dist/ClientMock.es.js +9 -1
- package/dist/EncryptionManager.cjs.js +1 -1
- package/dist/EncryptionManager.d.ts +171 -161
- package/dist/EncryptionManager.es.js +294 -294
- package/dist/browser.js +10 -10
- package/dist/dependencies.txt +3 -3
- package/dist/index.cjs.js +7 -7
- package/dist/index.d.ts +110 -100
- package/dist/index.es.js +6405 -6223
- package/dist/index.es5.js +5659 -5443
- package/dist/index.rn.js +7 -7
- package/dist/ts3.4/dist/EncryptionManager.d.ts +168 -158
- package/dist/ts3.4/dist/index.d.ts +109 -99
- package/package.json +5 -4
package/dist/index.rn.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";var dS=Object.defineProperty;var lS=(s,t,e)=>t in s?dS(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var h=(s,t,e)=>(lS(s,typeof t!="symbol"?t+"":t,e),e),iu=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)};var n=(s,t,e)=>(iu(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)=>(iu(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e);var I=(s,t,e)=>(iu(s,t,"access private method"),e);const Qr=require("uuid"),Qg=require("bowser"),T=require("@protobuf-ts/runtime"),uS=require("worker-timers"),hS=require("sdp-transform");function Xg(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 io=Xg(uS),Zt=Xg(hS);function pS(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:pS});function gS(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:gS});const mS=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",Zg="opera",em="firefox",tm="iexplorer",sm="safari",rm="nwjs",im="electron",nm="react-native",Ph="unknown",Sd={Chrome:mo,Chromium:mo,Opera:Zg,Firefox:em,"Internet Explorer":tm,Safari:sm};function fS(){const{userAgent:s}=navigator,t={name:Ph,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 TS(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:im,version:t}}return null}function SS(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:rm,version:t}}}function vS(){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:nm,version:t}}function yS(s){let t;const e=[vS,TS,SS];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in Sd?{name:Sd[r],version:s.getBrowserVersion()}:(t=fS(),t||{name:Ph,version:void 0})}class ES{constructor(){h(this,"_bowser");h(this,"_name");h(this,"_version");h(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=Qg.getParser(navigator.userAgent),typeof t=="undefined"){const i=yS(this._bowser);e=i.name,r=i.version}else t.name in Sd?(e=Sd[t.name],r=t.version):(e=Ph,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===mo}isOpera(){return this._name===Zg}isFirefox(){return this._name===em}isIExplorer(){return this._name===tm}isSafari(){return this._name===sm}isNWJS(){return this._name===rm}isElectron(){return this._name===im}isReactNative(){return this._name===nm||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 PS extends ES{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 me=new PS;var ht={},_S={get exports(){return ht},set exports(s){ht=s}},vn=typeof Reflect=="object"?Reflect:null,op=vn&&typeof vn.apply=="function"?vn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},rd;vn&&typeof vn.ownKeys=="function"?rd=vn.ownKeys:Object.getOwnPropertySymbols?rd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:rd=function(t){return Object.getOwnPropertyNames(t)};function CS(s){console&&console.warn&&console.warn(s)}var am=Number.isNaN||function(t){return t!==t};function oe(){oe.init.call(this)}_S.exports=oe;ht.once=kS;oe.EventEmitter=oe;oe.prototype._events=void 0;oe.prototype._eventsCount=0;oe.prototype._maxListeners=void 0;var cp=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(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return cp},set:function(s){if(typeof s!="number"||s<0||am(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");cp=s}});oe.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};oe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||am(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 om(s){return s._maxListeners===void 0?oe.defaultMaxListeners:s._maxListeners}oe.prototype.getMaxListeners=function(){return om(this)};oe.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")op(d,this,e);else for(var l=d.length,u=hm(d,l),r=0;r<l;++r)op(u[r],this,e);return!0};function cm(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=om(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,CS(c)}return s}oe.prototype.addListener=function(t,e){return cm(this,t,e,!1)};oe.prototype.on=oe.prototype.addListener;oe.prototype.prependListener=function(t,e){return cm(this,t,e,!0)};function wS(){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 dm(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=wS.bind(r);return i.listener=e,r.wrapFn=i,i}oe.prototype.once=function(t,e){return Ll(e),this.on(t,dm(this,t,e)),this};oe.prototype.prependOnceListener=function(t,e){return Ll(e),this.prependListener(t,dm(this,t,e)),this};oe.prototype.removeListener=function(t,e){var r,i,a,o,c;if(Ll(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():RS(r,a),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this};oe.prototype.off=oe.prototype.removeListener;oe.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 lm(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?bS(i):hm(i,i.length)}oe.prototype.listeners=function(t){return lm(this,t,!0)};oe.prototype.rawListeners=function(t){return lm(this,t,!1)};oe.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):um.call(s,t)};oe.prototype.listenerCount=um;function um(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}oe.prototype.eventNames=function(){return this._eventsCount>0?rd(this._events):[]};function hm(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function RS(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function bS(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function kS(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))}pm(s,t,a,{once:!0}),t!=="error"&&AS(s,i,{once:!0})})}function AS(s,t,e){typeof s.on=="function"&&pm(s,"error",t,e)}function pm(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 j;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(j||(j={}));var O;(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"})(O||(O={}));const MS=new Map([[O.PRECALL_TEST_BEGIN,j.MINOR_EVENT],[O.PRECALL_TEST_COMPLETE,j.MINOR_EVENT],[O.CALL_JOIN_BEGIN,j.MAJOR_EVENT],[O.NET_QUALITY_TEST_BEGIN,j.MINOR_EVENT],[O.NET_QUALITY_TEST_END,j.MINOR_EVENT],[O.WEBSOCKET_CONNECTED,j.MINOR_EVENT],[O.TRANSPORT_CONNECTED,j.MAJOR_EVENT],[O.AUDIO_ON,j.MINOR_EVENT],[O.AUDIO_OFF,j.MINOR_EVENT],[O.VIDEO_ON,j.MINOR_EVENT],[O.VIDEO_OFF,j.MINOR_EVENT],[O.PARTICIPANT_ROLE,j.MINOR_EVENT],[O.PING_STAT,j.MAJOR_EVENT],[O.DISCONNECT,j.MAJOR_EVENT],[O.RECONNECT_ATTEMPT,j.MAJOR_EVENT],[O.SCREENSHARE_START_REQUESTED,j.MINOR_EVENT],[O.SCREENSHARE_STARTED,j.MINOR_EVENT],[O.SCREENSHARE_STOPPED,j.MINOR_EVENT],[O.TAB_CHANGE,j.MINOR_EVENT],[O.BROWSER_BACKGROUNDED,j.MINOR_EVENT],[O.BROWSER_FOREGROUNDED,j.MINOR_EVENT],[O.DOMINANT_SPEAKER,j.MINOR_EVENT],[O.AUDIO_DEVICES_UPDATES,j.MINOR_EVENT],[O.VIDEO_DEVICES_UPDATES,j.MINOR_EVENT],[O.SPEAKER_DEVICES_UPDATES,j.MINOR_EVENT],[O.SELECTED_MICROHPONE_UPDATE,j.MINOR_EVENT],[O.SELECTED_CAMERA_UPDATE,j.MINOR_EVENT],[O.SELECTED_SPEAKER_UPDATE,j.MINOR_EVENT],[O.MEDIA_PERMISSION,j.MINOR_EVENT],[O.LEGACY_SWITCH,j.MINOR_EVENT],[O.AUDIO_PLAY_FAILED,j.MINOR_EVENT],[O.VIDEO_PLAY_FAILED,j.MINOR_EVENT],[O.AUDIO_TRACK_MUTED,j.MINOR_EVENT],[O.VIDEO_TRACK_MUTED,j.MINOR_EVENT],[O.IVS_PLAYER_REBUFFERING,j.MAJOR_EVENT],[O.IVS_PLAYER_AUDIO_BLOCKED,j.MAJOR_EVENT],[O.IVS_PLAYER_PLAYBACK_BLOCKED,j.MAJOR_EVENT],[O.IVS_PLAYER_ERROR,j.MAJOR_EVENT],[O.IVS_PLAYER_RECOVERABLE_ERROR,j.MAJOR_EVENT],[O.IVS_PLAYER_WORKER_ERROR,j.MAJOR_EVENT],[O.IVS_PLAYER_NETWORK_UNAVAILABLE,j.MAJOR_EVENT],[O.LIVESTREAM_LATENCY,j.MAJOR_EVENT],[O.IVS_PLAYER_ANALYTICS_EVENT,j.MINOR_EVENT],[O.IVS_PLAYER_PLAYBACK_RATE_CHANGED,j.MINOR_EVENT],[O.IVS_PLAYER_QUALITY_CHANGED,j.MINOR_EVENT],[O.IVS_PLAYER_INITIALIZED,j.MINOR_EVENT],[O.EXPECTED_VIDEO_RESOLUTION,j.MINOR_EVENT],[O.EXPECTED_SCREENSHARE_RESOLUTION,j.MINOR_EVENT]]);class IS{constructor(){h(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class DS extends ht{constructor({logger:e,peerId:r,apiHostnames:i,authToken:a}){super();h(this,"logger");h(this,"peerId");h(this,"eventStore");h(this,"apiEndpoint");h(this,"authToken");this.logger=e,this.peerId=r,this.authToken=a,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new IS}async sendEventsChunkToServer(e){const r={payload:e,peerId:this.peerId},i=new AbortController,a=setTimeout(()=>i.abort(),3e3);try{return await fetch(this.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.authToken}`},body:JSON.stringify(r),signal:i.signal}),!0}catch(o){return this.logger.error("callStats::sendEventsChunkToServer::catch",{peerId:this.peerId,endpoint:this.apiEndpoint,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0}),!1}finally{clearTimeout(a)}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),MS.get(e.event)===j.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();if((r=e==null?void 0:e.entries)!=null&&r.length){const i=await this.sendEventsChunkToServer(e);return i||e.entries.forEach(a=>{this.eventStore.add(a)}),i}return!1}}var dp;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(dp||(dp={}));const gm={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Ut;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Ut||(Ut={}));var lp;(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"})(lp||(lp={}));function Kr(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function vd({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function yd({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const mm=240,fm=720,Tm=8,Sm=3,Vl=10,xl=.02,Ul=.03;function sr({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 vm({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 ym({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Em({packetsLost:s,packetsSent:t,jitter:e}){const i=sr({stat:ym({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:Vl,rangeRankingDirection:"UP"}),o=sr({stat:e,weight:.3,rangeMin:xl,rangeMax:Ul,rangeRankingDirection:"UP"});return i+o}function OS({frameWidth:s,isScreenShare:t}){return s<(t?fm:mm)}function NS({framesPerSecond:s,isScreenShare:t}){return s<(t?Sm:Tm)}function LS({framesEncoded:s}){return s===0}function Pm({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:a,framesEncoded:o}){const c=sr({stat:ym({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:Vl,rangeRankingDirection:"UP"}),d=sr({stat:i,weight:1,rangeMin:xl,rangeMax:Ul,rangeRankingDirection:"UP"}),l=OS({frameWidth:s,isScreenShare:a}),u=NS({framesPerSecond:t,isScreenShare:a}),p=LS({framesEncoded:o,isScreenShare:a});return vm({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}function _m({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function Cm({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const a=sr({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=sr({stat:_m({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:Vl,rangeRankingDirection:"UP"}),l=sr({stat:r,weight:.3,rangeMin:xl,rangeMax:Ul,rangeRankingDirection:"UP"});return a+c+l}function VS({framesDecoded:s}){return s===0}function xS({framesPerSecond:s,isScreenShare:t}){return s<(t?Sm:Tm)}function US({frameWidth:s,isScreenShare:t}){return s<(t?fm:mm)}function wm({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:a,framesDecoded:o}){const c=sr({stat:_m({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:Vl,rangeRankingDirection:"UP"}),d=sr({stat:i,weight:1,rangeMin:xl,rangeMax:Ul,rangeRankingDirection:"UP"}),l=US({frameWidth:s,isScreenShare:a}),u=xS({framesPerSecond:t,isScreenShare:a}),p=VS({framesDecoded:o,isScreenShare:a});return vm({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}class nr{constructor(t){h(this,"pc1");h(this,"pc2");h(this,"constrainVideoBitrateKbps");h(this,"constrainOfferToRemoveVideoFec",!1);h(this,"iceCandidateFilter");const e=new RTCPeerConnection(t),r=new RTCPeerConnection(t);this.pc1=e,this.pc2=r,this.iceCandidateFilter=nr.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=nr.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
|
|
1
|
+
"use strict";var IT=Object.defineProperty;var MT=(s,t,e)=>t in s?IT(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var h=(s,t,e)=>(MT(s,typeof t!="symbol"?t+"":t,e),e),yu=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)};var n=(s,t,e)=>(yu(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)=>(yu(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e);var b=(s,t,e)=>(yu(s,t,"access private method"),e);const hr=require("uuid"),Sm=require("bowser"),v=require("@protobuf-ts/runtime"),AT=require("worker-timers"),DT=require("sdp-transform");function Tm(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 po=Tm(AT),rs=Tm(DT);function OT(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:OT});function NT(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:NT});const LT=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")}))},wo="chrome",vm="opera",ym="firefox",Em="iexplorer",Pm="safari",wm="nwjs",_m="electron",Cm="react-native",Bh="unknown",bd={Chrome:wo,Chromium:wo,Opera:vm,Firefox:ym,"Internet Explorer":Em,Safari:Pm};function VT(){const{userAgent:s}=navigator,t={name:Bh,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=wo,t.version=e)}else t.name=wo,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function $T(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:_m,version:t}}return null}function xT(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:wm,version:t}}}function UT(){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:Cm,version:t}}function HT(s){let t;const e=[UT,$T,xT];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in bd?{name:bd[r],version:s.getBrowserVersion()}:(t=VT(),t||{name:Bh,version:void 0})}class BT{constructor(){h(this,"_bowser");h(this,"_name");h(this,"_version");h(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=Sm.getParser(navigator.userAgent),typeof t=="undefined"){const i=HT(this._bowser);e=i.name,r=i.version}else t.name in bd?(e=bd[t.name],r=t.version):(e=Bh,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===wo}isOpera(){return this._name===vm}isFirefox(){return this._name===ym}isIExplorer(){return this._name===Em}isSafari(){return this._name===Pm}isNWJS(){return this._name===wm}isElectron(){return this._name===_m}isReactNative(){return this._name===Cm||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 FT extends BT{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 ve=new FT;var ft={},jT={get exports(){return ft},set exports(s){ft=s}},Cn=typeof Reflect=="object"?Reflect:null,Rp=Cn&&typeof Cn.apply=="function"?Cn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},pd;Cn&&typeof Cn.ownKeys=="function"?pd=Cn.ownKeys:Object.getOwnPropertySymbols?pd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:pd=function(t){return Object.getOwnPropertyNames(t)};function qT(s){console&&console.warn&&console.warn(s)}var Rm=Number.isNaN||function(t){return t!==t};function de(){de.init.call(this)}jT.exports=de;ft.once=KT;de.EventEmitter=de;de.prototype._events=void 0;de.prototype._eventsCount=0;de.prototype._maxListeners=void 0;var bp=10;function Ql(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return bp},set:function(s){if(typeof s!="number"||s<0||Rm(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");bp=s}});de.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};de.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Rm(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 bm(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return bm(this)};de.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")Rp(d,this,e);else for(var l=d.length,u=Dm(d,l),r=0;r<l;++r)Rp(u[r],this,e);return!0};function km(s,t,e,r){var i,a,o;if(Ql(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=bm(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,qT(c)}return s}de.prototype.addListener=function(t,e){return km(this,t,e,!1)};de.prototype.on=de.prototype.addListener;de.prototype.prependListener=function(t,e){return km(this,t,e,!0)};function GT(){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 Im(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=GT.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(t,e){return Ql(e),this.on(t,Im(this,t,e)),this};de.prototype.prependOnceListener=function(t,e){return Ql(e),this.prependListener(t,Im(this,t,e)),this};de.prototype.removeListener=function(t,e){var r,i,a,o,c;if(Ql(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():WT(r,a),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this};de.prototype.off=de.prototype.removeListener;de.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 Mm(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?JT(i):Dm(i,i.length)}de.prototype.listeners=function(t){return Mm(this,t,!0)};de.prototype.rawListeners=function(t){return Mm(this,t,!1)};de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Am.call(s,t)};de.prototype.listenerCount=Am;function Am(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}de.prototype.eventNames=function(){return this._eventsCount>0?pd(this._events):[]};function Dm(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function WT(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function JT(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function KT(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))}Om(s,t,a,{once:!0}),t!=="error"&&zT(s,i,{once:!0})})}function zT(s,t,e){typeof s.on=="function"&&Om(s,"error",t,e)}function Om(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 q;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(q||(q={}));var O;(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"})(O||(O={}));const YT=new Map([[O.PRECALL_TEST_BEGIN,q.MINOR_EVENT],[O.PRECALL_TEST_COMPLETE,q.MINOR_EVENT],[O.CALL_JOIN_BEGIN,q.MAJOR_EVENT],[O.NET_QUALITY_TEST_BEGIN,q.MINOR_EVENT],[O.NET_QUALITY_TEST_END,q.MINOR_EVENT],[O.WEBSOCKET_CONNECTED,q.MINOR_EVENT],[O.TRANSPORT_CONNECTED,q.MAJOR_EVENT],[O.AUDIO_ON,q.MINOR_EVENT],[O.AUDIO_OFF,q.MINOR_EVENT],[O.VIDEO_ON,q.MINOR_EVENT],[O.VIDEO_OFF,q.MINOR_EVENT],[O.PARTICIPANT_ROLE,q.MINOR_EVENT],[O.PING_STAT,q.MAJOR_EVENT],[O.DISCONNECT,q.MAJOR_EVENT],[O.RECONNECT_ATTEMPT,q.MAJOR_EVENT],[O.SCREENSHARE_START_REQUESTED,q.MINOR_EVENT],[O.SCREENSHARE_STARTED,q.MINOR_EVENT],[O.SCREENSHARE_STOPPED,q.MINOR_EVENT],[O.TAB_CHANGE,q.MINOR_EVENT],[O.BROWSER_BACKGROUNDED,q.MINOR_EVENT],[O.BROWSER_FOREGROUNDED,q.MINOR_EVENT],[O.DOMINANT_SPEAKER,q.MINOR_EVENT],[O.AUDIO_DEVICES_UPDATES,q.MINOR_EVENT],[O.VIDEO_DEVICES_UPDATES,q.MINOR_EVENT],[O.SPEAKER_DEVICES_UPDATES,q.MINOR_EVENT],[O.SELECTED_MICROHPONE_UPDATE,q.MINOR_EVENT],[O.SELECTED_CAMERA_UPDATE,q.MINOR_EVENT],[O.SELECTED_SPEAKER_UPDATE,q.MINOR_EVENT],[O.MEDIA_PERMISSION,q.MINOR_EVENT],[O.LEGACY_SWITCH,q.MINOR_EVENT],[O.AUDIO_PLAY_FAILED,q.MINOR_EVENT],[O.VIDEO_PLAY_FAILED,q.MINOR_EVENT],[O.AUDIO_TRACK_MUTED,q.MINOR_EVENT],[O.VIDEO_TRACK_MUTED,q.MINOR_EVENT],[O.IVS_PLAYER_REBUFFERING,q.MAJOR_EVENT],[O.IVS_PLAYER_AUDIO_BLOCKED,q.MAJOR_EVENT],[O.IVS_PLAYER_PLAYBACK_BLOCKED,q.MAJOR_EVENT],[O.IVS_PLAYER_ERROR,q.MAJOR_EVENT],[O.IVS_PLAYER_RECOVERABLE_ERROR,q.MAJOR_EVENT],[O.IVS_PLAYER_WORKER_ERROR,q.MAJOR_EVENT],[O.IVS_PLAYER_NETWORK_UNAVAILABLE,q.MAJOR_EVENT],[O.LIVESTREAM_LATENCY,q.MAJOR_EVENT],[O.IVS_PLAYER_ANALYTICS_EVENT,q.MINOR_EVENT],[O.IVS_PLAYER_PLAYBACK_RATE_CHANGED,q.MINOR_EVENT],[O.IVS_PLAYER_QUALITY_CHANGED,q.MINOR_EVENT],[O.IVS_PLAYER_INITIALIZED,q.MINOR_EVENT],[O.EXPECTED_VIDEO_RESOLUTION,q.MINOR_EVENT],[O.EXPECTED_SCREENSHARE_RESOLUTION,q.MINOR_EVENT]]);class QT{constructor(){h(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class XT extends ft{constructor({logger:e,peerId:r,apiHostnames:i,authToken:a}){super();h(this,"logger");h(this,"peerId");h(this,"eventStore");h(this,"apiEndpoint");h(this,"authToken");this.logger=e,this.peerId=r,this.authToken=a,this.apiEndpoint=`https://${i.daCollector}`,this.eventStore=new QT}async sendEventsChunkToServer(e){const r={payload:e,peerId:this.peerId},i=new AbortController,a=setTimeout(()=>i.abort(),3e3);try{return await fetch(this.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.authToken}`},body:JSON.stringify(r),signal:i.signal}),!0}catch(o){return this.logger.error("callStats::sendEventsChunkToServer::catch",{peerId:this.peerId,endpoint:this.apiEndpoint,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0}),!1}finally{clearTimeout(a)}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),YT.get(e.event)===q.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();if((r=e==null?void 0:e.entries)!=null&&r.length){const i=await this.sendEventsChunkToServer(e);return i||e.entries.forEach(a=>{this.eventStore.add(a)}),i}return!1}}var kp;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(kp||(kp={}));const Nm={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Bt;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Bt||(Bt={}));var Ip;(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"})(Ip||(Ip={}));function ri(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function kd({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Id({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Lm=240,Vm=720,$m=8,xm=3,Xl=10,Zl=.02,eu=.03;function ur({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 Um({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 Hm({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Bm({packetsLost:s,packetsSent:t,jitter:e}){const i=ur({stat:Hm({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:Xl,rangeRankingDirection:"UP"}),o=ur({stat:e,weight:.3,rangeMin:Zl,rangeMax:eu,rangeRankingDirection:"UP"});return i+o}function ZT({frameWidth:s,isScreenShare:t}){return s<(t?Vm:Lm)}function ev({framesPerSecond:s,isScreenShare:t}){return s<(t?xm:$m)}function tv({framesEncoded:s}){return s===0}function Fm({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:a,framesEncoded:o}){const c=ur({stat:Hm({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:Xl,rangeRankingDirection:"UP"}),d=ur({stat:i,weight:1,rangeMin:Zl,rangeMax:eu,rangeRankingDirection:"UP"}),l=ZT({frameWidth:s,isScreenShare:a}),u=ev({framesPerSecond:t,isScreenShare:a}),p=tv({framesEncoded:o,isScreenShare:a});return Um({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}function jm({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function qm({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const a=ur({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=ur({stat:jm({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:Xl,rangeRankingDirection:"UP"}),l=ur({stat:r,weight:.3,rangeMin:Zl,rangeMax:eu,rangeRankingDirection:"UP"});return a+c+l}function sv({framesDecoded:s}){return s===0}function rv({framesPerSecond:s,isScreenShare:t}){return s<(t?xm:$m)}function iv({frameWidth:s,isScreenShare:t}){return s<(t?Vm:Lm)}function Gm({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:a,framesDecoded:o}){const c=ur({stat:jm({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:Xl,rangeRankingDirection:"UP"}),d=ur({stat:i,weight:1,rangeMin:Zl,rangeMax:eu,rangeRankingDirection:"UP"}),l=iv({frameWidth:s,isScreenShare:a}),u=rv({framesPerSecond:t,isScreenShare:a}),p=sv({framesDecoded:o,isScreenShare:a});return Um({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}class pr{constructor(t){h(this,"pc1");h(this,"pc2");h(this,"constrainVideoBitrateKbps");h(this,"constrainOfferToRemoveVideoFec",!1);h(this,"iceCandidateFilter");const e=new RTCPeerConnection(t),r=new RTCPeerConnection(t);this.pc1=e,this.pc2=r,this.iceCandidateFilter=pr.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=pr.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 Rm extends ht{constructor(e){super();h(this,"call");h(this,"timeOut");this.call=new nr(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 $S=8,HS=1/1e3;class BS extends Rm{constructor(e){super(e);h(this,"senderChannel");h(this,"recieveChannel");h(this,"startTime");h(this,"lastBitrateMeasureTime");h(this,"sentPayloadBytes",0);h(this,"recievedPayloadBytes",0);h(this,"lastReceivedPayloadBytes",0);h(this,"stopSending",!1);h(this,"testProgress",0);h(this,"samplePacket","");h(this,"finalBitrateSum",0);h(this,"bitRateSampels",0);h(this,"maxNumberOfPacketsToSend",0);h(this,"bytesToKeepBuffered",0);h(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(nr.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)*$S/(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*HS)})}}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 _h extends Rm{constructor(e,r=nr.noFilter){super(e);h(this,"ch1");h(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 FS extends _h{constructor(t){super(t,nr.isHost)}}class qS extends _h{constructor(t){super(t,nr.isRelay)}}class jS extends _h{constructor(t){super(t,nr.isReflexive)}}class GS{constructor(){h(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=Kr(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=Kr(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 bm=new GS,up=[{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 hp(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class km{constructor(){h(this,"transport");h(this,"candidatePair");h(this,"outboundVideoRtp",new Map);h(this,"inboundVideoRtp",new Map);h(this,"outboundAudioRtp",new Map);h(this,"inboundAudioRtp",new Map);h(this,"remoteInboundRtp",new Map);h(this,"producerStreamMap",new Map);h(this,"consumerStreamMap",new Map);h(this,"staleProducerStreamMap",!1);h(this,"staleConsumerStreamMap",!1)}}class Am extends ht{constructor(){super();h(this,"observer");h(this,"outboundProducerMap",new Map);h(this,"inboundConsumerMap",new Map);h(this,"consumerPeerIdMap",new Map);h(this,"pausedConsumerMap",new Map);h(this,"pausedProducerMap",new Map);h(this,"overallProducingTransportsStatsMap",{});h(this,"overallConsumingTransportsStatsMap",{});h(this,"overallConsumersStatsMap",{});h(this,"overallProducersStatsMap",{});h(this,"videoProducerToStatsMap",new Map);h(this,"audioProducerToStatsMap",new Map);h(this,"videoConsumerToStatsMap",new Map);h(this,"audioConsumerToStatsMap",new Map);h(this,"consumerIdsWithFreezedVideo",new Set);h(this,"consumerIdsWithFreezedAudio",new Set);h(this,"producerIdsWithFreezedVideo",new Set);h(this,"producerIdsWithFreezedAudio",new Set);h(this,"freezedProducingTransportIds",new Set);h(this,"freezedConsumingTransportIds",new Set);h(this,"screenShareProducers",new Set);h(this,"screenShareConsumers",new Set);h(this,"ipDetails");h(this,"callStatsInstance");this.observer=new ht}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 u;const a=((u=this==null?void 0:this.callStatsInstance)==null?void 0:u.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,u)=>l||u.audio||u.video||u.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 R,A,b,V,D,L,U,B,z,Q,Ge,tt,Et;const c=e,d=new km,l=r.length?new Set(r):void 0,u=[],p=[],f=[],v=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":{u.push(this.getIceCandidateStats(k));break}case"remote-candidate":{p.push(this.getIceCandidateStats(k));break}case"candidate-pair":{const{nominated:S}=k,{selected:P}=k,$=k,fe={nominated:S!=null?S:P,currentRoundTripTime:$.currentRoundTripTime,totalRoundTripTime:$.totalRoundTripTime,bytesReceived:$.bytesReceived,bytesSent:$.bytesSent,availableOutgoingBitrate:$.availableOutgoingBitrate,availableIncomingBitrate:$.availableIncomingBitrate,lastPacketReceivedTimestamp:$.lastPacketReceivedTimestamp,lastPacketSentTimestamp:$.lastPacketSentTimestamp,localCandidateId:$.localCandidateId,remoteCandidateId:$.remoteCandidateId,bytesDiscardedOnSend:$.bytesDiscardedOnSend,packetsSent:$.packetsSent,packetsReceived:$.packetsReceived,packetsDiscardedOnSend:$.packetsDiscardedOnSend};f.push(fe),(k.nominated===!0||k.selected===!0)&&(d.candidatePair=fe);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 $=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,$,P)}if(o.consuming){const $=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,$,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),$=this.pausedProducerMap.get(P);if($){if($.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const fe=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 ye=this.callStatsInstance.producers.get(P);if(((R=ye==null?void 0:ye.track)==null?void 0:R.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const N={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 w=S,Re={frameHeight:w.frameHeight,frameWidth:w.frameWidth,framesEncoded:w.framesEncoded,framesDropped:w.framesDropped,framesPerSecond:w.framesPerSecond,framesSent:w.framesSent,keyFramesEncoded:w.keyFramesEncoded,firCount:w.firCount,encoderImplementation:w.encoderImplementation,hugeFramesSent:w.hugeFramesSent,pliCount:w.pliCount,qpSum:w.qpSum,qualityLimitationDurations:w.qualityLimitationDurations,qualityLimitationReason:w.qualityLimitationReason,qualityLimitationResolutionChanges:w.qualityLimitationResolutionChanges,totalEncodeTime:w.targetBitrate,totalPacketSendDelay:w.totalPacketSendDelay,retransmittedBytesSent:w.retransmittedBytesSent,retransmittedPacketsSent:w.retransmittedPacketsSent,scalabilityMode:w.scalabilityMode,powerEfficientEncoder:w.powerEfficientEncoder,...N};d.outboundVideoRtp.set(k.id,Re),d.producerStreamMap.get(P).outboundVideoRtpId.push(k.id),this.processOutboundProducerVideoStats(P,fe,Re)}else if(S.mediaType==="audio"||S.kind==="audio"){const w=S,Re={retransmittedBytesSent:w.retransmittedBytesSent,retransmittedPacketsSent:w.retransmittedPacketsSent,...N};d.outboundAudioRtp.set(k.id,Re),d.producerStreamMap.get(P).outboundAudioRtpId.push(k.id),this.processOutboundProducerAudioStats(P,fe,Re)}}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),$=this.pausedConsumerMap.get(P);if($){if($.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 fe=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 ye={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 N=S,w={frameHeight:N.frameHeight,frameWidth:N.frameWidth,framesDecoded:N.framesDecoded,framesDropped:N.framesDropped,framesPerSecond:N.framesPerSecond,framesReceived:N.framesReceived,keyFramesDecoded:N.keyFramesDecoded,firCount:N.firCount,decoderImplementation:N.decoderImplementation,pliCount:N.pliCount,totalProcessingDelay:N.totalProcessingDelay,qpSum:N.qpSum||0,totalAssemblyTime:N.totalAssemblyTime||0,totalDecodeTime:N.totalDecodeTime||0,totalFreezesDuration:N.totalFreezesDuration||0,totalInterFrameDelay:N.totalInterFrameDelay||0,totalPausesDuration:N.totalPausesDuration||0,totalSquaredInterFrameDelay:N.totalSquaredInterFrameDelay||0,freezeCount:N.freezeCount||0,pauseCount:N.pauseCount||0,powerEfficientDecoder:N.powerEfficientDecoder,...ye};w.score=wm({frameWidth:w.frameWidth||0,framesDecoded:(w.framesDecoded||0)-(((A=this.videoConsumerToStatsMap.get(P))==null?void 0:A.framesDecoded)||0),framesPerSecond:w.framesPerSecond||0,packetsLost:(w.packetsLost||0)-(((b=this.videoConsumerToStatsMap.get(P))==null?void 0:b.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((V=this.videoConsumerToStatsMap.get(P))==null?void 0:V.packetsReceived)||0),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(w.score*10).toFixed(),frameWidth:w.frameWidth||0,frameHeight:w.frameHeight||0,framesPerSecond:w.framesPerSecond||0,packetsLostPercentage:yd({packetsLost:(w.packetsLost||0)-(((D=this.videoConsumerToStatsMap.get(P))==null?void 0:D.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(P))==null?void 0:L.packetsReceived)||0)}),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((w.bytesReceived||0)-(((U=this.videoConsumerToStatsMap.get(P))==null?void 0:U.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,w),d.inboundVideoRtp.set(k.id,w),d.consumerStreamMap.get(P).inboundVideoRtpId.push(k.id),this.processInboundConsumerVideoStats(P,fe,w)}else if(S.mediaType==="audio"||S.kind==="audio"){const N=S,w={audioLevel:N.audioLevel,concealedSamples:N.concealedSamples,concealmentEvents:N.concealmentEvents,totalAudioEnergy:N.totalAudioEnergy,totalSamplesDuration:N.totalSamplesDuration,totalSamplesReceived:N.totalSamplesReceived,fecPacketsDiscarded:N.fecPacketsDiscarded||0,fecPacketsReceived:N.fecPacketsReceived||0,insertedSamplesForDeceleration:N.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:N.removedSamplesForAcceleration||0,silentConcealedSamples:N.silentConcealedSamples||0,playoutId:N.playoutId,...ye};w.score=Cm({concealmentEvents:(w.concealmentEvents||0)-(((B=this.audioConsumerToStatsMap.get(P))==null?void 0:B.concealmentEvents)||0),packetsLost:(w.packetsLost||0)-(((z=this.audioConsumerToStatsMap.get(P))==null?void 0:z.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((Q=this.audioConsumerToStatsMap.get(P))==null?void 0:Q.packetsReceived)||0),jitter:w.jitter||0}),E.set(P,{score:+(w.score*10).toFixed(),packetsLostPercentage:yd({packetsLost:(w.packetsLost||0)-(((Ge=this.audioConsumerToStatsMap.get(P))==null?void 0:Ge.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((tt=this.audioConsumerToStatsMap.get(P))==null?void 0:tt.packetsReceived)||0)}),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((w.bytesReceived||0)-(((Et=this.audioConsumerToStatsMap.get(P))==null?void 0:Et.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,w),d.inboundAudioRtp.set(k.id,w),d.consumerStreamMap.get(P).inboundAudioRtpId.push(k.id),this.processInboundConsumerAudioStats(P,fe,w)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((k,S)=>{var P,$,fe,ye,N,w,Re,ka,Aa,Ma,Ia,Da,Oa,Na,La,Va,xa,Ua,$a,Ha,Ba,Fa,qa;if(k.outboundVideoRtpId.length>0){const de=[];k.outboundVideoRtpId.forEach(ru=>{de.push(d.outboundVideoRtp.get(ru))});const Y=this.getWorkingSimulcastVideoStats(de);Y.score=Pm({frameWidth:Y.frameWidth||0,framesPerSecond:Y.framesPerSecond||0,jitter:((P=Y.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(Y.packetsSent||0)-((($=this.videoProducerToStatsMap.get(S))==null?void 0:$.packetsSent)||0),packetsLost:(((fe=Y.remoteData)==null?void 0:fe.packetsLost)||0)-(((N=(ye=this.videoProducerToStatsMap.get(S))==null?void 0:ye.remoteData)==null?void 0:N.packetsLost)||0),framesEncoded:(Y.framesEncoded||0)-(((w=this.videoProducerToStatsMap.get(S))==null?void 0:w.framesEncoded)||0)}),v.set(S,{score:+(Y.score*10).toFixed(),frameWidth:Y.frameWidth||0,frameHeight:Y.frameHeight||0,framesPerSecond:Y.framesPerSecond||0,jitter:((Re=Y.remoteData)==null?void 0:Re.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:vd({packetsSent:(Y.packetsSent||0)-(((ka=this.videoProducerToStatsMap.get(S))==null?void 0:ka.packetsSent)||0),packetsLost:(((Aa=Y.remoteData)==null?void 0:Aa.packetsLost)||0)-(((Ia=(Ma=this.videoProducerToStatsMap.get(S))==null?void 0:Ma.remoteData)==null?void 0:Ia.packetsLost)||0)}),bitrate:((Y.bytesSent||0)-(((Da=this.videoProducerToStatsMap.get(S))==null?void 0:Da.bytesSent)||0))*8/7,cpuLimitations:Y.qualityLimitationReason==="cpu",bandwidthLimitations:Y.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,Y)}else if(k.outboundAudioRtpId.length>0){const de=d.outboundAudioRtp.get(k.outboundAudioRtpId[0]);de.score=Em({packetsSent:(de.packetsSent||0)-(((Oa=this.audioProducerToStatsMap.get(S))==null?void 0:Oa.packetsSent)||0),packetsLost:(((Na=de.remoteData)==null?void 0:Na.packetsLost)||0)-(((Va=(La=this.audioProducerToStatsMap.get(S))==null?void 0:La.remoteData)==null?void 0:Va.packetsLost)||0),jitter:((xa=de.remoteData)==null?void 0:xa.jitter)||0}),v.set(S,{score:+(de.score*10).toFixed(),bitrate:((de.bytesSent||0)-(((Ua=this.audioProducerToStatsMap.get(S))==null?void 0:Ua.bytesSent)||0))*8/7,packetsLostPercentage:vd({packetsSent:(de.packetsSent||0)-((($a=this.audioProducerToStatsMap.get(S))==null?void 0:$a.packetsSent)||0),packetsLost:(((Ha=de.remoteData)==null?void 0:Ha.packetsLost)||0)-(((Fa=(Ba=this.audioProducerToStatsMap.get(S))==null?void 0:Ba.remoteData)==null?void 0:Fa.packetsLost)||0)}),jitter:((qa=de.remoteData)==null?void 0:qa.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,de)}}),f.forEach(k=>{const S=u.find($=>$.id===k.localCandidateId?(k.localCandidateId=$.id,$):null),P=p.find($=>$.id===k.remoteCandidateId?(k.remoteCandidateId=$.id,$):null);S&&(k.localCandidateType=S.type,k.localCandidateAddress=Kr(S.address),k.localCandidatePort=S.port,k.localCandidateProtocol=S.protocol,k.localCandidateUrl=S.url,k.localCandidateNetworkType=S.networkType,k.localCandidateRelatedAddress=Kr(S.relatedAddress),k.localCandidateRelatedPort=S.relatedPort),P&&(k.remoteCandidateType=P.type,k.remoteCandidateAddress=Kr(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,$)=>{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(v.size>0)try{this.observer.emit("producer_score",v)}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},u=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),p=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:u,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||up},i=new Promise((u,p)=>{try{const f=new FS(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),a=new Promise((u,p)=>{try{const f=new qS(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),o=new Promise((u,p)=>{try{const f=new jS(r);f.addListener("done",u),f.addListener("failed",()=>{u({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||up},d=new BS(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 bm.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?hp(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?hp(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 WS extends Am{}class Mm extends Am{constructor(){super(...arguments);h(this,"producerMap",new Map);h(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 R,A,b,V,D,L,U,B,z,Q,Ge,tt,Et;const c=e,d=new km,l=r.length?new Set(r):void 0,u=[],p=[],f=[],v=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":{u.push(this.getIceCandidateStats(k));break}case"remote-candidate":{p.push(this.getIceCandidateStats(k));break}case"candidate-pair":{const{nominated:S}=k,{selected:P}=k,$=k,fe={nominated:S!=null?S:P,currentRoundTripTime:$.currentRoundTripTime,totalRoundTripTime:$.totalRoundTripTime,bytesReceived:$.bytesReceived,bytesSent:$.bytesSent,availableOutgoingBitrate:$.availableOutgoingBitrate,availableIncomingBitrate:$.availableIncomingBitrate,lastPacketReceivedTimestamp:$.lastPacketReceivedTimestamp,lastPacketSentTimestamp:$.lastPacketSentTimestamp,localCandidateId:$.localCandidateId,remoteCandidateId:$.remoteCandidateId,bytesDiscardedOnSend:$.bytesDiscardedOnSend,packetsSent:$.packetsSent,packetsReceived:$.packetsReceived,packetsDiscardedOnSend:$.packetsDiscardedOnSend};f.push(fe),(k.nominated===!0||k.selected===!0)&&(d.candidatePair=fe);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 $=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,$,P)}if(o.consuming){const $=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,$,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),$=this.pausedProducerMap.get(P);if($){if($.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const fe=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 ye=this.callStatsInstance.producers.get(P);if(((R=ye==null?void 0:ye.track)==null?void 0:R.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const N={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 w=S,Re={frameHeight:w.frameHeight,frameWidth:w.frameWidth,framesEncoded:w.framesEncoded,framesDropped:w.framesDropped?w.framesDropped:w.droppedFrames,framesPerSecond:w.framesPerSecond?w.framesPerSecond:w.framerateMean,framesSent:w.framesSent,keyFramesEncoded:w.keyFramesEncoded,firCount:w.firCount,encoderImplementation:w.encoderImplementation,hugeFramesSent:w.hugeFramesSent,pliCount:w.pliCount,qpSum:w.qpSum,qualityLimitationReason:w.qualityLimitationReason,qualityLimitationDurations:w.qualityLimitationDurations,qualityLimitationResolutionChanges:w.qualityLimitationResolutionChanges,totalEncodeTime:w.totalEncodeTime,totalPacketSendDelay:w.totalEncodeTime,retransmittedBytesSent:w.retransmittedBytesSent,retransmittedPacketsSent:w.retransmittedPacketsSent,scalabilityMode:w.scalabilityMode,powerEfficientEncoder:w.powerEfficientEncoder,...N};d.outboundVideoRtp.set(k.id,Re),d.producerStreamMap.get(P).outboundVideoRtpId.push(k.id),this.processOutboundProducerVideoStats(P,fe,Re)}else if(S.mediaType==="audio"||S.kind==="audio"){const w=S,Re={retransmittedBytesSent:w.retransmittedBytesSent,retransmittedPacketsSent:w.retransmittedPacketsSent,...N};d.outboundAudioRtp.set(k.id,Re),d.producerStreamMap.get(P).outboundAudioRtpId.push(k.id),this.processOutboundProducerAudioStats(P,fe,Re)}}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),$=this.pausedConsumerMap.get(P);if($){if($.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 fe=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 ye={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 N=S,w={frameHeight:N.frameHeight,frameWidth:N.frameWidth,framesDecoded:N.framesDecoded,framesDropped:N.framesDropped?N.framesDropped:N.droppedFrames,framesPerSecond:N.framesPerSecond?N.framesPerSecond:N.framerateMean,framesReceived:N.framesReceived,keyFramesDecoded:N.keyFramesDecoded,firCount:N.firCount,decoderImplementation:N.decoderImplementation,pliCount:N.pliCount,totalProcessingDelay:N.totalProcessingDelay,qpSum:N.qpSum||0,totalAssemblyTime:N.totalAssemblyTime||0,totalDecodeTime:N.totalDecodeTime||0,totalFreezesDuration:N.totalFreezesDuration||0,totalInterFrameDelay:N.totalInterFrameDelay||0,totalPausesDuration:N.totalPausesDuration||0,totalSquaredInterFrameDelay:N.totalSquaredInterFrameDelay||0,freezeCount:N.freezeCount||0,pauseCount:N.pauseCount||0,powerEfficientDecoder:N.powerEfficientDecoder,...ye};w.score=wm({frameWidth:w.frameWidth||0,framesDecoded:(w.framesDecoded||0)-(((A=this.videoConsumerToStatsMap.get(P))==null?void 0:A.framesDecoded)||0),framesPerSecond:w.framesPerSecond||0,packetsLost:(w.packetsLost||0)-(((b=this.videoConsumerToStatsMap.get(P))==null?void 0:b.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((V=this.videoConsumerToStatsMap.get(P))==null?void 0:V.packetsReceived)||0),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(w.score*10).toFixed(),frameWidth:w.frameWidth||0,frameHeight:w.frameHeight||0,framesPerSecond:w.framesPerSecond||0,packetsLostPercentage:yd({packetsLost:(w.packetsLost||0)-(((D=this.videoConsumerToStatsMap.get(P))==null?void 0:D.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(P))==null?void 0:L.packetsReceived)||0)}),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((w.bytesReceived||0)-(((U=this.videoConsumerToStatsMap.get(P))==null?void 0:U.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,w),d.inboundVideoRtp.set(k.id,w),d.consumerStreamMap.get(P).inboundVideoRtpId.push(k.id),this.processInboundConsumerVideoStats(P,fe,w)}else if(S.mediaType==="audio"||S.kind==="audio"){const N=S,w={audioLevel:N.audioLevel,concealedSamples:N.concealedSamples,concealmentEvents:N.concealmentEvents,totalAudioEnergy:N.totalAudioEnergy,totalSamplesDuration:N.totalSamplesDuration,totalSamplesReceived:N.totalSamplesReceived,fecPacketsDiscarded:N.fecPacketsDiscarded||0,fecPacketsReceived:N.fecPacketsReceived||0,insertedSamplesForDeceleration:N.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:N.removedSamplesForAcceleration||0,silentConcealedSamples:N.silentConcealedSamples||0,playoutId:N.playoutId,...ye};w.score=Cm({concealmentEvents:(w.concealmentEvents||0)-(((B=this.audioConsumerToStatsMap.get(P))==null?void 0:B.concealmentEvents)||0),packetsLost:(w.packetsLost||0)-(((z=this.audioConsumerToStatsMap.get(P))==null?void 0:z.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((Q=this.audioConsumerToStatsMap.get(P))==null?void 0:Q.packetsReceived)||0),jitter:w.jitter||0}),E.set(P,{score:+(w.score*10).toFixed(),packetsLostPercentage:yd({packetsLost:(w.packetsLost||0)-(((Ge=this.audioConsumerToStatsMap.get(P))==null?void 0:Ge.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((tt=this.audioConsumerToStatsMap.get(P))==null?void 0:tt.packetsReceived)||0)}),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((w.bytesReceived||0)-(((Et=this.audioConsumerToStatsMap.get(P))==null?void 0:Et.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,w),d.inboundAudioRtp.set(k.id,w),d.consumerStreamMap.get(P).inboundAudioRtpId.push(k.id),this.processInboundConsumerAudioStats(P,fe,w)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((k,S)=>{var P,$,fe,ye,N,w,Re,ka,Aa,Ma,Ia,Da,Oa,Na,La,Va,xa,Ua,$a,Ha,Ba,Fa,qa;if(k.outboundVideoRtpId.length>0){const de=[];k.outboundVideoRtpId.forEach(ru=>{de.push(d.outboundVideoRtp.get(ru))});const Y=this.getWorkingSimulcastVideoStats(de);Y.score=Pm({frameWidth:Y.frameWidth||0,framesPerSecond:Y.framesPerSecond||0,jitter:((P=Y.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(Y.packetsSent||0)-((($=this.videoProducerToStatsMap.get(S))==null?void 0:$.packetsSent)||0),packetsLost:(((fe=Y.remoteData)==null?void 0:fe.packetsLost)||0)-(((N=(ye=this.videoProducerToStatsMap.get(S))==null?void 0:ye.remoteData)==null?void 0:N.packetsLost)||0),framesEncoded:(Y.framesEncoded||0)-(((w=this.videoProducerToStatsMap.get(S))==null?void 0:w.framesEncoded)||0)}),v.set(S,{score:+(Y.score*10).toFixed(),frameWidth:Y.frameWidth||0,frameHeight:Y.frameHeight||0,framesPerSecond:Y.framesPerSecond||0,jitter:((Re=Y.remoteData)==null?void 0:Re.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:vd({packetsSent:(Y.packetsSent||0)-(((ka=this.videoProducerToStatsMap.get(S))==null?void 0:ka.packetsSent)||0),packetsLost:(((Aa=Y.remoteData)==null?void 0:Aa.packetsLost)||0)-(((Ia=(Ma=this.videoProducerToStatsMap.get(S))==null?void 0:Ma.remoteData)==null?void 0:Ia.packetsLost)||0)}),bitrate:((Y.bytesSent||0)-(((Da=this.videoProducerToStatsMap.get(S))==null?void 0:Da.bytesSent)||0))*8/7,cpuLimitations:Y.qualityLimitationReason==="cpu",bandwidthLimitations:Y.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,Y)}else if(k.outboundAudioRtpId.length>0){const de=d.outboundAudioRtp.get(k.outboundAudioRtpId[0]);de.score=Em({packetsSent:(de.packetsSent||0)-(((Oa=this.audioProducerToStatsMap.get(S))==null?void 0:Oa.packetsSent)||0),packetsLost:(((Na=de.remoteData)==null?void 0:Na.packetsLost)||0)-(((Va=(La=this.audioProducerToStatsMap.get(S))==null?void 0:La.remoteData)==null?void 0:Va.packetsLost)||0),jitter:((xa=de.remoteData)==null?void 0:xa.jitter)||0}),v.set(S,{score:+(de.score*10).toFixed(),bitrate:((de.bytesSent||0)-(((Ua=this.audioProducerToStatsMap.get(S))==null?void 0:Ua.bytesSent)||0))*8/7,packetsLostPercentage:vd({packetsSent:(de.packetsSent||0)-((($a=this.audioProducerToStatsMap.get(S))==null?void 0:$a.packetsSent)||0),packetsLost:(((Ha=de.remoteData)==null?void 0:Ha.packetsLost)||0)-(((Fa=(Ba=this.audioProducerToStatsMap.get(S))==null?void 0:Ba.remoteData)==null?void 0:Fa.packetsLost)||0)}),jitter:((qa=de.remoteData)==null?void 0:qa.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,de)}}),f.forEach(k=>{const S=u.find($=>$.id===k.localCandidateId?(k.localCandidateId=$.id,$):null),P=p.find($=>$.id===k.remoteCandidateId?(k.remoteCandidateId=$.id,$):null);S&&(k.localCandidateType=S.type,k.localCandidateAddress=Kr(S.address),k.localCandidatePort=S.port,k.localCandidateProtocol=S.protocol,k.localCandidateUrl=S.url,k.localCandidateNetworkType=S.networkType,k.localCandidateRelatedAddress=Kr(S.relatedAddress),k.localCandidateRelatedPort=S.relatedPort),P&&(k.remoteCandidateType=P.type,k.remoteCandidateAddress=Kr(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,$)=>{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(v.size>0)try{this.observer.emit("producer_score",v)}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(u=>{const p=e.outboundVideoRtp.get(u);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(u=>e.outboundAudioRtp.get(u))};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(u=>{const f=this.consumerMap.get(i).track.getSettings(),v=e.inboundVideoRtp.get(u);return v.frameHeight||(v.frameHeight=f.height,v.frameWidth=f.width,v.framesPerSecond=f.frameRate),v});a={consumerId:i,peerId:o,producerId:c,appData:d,videoStats:l,audioStats:r==null?void 0:r.inboundAudioRtpId.map(u=>e.inboundAudioRtp.get(u))}}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 JS extends Mm{}function Ed(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 pp(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=>{Ed(this,t,e,o)}):a}catch(a){Ed(this,t,e,a)}return null},s}const K=(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=>{Ed(this,s,t,d)}):c}catch(c){Ed(this,s,t,c)}return null},i},KS=(s,t)=>(e,r,i)=>{if(i)return pp(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,pp(o,s,t))}};var G=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 W=console;let F=class extends ht{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=gm.PROD,a,o,c,d,l){super();h(this,"observer");h(this,"eventHandler");h(this,"measurements");h(this,"producingTransport");h(this,"consumingTransport");h(this,"producers",new Map);h(this,"consumers",new Map);h(this,"iceServers");h(this,"connectionInfoPromise");h(this,"pingStatsTimeout");h(this,"logger");h(this,"env");h(this,"apiHostnames");h(this,"peerId");h(this,"consumerSharedMediaStatesMap",new Map);h(this,"currentUserMediaStates",{});if(!l)throw Error("authToken is missing but required to initialize CallStats!");switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new DS({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new WS;break;case"Gecko":this.measurements=new Mm;break;case"WebKit":this.measurements=new JS;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 ht,this.measurements.observer.on("consumer_score",u=>{o.debug(`callStats::consumer_score ${[...u.entries()]}`),this.eventHandler.emit("consumer_score",u)}),this.measurements.observer.on("producer_score",u=>{o.debug(`callStats::producer_score ${[...u.entries()]}`),this.eventHandler.emit("producer_score",u)})}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:O.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:O.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?O.SCREENSHARE_STARTED:O.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:O.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:O.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===Ut.AUDIO&&O.AUDIO_DEVICES_UPDATES||e===Ut.VIDEO&&O.VIDEO_DEVICES_UPDATES||e===Ut.SPEAKER&&O.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===Ut.AUDIO&&O.SELECTED_MICROHPONE_UPDATE||e===Ut.VIDEO&&O.SELECTED_CAMERA_UPDATE||e===Ut.SPEAKER&&O.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:O.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===Ut.AUDIO&&O.AUDIO_PLAY_FAILED||e===Ut.VIDEO&&O.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===Ut.AUDIO&&O.AUDIO_TRACK_MUTED||e===Ut.VIDEO&&O.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:O.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:O.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:O.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:O.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:O.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:O.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:O.NET_QUALITY_TEST_END,timestamp:r,metaData:a})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:O.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:O.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=O.AUDIO_ON:i=O.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=O.VIDEO_ON:i=O.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:O.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:O.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:O.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:O.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:O.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:O.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:O.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:O.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:O.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:O.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:O.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:O.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerIceServers",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerConsumer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerProducer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendConsumerSharedMediaStateEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerProducingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerConsumingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"deRegisterConsumer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"deRegisterProducer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"disconnectConsumingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"disconnectProducingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPreCallTestBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendScreenShareToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendScreenShareRequestedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendActiveSpeakerEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"devices",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"selectedDevice",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaPermission",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaPlaybackFailed",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaTrackMuted",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"tabChanged",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"browserBackgrounded",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"browserForegrounded",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"legacySwitch",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"getPreCallTestResults",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendCallJoinBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendNetworkQualityTestBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendWebSocketConnectedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendTransportConnectedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendAudioToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendVideoToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendParticipantRoleToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"startPingStats",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"stopPingStats",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPingStatsEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerRebufferEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerAudioBlockEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerInitializedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerWorkerErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerRecoverableErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerAnalyticsEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerQualityChanged",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPlayerLiveLatency",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendDisconnectEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendReconnectEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"expectedVideoResolution",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"expectedScreenshareResolution",null);F=G([KS(TypeError,(s,t)=>W.error(t,s))],F);const zS=F;class Im extends ht{constructor(){super(...arguments);h(this,"stats");h(this,"peerId");h(this,"backend");h(this,"iceServers");h(this,"initialized",!1);h(this,"stalled",!1);h(this,"ipInformation");h(this,"logger")}async initialize({peerId:e,engineName:r,env:i=gm.PROD,iceServers:a,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:p}){var f,v,E;try{if(this.peerId=e,this.logger=d,!p){this.logger.error("callStats::initialize",{event:"auth_token_missing",peerId:this.peerId}),this.stallCallStats();return}this.ipInformation=await bm.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new zS(o,r,i,c,d,e,l,p),this.iceServers=a,(f=this.backend)==null||f.registerIceServers(this.iceServers),this.initialized=!0,(E=(v=this.backend)==null?void 0:v.eventHandler)==null||E.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(R){this.logger.error("callStats::CallStatsIntegration",{peerId:this.peerId,error:R instanceof Error?R.message:String(R),stack:R instanceof Error?R.stack:void 0}),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,u,p,f,v,E,R;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":(u=this.backend)==null||u.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":(v=this.backend)==null||v.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(E=this.backend)==null||E.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(R=this.backend)==null||R.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 YS=new Im;YS.setMaxListeners(30);var Co;class QS{constructor(){g(this,Co,void 0)}get telemetry(){var t;return(t=n(this,Co))==null?void 0:t.getValue("telemetry")}init(t){m(this,Co,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)}}Co=new WeakMap;function gp(s,t,e,r){try{t==null||t.error(`EventEmitter listener error on event ${e.toString()}`,{error:r,eventListener:{eventName:e.toString(),listenerCount:s.listenerCount(e)}});return}catch(i){return}}function fo(s,t,e,r){const i=s.rawListeners(t);return i.forEach(a=>{try{const o=Reflect.apply(a,s,e);o&&typeof o.then=="function"&&Promise.resolve(o).catch(c=>gp(s,r,t,c))}catch(o){gp(s,r,t,o)}}),i.length>0}class Ca extends ht.EventEmitter{constructor(e){super();h(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return fo(this,"*",[e,...r],this.logger),fo(this,e,r,this.logger)}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 Nt extends ht.EventEmitter{constructor(e){super();h(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return fo(this,"*",[e,...r],this.logger),fo(this,e,r,this.logger)}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)}}var Ns,Ls;class XS extends ht.EventEmitter{constructor(e){super();g(this,Ns,void 0);g(this,Ls,void 0);h(this,"asyncPromiseTimeout");h(this,"logger");this.logger=e,m(this,Ns,new Map),m(this,Ls,new Map),this.asyncPromiseTimeout=8e3}emit(e,...r){return fo(this,e,r,this.logger)}async emitAsync(e,...r){n(this,Ns).set(e,[]);const i=n(this,Ls).get(e).map(()=>new Promise(a=>{n(this,Ns).get(e).push(a)}));this.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,Ns).delete(e)}onAsync(e,r){const i=n(this,Ns),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,Ls).get(e)||n(this,Ls).set(e,[]),n(this,Ls).get(e).push(a),super.on(e,a)}reset(){m(this,Ns,new Map),m(this,Ls,new Map),super.removeAllListeners()}}Ns=new WeakMap,Ls=new WeakMap;var ZS=typeof global=="object"&&global&&global.Object===Object&&global;const Dm=ZS;var ev=typeof self=="object"&&self&&self.Object===Object&&self,tv=Dm||ev||Function("return this")();const us=tv;var sv=us.Symbol;const Rs=sv;var Om=Object.prototype,rv=Om.hasOwnProperty,iv=Om.toString,ja=Rs?Rs.toStringTag:void 0;function nv(s){var t=rv.call(s,ja),e=s[ja];try{s[ja]=void 0;var r=!0}catch(a){}var i=iv.call(s);return r&&(t?s[ja]=e:delete s[ja]),i}var av=Object.prototype,ov=av.toString;function cv(s){return ov.call(s)}var dv="[object Null]",lv="[object Undefined]",mp=Rs?Rs.toStringTag:void 0;function sn(s){return s==null?s===void 0?lv:dv:mp&&mp in Object(s)?nv(s):cv(s)}function bs(s){return s!=null&&typeof s=="object"}var uv="[object Symbol]";function $l(s){return typeof s=="symbol"||bs(s)&&sn(s)==uv}function hv(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 pv=Array.isArray;const Dt=pv;var gv=1/0,fp=Rs?Rs.prototype:void 0,Tp=fp?fp.toString:void 0;function Nm(s){if(typeof s=="string")return s;if(Dt(s))return hv(s,Nm)+"";if($l(s))return Tp?Tp.call(s):"";var t=s+"";return t=="0"&&1/s==-gv?"-0":t}var mv=/\s/;function fv(s){for(var t=s.length;t--&&mv.test(s.charAt(t)););return t}var Tv=/^\s+/;function Sv(s){return s&&s.slice(0,fv(s)+1).replace(Tv,"")}function zt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var Sp=0/0,vv=/^[-+]0x[0-9a-f]+$/i,yv=/^0b[01]+$/i,Ev=/^0o[0-7]+$/i,Pv=parseInt;function vp(s){if(typeof s=="number")return s;if($l(s))return Sp;if(zt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=zt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=Sv(s);var e=yv.test(s);return e||Ev.test(s)?Pv(s.slice(2),e?2:8):vv.test(s)?Sp:+s}function Ch(s){return s}var _v="[object AsyncFunction]",Cv="[object Function]",wv="[object GeneratorFunction]",Rv="[object Proxy]";function wh(s){if(!zt(s))return!1;var t=sn(s);return t==Cv||t==wv||t==_v||t==Rv}var bv=us["__core-js_shared__"];const nu=bv;var yp=function(){var s=/[^.]+$/.exec(nu&&nu.keys&&nu.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function kv(s){return!!yp&&yp in s}var Av=Function.prototype,Mv=Av.toString;function rn(s){if(s!=null){try{return Mv.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var Iv=/[\\^$.*+?()[\]{}|]/g,Dv=/^\[object .+?Constructor\]$/,Ov=Function.prototype,Nv=Object.prototype,Lv=Ov.toString,Vv=Nv.hasOwnProperty,xv=RegExp("^"+Lv.call(Vv).replace(Iv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Uv(s){if(!zt(s)||kv(s))return!1;var t=wh(s)?xv:Dv;return t.test(rn(s))}function $v(s,t){return s==null?void 0:s[t]}function nn(s,t){var e=$v(s,t);return Uv(e)?e:void 0}var Hv=nn(us,"WeakMap");const yu=Hv;var Ep=Object.create,Bv=function(){function s(){}return function(t){if(!zt(t))return{};if(Ep)return Ep(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const Fv=Bv;function qv(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 jv(){}function Lm(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var Gv=800,Wv=16,Jv=Date.now;function Kv(s){var t=0,e=0;return function(){var r=Jv(),i=Wv-(r-e);if(e=r,i>0){if(++t>=Gv)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function zv(s){return function(){return s}}var Yv=function(){try{var s=nn(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const Pd=Yv;var Qv=Pd?function(s,t){return Pd(s,"toString",{configurable:!0,enumerable:!1,value:zv(t),writable:!0})}:Ch;const Xv=Qv;var Zv=Kv(Xv);const ey=Zv;function ty(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function sy(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 ry(s){return s!==s}function iy(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function ny(s,t,e){return t===t?iy(s,t,e):sy(s,ry,e)}function ay(s,t){var e=s==null?0:s.length;return!!e&&ny(s,t,0)>-1}var oy=9007199254740991,cy=/^(?:0|[1-9]\d*)$/;function Rh(s,t){var e=typeof s;return t=t==null?oy:t,!!t&&(e=="number"||e!="symbol"&&cy.test(s))&&s>-1&&s%1==0&&s<t}function bh(s,t,e){t=="__proto__"&&Pd?Pd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function Uc(s,t){return s===t||s!==s&&t!==t}var dy=Object.prototype,ly=dy.hasOwnProperty;function Vm(s,t,e){var r=s[t];(!(ly.call(s,t)&&Uc(r,e))||e===void 0&&!(t in s))&&bh(s,t,e)}function $c(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?bh(e,c,d):Vm(e,c,d)}return e}var Pp=Math.max;function uy(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),qv(s,this,c)}}function hy(s,t){return ey(uy(s,t,Ch),s+"")}var py=9007199254740991;function kh(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=py}function Hc(s){return s!=null&&kh(s.length)&&!wh(s)}function gy(s,t,e){if(!zt(e))return!1;var r=typeof t;return(r=="number"?Hc(e)&&Rh(t,e.length):r=="string"&&t in e)?Uc(e[t],s):!1}function my(s){return hy(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&&gy(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 fy=Object.prototype;function Hl(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||fy;return s===e}function Ty(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var Sy="[object Arguments]";function _p(s){return bs(s)&&sn(s)==Sy}var xm=Object.prototype,vy=xm.hasOwnProperty,yy=xm.propertyIsEnumerable,Ey=_p(function(){return arguments}())?_p:function(s){return bs(s)&&vy.call(s,"callee")&&!yy.call(s,"callee")};const To=Ey;function Py(){return!1}var Um=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Cp=Um&&typeof module=="object"&&module&&!module.nodeType&&module,_y=Cp&&Cp.exports===Um,wp=_y?us.Buffer:void 0,Cy=wp?wp.isBuffer:void 0,wy=Cy||Py;const Ea=wy;var Ry="[object Arguments]",by="[object Array]",ky="[object Boolean]",Ay="[object Date]",My="[object Error]",Iy="[object Function]",Dy="[object Map]",Oy="[object Number]",Ny="[object Object]",Ly="[object RegExp]",Vy="[object Set]",xy="[object String]",Uy="[object WeakMap]",$y="[object ArrayBuffer]",Hy="[object DataView]",By="[object Float32Array]",Fy="[object Float64Array]",qy="[object Int8Array]",jy="[object Int16Array]",Gy="[object Int32Array]",Wy="[object Uint8Array]",Jy="[object Uint8ClampedArray]",Ky="[object Uint16Array]",zy="[object Uint32Array]",ge={};ge[By]=ge[Fy]=ge[qy]=ge[jy]=ge[Gy]=ge[Wy]=ge[Jy]=ge[Ky]=ge[zy]=!0;ge[Ry]=ge[by]=ge[$y]=ge[ky]=ge[Hy]=ge[Ay]=ge[My]=ge[Iy]=ge[Dy]=ge[Oy]=ge[Ny]=ge[Ly]=ge[Vy]=ge[xy]=ge[Uy]=!1;function Yy(s){return bs(s)&&kh(s.length)&&!!ge[sn(s)]}function Ah(s){return function(t){return s(t)}}var $m=typeof exports=="object"&&exports&&!exports.nodeType&&exports,no=$m&&typeof module=="object"&&module&&!module.nodeType&&module,Qy=no&&no.exports===$m,au=Qy&&Dm.process,Xy=function(){try{var s=no&&no.require&&no.require("util").types;return s||au&&au.binding&&au.binding("util")}catch(t){}}();const Pa=Xy;var Rp=Pa&&Pa.isTypedArray,Zy=Rp?Ah(Rp):Yy;const Bl=Zy;var eE=Object.prototype,tE=eE.hasOwnProperty;function Hm(s,t){var e=Dt(s),r=!e&&To(s),i=!e&&!r&&Ea(s),a=!e&&!r&&!i&&Bl(s),o=e||r||i||a,c=o?Ty(s.length,String):[],d=c.length;for(var l in s)(t||tE.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||a&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||Rh(l,d)))&&c.push(l);return c}function Bm(s,t){return function(e){return s(t(e))}}var sE=Bm(Object.keys,Object);const rE=sE;var iE=Object.prototype,nE=iE.hasOwnProperty;function Fm(s){if(!Hl(s))return rE(s);var t=[];for(var e in Object(s))nE.call(s,e)&&e!="constructor"&&t.push(e);return t}function Fl(s){return Hc(s)?Hm(s):Fm(s)}function aE(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var oE=Object.prototype,cE=oE.hasOwnProperty;function dE(s){if(!zt(s))return aE(s);var t=Hl(s),e=[];for(var r in s)r=="constructor"&&(t||!cE.call(s,r))||e.push(r);return e}function Bc(s){return Hc(s)?Hm(s,!0):dE(s)}var lE=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,uE=/^\w*$/;function Mh(s,t){if(Dt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||$l(s)?!0:uE.test(s)||!lE.test(s)||t!=null&&s in Object(t)}var hE=nn(Object,"create");const So=hE;function pE(){this.__data__=So?So(null):{},this.size=0}function gE(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var mE="__lodash_hash_undefined__",fE=Object.prototype,TE=fE.hasOwnProperty;function SE(s){var t=this.__data__;if(So){var e=t[s];return e===mE?void 0:e}return TE.call(t,s)?t[s]:void 0}var vE=Object.prototype,yE=vE.hasOwnProperty;function EE(s){var t=this.__data__;return So?t[s]!==void 0:yE.call(t,s)}var PE="__lodash_hash_undefined__";function _E(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=So&&t===void 0?PE:t,this}function en(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])}}en.prototype.clear=pE;en.prototype.delete=gE;en.prototype.get=SE;en.prototype.has=EE;en.prototype.set=_E;function CE(){this.__data__=[],this.size=0}function ql(s,t){for(var e=s.length;e--;)if(Uc(s[e][0],t))return e;return-1}var wE=Array.prototype,RE=wE.splice;function bE(s){var t=this.__data__,e=ql(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():RE.call(t,e,1),--this.size,!0}function kE(s){var t=this.__data__,e=ql(t,s);return e<0?void 0:t[e][1]}function AE(s){return ql(this.__data__,s)>-1}function ME(s,t){var e=this.__data__,r=ql(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function cr(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])}}cr.prototype.clear=CE;cr.prototype.delete=bE;cr.prototype.get=kE;cr.prototype.has=AE;cr.prototype.set=ME;var IE=nn(us,"Map");const vo=IE;function DE(){this.size=0,this.__data__={hash:new en,map:new(vo||cr),string:new en}}function OE(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function jl(s,t){var e=s.__data__;return OE(t)?e[typeof t=="string"?"string":"hash"]:e.map}function NE(s){var t=jl(this,s).delete(s);return this.size-=t?1:0,t}function LE(s){return jl(this,s).get(s)}function VE(s){return jl(this,s).has(s)}function xE(s,t){var e=jl(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function dr(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])}}dr.prototype.clear=DE;dr.prototype.delete=NE;dr.prototype.get=LE;dr.prototype.has=VE;dr.prototype.set=xE;var UE="Expected a function";function Ih(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(UE);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(Ih.Cache||dr),e}Ih.Cache=dr;var $E=500;function HE(s){var t=Ih(s,function(r){return e.size===$E&&e.clear(),r}),e=t.cache;return t}var BE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,FE=/\\(\\)?/g,qE=HE(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(BE,function(e,r,i,a){t.push(i?a.replace(FE,"$1"):r||e)}),t});const jE=qE;function GE(s){return s==null?"":Nm(s)}function qm(s,t){return Dt(s)?s:Mh(s,t)?[s]:jE(GE(s))}var WE=1/0;function Gl(s){if(typeof s=="string"||$l(s))return s;var t=s+"";return t=="0"&&1/s==-WE?"-0":t}function jm(s,t){t=qm(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[Gl(t[e++])];return e&&e==r?s:void 0}function JE(s,t,e){var r=s==null?void 0:jm(s,t);return r===void 0?e:r}function Gm(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var KE=Bm(Object.getPrototypeOf,Object);const Dh=KE;var zE="[object Object]",YE=Function.prototype,QE=Object.prototype,Wm=YE.toString,XE=QE.hasOwnProperty,ZE=Wm.call(Object);function eP(s){if(!bs(s)||sn(s)!=zE)return!1;var t=Dh(s);if(t===null)return!0;var e=XE.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Wm.call(e)==ZE}function tP(){this.__data__=new cr,this.size=0}function sP(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function rP(s){return this.__data__.get(s)}function iP(s){return this.__data__.has(s)}var nP=200;function aP(s,t){var e=this.__data__;if(e instanceof cr){var r=e.__data__;if(!vo||r.length<nP-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new dr(r)}return e.set(s,t),this.size=e.size,this}function ls(s){var t=this.__data__=new cr(s);this.size=t.size}ls.prototype.clear=tP;ls.prototype.delete=sP;ls.prototype.get=rP;ls.prototype.has=iP;ls.prototype.set=aP;function oP(s,t){return s&&$c(t,Fl(t),s)}function cP(s,t){return s&&$c(t,Bc(t),s)}var Jm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,bp=Jm&&typeof module=="object"&&module&&!module.nodeType&&module,dP=bp&&bp.exports===Jm,kp=dP?us.Buffer:void 0,Ap=kp?kp.allocUnsafe:void 0;function Km(s,t){if(t)return s.slice();var e=s.length,r=Ap?Ap(e):new s.constructor(e);return s.copy(r),r}function lP(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 zm(){return[]}var uP=Object.prototype,hP=uP.propertyIsEnumerable,Mp=Object.getOwnPropertySymbols,pP=Mp?function(s){return s==null?[]:(s=Object(s),lP(Mp(s),function(t){return hP.call(s,t)}))}:zm;const Oh=pP;function gP(s,t){return $c(s,Oh(s),t)}var mP=Object.getOwnPropertySymbols,fP=mP?function(s){for(var t=[];s;)Gm(t,Oh(s)),s=Dh(s);return t}:zm;const Ym=fP;function TP(s,t){return $c(s,Ym(s),t)}function Qm(s,t,e){var r=t(s);return Dt(s)?r:Gm(r,e(s))}function Eu(s){return Qm(s,Fl,Oh)}function SP(s){return Qm(s,Bc,Ym)}var vP=nn(us,"DataView");const Pu=vP;var yP=nn(us,"Promise");const _u=yP;var EP=nn(us,"Set");const yn=EP;var Ip="[object Map]",PP="[object Object]",Dp="[object Promise]",Op="[object Set]",Np="[object WeakMap]",Lp="[object DataView]",_P=rn(Pu),CP=rn(vo),wP=rn(_u),RP=rn(yn),bP=rn(yu),ri=sn;(Pu&&ri(new Pu(new ArrayBuffer(1)))!=Lp||vo&&ri(new vo)!=Ip||_u&&ri(_u.resolve())!=Dp||yn&&ri(new yn)!=Op||yu&&ri(new yu)!=Np)&&(ri=function(s){var t=sn(s),e=t==PP?s.constructor:void 0,r=e?rn(e):"";if(r)switch(r){case _P:return Lp;case CP:return Ip;case wP:return Dp;case RP:return Op;case bP:return Np}return t});const _a=ri;var kP=Object.prototype,AP=kP.hasOwnProperty;function MP(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&AP.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var IP=us.Uint8Array;const _d=IP;function Nh(s){var t=new s.constructor(s.byteLength);return new _d(t).set(new _d(s)),t}function DP(s,t){var e=t?Nh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var OP=/\w*$/;function NP(s){var t=new s.constructor(s.source,OP.exec(s));return t.lastIndex=s.lastIndex,t}var Vp=Rs?Rs.prototype:void 0,xp=Vp?Vp.valueOf:void 0;function LP(s){return xp?Object(xp.call(s)):{}}function Xm(s,t){var e=t?Nh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var VP="[object Boolean]",xP="[object Date]",UP="[object Map]",$P="[object Number]",HP="[object RegExp]",BP="[object Set]",FP="[object String]",qP="[object Symbol]",jP="[object ArrayBuffer]",GP="[object DataView]",WP="[object Float32Array]",JP="[object Float64Array]",KP="[object Int8Array]",zP="[object Int16Array]",YP="[object Int32Array]",QP="[object Uint8Array]",XP="[object Uint8ClampedArray]",ZP="[object Uint16Array]",e_="[object Uint32Array]";function t_(s,t,e){var r=s.constructor;switch(t){case jP:return Nh(s);case VP:case xP:return new r(+s);case GP:return DP(s,e);case WP:case JP:case KP:case zP:case YP:case QP:case XP:case ZP:case e_:return Xm(s,e);case UP:return new r;case $P:case FP:return new r(s);case HP:return NP(s);case BP:return new r;case qP:return LP(s)}}function Zm(s){return typeof s.constructor=="function"&&!Hl(s)?Fv(Dh(s)):{}}var s_="[object Map]";function r_(s){return bs(s)&&_a(s)==s_}var Up=Pa&&Pa.isMap,i_=Up?Ah(Up):r_;const n_=i_;var a_="[object Set]";function o_(s){return bs(s)&&_a(s)==a_}var $p=Pa&&Pa.isSet,c_=$p?Ah($p):o_;const d_=c_;var l_=1,u_=2,h_=4,ef="[object Arguments]",p_="[object Array]",g_="[object Boolean]",m_="[object Date]",f_="[object Error]",tf="[object Function]",T_="[object GeneratorFunction]",S_="[object Map]",v_="[object Number]",sf="[object Object]",y_="[object RegExp]",E_="[object Set]",P_="[object String]",__="[object Symbol]",C_="[object WeakMap]",w_="[object ArrayBuffer]",R_="[object DataView]",b_="[object Float32Array]",k_="[object Float64Array]",A_="[object Int8Array]",M_="[object Int16Array]",I_="[object Int32Array]",D_="[object Uint8Array]",O_="[object Uint8ClampedArray]",N_="[object Uint16Array]",L_="[object Uint32Array]",he={};he[ef]=he[p_]=he[w_]=he[R_]=he[g_]=he[m_]=he[b_]=he[k_]=he[A_]=he[M_]=he[I_]=he[S_]=he[v_]=he[sf]=he[y_]=he[E_]=he[P_]=he[__]=he[D_]=he[O_]=he[N_]=he[L_]=!0;he[f_]=he[tf]=he[C_]=!1;function ao(s,t,e,r,i,a){var o,c=t&l_,d=t&u_,l=t&h_;if(e&&(o=i?e(s,r,i,a):e(s)),o!==void 0)return o;if(!zt(s))return s;var u=Dt(s);if(u){if(o=MP(s),!c)return Lm(s,o)}else{var p=_a(s),f=p==tf||p==T_;if(Ea(s))return Km(s,c);if(p==sf||p==ef||f&&!i){if(o=d||f?{}:Zm(s),!c)return d?TP(s,cP(o,s)):gP(s,oP(o,s))}else{if(!he[p])return i?s:{};o=t_(s,p,c)}}a||(a=new ls);var v=a.get(s);if(v)return v;a.set(s,o),d_(s)?s.forEach(function(A){o.add(ao(A,t,e,A,s,a))}):n_(s)&&s.forEach(function(A,b){o.set(b,ao(A,t,e,b,s,a))});var E=l?d?SP:Eu:d?Bc:Fl,R=u?void 0:E(s);return ty(R||s,function(A,b){R&&(b=A,A=s[b]),Vm(o,b,ao(A,t,e,b,s,a))}),o}var V_=4;function x_(s){return ao(s,V_)}var U_=1,$_=4;function Lh(s){return ao(s,U_|$_)}var H_="__lodash_hash_undefined__";function B_(s){return this.__data__.set(s,H_),this}function F_(s){return this.__data__.has(s)}function yo(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new dr;++t<e;)this.add(s[t])}yo.prototype.add=yo.prototype.push=B_;yo.prototype.has=F_;function q_(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 rf(s,t){return s.has(t)}var j_=1,G_=2;function nf(s,t,e,r,i,a){var o=e&j_,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=a.get(s),u=a.get(t);if(l&&u)return l==t&&u==s;var p=-1,f=!0,v=e&G_?new yo:void 0;for(a.set(s,t),a.set(t,s);++p<c;){var E=s[p],R=t[p];if(r)var A=o?r(R,E,p,t,s,a):r(E,R,p,s,t,a);if(A!==void 0){if(A)continue;f=!1;break}if(v){if(!q_(t,function(b,V){if(!rf(v,V)&&(E===b||i(E,b,e,r,a)))return v.push(V)})){f=!1;break}}else if(!(E===R||i(E,R,e,r,a))){f=!1;break}}return a.delete(s),a.delete(t),f}function W_(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function Vh(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var J_=1,K_=2,z_="[object Boolean]",Y_="[object Date]",Q_="[object Error]",X_="[object Map]",Z_="[object Number]",eC="[object RegExp]",tC="[object Set]",sC="[object String]",rC="[object Symbol]",iC="[object ArrayBuffer]",nC="[object DataView]",Hp=Rs?Rs.prototype:void 0,ou=Hp?Hp.valueOf:void 0;function aC(s,t,e,r,i,a,o){switch(e){case nC:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case iC:return!(s.byteLength!=t.byteLength||!a(new _d(s),new _d(t)));case z_:case Y_:case Z_:return Uc(+s,+t);case Q_:return s.name==t.name&&s.message==t.message;case eC:case sC:return s==t+"";case X_:var c=W_;case tC:var d=r&J_;if(c||(c=Vh),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=K_,o.set(s,t);var u=nf(c(s),c(t),r,i,a,o);return o.delete(s),u;case rC:if(ou)return ou.call(s)==ou.call(t)}return!1}var oC=1,cC=Object.prototype,dC=cC.hasOwnProperty;function lC(s,t,e,r,i,a){var o=e&oC,c=Eu(s),d=c.length,l=Eu(t),u=l.length;if(d!=u&&!o)return!1;for(var p=d;p--;){var f=c[p];if(!(o?f in t:dC.call(t,f)))return!1}var v=a.get(s),E=a.get(t);if(v&&E)return v==t&&E==s;var R=!0;a.set(s,t),a.set(t,s);for(var A=o;++p<d;){f=c[p];var b=s[f],V=t[f];if(r)var D=o?r(V,b,f,t,s,a):r(b,V,f,s,t,a);if(!(D===void 0?b===V||i(b,V,e,r,a):D)){R=!1;break}A||(A=f=="constructor")}if(R&&!A){var L=s.constructor,U=t.constructor;L!=U&&"constructor"in s&&"constructor"in t&&!(typeof L=="function"&&L instanceof L&&typeof U=="function"&&U instanceof U)&&(R=!1)}return a.delete(s),a.delete(t),R}var uC=1,Bp="[object Arguments]",Fp="[object Array]",Kc="[object Object]",hC=Object.prototype,qp=hC.hasOwnProperty;function pC(s,t,e,r,i,a){var o=Dt(s),c=Dt(t),d=o?Fp:_a(s),l=c?Fp:_a(t);d=d==Bp?Kc:d,l=l==Bp?Kc:l;var u=d==Kc,p=l==Kc,f=d==l;if(f&&Ea(s)){if(!Ea(t))return!1;o=!0,u=!1}if(f&&!u)return a||(a=new ls),o||Bl(s)?nf(s,t,e,r,i,a):aC(s,t,d,e,r,i,a);if(!(e&uC)){var v=u&&qp.call(s,"__wrapped__"),E=p&&qp.call(t,"__wrapped__");if(v||E){var R=v?s.value():s,A=E?t.value():t;return a||(a=new ls),i(R,A,e,r,a)}}return f?(a||(a=new ls),lC(s,t,e,r,i,a)):!1}function Wl(s,t,e,r,i){return s===t?!0:s==null||t==null||!bs(s)&&!bs(t)?s!==s&&t!==t:pC(s,t,e,r,Wl,i)}var gC=1,mC=2;function fC(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],u=c[1];if(o&&c[2]){if(l===void 0&&!(d in s))return!1}else{var p=new ls;if(r)var f=r(l,u,d,s,t,p);if(!(f===void 0?Wl(u,l,gC|mC,r,p):f))return!1}}return!0}function af(s){return s===s&&!zt(s)}function TC(s){for(var t=Fl(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,af(i)]}return t}function of(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function SC(s){var t=TC(s);return t.length==1&&t[0][2]?of(t[0][0],t[0][1]):function(e){return e===s||fC(e,s,t)}}function vC(s,t){return s!=null&&t in Object(s)}function yC(s,t,e){t=qm(t,s);for(var r=-1,i=t.length,a=!1;++r<i;){var o=Gl(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&&kh(i)&&Rh(o,i)&&(Dt(s)||To(s)))}function EC(s,t){return s!=null&&yC(s,t,vC)}var PC=1,_C=2;function CC(s,t){return Mh(s)&&af(t)?of(Gl(s),t):function(e){var r=JE(e,s);return r===void 0&&r===t?EC(e,s):Wl(t,r,PC|_C)}}function wC(s){return function(t){return t==null?void 0:t[s]}}function RC(s){return function(t){return jm(t,s)}}function bC(s){return Mh(s)?wC(Gl(s)):RC(s)}function kC(s){return typeof s=="function"?s:s==null?Ch:typeof s=="object"?Dt(s)?CC(s[0],s[1]):SC(s):bC(s)}function AC(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 MC=AC();const IC=MC;var DC=function(){return us.Date.now()};const cu=DC;var OC="Expected a function",NC=Math.max,LC=Math.min;function xh(s,t,e){var r,i,a,o,c,d,l=0,u=!1,p=!1,f=!0;if(typeof s!="function")throw new TypeError(OC);t=vp(t)||0,zt(e)&&(u=!!e.leading,p="maxWait"in e,a=p?NC(vp(e.maxWait)||0,t):a,f="trailing"in e?!!e.trailing:f);function v(B){var z=r,Q=i;return r=i=void 0,l=B,o=s.apply(Q,z),o}function E(B){return l=B,c=setTimeout(b,t),u?v(B):o}function R(B){var z=B-d,Q=B-l,Ge=t-z;return p?LC(Ge,a-Q):Ge}function A(B){var z=B-d,Q=B-l;return d===void 0||z>=t||z<0||p&&Q>=a}function b(){var B=cu();if(A(B))return V(B);c=setTimeout(b,R(B))}function V(B){return c=void 0,f&&r?v(B):(r=i=void 0,o)}function D(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function L(){return c===void 0?o:V(cu())}function U(){var B=cu(),z=A(B);if(r=arguments,i=this,d=B,z){if(c===void 0)return E(d);if(p)return clearTimeout(c),c=setTimeout(b,t),v(d)}return c===void 0&&(c=setTimeout(b,t)),o}return U.cancel=D,U.flush=L,U}function Cu(s,t,e){(e!==void 0&&!Uc(s[t],e)||e===void 0&&!(t in s))&&bh(s,t,e)}function VC(s){return bs(s)&&Hc(s)}function wu(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function xC(s){return $c(s,Bc(s))}function UC(s,t,e,r,i,a,o){var c=wu(s,e),d=wu(t,e),l=o.get(d);if(l){Cu(s,e,l);return}var u=a?a(c,d,e+"",s,t,o):void 0,p=u===void 0;if(p){var f=Dt(d),v=!f&&Ea(d),E=!f&&!v&&Bl(d);u=d,f||v||E?Dt(c)?u=c:VC(c)?u=Lm(c):v?(p=!1,u=Km(d,!0)):E?(p=!1,u=Xm(d,!0)):u=[]:eP(d)||To(d)?(u=c,To(c)?u=xC(c):(!zt(c)||wh(c))&&(u=Zm(d))):p=!1}p&&(o.set(d,u),i(u,d,r,a,o),o.delete(d)),Cu(s,e,u)}function cf(s,t,e,r,i){s!==t&&IC(t,function(a,o){if(i||(i=new ls),zt(a))UC(s,t,o,e,cf,r,i);else{var c=r?r(wu(s,o),a,o+"",s,t,i):void 0;c===void 0&&(c=a),Cu(s,o,c)}},Bc)}function $C(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 HC="[object Map]",BC="[object Set]",FC=Object.prototype,qC=FC.hasOwnProperty;function jC(s){if(s==null)return!0;if(Hc(s)&&(Dt(s)||typeof s=="string"||typeof s.splice=="function"||Ea(s)||Bl(s)||To(s)))return!s.length;var t=_a(s);if(t==HC||t==BC)return!s.size;if(Hl(s))return!Fm(s).length;for(var e in s)if(qC.call(s,e))return!1;return!0}function GC(s,t){return Wl(s,t)}var WC=my(function(s,t,e){cf(s,t,e)});const mr=WC;var JC=1/0,KC=yn&&1/Vh(new yn([,-0]))[1]==JC?function(s){return new yn(s)}:jv;const zC=KC;var YC=200;function df(s,t,e){var r=-1,i=ay,a=s.length,o=!0,c=[],d=c;if(e)o=!1,i=$C;else if(a>=YC){var l=t?null:zC(s);if(l)return Vh(l);o=!1,i=rf,d=new yo}else d=t?[]:c;e:for(;++r<a;){var u=s[r],p=t?t(u):u;if(u=e||u!==0?u:0,o&&p===p){for(var f=d.length;f--;)if(d[f]===p)continue e;t&&d.push(p),c.push(u)}else i(d,p,e)||(d!==c&&d.push(p),c.push(u))}return c}function QC(s){return s&&s.length?df(s):[]}function XC(s,t){return s&&s.length?df(s,kC(t)):[]}function id(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 ZC={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},jp={STAGING:"staging",PROD:"prod"},ew={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 Eo(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function tw({baseURI:s}){return s.includes("staging.realtime")?jp.STAGING:jp.PROD}function Cd({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function Uh({servicePrefix:s,baseURI:t}){const e=s==="ws"?"wss":"https",r=Cd({servicePrefix:"api",baseURI:t});return`${e}://${r}/${s}`}function sw(s){const t=s.getValue("baseURI");return{location:Cd({servicePrefix:"location",baseURI:t}),locationLegacy:Cd({servicePrefix:"location-legacy",baseURI:t}),daCollector:Uh({servicePrefix:"telemetry",baseURI:t}).replace("https://","")}}const rw='<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>',iw='<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>',zc=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})},di={logs:"https://api.realtime.cloudflare.com/logs/otel/logs",mock:{url:"https://api.realtime.cloudflare.com/mock",domain:"mock.realtime.cloudflare.com",app:"https://examples.realtime.cloudflare.com/meeting",stagingApp:"https://examples.staging.realtime.cloudflare.com/meeting"},apiBase:{prod:"https://api.realtime.cloudflare.com",staging:"https://api.staging.realtime.cloudflare.com",prodAlternate:"https://api.realtime.cloudflare.com"},baseURI:{prod:"realtime.cloudflare.com",staging:"staging.realtime.cloudflare.com"}},nw=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/,Ru="__rtk_plugins__",aw=[Ru];function lf(s){var r,i,a;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(di.baseURI.staging)),e=!!((a=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&a.logs);return t||e}function ow(s,t){var r;const e=(r=s==null?void 0:s.getValue("telemetry"))==null?void 0:r.logLevel;if(e==="off")return!1;if(e!=="all"){const i=["debug","log","info","warn","error"],a=i.indexOf(t.toLowerCase()),o=i.indexOf(e);if(a<o)return!1}return!0}function uf(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"?uf(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function Gp(s,t,e={},r=""){const i={};try{const a=JSON.stringify(e),o=JSON.parse(a),c=uf(o,r),d=JSON.stringify(c);if(!(t==null?void 0:t.startsWith("[SDP]"))&&d.length>5e3){const u=`Log named: "${t}" is trying to log an flattened object of size
|
|
5
|
-
${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw
|
|
6
|
-
${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=zr.getContext(zr.getMostRecentPeerId());if(l){const u=l.getValue("onError");try{u(this)}catch(p){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(d){}}}function Yc(s,t,e,r){if(r instanceof C)throw r;if(r instanceof t){const i=new C(r.message,e);throw i.stack=r.stack,i}else throw r}function Wp(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){Yc(this,t,e,o)}}),a&&(s.set=function(o){try{return a.apply(this,[o])}catch(c){Yc(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=>{Yc(this,t,e,o)}):a}catch(a){Yc(this,t,e,a)}},s}function uw(s,t){return(e,r,i)=>{if(i)return Wp(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,Wp(o,s,t))}}}const et=s=>uw(Error,s);var rr=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(rr||{}),q=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(q||{}),Dg;typeof process!="undefined"&&(Dg=process==null?void 0:process.env)!=null&&Dg.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var hf=[-2,-1,0,1,2],hw=[0,1,2,3,4];function pw(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 gw=(s,t,e)=>{let r,i,a;if(t==0)r=i=a=e;else{const o=(l,u,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?l+(u-l)*6*p:p<.5?u:p<.6666666666666666?l+(u-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)]},mw=(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]},fw=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},pf=(s,t=hf,e=.4)=>{const r=[],[i,a,o]=pw(s),[c,d,l]=mw(i,a,o),u=Math.round(l*100);u>70?e=.8:u>60?e=.9:u<10?e=.075:u<42&&(e=.3);const p=t.findIndex(A=>A===0);if(p===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const f=5-p,v=p+1,E=(100-u)/f,R=u/v;for(const A of t){let b;A<0?b=u+A*R*e:A>0?b=u+A*E*e:b=u;const[V,D,L]=gw(c,d,b/100);r.push(fw(V,D,L))}return r},Jp={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"}},Tw=s=>{const[t,e,r,i,a]=pf(s,hf);return{300:t,400:e,500:r,600:i,700:a}},Sw=s=>{if(s==="#FFFFFF")return Jp.light.background;if(s==="#000000")return Jp.dark.background;const[t,e,r,i,a]=pf(s,hw);return{1e3:t,900:e,800:r,700:i,600:a}},vw={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:Tw("#2160FD"),background:Sw("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function gf(){return Lh(vw)}var yw={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:gf(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function Ew(){return Lh(yw)}var Pw={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:gf(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function $h(){return Lh(Pw)}function _w(){me.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 _=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.PRODUCER_HANDOVER="PRODUCER_HANDOVER",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.NEW_CONSUMER_CREATED="NEW_CONSUMER_CREATED",s.PRODUCER_CLOSED="websocket/producer-closed",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="cf/producer-toggle",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="cf/reset-producer-state",s.ROOM_STATE="sockethub/room-state",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER="ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(_||{});function Cw(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 Kp=1080,zp=1920,ww=(s,t,e,r,i,a)=>{let o=.5,c=.5;const d=i,l=a,u=Math.min(e/d,r/l);let p=d*u,f=l*u,v,E,R,A,b=1;return p<e&&(b=e/p),Math.abs(b-1)<1e-14&&f<r&&(b=r/f),p*=b,f*=b,R=d/(p/e),A=l/(f/r),v=(d-R)*o,E=(l-A)*c,v<0&&(v=0),E<0&&(E=0),R>d&&(R=d),A>l&&(A=l),[v,E,R,A,s,t,e,r]};var $t,li,Xe,Ht,Pe,es,Vs,rt,be,Cn,wn,xs,Rn;const ap=class extends Nt{constructor(e,r,i,a){const o=e.getValue("logger");super(o);g(this,$t,void 0);g(this,li,void 0);g(this,Xe,void 0);g(this,Ht,void 0);g(this,Pe,{height:Kp,width:zp});g(this,es,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,Vs,void 0);g(this,rt,{});g(this,be,void 0);g(this,Cn,void 0);g(this,wn,void 0);g(this,xs,void 0);g(this,Rn,!1);h(this,"cleanupEventListeners",()=>{n(this,li).unsubscribe("stageStatus",this.handlePipMediaControls),n(this,be).removeListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,be).removeListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,be).removeListener("roomLeft",()=>this.disable())});h(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});h(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});h(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});h(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});h(this,"eventCallback",e=>{e==="CAMERA"&&(n(this,be).videoEnabled?n(this,be).disableVideo():n(this,be).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(n(this,be).audioEnabled?n(this,be).disableAudio():n(this,be).enableAudio(),this.emit("micToggled")),e==="END"&&(n(this,li).getValue("peerSessionStore").emit(_.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});h(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});h(this,"animate",()=>{if(!this.isActive&&n(this,xs)==="active"){this.disable(!0);return}n(this,rt)!==void 0&&this.paintCanvas(),n(this,Vs)!==void 0&&m(this,Vs,requestAnimationFrame(()=>this.animate()))});h(this,"disable",(e=!1)=>{m(this,xs,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(n(this,Vs)),e!==!0&&document.body.removeChild(n(this,Xe)),m(this,Vs,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});m(this,li,e),m(this,xs,"idle"),m(this,be,r),m(this,es,{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 zc(rw),a=await zc(iw)}catch(o){}return new ap(e,r,i,a)}async setupIcon(e,r){switch(e){case"handRaise":m(this,wn,r);break;case"pin":m(this,Cn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":m(this,wn,await zc(r));break;case"pin":m(this,Cn,await zc(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,Ht))}setupEventListeners(){n(this,li).subscribe("stageStatus",this.handlePipMediaControls),n(this,be).addListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,be).addListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,be).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=n(this,Pe).height,e.width=n(this,Pe).width,m(this,$t,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,be).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||n(this,be).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(n(this,rt)).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,$t)===void 0)return;const o=n(this,$t).getContext("2d"),c=n(this,$t).width,d=0,l=0,u=r-d*2,p=i-d*2,f=Math.floor(c/u),v=Math.floor(e/f),R=e%f*(u+d)+d,A=v*(p+d)+d,{displayText:b,image:V}=a!=null?a:{};o.fillStyle=b||V?n(this,es).videoBackground:n(this,es).background,o.strokeStyle=n(this,es).brand,o.beginPath(),o.moveTo(R+l,A),o.arcTo(R+u,A,R+u,A+l,l),o.arcTo(R+u,A+p,R+u-l,A+p,l),o.arcTo(R,A+p,R,A+p-l,l),o.arcTo(R,A,R+l,A,l),o.closePath(),o.fill(),o.stroke();const D=u/6,L=u/2+R,U=p/2+A;o.save(),(b||V)&&(o.beginPath(),o.arc(L,U,D,0,Math.PI*2),o.fillStyle=n(this,es).brand,o.fill(),V?(o.clip(),o.drawImage(V,L-D,U-D,D*2,D*2),o.restore()):b&&(o.fillStyle=n(this,es).textOnBrand,o.font=`${D/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(b,L,U)),this.drawIcons(a,R,A,Math.max(u,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 u=i+c,p=f=>{const v=n(this,$t).getContext("2d");v.save(),v.fillStyle=n(this,es).background,v.beginPath(),v.moveTo(l+d,u),v.arcTo(l+o,u,l+o,u+d,d),v.arcTo(l+o,u+o,l+o-d,u+o,d),v.arcTo(l,u+o,l,u+o-d,d),v.arcTo(l,u,l+d,u,d),v.closePath(),v.fill(),typeof f=="string"?(v.font=`${o/1.5}px sans-serif`,v.fillStyle=n(this,es).text,v.textAlign="center",v.textBaseline="top",v.fillText(f,o/2+l,u+c)):v.drawImage(f,l+c,u+c,o-c*2,o-c*2),l+=o+c,v.restore()};e.pinned&&p(n(this,Cn)),e.handRaised&&p(n(this,wn)),e.reaction&&p(e.reaction)}drawTile(e,r,i){var l,u;if(n(this,$t)===void 0)return;const a=n(this,$t).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<n(this,Pe).height-5;){let p=0;for(;p<n(this,Pe).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const f=o[d].element,[v,E,R,A,b,V,D,L]=ww(p,c,e,r,f.videoWidth,f.videoHeight);((u=f==null?void 0:f.classList)==null?void 0:u.contains("mirror"))?(a.save(),a.scale(-1,1),a.drawImage(f,v,E,R,A,-1*b,V,-1*D,L),a.restore()):a.drawImage(f,v,E,R,A,b,V,D,L),this.drawIcons(o[d],b,V,Math.max(D,L))}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,Pe).width,n(this,Pe).height];case 2:return[Math.floor(n(this,Pe).width/2),n(this,Pe).height];case 3:case 4:return[Math.floor(n(this,Pe).width/2),Math.floor(n(this,Pe).height/2)];case 5:case 6:return[Math.floor(n(this,Pe).width/3),Math.floor(n(this,Pe).height/2)];case 7:case 8:case 9:return[Math.floor(n(this,Pe).width/3),Math.floor(n(this,Pe).height/3)];default:return[Math.floor(n(this,Pe).width/3),Math.floor(n(this,Pe).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,be).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(m(this,Rn,!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,$t,void 0),m(this,Ht,void 0),m(this,Vs,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,Rn))return;m(this,Rn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");m(this,Pe,{height:e!=null?e:Kp,width:r!=null?r:zp}),i.height=n(this,Pe).height,i.width=n(this,Pe).width,i.autoplay=!0,i.muted=!0,i.srcObject=n(this,$t).captureStream(24),m(this,Ht,i),n(this,Ht).onloadedmetadata=()=>{try{this.emit("pipStarted"),n(this,Ht).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,rt)[e]!==void 0&&(n(this,rt)[e].enabled=!0)}disableSource(e){n(this,rt)[e]!==void 0&&(n(this,rt)[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,rt)[e]={id:e,element:r,enabled:i,pinned:a,displayText:o?Cw(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,rt)[e];i&&(n(this,rt)[e]={...i,...r})}removeSource(e){delete n(this,rt)[e]}removePinnedSource(){Object.values(n(this,rt)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){m(this,rt,{})}enable(){m(this,xs,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",n(this,be).videoEnabled),this.updateMediaSession("MIC",n(this,be).audioEnabled),document.body.appendChild(n(this,Xe)),m(this,Vs,requestAnimationFrame(()=>this.animate())),n(this,Ht).onloadedmetadata=()=>{n(this,Ht).requestPictureInPicture().then(()=>{m(this,xs,"active")})},n(this,Ht).readyState===4&&n(this,Ht).requestPictureInPicture().then(()=>{m(this,xs,"active")})}};let bu=ap;$t=new WeakMap,li=new WeakMap,Xe=new WeakMap,Ht=new WeakMap,Pe=new WeakMap,es=new WeakMap,Vs=new WeakMap,rt=new WeakMap,be=new WeakMap,Cn=new WeakMap,wn=new WeakMap,xs=new WeakMap,Rn=new WeakMap;var ar;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(ar||(ar={}));var ir;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(ir||(ir={}));class Rw extends T.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 mf=new Rw;class bw extends T.MessageType{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const kw=new bw;class Aw extends T.MessageType{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new Aw;class Mw extends T.MessageType{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",ar]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const hs=new Mw;class Iw extends T.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 Dw=new Iw;class Ow extends T.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:()=>hs},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>Dw}])}}const Nw=new Ow;class Lw extends T.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 Vw=new Lw;class xw extends T.MessageType{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>hs},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const ff=new xw;class Uw extends T.MessageType{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>hs}])}}const $w=new Uw;class Hw extends T.MessageType{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>hs}])}}new Hw;class Bw extends T.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 Fw=new Bw;class qw extends T.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 jw=new qw;class Gw extends T.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 Gw;class Ww extends T.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 Ww;class Jw extends T.MessageType{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",ir]},{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:()=>mf}])}}const Fc=new Jw;class Kw extends T.MessageType{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Fc},{no:3,name:"producer_track",kind:"message",T:()=>jw},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const zw=new Kw;class Yw extends T.MessageType{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>zw}}])}}const Tf=new Yw;class Qw extends T.MessageType{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Qp},{no:2,name:"receiver",kind:"message",T:()=>Qp}])}}const Sf=new Qw;class Xw extends T.MessageType{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>mf},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>kw}])}}const Yp=new Xw;class Zw extends T.MessageType{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Yp},{no:2,name:"video",kind:"message",T:()=>Yp}])}}const Qp=new Zw;class eR extends T.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 tR=new eR;class sR extends T.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 vf=new sR;class rR extends T.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 iR=new rR;class nR extends T.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:()=>iR},{no:9,name:"capabilities",kind:"message",T:()=>Sf}])}}const aR=new nR;class oR extends T.MessageType{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const cR=new oR;class dR extends T.MessageType{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const lR=new dR;class uR extends T.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 uR;class hR extends T.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:()=>tR},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>vf}])}}const pR=new hR;class gR extends T.MessageType{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>pR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const mR=new gR;class fR extends T.MessageType{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>vf},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const TR=new fR;class SR extends T.MessageType{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>TR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const vR=new SR;class yR extends T.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:()=>hs},{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 ER=new yR;class PR extends T.MessageType{constructor(){super("media.edge.SelectedPeersRequest",[])}}new PR;class _R extends T.MessageType{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const CR=new _R;class wR extends T.MessageType{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Qc=new wR;class RR extends T.MessageType{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new RR;class bR extends T.MessageType{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>hs},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const kR=new bR;class AR extends T.MessageType{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>hs},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const MR=new AR;class IR extends T.MessageType{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new IR;class DR extends T.MessageType{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const yf=new DR;class OR extends T.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 NR=new OR;class LR extends T.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 VR=new LR;class xR extends T.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 UR=new xR;class $R extends T.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 HR=new $R;class BR extends T.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 FR=new BR;class qR extends T.MessageType{constructor(){super("media.edge.EmptyResponse",[])}}new qR;class jR extends T.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:()=>Fc},{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:()=>Sf}])}}const Ef=new jR;class GR extends T.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 ku=new GR;class WR extends T.MessageType{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const JR=new WR;class KR extends T.MessageType{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>JR}])}}const Xp=new KR;class zR extends T.MessageType{constructor(){super("media.edge.PeerJoinResponse",[])}}new zR;class YR extends T.MessageType{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>HR},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Ef},{no:3,name:"selected_peers",kind:"message",T:()=>ku},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Au=new YR;class QR extends T.MessageType{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}new QR;class XR extends T.MessageType{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Tf}])}}new XR;class ZR extends T.MessageType{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Tf},{no:3,name:"description",kind:"message",T:()=>hs}])}}const eb=new ZR;class tb extends T.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:()=>hs}])}}const sb=new tb;class rb extends T.MessageType{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>Fw}])}}new rb;class ib extends T.MessageType{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new ib;class nb extends T.MessageType{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new nb;class ab extends T.MessageType{constructor(){super("media.edge.ProducerToggleResponse",[])}}new ab;class ob extends T.MessageType{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new ob;class cb extends T.MessageType{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>hs}])}}const db=new cb;class lb extends T.MessageType{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>hs}])}}const ub=new lb;class hb extends T.MessageType{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new hb;class pb extends T.MessageType{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new pb;class gb extends T.MessageType{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new gb;class mb extends T.MessageType{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const fb=new mb;class Tb extends T.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Sb=new Tb;class vb extends T.MessageType{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const yb=new vb;class Eb extends T.MessageType{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Ef}])}}const Zp=new Eb;class Pb extends T.MessageType{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const eg=new Pb;class _b extends T.MessageType{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>eg},{no:3,name:"screenshare",kind:"message",T:()=>eg}])}}const Cb=new _b;class wb extends T.MessageType{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>ff},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>Cb}])}}new wb;class Rb extends T.MessageType{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Fc},{no:3,name:"producer_handover_from_peer_id",kind:"scalar",opt:!0,T:9}])}}const bb=new Rb;class kb extends T.MessageType{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Fc},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const tg=new kb;class Ab extends T.MessageType{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Fc}])}}const Mb=new Ab;class Ib extends T.MessageType{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Mu=new Ib;class Db extends T.MessageType{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const sg=new Db;class Ob extends T.MessageType{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Ob;class Nb extends T.MessageType{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Nb;class Lb extends T.MessageType{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Lb;class Vb extends T.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 Vb;class xb extends T.MessageType{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new xb;class Ub extends T.MessageType{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new Ub;class $b extends T.MessageType{constructor(){super("socket.ai.TranscriptSpeaker",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"participant_id",kind:"scalar",T:9},{no:3,name:"custom_participant_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9}])}}const Hb=new $b;class Bb extends T.MessageType{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8},{no:4,name:"sentence",kind:"scalar",T:9},{no:5,name:"speaker",kind:"message",T:()=>Hb},{no:6,name:"started_at",kind:"scalar",T:4,L:2},{no:7,name:"ended_at",kind:"scalar",T:4,L:2},{no:8,name:"confidence",kind:"scalar",T:2}])}}const du=new Bb;class Fb extends T.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 qb extends T.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 jb=new qb;var Xi;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(Xi||(Xi={}));var er;(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"})(er||(er={}));var Iu;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(Iu||(Iu={}));var Du;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(Du||(Du={}));var wd;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(wd||(wd={}));class Gb extends T.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 Wb=new Gb;class Jb extends T.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",er,"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:()=>Wb}])}}const Jl=new Jb;class Kb extends T.MessageType{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Jl}])}}const ln=new Kb;class zb extends T.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",er,"STAGE_TYPE_"]}])}}const rg=new zb;class Yb extends T.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 Qb=new Yb;class Xb extends T.MessageType{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Jl}])}}const lu=new Xb;class Zb extends T.MessageType{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const ig=new Zb;class ek extends T.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:()=>sk},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Pf=new ek;class tk extends T.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",Xi]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const sk=new tk;class rk extends T.MessageType{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Pf}])}}const ng=new rk;class ik extends T.MessageType{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const _f=new ik;class nk extends T.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 nk;class ak extends T.MessageType{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Jl},{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",wd,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const ok=new ak;class ck extends T.MessageType{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Jl},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const dk=new ck;class lk extends T.MessageType{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Pf}])}}new lk;class uk extends T.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new uk;class hk extends T.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 Hh=new hk;class pk extends T.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 gk=new pk;class mk extends T.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:()=>gk}])}}const ag=new mk;class fk extends T.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>ag},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>ag}])}}const Tk=new fk;class Sk extends T.MessageType{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const vk=new Sk;class yk extends T.MessageType{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>vk}])}}const Ek=new yk;class Pk extends T.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:()=>Hh}])}}const _k=new Pk;class Ck extends T.MessageType{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>_k}])}}const og=new Ck;class wk extends T.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 Rk=new wk;class bk extends T.MessageType{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Rk}])}}new bk;class kk extends T.MessageType{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const Ak=new kk;class Mk extends T.MessageType{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Ak}])}}const Ik=new Mk;class Dk extends T.MessageType{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Lk}])}}const Ok=new Dk;class Nk extends T.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:()=>Hh}])}}const Lk=new Nk;class Vk extends T.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 xk=new Vk;class Uk extends T.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:()=>xk}])}}const $k=new Uk;class Hk extends T.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:()=>Hh}])}}const Cf=new Hk;class Bk extends T.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Cf}])}}new Bk;class Fk extends T.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 qk=new Fk;class jk extends T.MessageType{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>Jk}])}}const Gk=new jk;class Wk extends T.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 Jk=new Wk;class Kk extends T.MessageType{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const wf=new Kk;class zk extends T.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",Du,"BROADCAST_TYPE_"]}])}}const Ga=new zk;class Yk extends T.MessageType{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Qk=new Yk;class Xk extends T.MessageType{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Zk=new Xk;class eA extends T.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 tA=new eA;class sA extends T.MessageType{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>tA}])}}const cg=new sA;class rA extends T.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 dg=new rA;var Ou;(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"})(Ou||(Ou={}));var Wr;(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"})(Wr||(Wr={}));class iA extends T.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 nA=new iA;class aA extends T.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 oA=new aA;class cA extends T.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 dA=new cA;class lA extends T.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 uA=new lA;class hA extends T.MessageType{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>dA},{no:2,name:"private",kind:"message",T:()=>uA}])}}const pA=new hA;class gA extends T.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 mA=new gA;class fA extends T.MessageType{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Wr,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Wr,"STREAM_PERMISSION_TYPE_"]}])}}const uu=new fA;class TA extends T.MessageType{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>uu},{no:2,name:"audio",kind:"message",T:()=>uu},{no:3,name:"screenshare",kind:"message",T:()=>uu}])}}const SA=new TA;class vA extends T.MessageType{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>nA},{no:2,name:"plugins",kind:"message",T:()=>oA},{no:3,name:"chat",kind:"message",T:()=>pA},{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",Ou,"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",Iu,"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:()=>mA},{no:23,name:"media",kind:"message",T:()=>SA}])}}const Bh=new vA;class yA extends T.MessageType{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const EA=new yA;class PA extends T.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 _A=new PA;class CA extends T.MessageType{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>_A}])}}const wA=new CA;class RA extends T.MessageType{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Bh}])}}const Rf=new RA;class bA extends T.MessageType{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Rf}])}}const kA=new bA;class AA extends T.MessageType{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Rf}])}}const lg=new AA;class MA extends T.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 IA=new MA;class DA extends T.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>IA},{no:2,name:"patch",kind:"message",T:()=>Bh}])}}new DA;class OA extends T.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Bh}])}}new OA;class NA extends T.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 Zr=new NA;class LA extends T.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 VA=new LA;class xA extends T.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:()=>VA}])}}const UA=new xA;class $A extends T.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Zr},{no:2,name:"next",kind:"scalar",T:8}])}}const HA=new $A;class BA extends T.MessageType{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Zr}])}}const bf=new BA;class FA extends T.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const qA=new FA;class jA extends T.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Zr}])}}const hu=new jA;class GA extends T.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 WA=new GA;class JA extends T.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Zr}])}}const pu=new JA;class KA extends T.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 KA;class zA extends T.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Zr}])}}new zA;class YA extends T.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 QA=new YA;class XA extends T.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 ZA=new XA;class eM extends T.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:()=>Zr}])}}const Xc=new eM;class tM extends T.MessageType{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Zr}])}}const Zc=new tM;class sM extends T.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 rM=new sM;class iM extends T.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 ed=new iM;class nM extends T.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 aM=new nM;class oM extends T.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 oM;class cM extends T.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new cM;class dM extends T.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 dM;class lM extends T.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 lM;class uM extends T.MessageType{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new uM;class hM extends T.MessageType{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new hM;class pM extends T.MessageType{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Zr},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const gM=new pM;class mM extends T.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:()=>gM},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const fM=new mM;class TM extends T.MessageType{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>fM}])}}new TM;class SM extends T.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 vM=new SM;class yM extends T.MessageType{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>vM}])}}new yM;class EM extends T.MessageType{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new EM;class PM extends T.MessageType{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new PM;class _M extends T.MessageType{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new _M;class CM extends T.MessageType{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new CM;class wM extends T.MessageType{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}new wM;class RM extends T.MessageType{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}new RM;class bM extends T.MessageType{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new bM;class kM extends T.MessageType{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}new kM;class AM extends T.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 Fh=new AM;class MM extends T.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:()=>Fh}])}}const IM=new MM;class DM extends T.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:()=>Fh}])}}const OM=new DM;class NM extends T.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:()=>Fh}])}}const LM=new NM;class VM extends T.MessageType{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}new VM;class xM extends T.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 UM=new xM;class $M extends T.MessageType{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>UM}])}}new $M;class HM extends T.MessageType{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}new HM;class BM extends T.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 FM=new BM;class qM extends T.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:()=>FM}])}}const ug=new qM;class jM extends T.MessageType{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new jM;class GM extends T.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 hg=new GM;class WM extends T.MessageType{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const pg=new WM;class JM extends T.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 KM=new JM;class zM extends T.MessageType{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>KM}])}}const gu=new zM;class YM extends T.MessageType{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const QM=new YM;class XM extends T.MessageType{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const ZM=new XM;class eI extends T.MessageType{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const gg=new eI;class tI extends T.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:()=>rI},{no:6,name:"hide_votes",kind:"scalar",T:8},{no:7,name:"anonymous",kind:"scalar",T:8},{no:8,name:"votes",kind:"scalar",repeat:2,T:9}])}}const kf=new tI;class sI extends T.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:()=>nI}])}}const rI=new sI;class iI extends T.MessageType{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const nI=new iI;class aI extends T.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 oI=new aI;class cI extends T.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 dI=new cI;class lI extends T.MessageType{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>kf}])}}const mu=new lI;class uI extends T.MessageType{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>kf}])}}const hI=new uI;class pI extends T.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",Xi]}])}}const mg=new pI;class gI extends T.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=T.PbLong.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(T.PbLong.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=T.PbLong.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=T.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 "+T.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=T.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 gI;class mI extends T.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 Nu=new mI;class fI extends T.MessageType{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Nu}])}}new fI;class TI extends T.MessageType{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>Nu},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>Nu}])}}new TI;const SI=0,vI=1,yI=2,EI=3,PI=5,_I={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},CI={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},wI={getPlugins:0,addPlugin:1,enablePluginForRoom:2,disablePluginForPeers:3,enablePluginForPeers:4,disablePluginForRoom:5,removePlugin:6,customPluginEventToRoom:7,customPluginEventToPeers:8,storeInsertKeys:9,storeGetKeys:10,storeDeleteKeys:11,storeDelete:12},RI={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},bI={getUserPresets:0,updateUserPreset:1};function qc(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function Mf(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const x=qc(SI,_I),Fe=qc(vI,CI),Ds=qc(yI,wI),Os=qc(EI,RI),yr=Mf(Af,16777216),ds=Mf(Af,50331648),ad=qc(PI,bI);var kI=Object.defineProperty,AI=Object.getOwnPropertyDescriptor,ei=(s,t,e,r)=>{for(var i=r>1?void 0:r?AI(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&&kI(t,e,i),i},Kt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(Kt||{}),_t,bn;class lr{constructor(t,e){g(this,_t,void 0);g(this,bn,void 0);m(this,_t,e),m(this,bn,t)}get telemetry(){return n(this,bn).getValue("telemetry")}get logger(){return n(this,bn).getValue("logger")}getChatMessages(){return n(this,_t).sendMessagePromise(Fe.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,_t).sendMessagePromise(Fe.getPaginatedMessages,UA.toBinary(a));return o.payload?HA.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};n(this,_t).sendMessage(Fe.sendMessageToRoom,qA.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};n(this,_t).sendMessage(Fe.sendMessageToPeers,WA.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,_t).sendMessagePromise(Fe.editMessage,QA.toBinary(a));return Zc.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await n(this,_t).sendMessagePromise(Fe.deleteMessage,rM.toBinary(e));return{id:ed.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,_t).sendMessagePromise(Fe.searchChannelMessages,aM.toBinary(r));return bf.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await n(this,_t).sendMessagePromise(Fe.pinMessage,ZA.toBinary(r));return Xc.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Fe.sendMessageToRoom:{r=hu.fromBinary.bind(hu),i=hu.create();break}case Fe.sendMessageToPeers:{r=pu.fromBinary.bind(pu),i=pu.create();break}case Fe.editMessage:{r=Zc.fromBinary.bind(Zc),i=Zc.create();break}case Fe.pinMessage:{r=Xc.fromBinary.bind(Xc),i=Xc.create();break}case Fe.deleteMessage:{r=ed.fromBinary.bind(ed),i=ed.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}n(this,_t).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)})}}_t=new WeakMap,bn=new WeakMap;ei([y.trace("SocketService.getChatMessages")],lr.prototype,"getChatMessages",1);ei([y.trace("SocketService.getChatMessagesPaginated")],lr.prototype,"getChatMessagesPaginated",1);ei([y.trace("SocketService.sendMessageToRoom")],lr.prototype,"sendMessageToRoom",1);ei([y.trace("SocketService.sendMessageToPeers")],lr.prototype,"sendMessageToPeers",1);ei([y.trace("SocketService.sendMessage")],lr.prototype,"sendMessage",1);ei([y.trace("SocketService.editMessage")],lr.prototype,"editMessage",1);ei([y.trace("SocketService.deleteMessage")],lr.prototype,"deleteMessage",1);ei([y.trace("SocketService.searchMessages")],lr.prototype,"searchMessages",1);function MI(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function ws(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>ws(e));const t={};return Object.keys(s).forEach(e=>{const r=Qr.validate(e)?e:MI(e);t[r]=ws(s[e])}),t}function II(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function If(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>If(e));const t={};return Object.keys(s).forEach(e=>{const r=Qr.validate(e)?e:II(e);t[r]=s[e]}),t}class Rd extends Error{constructor(e){const r=e instanceof Error?e.message:`Request failed with status ${e.status}`;super(r);h(this,"status");h(this,"response");h(this,"isTimeout");e instanceof Error?(this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(this.status=e.status,this.response=e,this.isTimeout=!1),this.name="RequestError"}get isHttpError(){return this.status!==void 0}get isNetworkError(){return this.status===void 0&&!this.isTimeout}}class fg{constructor(t){h(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,u=t.retryDelay||this.defaults.retryDelay;try{const f=new AbortController,v=setTimeout(()=>f.abort(),d);c.signal=f.signal;const E=await fetch(r,c);clearTimeout(v);let R=null;const A=E.headers.get("content-type");A&&A.includes("application/json")?R=await E.json():R=await E.text();const b={};E.headers.forEach((D,L)=>{b[L]=D});const V={data:R,status:E.status,statusText:E.statusText,headers:b,config:t};if(!E.ok)throw V;return V}catch(f){if(f instanceof Error&&l>0)return await new Promise(v=>setTimeout(v,u)),this.defaults.baseURL===di.apiBase.prod?this.defaults.baseURL=di.apiBase.prodAlternate:this.defaults.baseURL===di.apiBase.prodAlternate&&(this.defaults.baseURL=di.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 DI=3,OI=30,NI=8e3;class LI{constructor(t,e){h(this,"fetchClient");h(this,"requests");h(this,"roomName");h(this,"roomUUID");h(this,"authToken");h(this,"organizationId");h(this,"iceServers");h(this,"userDetails");h(this,"roomDetails");h(this,"context");this.context=t;const{timeout:r=NI,retry:i=DI,retryDelay:a=OI,baseURL:o=di.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new fg({baseURL:o,timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.fetchClient=new fg({baseURL:"",timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var f,v,E,R,A;const p=t.getValue("telemetry");try{p.injectContext(this.requests.defaults.headers.common);const b=await l(u);return u.url!==p.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:b.status,statusText:b.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),b}catch(b){if(!b)throw new C("Unknown network error occurred","0011");if(b instanceof C||b instanceof Rd)throw b;((f=b.config)==null?void 0:f.url)!==p.logsEndpoint&&this.logger.error("xhr::fetch",{error:b,networkCall:{status:b.status,statusText:b.statusText,baseURL:((v=b.config)==null?void 0:v.baseURL)||this.requests.defaults.baseURL,url:(E=b.config)==null?void 0:E.url,retries:(R=b.config)==null?void 0:R.retry,method:(A=b.config)==null?void 0:A.method,isOnline:navigator.onLine?"online":"offline"}});const V=b instanceof Error&&b.message||"Network request failed";throw new C(V,"0011"),new Rd(b)}}}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 VI=Object.defineProperty,xI=Object.getOwnPropertyDescriptor,ur=(s,t,e,r)=>{for(var i=r>1?void 0:r?xI(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&&VI(t,e,i),i};class ks extends LI{constructor(e,r){super(e,r);h(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(await this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r}async getPresignedUrls(e){const r=Eo(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=ws(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=ws((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 ws(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...If(e),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r})).data.data.id}async updateRecording(e,r){return this.requests.put(`v2/recordings/${e}`,{action:r})}async getActiveRecording(){const{status:e,id:r}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}}async getActiveTranscript(){const{transcript_download_url:e}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.fetchClient.get(e)).data}}catch(r){throw new C("Cant fetch transcript s3 url","1801")}}}ur([y.trace("APIClient.getICEServers")],ks.prototype,"getICEServers",1);ur([y.trace("APIClient.startLivestreaming")],ks.prototype,"startLivestreaming",1);ur([y.trace("APIClient.stopLivestreaming")],ks.prototype,"stopLivestreaming",1);ur([y.trace("APIClient.getActiveLivestream")],ks.prototype,"getActiveLivestream",1);ur([y.trace("APIClient.getUserDetails")],ks.prototype,"getUserDetails",1);ur([y.trace("APIClient.startRecording")],ks.prototype,"startRecording",1);ur([y.trace("APIClient.stopRecording")],ks.prototype,"updateRecording",1);ur([y.trace("APIClient.getActiveRecording")],ks.prototype,"getActiveRecording",1);ur([y.trace("APIClient.getActiveTranscript")],ks.prototype,"getActiveTranscript",1);let Lu;function UI(s,t){return Lu=new ks(s,t),Lu}function It(){return Lu}const wa={maxInvocations:5,period:1};function Lt(s,t){return function(e,r,i){const a=i.value;let o=0,c=Date.now();return i.value=function(...d){const l=Date.now(),u=t?this[t]:s;if(l-c>u.period*1e3&&(c=l,o=0),o>=u.maxInvocations)throw new C(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,a.apply(this,d)},i}}var $I=Object.defineProperty,HI=Object.getOwnPropertyDescriptor,As=(s,t,e,r)=>{for(var i=r>1?void 0:r?HI(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&&$I(t,e,i),i};const BI=["text","image","file","custom","poll"],od={maxInvocations:180,period:60};var Z,ui,We,kn,Ld,Df,wo,Vu,Og;let Yt=(Og=class extends Nt{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,Ld);g(this,wo);h(this,"messages");g(this,Z,void 0);g(this,ui,void 0);g(this,We,void 0);g(this,kn,void 0);h(this,"maxTextLimit",2e3);m(this,kn,t),m(this,We,e),m(this,Z,r),m(this,ui,i),this.messages=[]}get telemetry(){return n(this,kn).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e){switch(t.type){case"text":{await this.sendTextMessageInternal(t.message,e);break}case"image":await this.sendImageMessageInternal(t.image,e);break;case"file":await this.sendFileMessageInternal(t.file,e);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e){var i,a,o,c,d,l;if(t.length>this.maxTextLimit)throw new C("Max character limit breached","0503");if(e&&e.length>0){if(!((i=n(this,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 C("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 C("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new C("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(n(this,Z).id),r=n(this,ui).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(n(this,Z).userId)),n(this,We).sendMessage(t,Kt.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 u=It(),{getLocation:p,putLocation:f}=await u.getPresignedUrls(t.name);await u.uploadFile(t,f);let v=[];e&&e.length>0&&(e.push(n(this,Z).id),v=n(this,ui).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),v.push(n(this,Z).userId)),n(this,We).sendMessage(p,Kt.IMAGE,e)}catch(u){throw new C("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,a,o,c,d;if(e&&e.length>0){if(!((r=n(this,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:u,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,ui).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),f.push(n(this,Z).userId));const v=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});n(this,We).sendMessage(v,Kt.FILE,e)}catch(l){throw new C("Error sending file message.","0500",this.logger)}}get rateLimits(){return od}updateRateLimits(t,e){od.maxInvocations=t,od.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var a,o,c,d,l,u,p,f,v,E,R,A,b,V,D;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=(u=n(this,Z).permissions)==null?void 0:u.chatPublic)!=null&&p.files)||!((v=(f=n(this,Z).permissions)==null?void 0:f.chatPublic)!=null&&v.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async L=>{try{if(typeof L=="string")return{link:L};const U=It(),{getLocation:B,putLocation:z}=await U.getPresignedUrls(L.name);return await U.uploadFile(L,z),{link:B,type:L.type,name:L.name,size:L.size}}catch(U){throw new C("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((R=(E=t.files)!=null?E:[])==null?void 0:R.map(async L=>r(L))),images:await Promise.all((b=(A=t.images)!=null?A:[])==null?void 0:b.map(async L=>r(L))),videos:await Promise.all((D=(V=t.videos)!=null?V:[])==null?void 0:D.map(async L=>r(L)))};n(this,We).sendMessage(JSON.stringify(i),Kt.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,We).editMessage(t,e,Kt.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:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),n(this,We).editMessage(t,l,Kt.IMAGE)}catch(d){throw new C("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,a,o;if(!((i=(r=n(this,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,We).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),Kt.FILE)}catch(c){throw new C("Error editing file message.","0500",this.logger)}}async editMessage(t,e){switch(e.type){case"text":{this.editTextMessage(t,e.message);break}case"image":{this.editImageMessage(t,e.image);break}case"file":{this.editFileMessage(t,e.file);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t){n(this,We).deleteMessage(t)}async pin(t){if(!n(this,wo,Vu))throw new C("Can`t pin message without joining room","0505");try{await n(this,We).setPinState(t,!0)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!n(this,wo,Vu))throw new C("Can`t unpin message without joining room","0505");try{await n(this,We).setPinState(t,!1)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,We).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>oo.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await n(this,We).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>oo.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,We).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>oo.formatSocketPeerMessage(o))}},Z=new WeakMap,ui=new WeakMap,We=new WeakMap,kn=new WeakMap,Ld=new WeakSet,Df=function(){return n(this,kn).getValue("connectionHandler")},wo=new WeakSet,Vu=function(){return n(this,Ld,Df).socketJoined===!0},Og);As([y.trace("Chat.sendTextMessage"),Lt(od)],Yt.prototype,"sendTextMessage",1);As([y.trace("Chat.sendImageMessage"),Lt({maxInvocations:20,period:60})],Yt.prototype,"sendImageMessage",1);As([y.trace("Chat.sendFileMessage"),Lt({maxInvocations:20,period:60})],Yt.prototype,"sendFileMessage",1);As([y.trace("Chat.sendMessage"),Lt({maxInvocations:180,period:60})],Yt.prototype,"sendMessage",1);As([y.trace("Chat.editTextMessage")],Yt.prototype,"editTextMessage",1);As([y.trace("Chat.editImageMessage")],Yt.prototype,"editImageMessage",1);As([y.trace("Chat.editFileMessage")],Yt.prototype,"editFileMessage",1);As([y.trace("Chat.editMessage")],Yt.prototype,"editMessage",1);As([y.trace("Chat.deleteMessage")],Yt.prototype,"deleteMessage",1);Yt=As([et("0500")],Yt);var FI=Object.defineProperty,qI=Object.getOwnPropertyDescriptor,jI=(s,t,e,r)=>{for(var i=r>1?void 0:r?qI(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&&FI(t,e,i),i},hi,Ng;const fr=(Ng=class{constructor(s,t,e,r){h(this,"chat");h(this,"chatSocketHandler");h(this,"self");g(this,hi,void 0);m(this,hi,s),this.chatSocketHandler=t,this.chat=new Yt(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return n(this,hi).getValue("telemetry")}get logger(){return n(this,hi).getValue("logger")}static async init(s,t,e,r){return new fr(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:BI[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 Kt.TEXT:{e.message=s.payload;break}case Kt.IMAGE:{e.link=s.payload;break}case Kt.FILE:{const{link:r,name:i,size:a}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=a;break}case Kt.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 fr.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=bf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>fr.formatSocketPeerMessage(e))}setupEvents(){n(this,hi).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Fe.sendMessageToRoom,s=>{if(!s.message)return;const t=fr.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(Fe.sendMessageToPeers,s=>{const t=fr.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(Fe.editMessage,s=>{if(!s.message)return;const t=fr.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(Fe.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(Fe.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=fr.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})})}},hi=new WeakMap,Ng);let oo=fr;jI([y.trace("ChatController.setupEvents")],oo.prototype,"setupEvents",1);var GI=Object.defineProperty,WI=Object.getOwnPropertyDescriptor,JI=(s,t,e,r)=>{for(var i=r>1?void 0:r?WI(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&&GI(t,e,i),i},Vd,Of,xd,Nf,An,Mn,Ro,Lg;let xu=(Lg=class extends Nt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Vd);g(this,xd);h(this,"items");g(this,An,void 0);g(this,Mn,void 0);g(this,Ro,void 0);m(this,Ro,t),m(this,An,e),m(this,Mn,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!n(this,xd,Nf))throw new C("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)}},Vd=new WeakSet,Of=function(){return n(this,Ro).getValue("connectionHandler")},xd=new WeakSet,Nf=function(){var t;return((t=n(this,Vd,Of))==null?void 0:t.socketJoined)===!0},An=new WeakMap,Mn=new WeakMap,Ro=new WeakMap,Lg);xu=JI([et("0700")],xu);var KI=Object.defineProperty,zI=Object.getOwnPropertyDescriptor,YI=(s,t,e,r)=>{for(var i=r>1?void 0:r?zI(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&&KI(t,e,i),i},_r,In,pi,Vg;const un=(Vg=class{constructor(s,t,e){h(this,"polls");g(this,_r,void 0);g(this,In,void 0);g(this,pi,void 0);this.polls=new xu(s,t,e),m(this,In,t),m(this,_r,s),m(this,pi,e),this.setupEvents()}get telemetry(){return n(this,_r).getValue("telemetry")}get logger(){return n(this,_r).getValue("logger")}static async init(s,t,e){return new un(s,t,e)}canViewPolls(){return n(this,In).permissions.polls.canView}setupEvents(){const s={[Os.createPoll]:r=>{r.poll&&this.updatePoll(un.formatSocketServicePoll(r.poll))},[Os.updatePoll]:r=>{r.poll&&this.updatePoll(un.formatSocketServicePoll(r.poll))},[Os.votePoll]:r=>{r.poll&&this.updatePoll(un.formatSocketServicePoll(r.poll))}},t=()=>{n(this,_r).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,pi).on(r,s[r])})},e=()=>{n(this,_r).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,pi).removeListeners(r)})};n(this,In).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,pi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=hI.fromBinary(s.payload);this.polls.items=t.map(e=>un.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}}},_r=new WeakMap,In=new WeakMap,pi=new WeakMap,Vg);let Lf=un;YI([y.trace("PollController.setupEvents")],Lf.prototype,"setupEvents",1);var QI=Object.defineProperty,XI=Object.getOwnPropertyDescriptor,ZI=(s,t,e,r)=>{for(var i=r>1?void 0:r?XI(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&&QI(t,e,i),i},Vf=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(Vf||{}),Dn,bo,$u,gi,ko,xg;let Uu=(xg=class extends Nt{constructor(t,e,r,i,a){const o=t.getValue("logger");super(o);g(this,bo);h(this,"selfActiveTab");h(this,"broadcastTabChanges");g(this,Dn,void 0);g(this,gi,void 0);g(this,ko,void 0);h(this,"viewType");h(this,"meetingStartedTimestamp");h(this,"meetingTitle");h(this,"sessionId");m(this,Dn,t),m(this,gi,e),this.viewType=r,m(this,ko,i),this.meetingTitle=a,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return n(this,bo,$u).socketState}get mediaState(){return n(this,bo,$u).mediaState}get meetingId(){return n(this,Dn).getValue("meetingId")}setBroadcastTabChanges(t){if(!n(this,gi).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new C("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;this.logger.info("Spotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=n(this,gi).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){n(this,ko).broadcastMessage("spotlight",{userId:n(this,gi).userId,currentTab:this.selfActiveTab})}},Dn=new WeakMap,bo=new WeakSet,$u=function(){return n(this,Dn).getValue("connectionHandler")},gi=new WeakMap,ko=new WeakMap,xg);Uu=ZI([et("0800")],Uu);function e0(s){let t="",e=[""];const r=[e];let i=0,a=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
|
|
7
|
-
`&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++a]=[c=""],i=0):e[i]+=c,t=c;return r}var
|
|
8
|
-
`).map(e=>Yr.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=It(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Yr.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)}},Ao=new WeakMap,Ug);xf([y.trace("Ai.getActiveTranscript")],Yr.prototype,"getActiveTranscript",1);Yr=xf([et("0000")],Yr);var r0=Object.defineProperty,i0=Object.getOwnPropertyDescriptor,n0=(s,t,e,r)=>{for(var i=r>1?void 0:r?i0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&r0(t,e,i),i},Cr,On,Ct,$g;const Uf=($g=class{constructor(s,t,e,r,i,a){h(this,"meta");h(this,"ai");g(this,Cr,void 0);g(this,On,void 0);h(this,"aiSocketHandler");g(this,Ct,void 0);m(this,Ct,s),this.meta=new Uu(s,t,t.config.viewType,e,a),this.ai=r,m(this,Cr,t),m(this,On,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return n(this,Ct).getValue("telemetry")}get logger(){return n(this,Ct).getValue("logger")}static async init(s,t,e,r,i){const a=await Yr.init(s,t.permissions.transcriptionEnabled);return new Uf(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,Vf.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){n(this,Ct).getValue("peerSessionStore").on(_.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),n(this,Ct).getValue("peerSessionStore").on(_.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),n(this,Ct).getValue("peerSessionStore").on(_.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,Ct).getValue("peerSessionStore").on(_.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),n(this,Cr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&n(this,On).broadcastMessage("spotlight",{userId:n(this,Cr).userId,currentTab:this.meta.selfActiveTab})),n(this,Ct).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async s=>{n(this,Cr).permissions.canSpotlight&&this.meta.selfActiveTab&&n(this,On).broadcastToPeers("spotlight",[s.id],{userId:n(this,Cr).userId,currentTab:this.meta.selfActiveTab})}),n(this,Ct).getValue("peerSessionStore").on(_.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,Ct).getValue("peerSessionStore").on(_.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(x.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=Yr.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);const{peerId:a,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${a} - ${o}: ${c}`)})}},Cr=new WeakMap,On=new WeakMap,Ct=new WeakMap,$g);let $f=Uf;n0([y.trace("MetaController.setupEvents")],$f.prototype,"setupEvents",1);const Wa={},hr={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,a)=>{const o=a.value;return a.value=function(...d){var E,R;const l=(R=(this==null?void 0:this.peerId)||((E=d[0])==null?void 0:E.authToken))!=null?R:"",u=`${t}-${l}`,p=this==null?void 0:this.logger;if(Wa[u]){const A=new Error(`Unsupported concurrent calls on method: ${s}.`);throw A.name="UnsupportedConcurrentMethodExecution",p==null||p.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:A.stack},locker:{methodName:s,lockName:u}}),A}Wa[u]=!0;const f=setTimeout(()=>delete Wa[u],e),v=o.apply(this,d);return Promise.resolve(v).then(()=>{delete Wa[u],clearTimeout(f)}).catch(()=>{delete Wa[u],clearTimeout(f)}),v},a}}};var a0=Object.defineProperty,o0=Object.getOwnPropertyDescriptor,an=(s,t,e,r)=>{for(var i=r>1?void 0:r?o0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&a0(t,e,i),i},Bt,Ud,re,Mo,gs,Ne,Io,Hu,Nn,cd;class ti extends Nt{constructor(e,r,i,a,o){const c=e.getValue("logger");super(c);g(this,Io);g(this,Nn);g(this,Bt,void 0);g(this,Ud,void 0);g(this,re,void 0);g(this,Mo,void 0);g(this,gs,void 0);g(this,Ne,void 0);m(this,Ne,e),m(this,Bt,a),m(this,Ud,o),m(this,re,r),m(this,Mo,i),m(this,gs,[]),this.setupEvents()}get telemetry(){return n(this,Ne).getValue("telemetry")}get status(){return n(this,Ne).getValue("stageStatus")}setupEvents(){const e={[_.GET_STAGE_REQUESTS]:async a=>{m(this,gs,a)},[_.UPDATE_STAGE_REQUESTS]:async({add:a})=>{const o=n(this,gs).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,Ne).getValue("peerSessionStore").onAsync(a,o)})},i=()=>{Object.entries(e).forEach(([a,o])=>{n(this,Ne).getValue("peerSessionStore").removeListener(a,o)})};n(this,re).permissions.on("permissionsUpdate",a=>{const{canAcceptProductionRequests:o}=a;o!==void 0&&(n(this,re).permissions.acceptStageRequests?(r(),n(this,Bt).getStageRequests()):(i(),m(this,gs,[]),this.emit("stageAccessRequestUpdate",n(this,gs))))}),n(this,re).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!n(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,re).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new C("You do not have permission to perform this action","2001");const e=n(this,Mo).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return m(this,gs,e),{stageRequests:n(this,gs)}}async requestAccess(){if(!n(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new C(`Unable to request access you are currently ${this.status}`,"2006");if(n(this,re).permissions.stageAccess===q.Allowed){I(this,Nn,cd).call(this,"ACCEPTED_TO_JOIN_STAGE");return}n(this,Bt).requestAccess(),I(this,Nn,cd).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!n(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");n(this,Bt).cancelRequestAccess(),I(this,Nn,cd).call(this,"OFF_STAGE")}grantAccess(e){if(!n(this,re).roomJoined)throw new C("Can`t grant for participant without joining room");if(!n(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,re).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new C("You do not have permission to perform this action","2001");return n(this,Bt).grantAccess(e)}denyAccess(e){if(!n(this,re).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!n(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,re).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new C("You do not have permission to perform this action","2001");return n(this,Bt).denyAccess(e)}get peerId(){return n(this,Ne).getValue("peerId")}async join(){const e=n(this,Ne).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||n(this,re).permissions.stageAccess===q.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`,"2006");if(n(this,Ne).setValue("stageStatus","ON_STAGE",!1),await n(this,Bt).joinStage(),e===rr.Livestream){await n(this,Ne).getValue("selfController").joinRoom();return}n(this,Ne).notify("stageStatus"),n(this,re).audioEnabled&&n(this,Io,Hu).shareMic(n(this,re).audioTrack),n(this,re).videoEnabled&&n(this,Io,Hu).shareWebcam(n(this,re).videoTrack)}async leave(){if(!n(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new C(`Unable to leave stage you are currently ${this.status}`,"2006");n(this,re).setIsPinned(!1),n(this,Ne).setValue("stageStatus","OFF_STAGE",!1),await n(this,Bt).leaveStage(n(this,re).userId);try{await n(this,Ne).getValue("peerSessionStore").emitAsync(_.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}n(this,Ne).notify("stageStatus")}async kick(e){if(!n(this,re).roomJoined)throw new C("Can`t kick participant without joining room","2005");if(!n(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,re).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new C("You do not have permissions for kick","2001");return n(this,Bt).kick(e)}}Bt=new WeakMap,Ud=new WeakMap,re=new WeakMap,Mo=new WeakMap,gs=new WeakMap,Ne=new WeakMap,Io=new WeakSet,Hu=function(){return n(this,Ne).getValue("roomNodeClient")},Nn=new WeakSet,cd=async function(e){this.status!==e&&n(this,Ne).setValue("stageStatus",e)};an([y.trace("Stage.getStageRequests")],ti.prototype,"getAccessRequests",1);an([y.trace("Stage.requestAccess")],ti.prototype,"requestAccess",1);an([y.trace("Stage.cancelRequestAccess")],ti.prototype,"cancelRequestAccess",1);an([y.trace("Stage.grantAccess")],ti.prototype,"grantAccess",1);an([y.trace("Stage.denyAccess")],ti.prototype,"denyAccess",1);an([hr.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),y.trace("Stage.joinStage")],ti.prototype,"join",1);an([y.trace("Stage.leaveStage")],ti.prototype,"leave",1);function c0(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function qh(s){switch(s){case er.UNSPECIFIED:return"OFF_STAGE";case er.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case er.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case er.OFF_STAGE:return"OFF_STAGE";case er.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var d0=Object.defineProperty,l0=Object.getOwnPropertyDescriptor,u0=(s,t,e,r)=>{for(var i=r>1?void 0:r?l0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&d0(t,e,i),i},wr,ts,Rr,Do,it;class Hf{constructor(t,e,r,i,a){h(this,"stage");g(this,wr,void 0);g(this,ts,void 0);g(this,Rr,void 0);g(this,Do,0);g(this,it,void 0);m(this,it,t),this.stage=new ti(t,i,a,e,r),m(this,Rr,e),m(this,wr,i),m(this,ts,a),this.setupEvents()}get telemetry(){return n(this,it).getValue("telemetry")}get logger(){return n(this,it).getValue("logger")}setupEvents(){n(this,it).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),n(this,Rr).on(x.grantStageAccess,()=>{n(this,wr).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),n(this,Rr).on(x.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===n(this,wr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),n(this,Rr).on(x.denyStageAccess,()=>{n(this,wr).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),n(this,Rr).on(x.getStageRequests,async t=>{var r;if(n(this,wr).permissions.stageAccess!==q.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await n(this,it).getValue("peerSessionStore").emitAsync(_.GET_STAGE_REQUESTS,e),n(this,Do)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),m(this,Do,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return n(this,ts).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,it).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=qh(t.stageType),r=n(this,it).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:n(this,it).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,it).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=n(this,ts).joined.get(t.peerId),r=n(this,ts).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,it).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:n(this,ts).viewMode,page:n(this,ts).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,it).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:n(this,ts).viewMode,page:n(this,ts).currentPage});break}n(this,it).getValue("peerSessionStore").emit(_.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}wr=new WeakMap,ts=new WeakMap,Rr=new WeakMap,Do=new WeakMap,it=new WeakMap;u0([y.trace("Stage.setupEvents")],Hf.prototype,"setupEvents",1);var h0=Object.defineProperty,p0=Object.getOwnPropertyDescriptor,jh=(s,t,e,r)=>{for(var i=r>1?void 0:r?p0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&h0(t,e,i),i},mi,Us,Oo,No,fi,Hg;let Po=(Hg=class extends Ca{constructor(t,e,r,i){const a=t.getValue("logger");super(a);h(this,"name");h(this,"icon");h(this,"id");h(this,"permissions");g(this,mi,void 0);g(this,Us,void 0);g(this,Oo,void 0);g(this,No,void 0);g(this,fi,void 0);h(this,"active");h(this,"enabledBy");m(this,Oo,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,m(this,No,e.component),this.permissions=e.permissions,m(this,mi,i),m(this,Us,r),this.active=!1,this.enabledBy=""}get component(){return n(this,No)}get telemetry(){return n(this,Oo).getValue("telemetry")}set activePluginsStore(t){m(this,Us,t)}activateForSelf(){m(this,fi,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){m(this,fi,void 0),this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("closed")}async activate(){var t;if(!this.active&&(t=this.permissions)!=null&&t.canActivate){if(!n(this,Us))throw new C("Cannot activate plugin: active plugins store is not available yet.","0604");await n(this,Us).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:n(this,mi).id}),this.enabledBy=n(this,mi).id,this.activateForSelf(),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}})}}async deactivate(){var e;if(!this.active||!((e=this.permissions)!=null&&e.canDeactivate)&&this.enabledBy!==n(this,mi).id)return;if(!n(this,Us))throw new C("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=n(this,fi)?new Date().getTime()-n(this,fi).getTime():0;await n(this,Us).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},mi=new WeakMap,Us=new WeakMap,Oo=new WeakMap,No=new WeakMap,fi=new WeakMap,Hg);jh([y.trace("Plugin.activatePlugin")],Po.prototype,"activate",1);jh([y.trace("Plugin.deactivatePlugin")],Po.prototype,"deactivate",1);Po=jh([et("0600")],Po);var ke,Ti;class Bf extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:a,onClearEvent:o}=e;super();g(this,ke,void 0);g(this,Ti,void 0);h(this,"onAddEvent");h(this,"onDeleteEvent");h(this,"onClearEvent");m(this,ke,new Ca(r)),this.onAddEvent=i,this.onDeleteEvent=a,this.onClearEvent=o,m(this,Ti,new Map)}emit(e,...r){return n(this,ke).emit(e,...r)}on(e,r){return n(this,ke).on(e,r)}addListener(e,r){return n(this,ke).addListener(e,r)}off(e,r){return n(this,ke).off(e,r)}once(e,r){return n(this,ke).once(e,r)}prependListener(e,r){return n(this,ke).prependListener(e,r)}prependOnceListener(e,r){return n(this,ke).prependOnceListener(e,r)}removeListener(e,r){return n(this,ke).removeListener(e,r)}removeAllListeners(e){return n(this,ke).removeAllListeners(e)}listeners(e){return n(this,ke).listeners(e)}listenerCount(e){return n(this,ke).listenerCount(e)}getMaxListeners(){return n(this,ke).getMaxListeners()}setMaxListeners(e){return n(this,ke).setMaxListeners(e)}eventNames(){return n(this,ke).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,Ti).set(e,o),r.on("*",o),i&&n(this,ke).emit(this.onAddEvent,r),a}delete(e,r=!0,i=!1){const a=this.get(e);if(!a)return!1;a.removeListener("*",n(this,Ti).get(e));const o=super.delete(e);return i&&a.removeAllListeners(),r&&n(this,ke).emit(this.onDeleteEvent,a),o}clear(e=!0,r=!1){this.forEach(a=>{a.removeListener("*",n(this,Ti).get(a.id)),r&&a.removeAllListeners()});const i=super.clear();return e&&n(this,ke).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}ke=new WeakMap,Ti=new WeakMap;class Tg extends Bf{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 g0=Object.defineProperty,m0=Object.getOwnPropertyDescriptor,f0=(s,t,e,r)=>{for(var i=r>1?void 0:r?m0(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&&g0(t,e,i),i};let Bu=class{constructor(s){h(this,"all");h(this,"active");this.all=new Tg(s),this.active=new Tg(s)}};Bu=f0([et("0600")],Bu);var T0=Object.defineProperty,S0=Object.getOwnPropertyDescriptor,v0=(s,t,e,r)=>{for(var i=r>1?void 0:r?S0(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&&T0(t,e,i),i},ss,Ln,br,Si,$d,qf,Lo,Fu,Vo,qu,xo,ju,Bg;const Ff=(Bg=class{constructor(s,t,e,r){g(this,$d);g(this,Lo);g(this,Vo);g(this,xo);h(this,"plugins");g(this,ss,void 0);g(this,Ln,void 0);g(this,br,void 0);g(this,Si,null);m(this,br,s),this.plugins=t,m(this,Ln,e),m(this,ss,r),this.setupEvents()}get telemetry(){return n(this,br).getValue("telemetry")}get logger(){return n(this,br).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),a=s.getValue("connectionHandler"),o=new Bu(i);let c;a.socketState.state==="connected"?(i.info("Creating active plugins store immediately. Socket is already connected."),c=await r.create(Ru,!0)):i.info("Deferring active plugins store creation until socket connects."),t.forEach(p=>{const f=new Po(s,p,c,e);o.all.add(f)});const d=new Ff(s,o,r,c);return c?I(l=d,xo,ju).call(l):I(u=d,$d,qf).call(u),d}cleanup(){I(this,Lo,Fu).call(this)}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),n(this,br).getValue("peerSessionStore").onAsync(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{var t,e;if(((e=(t=this.plugins.active)==null?void 0:t.toArray())!=null?e:[]).forEach(r=>{r.deactivateForSelf()}),!n(this,ss)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await I(this,Vo,qu).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},ss=new WeakMap,Ln=new WeakMap,br=new WeakMap,Si=new WeakMap,$d=new WeakSet,qf=function(){const s=n(this,br).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!n(this,ss))try{m(this,ss,await n(this,Ln).create(Ru,!0)),I(this,Lo,Fu).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=n(this,ss)}),I(this,xo,ju).call(this),this.logger.info("Active plugins store created after socket connected"),await I(this,Vo,qu).call(this)}catch(r){this.logger.error("Failed to create active plugins store after socket connected, will retry on next reconnect",{error:r})}};s.on(_.SOCKET_STATE_UPDATE,t),m(this,Si,()=>{s.off(_.SOCKET_STATE_UPDATE,t)})},Lo=new WeakSet,Fu=function(){n(this,Si)&&(n(this,Si).call(this),m(this,Si,null))},Vo=new WeakSet,qu=async function(){try{await n(this,Ln).refresh(n(this,ss).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=n(this,ss).getAll();Object.entries(s).forEach(([t,e])=>{if(!e)return;const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store entry.`);return}r.active||(r.enabledBy=e.enabledBy,r.activateForSelf())})},xo=new WeakSet,ju=function(){n(this,ss).subscribe("*",s=>{Object.entries(s).forEach(([t,e])=>{const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store update.`);return}!e&&r.active&&r.deactivateForSelf(),e&&!r.active&&(r.enabledBy=e.enabledBy,r.activateForSelf())})})},Bg);let jf=Ff;v0([y.trace("PluginController.setupEvents")],jf.prototype,"setupEvents",1);var Uo;class y0{constructor(t){h(this,"mediaJoined");h(this,"socketJoined");h(this,"socketJoinAttempted");h(this,"mediaJoinAttempted");h(this,"socketState");h(this,"mediaState");g(this,Uo,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,Uo,t)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(t,e){let r;const{reconnected:i}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:i,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}r&&(this.socketState=r,n(this,Uo).getValue("peerSessionStore").emit(_.SOCKET_STATE_UPDATE,r))}}Uo=new WeakMap;var E0=Object.defineProperty,P0=Object.getOwnPropertyDescriptor,jc=(s,t,e,r)=>{for(var i=r>1?void 0:r?P0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&E0(t,e,i),i};const Sg="Cannot start recording: another recording is already in progress.";var Vn,xn,Un,dd,Fg;let tn=(Fg=class extends Nt{constructor(t,e){const r=t.getValue("logger");super(r);g(this,Un);g(this,Vn,void 0);g(this,xn,void 0);h(this,"recordingPeerIds",[]);h(this,"recordings",[]);m(this,xn,t),m(this,Vn,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,xn).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!n(this,Vn).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new C("User does not have permission to start recording","1001");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw this.logger.error("Recording::start::recording_in_progress",{recording:{state:this.recordingState}}),new C(Sg,"1005");try{const e=It(),{recording:r={}}=n(this,xn).getValue("defaults"),i=await e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw this.logger.error("Recording::start::recording_failed_to_start",{error:e}),e instanceof Rd&&e.status===409?new C(Sg,"1005"):new C("Error while starting recording","1000",this.logger)}}async stop(t){await I(this,Un,dd).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await I(this,Un,dd).call(this,"pause",["RECORDING"],t)}async resume(t){await I(this,Un,dd).call(this,"resume",["PAUSED"],t)}},Vn=new WeakMap,xn=new WeakMap,Un=new WeakSet,dd=async function(t,e,r){if(!n(this,Vn).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new C("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const a=this.recordings.find(o=>o.id===r);if(a===void 0)throw new C("Could not find the specified recording","1004");if(e.includes(a.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:a.state}});return}i.push(a)}else i=this.recordings.filter(a=>e.includes(a.state));i.forEach(async a=>{const o=a.state;t==="stop"&&(a.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await 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 C("Error while stopping recording","1000",this.logger)}})},Fg);jc([y.trace("Recording.start")],tn.prototype,"start",1);jc([y.trace("Recording.stop")],tn.prototype,"stop",1);jc([y.trace("Recording.stop")],tn.prototype,"pause",1);jc([y.trace("Recording.stop")],tn.prototype,"resume",1);tn=jc([et("1000")],tn);var _0=Object.defineProperty,C0=Object.getOwnPropertyDescriptor,w0=(s,t,e,r)=>{for(var i=r>1?void 0:r?C0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_0(t,e,i),i},vi;class Gf{constructor(t,e,r){h(this,"recording");h(this,"room");g(this,vi,void 0);m(this,vi,t),this.recording=new tn(t,e),this.room=r,this.setupEvents()}get telemetry(){return n(this,vi).getValue("telemetry")}get logger(){return n(this,vi).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case Xi.BROWSER:e="BROWSER";break;case Xi.COMPOSITE:e="COMPOSITE";break;case Xi.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){n(this,vi).getValue("peerSessionStore").on(_.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(x.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(x.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(x.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}vi=new WeakMap;w0([y.trace("RecordingController.setupEvents")],Gf.prototype,"setupEvents",1);var yi;class R0{constructor(t){g(this,yi,void 0);m(this,yi,t)}hasFeature(t){return n(this,yi).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return n(this,yi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return n(this,yi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}yi=new WeakMap;class Gh{constructor(t,e,r,i){h(this,"authToken");h(this,"logger");h(this,"features");h(this,"browserSpecs");h(this,"callStats");this.authToken=t,this.logger=e,this.features=r,this.browserSpecs=me,this.callStats=i}static init(t){return new Gh(t.getValue("authToken"),t.getValue("logger"),new R0(t),t.getValue("callstats"))}}class Wh{constructor(t){h(this,"internals");this.internals=t}static async init(t){const e=Gh.init(t);return new Wh(e)}}var b0=Object.defineProperty,k0=Object.getOwnPropertyDescriptor,Vt=(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},De,pe,le,$s,Ft,$o,_e;class yt extends Ca{constructor(e,r,i=bd,a=!0){const o=e.getValue("logger");super(o);g(this,De,void 0);g(this,pe,void 0);g(this,le,void 0);g(this,$s,void 0);g(this,Ft,void 0);g(this,$o,void 0);g(this,_e,void 0);h(this,"audioUpdateInProgress");h(this,"videoUpdateInProgress");m(this,_e,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,m(this,De,new Wf(e,r)),m(this,pe,new Q0(e,n(this,De),void 0,i)),m(this,le,new iD(e,n(this,De),void 0,i)),m(this,Ft,new tD(n(this,_e),n(this,De))),m(this,$s,new Z0(e,n(this,De))),m(this,$o,a),n(this,pe).on("trackMuted",this.onAudioTrackMuted.bind(this)),n(this,pe).on("trackChanged",this.onAudioTrackChanged.bind(this)),n(this,le).on("trackChanged",this.onVideoTrackChanged.bind(this)),n(this,le).on("trackEnded",this.onVideoTrackEnded.bind(this)),n(this,Ft).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return n(this,_e).getValue("telemetry")}set context(e){m(this,_e,e)}async onVisibilityChange(){n(this,_e).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?n(this,_e).getValue("callstats").browserBackgrounded():(n(this,_e).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?n(this,_e).getValue("callstats").audioOn():n(this,_e).getValue("callstats").audioOff(),r?n(this,_e).getValue("callstats").videoOn():n(this,_e).getValue("callstats").videoOff();let i,a;if(e&&r)try{const c=await n(this,De).getAudioAndVideoTrack(n(this,pe).userSelectedDevice,n(this,le).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,De).getAudioTrack(!1,n(this,pe).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!a&&r)try{a=await n(this,De).getVideoTrack(n(this,le).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&n(this,_e).getValue("callstats").audioOff(),r&&!a&&n(this,_e).getValue("callstats").videoOff(),await n(this,pe).setMediaTrack(i),await n(this,le).setMediaTrack(a);try{await this.setupSpeaker()}catch(c){}if(a){const c=await this.getDeviceById(a.getSettings().deviceId);n(this,_e).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);n(this,_e).getValue("callstats").selectedDevice("AUDIO",c)}(o=n(this,$s).currentDevice)!=null&&o.deviceId&&n(this,_e).getValue("callstats").selectedDevice("SPEAKER",n(this,$s).currentDevice),n(this,De).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:n(this,pe).currentDevice,video:n(this,le).currentDevice,speaker:n(this,$s).currentDevice}}get permissions(){return n(this,De).permissions}getAllDevices(){return n(this,De).getAvailableDevices()}getDeviceById(e,r){return n(this,De).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return n(this,pe).mediaTrack}get audioTrack(){return n(this,pe).transformedMediaTrack}get audioEnabled(){return n(this,pe).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await n(this,pe).enableTrack(!1,e):await n(this,pe).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){n(this,pe).mediaTrack&&!n(this,pe).isCustomTrack?n(this,pe).muteTrack():n(this,pe).disableTrack()}getAudioDevices(e){return n(this,De).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await n(this,pe).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,_e).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,$s).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,$s).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,_e).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,le).mediaTrack}get videoTrack(){return n(this,le).transformedMediaTrack}get videoEnabled(){return n(this,le).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await n(this,le).enableTrack(!1,e):await n(this,le).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){n(this,le).disableTrack()}getVideoDevices(e){return n(this,De).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await n(this,le).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,_e).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await n(this,le).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:n(this,Ft).audioMediaTrack,video:n(this,Ft).videoMediaTrack}}get screenShareEnabled(){return n(this,Ft).trackEnabled}async enableScreenShare(){await n(this,Ft).enableScreenShare()}async disableScreenShare(){n(this,Ft).disableScreenShare()}async updateScreenshareConstraints(e){await n(this,Ft).updateConstraints(e)}getSpeakerDevices(e){return n(this,De).getAudioOutputDevices(e)}addAudioMiddleware(e){return n(this,pe).addMiddleware(e)}removeAudioMiddleware(e){return n(this,pe).removeMiddleware(e)}removeAllAudioMiddlewares(){return n(this,pe).removeAllMiddlewares()}addVideoMiddleware(e){return n(this,le).addMiddleware(e)}removeVideoMiddleware(e){return n(this,le).removeMiddleware(e)}removeAllVideoMiddlewares(){return n(this,le).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return n(this,le).setVideoMiddlewareGlobalConfig(e)}destruct(){n(this,pe).disableTrack(),n(this,le).disableTrack(),n(this,le).terminateMiddlewareWebWorker(),n(this,Ft).disableScreenShare(),n(this,De).destruct()}async onDeviceChange(e,r){var a,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!n(this,$o))return;let i=!1;(a=e==null?void 0:e.added)==null||a.reverse().forEach(async c=>{var d;c&&!bd(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,pe).disableTrack()}removeVideoTrack(){n(this,le).disableTrack(),n(this,le).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}De=new WeakMap,pe=new WeakMap,le=new WeakMap,$s=new WeakMap,Ft=new WeakMap,$o=new WeakMap,_e=new WeakMap;Vt([y.trace("MediaHandler.setupStreams")],yt.prototype,"setupStreams",1);Vt([y.trace("MediaHandler.enableAudio")],yt.prototype,"enableAudio",1);Vt([y.trace("MediaHandler.disableAudio")],yt.prototype,"disableAudio",1);Vt([y.trace("MediaHandler.setAudioDevice")],yt.prototype,"setAudioDevice",1);Vt([y.trace("MediaHandler.enableVideo")],yt.prototype,"enableVideo",1);Vt([y.trace("MediaHandler.disableVideo")],yt.prototype,"disableVideo",1);Vt([y.trace("MediaHandler.setVideoDevice")],yt.prototype,"setVideoDevice",1);Vt([y.trace("MediaHandler.updateVideoConstraints")],yt.prototype,"updateVideoConstraints",1);Vt([y.trace("MediaHandler.enableScreenShare")],yt.prototype,"enableScreenShare",1);Vt([y.trace("MediaHandler.disableScreenShare")],yt.prototype,"disableScreenShare",1);Vt([y.trace("MediaHandler.updateScreenshareConstraints")],yt.prototype,"updateScreenshareConstraints",1);Vt([y.trace("MediaHandler.destruct")],yt.prototype,"destruct",1);Vt([y.trace("MediaHandler.onDeviceChange")],yt.prototype,"onDeviceChange",1);function td(s,t,e){switch(!0){case me.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case me.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case me.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 A0=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function bd(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=me._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:A0.some(i=>t==null?void 0:t.includes(i))}async function M0(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 Ei,Ho;class I0{constructor(t){g(this,Ei,void 0);g(this,Ho,void 0);m(this,Ho,t)}get logger(){return n(this,Ho).getValue("logger")}terminateMiddlewareWebWorker(){if(n(this,Ei))try{io.clearInterval(n(this,Ei)),m(this,Ei,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:io})));if(r.disablePerFrameCanvasRendering){const v=i.captureStream().getVideoTracks()[0];return Object.defineProperty(v,"originalSettings",{value:e.getSettings()}),v}const o=document.createElement("video"),c=new MediaStream;c.addTrack(e);const d=i.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=async()=>{if(e.enabled===!1||e.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let 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,Ei,io.setInterval(l,50))},!1);const p=i.captureStream().getVideoTracks()[0];return Object.defineProperty(p,"originalSettings",{value:e.getSettings()}),p}}Ei=new WeakMap,Ho=new WeakMap;const D0={qvga:{width:{ideal:320},height:{ideal:240},frameRate:{ideal:30}},vga:{width:{ideal:640},height:{ideal:480},frameRate:{ideal:30}},hd:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},fhd:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},uhd:{width:{ideal:3840},height:{ideal:2160},frameRate:{ideal:30}}},O0=[[320,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[640,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[1280,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[1920,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[3840,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]]],N0=(s,t)=>{var d,l,u;const e=(d=s==null?void 0:s.getValue("overrides"))==null?void 0:d.simulcastConfig;if((l=e==null?void 0:e.encodings)!=null&&l.length)return e.encodings;const r="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((u=t.originalSettings)==null?void 0:u.width),i=O0,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 Te=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Te||{});const L0=Ew(),dn=ws(L0.config.media);function V0(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 Pi,Hd;class x0{constructor(t,e){g(this,Pi,void 0);g(this,Hd,void 0);h(this,"getScreenShareConstraints",()=>{var l,u,p,f,v,E,R,A,b;const t=(l=n(this,Pi))==null?void 0:l.screenshare,e=(p=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?p:1920,r=(v=(f=t==null?void 0:t.height)==null?void 0:f.max)!=null?v:1080,i=(R=(E=t==null?void 0:t.frameRate)==null?void 0:E.max)!=null?R:5,a=(b=(A=t==null?void 0:t.frameRate)==null?void 0:A.ideal)!=null?b:5,o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;let d={width:{max:e},height:{max:r},frameRate:{ideal:a,max:i}};return o!==void 0&&["monitor","browser","window"].includes(o)&&(d={...d,displaySurface:o}),c!==void 0&&(d={...d,selfBrowserSurface:c}),{audio:!0,video:d}});h(this,"getAudioConstraints",t=>{var a,o,c,d,l,u,p;const e={},r=(a=n(this,Pi))==null?void 0:a.audio,i=r!=null&&r.enableStereo?2:1;return me.isFirefox()||me.isWebKitBased()?(e.audio={deviceId:t,autoGainControl:(o=r==null?void 0:r.autoGainControl)!=null?o:!0,echoCancellation:(c=r==null?void 0:r.echoCancellation)!=null?c:!0,noiseSuppression:(d=r==null?void 0:r.noiseSupression)!=null?d:!0,channelCount:i},e):(e.audio={autoGainControl:(l=r==null?void 0:r.autoGainControl)!=null?l:!0,echoCancellation:(u=r==null?void 0:r.echoCancellation)!=null?u:!0,noiseSuppression:(p=r==null?void 0:r.noiseSupression)!=null?p:!0,channelCount:i},t&&(e.audio.deviceId={exact:t}),e)});h(this,"getVideoConstraints",t=>{var o,c,d;const e={},r=(o=n(this,Pi))==null?void 0:o.video,i=x_(D0);let a=i.vga;if(typeof r=="string"){const l=i[r];l&&(a=l)}else r!==void 0&&(a.height.ideal=r.height.ideal,a.width.ideal=r.width.ideal,a.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=a,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});m(this,Hd,t),m(this,Pi,e)}getUpdatedVideoConstraints(t){return t}}Pi=new WeakMap,Hd=new WeakMap;class fu extends Error{constructor(e,r,i){super(r);h(this,"constraints");h(this,"name");this.name=e,this.constraints=i}}class U0{constructor(){h(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 $0=Object.defineProperty,H0=Object.getOwnPropertyDescriptor,ps=(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&&$0(t,e,i),i},$n,qt,Le,qg;let Ot=(qg=class extends U0{constructor(t,e){super();g(this,$n,void 0);g(this,qt,void 0);g(this,Le,void 0);m(this,Le,t),m(this,qt,new x0(t,e)),m(this,$n,new AbortController)}get telemetry(){return n(this,Le).getValue("telemetry")}get logger(){return n(this,Le).getValue("logger")}get constraintsBuilder(){return n(this,qt)}async destruct(){var t;(t=n(this,$n))==null||t.abort()}handlePermissionErrors(t,e){const r=td(t,e.name,e.message);return this.permissions[t]=r,n(this,Le).getValue("peerSessionStore").emit(_.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(b=>b.deviceId===t));let u;t&&l?u=t:c&&((r=c[0])!=null&&r.deviceId)&&(u=(i=c[0])==null?void 0:i.deviceId);const p=!!(d!=null&&d.find(b=>b.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 v={audio:n(this,qt).getAudioConstraints(u).audio,video:n(this,qt).getVideoConstraints(f).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(v)});const E=await navigator.mediaDevices.getUserMedia(v);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(v)});const R=E.getAudioTracks()[0];let A=E.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",A.label.includes("OBS Virtual")){const V=(await this.getVideoInputDevices()).find(D=>D.label.includes("OBS Virtual"));A=await this.getVideoTrack(V.deviceId)}return n(this,Le).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),n(this,Le).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:R,videoTrack:A}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new C("Couldnt fetch audio and video track","1605")}}async getAudioTrack(t,e){var c,d;let r=await this.getAudioInputDevices();if(!(r!=null&&r.length))throw this.permissions.audio="NO_DEVICES_AVAILABLE",n(this,Le).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new C("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let a;e&&i?a=e:(c=r[0])!=null&&c.deviceId&&(a=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(f=>f.deviceId!==l),u=n(this,qt).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[p]=(await navigator.mediaDevices.getUserMedia(u)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),p}catch(p){const f=td("audio",p.name,p.message),v=new fu(p.name,p.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw v;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const R=n(this,qt).getAudioConstraints(E.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(R)}),o(E.deviceId)}throw v}};try{const l=await o(a);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",n(this,Le).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new C(l.message,"1601")}}async getVideoTrack(t){var c,d,l;const e=(c=await this.getCurrentDeviceLabel(t))==null?void 0:c.includes("OBS Virtual"),r=await this.getVideoInputDevices();if(!(r!=null&&r.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",n(this,Le).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new C("No video devices available","1607");const i=!!(r!=null&&r.find(u=>u.deviceId===t));let a;t&&i?a=t:(d=r[0])!=null&&d.deviceId&&(a=(l=r[0])==null?void 0:l.deviceId);const o=async u=>{try{let p=u;const{video:f}=p;e&&typeof f!="boolean"&&(p={video:{deviceId:f.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(p)});const[v]=(await navigator.mediaDevices.getUserMedia(p)).getVideoTracks();if(e&&typeof f!="boolean"&&typeof f.width=="object"){const{width:E,height:R}=v.getSettings(),{ideal:A}=f.width;v.applyConstraints({width:{ideal:A},height:{ideal:Math.floor(R*A/E)},frameRate:f.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(p)}),v}catch(p){const f=td("video",p.name,p.message),v=new fu(p.name,p.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw v;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const R=n(this,qt).getVideoConstraints(E.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(R)}),o({video:R.video})}throw v}};try{const u=n(this,qt).getVideoConstraints(a),p=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",n(this,Le).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),p}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new C(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),n(this,Le).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=td("video",r.name,r.message),a=new fu(r.name,r.message,e),o={video:!0};if(GC(e,o))throw a;if(i==="COULD_NOT_START")return t(o);throw a}};try{const e=n(this,qt).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",n(this,Le).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new C(e.message,"1612")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async enumerateDevicesWithExternalFirst(){const t=await navigator.mediaDevices.enumerateDevices(),e=i=>{var o;const a=((o=i.label)==null?void 0:o.toLowerCase())||"";return bd(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 u,p;const o=e(i),c=e(a);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=a.deviceId==="default"||((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),v=r(a);if(f&&!v)return-1;if(!f&&v)return 1}return 0})}async getAvailableDevices(){try{return await this.enumerateDevicesWithExternalFirst()||[]}catch(t){return this.logger.error("enumerate_devices_failed",{error:t}),[]}}async getAvailableDevicesByKind(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(({kind:e})=>t===e)}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get available devices by kind","1609")}}async getDevice(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(r=>r.deviceId===t)[0]}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get device","1609")}}async onDeviceChange(t){if(me.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,u;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||(u=d.removed)!=null&&u.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,Le).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(f=>f.kind==="audioinput")),p.some(f=>f.kind==="videoinput")&&n(this,Le).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(f=>f.kind==="videoinput")),p.some(f=>f.kind==="audiooutput")&&n(this,Le).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(f=>f.kind==="audiooutput")),t(r,d,!1)}},{signal:n(this,$n).signal})}}},$n=new WeakMap,qt=new WeakMap,Le=new WeakMap,qg);ps([y.trace("WebMediaInterface.destruct")],Ot.prototype,"destruct",1);ps([y.trace("WebMediaInterface.handlePermissionErrors")],Ot.prototype,"handlePermissionErrors",1);ps([y.trace("WebMediaInterface.getAudioAndVideoTrack")],Ot.prototype,"getAudioAndVideoTrack",1);ps([y.trace("WebMediaInterface.getAudioTrack")],Ot.prototype,"getAudioTrack",1);ps([y.trace("WebMediaInterface.getVideoTrack")],Ot.prototype,"getVideoTrack",1);ps([y.trace("WebMediaInterface.getScreenShareTracks")],Ot.prototype,"getScreenShareTracks",1);ps([y.trace("WebMediaInterface.getAvailableDevices")],Ot.prototype,"getAvailableDevices",1);ps([y.trace("WebMediaInterface.getAvailableDevicesByKind")],Ot.prototype,"getAvailableDevicesByKind",1);ps([y.trace("WebMediaInterface.getDevice")],Ot.prototype,"getDevice",1);ps([y.trace("WebMediaInterface.onDeviceChange")],Ot.prototype,"onDeviceChange",1);Ot=ps([et("1600")],Ot);const Wf=Ot,Zi={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}},B0=(s=0)=>new Promise(t=>setTimeout(t,s)),F0=(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):B0().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},q0=typeof AudioContext!="undefined"?AudioContext:null;class Jh{constructor(t){h(this,"_AudioContext");h(this,"audioContext");h(this,"_audioContextRefContainers");const e={AudioContext:q0,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:Jh}})}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 vg=new Jh,j0=3,G0=250;function W0(s){const t={},e=vg.getOrCreate(t);let r=j0;function i(){return r-=1,F0(e,s.srcObject,G0).then(a=>a?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{vg.release(t)})}async function yg(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 W0(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 J0=Object.defineProperty,K0=Object.getOwnPropertyDescriptor,Jf=(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};let kd=class extends Ca{constructor(t,e,r,i){var o;const a=t.getValue("logger");super(a);h(this,"constructorName",this.constructor.name);h(this,"userSelectedDevice");h(this,"mediaInterface");h(this,"isNonPreferredDevice");h(this,"_mediaTrack");h(this,"transformedMediaTrack");h(this,"middlewares",[]);h(this,"currentDevice");h(this,"userPreferredDeviceKey",`Realtimekit::${this.constructorName}::UserDeviceID`);h(this,"setUserPreferredDevice",t=>Zi.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>Zi.getItem(this.userPreferredDeviceKey,this.logger));h(this,"isCustomTrack",!1);h(this,"context");this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(o=this.getUserPreferredDevice())!=null?o:void 0,this.isNonPreferredDevice=i,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}get telemetry(){return this.context.getValue("telemetry")}disableTrack(){var t,e;this.removeMediaTrackListeners(),this.isCustomTrack||(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}async setMediaTrack(t,e=!1){const r=i=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){r(i)}this._mediaTrack=await this.conditionallyChangeTrack(t,e),await this.setTransformedTrack();try{this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){r(i)}}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){this.logger.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}async unmuteTrack(){try{this.mediaTrack?this.mediaTrack.enabled=!0:await this.enableTrack(!1)}catch(t){throw this.logger.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new C("Failed to unmute track","1611")}}getCurrentDeviceId(){var e;const{kind:t}=this.mediaTrack;switch(t){case"audio":{const{deviceId:r}=this.mediaTrack.getSettings();if(r)return r;const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(i&&typeof i.deviceId=="object"&&"exact"in i.deviceId?i.deviceId.exact:i.deviceId)||((e=i==null?void 0:i.advanced)==null?void 0:e[0].deviceId)||"default":this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}async setCurrentDevice(){var e;if(!this.mediaTrack){this.currentDevice=void 0;return}const t=this.getCurrentDeviceId();((e=this.currentDevice)==null?void 0:e.deviceId)!==t&&(this.currentDevice=await this.mediaInterface.getDevice(t))}async setDevice(t,{saveDevicePreference:e}){if(!t)throw this.logger.warn(`${this.constructorName}.setDevice No device received`),new C("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(me.isWebKitBased()&&!(me.isSafari()&&nw.test(me.getVersion())))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&await this.setTransformedTrack(),{success:!0,message:"Successfully added the middleware."}}catch(e){return this.logger.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}}async removeMiddleware(t){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return this.logger.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}}async removeAllMiddlewares(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return this.logger.error("While removing all the middlewares",{error:e}),{success:!1,message:e==null?void 0:e.message}}return{success:!1,message:"No middlewares were found. Skipping."}}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.logger.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};Jf([y.trace("BaseMediaHandler.unmuteTrack")],kd.prototype,"unmuteTrack",1);kd=Jf([et("1600")],kd);const Kf=kd;var z0=Object.defineProperty,Y0=Object.getOwnPropertyDescriptor,Kh=(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&&z0(t,e,i),i};const Tu="[Realtimekit]nonSilentDeviceLabels";class Kl extends Kf{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new C("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new C("Non audio device received while setting device!","1603");try{const e=this.trackEnabled;this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getAudioTrack(!e,this.userSelectedDevice))}catch(e){throw this.logger.error("AudioMediaHandler.setDevice.error",{error:e}),this.disableTrack(),new C(e.message,"1604")}}async enableTrack(t,e){if(this.trackEnabled){this.logger.warn("AudioMediaHandler.enableTrack Track already enabled!");return}if(e){this.isCustomTrack=!0,await this.setMediaTrack(e,!0);return}this.isCustomTrack=!1;const r=await this.mediaInterface.getAudioTrack(t,this.userSelectedDevice);await this.setMediaTrack(r)}async setTransformedTrack(t){var e;if(!t&&!((e=this.middlewares)!=null&&e.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await M0(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(Zi.getItem(Tu,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await yg(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return Zi.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 u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await yg(this.logger,r)){const p=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return Zi.setItem(Tu,JSON.stringify({devices:p}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}Kh([y.trace("AudioMediaHandler.setTransformedTrack")],Kl.prototype,"setTransformedTrack",1);Kh([y.trace("AudioMediaHandler.onTrackEnded")],Kl.prototype,"onTrackEnded",1);Kh([y.trace("AudioMediaHandler.conditionallyChangeTrack")],Kl.prototype,"conditionallyChangeTrack",1);const Q0=Kl;var _i;class X0{constructor(t,e){g(this,_i,void 0);h(this,"currentDevice");h(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");h(this,"logger");h(this,"setUserPreferredDevice",t=>Zi.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>Zi.getItem(this.userPreferredDeviceKey,this.logger));m(this,_i,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await n(this,_i).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,_i)instanceof Wf))return;let r=t;if(t||([r]=(await n(this,_i).getAvailableDevicesByKind("audiooutput")).filter(d=>!bd(d))),!r)throw new C("No speaker found","1608");if(((a=this.currentDevice)==null?void 0:a.deviceId)===r.deviceId)return;e&&this.setUserPreferredDevice(r.deviceId),this.currentDevice=r;const i=document.querySelectorAll("audio");(o=i[0])!=null&&o.setSinkId&&i.forEach(async c=>{if(typeof c.sinkId!="undefined"&&this.currentDevice.deviceId&&c.sinkId!==this.currentDevice.deviceId)try{await c.setSinkId(this.currentDevice.deviceId)}catch(d){}})}}_i=new WeakMap;const Z0=X0;var Bo;class eD extends Ca{constructor(e,r){const i=e.getValue("logger");super(i);h(this,"mediaInterface");h(this,"audioMediaTrack");h(this,"videoMediaTrack");g(this,Bo,void 0);m(this,Bo,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,Bo).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(i){}}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}async updateConstraints(e){if(!this.videoMediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),me.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")}}Bo=new WeakMap;const tD=eD;var sD=Object.defineProperty,rD=Object.getOwnPropertyDescriptor,zl=(s,t,e,r)=>{for(var i=r>1?void 0:r?rD(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&&sD(t,e,i),i},Hn,Fo;class Gc extends Kf{constructor(e,r,i,a){super(e,r,i,a);g(this,Hn,void 0);g(this,Fo,{disablePerFrameCanvasRendering:!1});m(this,Hn,new I0(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new C("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new C("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){this.logger.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C("Failed to change device","1600",this.logger)}}async enableTrack(e,r){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,await this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=await this.mediaInterface.getVideoTrack(this.userSelectedDevice);await this.setMediaTrack(i)}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await n(this,Hn).getTransformedVideoTrack(this.middlewares,this.mediaTrack,n(this,Fo)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){m(this,Fo,e)}async updateConstraints(e){if(!this._mediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}}terminateMiddlewareWebWorker(){n(this,Hn).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}}Hn=new WeakMap,Fo=new WeakMap;zl([y.trace("VideoMediaHandler.setTransformedTrack")],Gc.prototype,"setTransformedTrack",1);zl([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],Gc.prototype,"setVideoMiddlewareGlobalConfig",1);zl([y.trace("VideoMediaHandler.onTrackEnded")],Gc.prototype,"onTrackEnded",1);zl([y.trace("VideoMediaHandler.conditionallyChangeTrack")],Gc.prototype,"conditionallyChangeTrack",1);const iD=Gc,Eg=ws($h());var nt,Ci,qo,Bn;const Tn=class{constructor(t){g(this,nt,void 0);g(this,Ci,void 0);g(this,qo,void 0);g(this,Bn,void 0);if(!t)throw new C("Could not load preset.","0904");m(this,nt,t.config),m(this,qo,t.name),m(this,Ci,t.ui||ws($h().ui)),m(this,Bn,t.permissions.plugins.config)}static fromResponse(t){return new Tn(t)}static default(){return new Tn(Eg)}static init(t,e=!0){return!t||e?new Tn(Eg):new Tn(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,Ci).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return n(this,nt).viewType}get livestreamViewerQualities(){return n(this,nt).livestreamViewerQualities||[]}get maxVideoStreams(){return n(this,nt).maxVideoStreams}get maxScreenShareCount(){return n(this,nt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(n(this,Bn)).filter(t=>n(this,Bn)[t].disabled)}get designTokens(){return n(this,Ci).designTokens}get configDiff(){return n(this,Ci).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=n(this,nt))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.simulcast)!=null?i:!1}get mediaConstraints(){var t,e,r,i,a,o,c,d,l,u,p,f,v,E,R,A,b,V,D,L,U,B,z,Q;return{audio:{enableStereo:(i=(r=(e=(t=n(this,nt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:dn.audio.enableStereo,enableHighBitrate:(d=(c=(o=(a=n(this,nt))==null?void 0:a.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:dn.audio.enableHighBitrate},video:{quality:(f=(p=(u=(l=n(this,nt))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:p.quality)!=null?f:dn.video.quality,frameRate:(A=(R=(E=(v=n(this,nt))==null?void 0:v.media)==null?void 0:E.video)==null?void 0:R.frameRate)!=null?A:dn.video.frameRate},screenshare:{quality:(L=(D=(V=(b=n(this,nt))==null?void 0:b.media)==null?void 0:V.screenshare)==null?void 0:D.quality)!=null?L:dn.screenshare.quality,frameRate:(Q=(z=(B=(U=n(this,nt))==null?void 0:U.media)==null?void 0:B.screenshare)==null?void 0:z.frameRate)!=null?Q:dn.screenshare.frameRate}}}get name(){return n(this,qo)}};let Gu=Tn;nt=new WeakMap,Ci=new WeakMap,qo=new WeakMap,Bn=new WeakMap;var nD=Object.defineProperty,aD=Object.getOwnPropertyDescriptor,zf=(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},Fn,jo;class zh extends Nt{constructor(e,r){const i=e.getValue("logger");super(i);g(this,Fn,void 0);h(this,"state","IDLE");h(this,"playbackUrl");h(this,"ingestionCredentials");h(this,"viewerCount");g(this,jo,void 0);m(this,Fn,r),m(this,jo,e),this.viewerCount=0}get telemetry(){return n(this,jo).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,Fn).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new C("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=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 C("Error while starting livestream","1900",this.logger)}}async stop(){if(!n(this,Fn).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new C("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw this.logger.error("Livestream::stop::inconsistent_state"),new C("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await It().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new C("Error while stopping livestream","1900",this.logger)}}}Fn=new WeakMap,jo=new WeakMap;zf([y.trace("livestream.start")],zh.prototype,"start",1);zf([y.trace("livestream.stop")],zh.prototype,"stop",1);var oD=Object.defineProperty,cD=Object.getOwnPropertyDescriptor,dD=(s,t,e,r)=>{for(var i=r>1?void 0:r?cD(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&&oD(t,e,i),i},qn,jn,Hs,ms;class Yf{constructor(t,e,r){h(this,"livestream");g(this,qn,void 0);g(this,jn,void 0);g(this,Hs,void 0);g(this,ms,void 0);m(this,ms,t),m(this,jn,e),this.livestream=new zh(t,e),m(this,Hs,r),this.setupEvents()}get logger(){return n(this,ms).getValue("logger")}get telemetry(){return n(this,ms).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,Hs).on(x.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{n(this,jn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),n(this,Hs).on(x.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{n(this,jn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),n(this,Hs).on(x.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),n(this,Hs).on(x.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),n(this,Hs).on(x.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),n(this,ms).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(m(this,qn,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),n(this,ms).getValue("peerSessionStore").on(_.PEER_CLOSED,t=>{t.id===n(this,qn)&&(m(this,qn,void 0),this.livestream.setLivestreamState("IDLE"))}),n(this,ms).getValue("peerSessionStore").onAsync(_.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,ms).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}qn=new WeakMap,jn=new WeakMap,Hs=new WeakMap,ms=new WeakMap;dD([y.trace("LivestreamController.setupEvents")],Yf.prototype,"setupEvents",1);var lD=Object.defineProperty,uD=Object.getOwnPropertyDescriptor,Wc=(s,t,e,r)=>{for(var i=r>1?void 0:r?uD(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},Je,kr,Ar,Bd,Qf;class Ra{constructor({name:t,socketHandler:e,meetingId:r}){g(this,Bd);h(this,"name","");g(this,Je,{});g(this,kr,"");g(this,Ar,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});h(this,"listeners",{});this.name=t,m(this,Ar,e),m(this,kr,r)}async set(t,e,r=!0,i=!1){n(this,Je)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(a=>a({[t]:n(this,Je)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(a=>a({[t]:n(this,Je)[t]})))}remoteSet(t,e){n(this,Ar).storeInsertKeys(n(this,kr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{n(this,Je)[e]=r}),n(this,Ar).storeInsertKeys(n(this,kr),this.name,t)}async update(t,e,r=!0){I(this,Bd,Qf).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(n(this,Je)[t]&&delete n(this,Je)[t],e)return n(this,Ar).storeDeleteKeys(n(this,kr),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,Je)[e]&&delete n(this,Je)[e]}),n(this,Ar).storeDeleteKeys(n(this,kr),this.name,t)}get(t){if(n(this,Je)[t])return n(this,Je)[t]}getAll(){return n(this,Je)}clear(){m(this,Je,{})}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,Je,t)}}Je=new WeakMap,kr=new WeakMap,Ar=new WeakMap,Bd=new WeakSet,Qf=function(t,e,r=!0){let i;const a=n(this,Je)[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)};Wc([Lt(wa,"rateLimitConfig")],Ra.prototype,"remoteSet",1);Wc([Lt(wa,"bulkRateLimitConfig")],Ra.prototype,"bulkSet",1);Wc([Lt(wa,"rateLimitConfig")],Ra.prototype,"update",1);Wc([Lt(wa,"rateLimitConfig")],Ra.prototype,"delete",1);Wc([Lt(wa,"bulkRateLimitConfig")],Ra.prototype,"bulkDelete",1);var Mr,Ir,Go,Wu,Wo,rs,Fd,Xf;class hD{constructor(t,e){g(this,Go);g(this,Fd);h(this,"stores",new Map);g(this,Mr,void 0);g(this,Ir,"");g(this,Wo,void 0);g(this,rs,new Map);m(this,Mr,e),m(this,Ir,t.getValue("meetingId")),m(this,Wo,t),I(this,Fd,Xf).call(this)}create(t,e=!1){if(aw.includes(t)&&!e)throw new C(`'${t}' is a reserved store name.`,"0601");const r=new Ra({name:t,socketHandler:n(this,Mr),meetingId:n(this,Ir)});return n(this,Mr).storeGetKeys(n(this,Ir),t,[]),new Promise((a,o)=>{const c=setTimeout(()=>{n(this,rs).delete(t),o(Error("Failed"))},3e3);n(this,rs).set(t,{rejectTimeout:c,resolve:a,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),n(this,Mr).storeGetKeys(n(this,Ir),t,[]),new Promise((i,a)=>{const o=setTimeout(()=>{n(this,rs).delete(t),a(Error("Store refresh timed out"))},3e3);n(this,rs).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}Mr=new WeakMap,Ir=new WeakMap,Go=new WeakSet,Wu=function(){return n(this,Wo).getValue("peerId")},Wo=new WeakMap,rs=new WeakMap,Fd=new WeakSet,Xf=function(){[Ds.storeInsertKeys,Ds.storeGetKeys,Ds.storeDeleteKeys].forEach(t=>{n(this,Mr).on(t,async e=>{var a,o;if(e.pluginId!==n(this,Ir))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===Ds.storeGetKeys){const c=n(this,rs).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(n(this,rs).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),n(this,rs).delete(e.storeName)),!d)return;r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=n(this,rs).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===Ds.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==n(this,Go,Wu)&&i.set(c,l,!1,!0)}),t===Ds.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==n(this,Go,Wu)&&i.delete(c,!1,!0)}))})})};function ci(s){var t,e,r,i,a,o,c,d,l,u,p,f,v;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(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=(u=s.screenShareTracks)==null?void 0:u.video)==null?void 0:p.enabled,trackId:(v=(f=s.screenShareTracks)==null?void 0:f.video)==null?void 0:v.id}}}}:{}}var pD=Object.defineProperty,gD=Object.getOwnPropertyDescriptor,ba=(s,t,e,r)=>{for(var i=r>1?void 0:r?gD(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&&pD(t,e,i),i};const mD=.8,fD=1.2;var Gn,Wn,wt,wi,Ka,Dr,hn,Ri,za,qd,Zf,Bs,Jo,Or,bi,Ya,Fs,jd,Ko,Ju,Gd,eT,Wd,tT,jg;let or=(jg=class extends Nt{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,wi);g(this,Dr);g(this,Ri);g(this,qd);g(this,bi);g(this,Ko);g(this,Gd);g(this,Wd);h(this,"id");h(this,"userId");h(this,"name");h(this,"picture");h(this,"isHost");h(this,"customParticipantId");h(this,"flags");h(this,"device");h(this,"videoTrack");h(this,"audioTrack");h(this,"screenShareTracks");h(this,"videoEnabled");h(this,"audioEnabled");h(this,"screenShareEnabled");h(this,"producers");h(this,"manualProducerConfig");g(this,Gn,void 0);h(this,"supportsRemoteControl",!1);g(this,Wn,void 0);h(this,"presetName");g(this,wt,void 0);g(this,Bs,void 0);g(this,Jo,void 0);g(this,Or,new Map);g(this,Fs,1);g(this,jd,xh(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>fD&&n(this,Fs)===1?(m(this,Fs,0),n(this,wt).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,Fs)})):d<mD&&n(this,Fs)===0&&(m(this,Fs,1),n(this,wt).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,Fs)}))},2e3));m(this,wt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:p,flags:f,stageStatus:v,customParticipantId:E,audioMuted:R,audioTrack:A,videoEnabled:b=!1,videoTrack:V,producers:D,metadata:L}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=p,this.flags=f,this.manualProducerConfig=ZC,m(this,Wn,v!=null?v:"ON_STAGE"),this.customParticipantId=E,this.audioEnabled=!R,this.audioTrack=A,this.videoEnabled=b,this.videoTrack=V,this.screenShareTracks={audio:void 0,video:void 0},this.producers=D!=null?D:[],this.presetName=L==null?void 0:L.preset_name,m(this,Gn,!1),m(this,Bs,r),m(this,Jo,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),I(this,Ko,Ju).call(this)}get stageStatus(){return n(this,Wn)}get telemetry(){return n(this,wt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...ci(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...ci(this)}),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",I(this,Ko,Ju)),n(this,Dr,hn)&&(this.on("audioUpdate",I(this,Gd,eT)),this.on("screenShareUpdate",I(this,Wd,tT)))}async pin(){if(!n(this,Ri,za))throw new C("Can`t pin participant without joining room","1205");if(!n(this,Bs).permissions.pinParticipant)throw new C("You do not have permission to pin participants.","1201");return n(this,wi,Ka).pinPeer(this.id)}async unpin(){if(!n(this,Ri,za))throw new C("Can`t unpin participant without joining room","1205");if(!n(this,Bs).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.","1201");return n(this,wi,Ka).pinPeer(null)}setIsPinned(t,e=!0){var i;m(this,Gn,t);const r=t?"pinned":"unpinned";(i=n(this,bi,Ya))==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,Ri,za))throw new C("Can`t disable participant audio without joining room","1205");if(n(this,Bs).permissions.canDisableParticipantAudio)return n(this,wi,Ka).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info("Participant::kick",{participant:{id:t}}),!n(this,qd,Zf))throw new C("Can`t kick participant without joining room","1205");if(n(this,Bs).permissions.kickParticipant){await n(this,wt).getValue("peerSessionStore").emitAsync(_.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new C("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info("Participant::disable_video",{participant:{id:t}}),!n(this,Ri,za))throw new C("Can`t disable participant video without joining room","1205");if(n(this,Bs).permissions.canDisableParticipantVideo)return n(this,wi,Ka).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return n(this,Jo).getUserPermissions(this.userId)}setStageStatus(t){m(this,Wn,t),this.emit("stageStatusUpdate",this)}get isPinned(){return n(this,Gn)}registerVideoElement(t){var r,i,a,o;if(!t)return;let e;(i=(r=n(this,Or).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>n(this,jd).call(this,t)),e.observe(t)),n(this,Or).set(t,{observer:e}),this.updateVideo(t),(o=n(this,bi,Ya))==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,bi,Ya))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=n(this,Or).get(t))==null?void 0:r.observer)==null||i.disconnect(),n(this,Or).delete(t),(a=n(this,bi,Ya))==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"}},Gn=new WeakMap,Wn=new WeakMap,wt=new WeakMap,wi=new WeakSet,Ka=function(){return n(this,wt).getValue("roomNodeClient")},Dr=new WeakSet,hn=function(){return n(this,wt).getValue("audioPlayback")},Ri=new WeakSet,za=function(){return n(this,wt).getValue("connectionHandler").mediaJoined},qd=new WeakSet,Zf=function(){return n(this,wt).getValue("connectionHandler").socketJoined},Bs=new WeakMap,Jo=new WeakMap,Or=new WeakMap,bi=new WeakSet,Ya=function(){return n(this,wt).getValue("pip")},Fs=new WeakMap,jd=new WeakMap,Ko=new WeakSet,Ju=function(){Array.from(n(this,Or).keys()).forEach(this.updateVideo)},Gd=new WeakSet,eT=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=n(this,Dr,hn))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=n(this,Dr,hn))==null||e.removeParticipantTrack(this.id)},Wd=new WeakSet,tT=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=n(this,Dr,hn))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=n(this,Dr,hn))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},jg);ba([y.trace("Participant.disableAudio")],or.prototype,"disableAudio",1);ba([y.trace("Participant.kick")],or.prototype,"kick",1);ba([y.trace("Participant.disableVideo")],or.prototype,"disableVideo",1);ba([y.trace("Participant.getPermissions")],or.prototype,"getPermissions",1);ba([y.trace("Participant.setStageStatus")],or.prototype,"setStageStatus",1);or=ba([et("1200")],or);class Ja extends Bf{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 Nr;class TD extends Ca{constructor(e){super(e);g(this,Nr,void 0);m(this,Nr,new Map)}__set(e,r){return n(this,Nr).set(e,r)}__clear(){return n(this,Nr).clear()}get(e){return n(this,Nr).get(e)}toArray(){return Array.from(n(this,Nr).values())}}Nr=new WeakMap;class SD{constructor(){h(this,"_orderedArray");h(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 vD{constructor(){h(this,"_activeSpeakerPeers");h(this,"_compulsoryPeers");this._activeSpeakerPeers=new SD,this._compulsoryPeers=new Set}add(t,e,r){if(!t)return-1;if(e<0)return this._compulsoryPeers.add(t),0;const i=r.getValue("logger");if(this.compulsoryPeers.includes(t)&&(e>0||e===246267631)){if(i.info("SelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),e===246267631)return-1}else if(e===229490415)return this.delete(t,r),-1;return this._activeSpeakerPeers.add(t,e)}delete(t,e){const r=e==null?void 0:e.getValue("logger");r==null||r.info("SelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),this._activeSpeakerPeers.delete(t)}reassignPeer(t,e,r){const i=this._activeSpeakerPeers.index(t),a=this._compulsoryPeers.has(t);this.delete(t,r),a&&this.add(e,-1,r),i>=0&&this.add(e,i+1,r)}index(t){return this._activeSpeakerPeers.index(t)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(t){this._compulsoryPeers.delete(t)}}const sT=new vD;var yD=Object.defineProperty,ED=Object.getOwnPropertyDescriptor,Ms=(s,t,e,r)=>{for(var i=r>1?void 0:r?ED(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&&yD(t,e,i),i};const PD=["ACTIVE_GRID","PAGINATED","MANUAL"];var Ce,zo,Ku,ki,Qa,Jn,ld,Ai,gt,Gg;let Qt=(Gg=class extends Nt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,zo);g(this,ki);g(this,Jn);h(this,"waitlisted");h(this,"joined");h(this,"active");h(this,"videoSubscribed");h(this,"audioSubscribed");h(this,"pinned");h(this,"all");g(this,Ce,void 0);g(this,Ai,void 0);g(this,gt,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"viewMode");h(this,"currentPage");h(this,"lastActiveSpeaker");h(this,"selectedPeers",sT);m(this,Ce,t),m(this,Ai,e),m(this,gt,r),this.waitlisted=new Ja(i),this.joined=new Ja(i),this.videoSubscribed=new Ja(i),this.audioSubscribed=new Ja(i),this.active=this.videoSubscribed,this.pinned=new Ja(i),this.all=new TD(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return n(this,Ce).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return n(this,Ce).getValue("telemetry")}setupEvents(){n(this,Ce).getValue("peerSessionStore").on(_.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=n(this,Ce).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,Ce).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,Ce))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24","1203");n(this,Ce).setValue("maxPreferredStreams",t),n(this,Jn,ld)&&n(this,Ce).getValue("peerSessionStore").emit(_.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,ki,Qa))throw new C("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return n(this,gt).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,gt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!n(this,ki,Qa))throw new C("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;n(this,gt).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=>PD.includes(r))(t))throw this.logger.error("Participants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new C(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){this.logger.info("Participants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,n(this,Ce).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,n(this,Ce).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,n(this,Ce).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)))}),n(this,Ce).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!1},i.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(i.id)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!1},i.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(i.id)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1},i.manualProducerConfig.audio||this.audioSubscribed.delete(i.id)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1},i.manualProducerConfig.video||this.videoSubscribed.delete(i.id)))}),n(this,Ce).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}getPeerIdsForCurrentPage(){this.logger.info("Participants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(c=>this.joined.has(c)),r=Array.from(this.pinned.keys()).filter(c=>!e.includes(c)),i=Array.from(this.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),a=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),o=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(a,o))}async setPage(t){if(this.logger.info("Participants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw this.logger.error("Participants::invalid_page_number"),new C(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,n(this,Ce).getValue("peerSessionStore").emit(_.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,Jn,ld))throw new C("Can`t disable all audio without joining room","1205");if(n(this,Ai).permissions.canAllowParticipantAudio)return n(this,zo,Ku).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new C("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!n(this,Jn,ld))throw new C("Can`t disable all video without joining room","1205");if(n(this,Ai).permissions.canAllowParticipantVideo)return n(this,zo,Ku).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.","1201")}async kickAll(){if(this.logger.info("Participants::kick_all"),n(this,Ce).getValue("viewType")!=="LIVESTREAM"&&!n(this,ki,Qa))throw new C("Can`t kick all without joining room","1205");if(!n(this,Ai).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;n(this,gt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!n(this,ki,Qa))throw new C("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new C("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await n(this,gt).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,gt).broadcastToPeers(t,i,e)}else await n(this,gt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await n(this,gt).getRoomPeers(t,e,r)).peers.map(pr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(a=>t.includes(a.id)).map(a=>a.userId),i=[...new Set(r)];if(!i.length)throw new C("Cannot update permissions, no valid userIDs found","1204");n(this,gt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return n(this,gt).getRoomPeersNonPaginated()}},Ce=new WeakMap,zo=new WeakSet,Ku=function(){return n(this,Ce).getValue("roomNodeClient")},ki=new WeakSet,Qa=function(){var t;return((t=n(this,Ce).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Jn=new WeakSet,ld=function(){var t;return((t=n(this,Ce).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Ai=new WeakMap,gt=new WeakMap,Gg);Ms([y.trace("Participants.setViewMode")],Qt.prototype,"setViewMode",1);Ms([y.trace("Participants.setPage")],Qt.prototype,"setPage",1);Ms([y.trace("Participants.disableAllAudio")],Qt.prototype,"disableAllAudio",1);Ms([y.trace("Participants.disableAllVideo")],Qt.prototype,"disableAllVideo",1);Ms([y.trace("Participants.kickAll")],Qt.prototype,"kickAll",1);Ms([y.trace("Participants.broadcastMessage"),Lt(wa,"rateLimitConfig")],Qt.prototype,"broadcastMessage",1);Ms([y.trace("Participants.getAllJoinedPeers"),Lt({maxInvocations:10,period:60})],Qt.prototype,"getAllJoinedPeers",1);Ms([y.trace("Participant.updatePermissions"),Lt({maxInvocations:1e3,period:60})],Qt.prototype,"updatePermissions",1);Ms([y.trace("Participants.getParticipantsInMeetingPreJoin")],Qt.prototype,"getParticipantsInMeetingPreJoin",1);Qt=Ms([et("1200")],Qt);var _D=Object.defineProperty,CD=Object.getOwnPropertyDescriptor,on=(s,t,e,r)=>{for(var i=r>1?void 0:r?CD(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&&_D(t,e,i),i},jt,is,Lr,Wg;const rT=(Wg=class{constructor(s,t,e){h(this,"participants");h(this,"self");h(this,"selectedPeers",sT);h(this,"maxSpatialLayerUpdates",new Map);h(this,"consumerPeerMap");h(this,"events");h(this,"roomSocketHandler");h(this,"context");h(this,"videoPeerConsumerMap",new Map);g(this,jt,{mode:"ACTIVE_GRID",page:0});g(this,is,!1);g(this,Lr,!1);h(this,"updateConsumerSpatialLayers",xh(()=>{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));h(this,"updateConsumers",async(s,t,e=[])=>{this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${s.length}, RemoveProducers: ${t.length}, RemoveStaleConsumers: ${e.length}, ConsumersSyncing: ${n(this,is)}`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${s.length} producers: [${s.map(r=>r.producerId).join(", ")}]`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(r){this.logger.error("updateConsumers: Error creating consumers",{error:r})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers for ${t.length} producers: [${t.map(r=>r.producerId).join(", ")}]`),await this.roomNodeClient.closeConsumers(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(r){this.logger.error("updateConsumers: Error closing consumers",{error:r})}try{e.length!==0&&(this.logger.info(`updateConsumers: Closing ${e.length} stale consumers: [${e.join(", ")}]`),await this.roomNodeClient.closeConsumersById(e),this.logger.info("updateConsumers: Successfully closed stale consumers."))}catch(r){this.logger.error("updateConsumers: Error closing stale consumers",{error:r})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new Qt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=ds,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(x.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(_.SOCKET_PEERS,s=>{const t=this.participants.joined.size>0;this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.joined.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",t&&this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount}),s==null||s.forEach(e=>{e.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(e))})}),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.onParticipantMediaJoined(s.peerId,s.producerStates)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:s,selectedPeers:t,roomState:e})=>{s.forEach(({peerId:a,producerStates:o})=>this.onParticipantMediaJoined(a,o));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(_.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(_.MAX_SPATIAL_LAYER_CHANGE,({peerId:s,maxSpatialLayer:t})=>{const e=this.videoPeerConsumerMap.get(s);e&&(this.maxSpatialLayerUpdates.set(e,t),this.updateConsumerSpatialLayers())}),this.context.getValue("peerSessionStore").on(_.PRODUCER_HANDOVER,s=>this.handleProducerHandover(s)),this.context.getValue("peerSessionStore").on(_.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}const r=e.producers.find(({producerId:i})=>i===t.producerId);if(r){Object.assign(r,t);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,is)}, 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(_.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(_.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(_.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,is)}, 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 or(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(u=>u.stageStatus==="ON_STAGE").map(u=>(t.set(u.id,!0),u.id))),r=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((u,p)=>(p.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(p.id):u.push(p.id),u),[]),a=this.self.stageStatus==="ON_STAGE"?1:0,o=s-a,c=new Set(r.concat(i).filter(u=>u!==this.self.id&&t.has(u)));let d=Array.from(c);const l=o-c.size;if(l>=0){const u=e.filter(p=>!c.has(p)&&p!==this.self.id).slice(0,l);d=Array.from(c).concat(u)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(s,t){const{page:e}=t!=null?t:{};s&&n(this,jt).mode!==s&&(n(this,jt).mode=s),e&&n(this,jt).page!==e&&(n(this,jt).page=e);const{mode:r,page:i}=n(this,jt);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,jt))==null?void 0:e.mode)==="PAGINATED"&&!n(this,is)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=n(this,jt))==null?void 0:r.mode}, ConsumersSyncing: ${n(this,is)}, Delay: ${t}, Page: ${(i=n(this,jt))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var v,E,R,A,b,V;const s=this.context.getValue("connectionHandler");if((v=s==null?void 0:s.socketState)!=null&&v.state&&s.socketState.state!=="connected"){this.logger.info("syncConsumers: Socket not connected, deferring sync.");return}if(((R=(E=s==null?void 0:s.mediaState)==null?void 0:E.recv)==null?void 0:R.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(n(this,is)){m(this,Lr,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),m(this,is,!0),m(this,Lr,!1);let t=[];this.participants.videoSubscribed.forEach(D=>{var B,z;const L=this.participants.joined.get(D.id),U=(z=(B=D.producers)==null?void 0:B.filter(Q=>Q.kind==="video"))!=null?z:[];L&&(U!=null&&U.length)&&U.forEach(Q=>{var Et,k,S,P;const Ge=((k=(Et=L.manualProducerConfig)==null?void 0:Et.video)!=null?k:!0)&&Q.kind==="video"&&!Q.screenShare,tt=((P=(S=L.manualProducerConfig)==null?void 0:S.screenshareVideo)!=null?P:!0)&&Q.kind==="video"&&Q.screenShare;(Ge||tt)&&(Q.pause||t.push(Q))})}),this.participants.audioSubscribed.forEach(D=>{var B,z;const L=this.participants.joined.get(D.id),U=(z=(B=D.producers)==null?void 0:B.filter(Q=>Q.kind==="audio"))!=null?z:[];L&&(U!=null&&U.length)&&U.forEach(Q=>{var Et,k,S,P;const Ge=((k=(Et=L.manualProducerConfig)==null?void 0:Et.audio)!=null?k:!0)&&Q.kind==="audio"&&!Q.screenShare,tt=((P=(S=L.manualProducerConfig)==null?void 0:S.screenshareAudio)!=null?P:!0)&&Q.kind==="audio"&&Q.screenShare;(Ge||tt)&&t.push(Q)})}),t=XC(t,D=>D.producerId);const e=new Map;t.forEach(D=>{e.set(D.producerId,D)});const r=(b=(A=this.roomNodeClient)==null?void 0:A.getConsumers())!=null?b:new Map,i=new Map(Array.from(r.values()).map(D=>[D.producerId,D]));let a=t.filter(D=>!i.has(D.producerId));t.filter(D=>!D.consumer&&i.has(D.producerId)).forEach(D=>{const L=i.get(D.producerId);L&&(this.logger.info(`syncConsumers: remapping existing consumer ${L.id} to producer ${D.producerId}`),this.processNewConsumer(L.id))});let c=[],d=Array.from(r.values()).filter(D=>!this.participants.joined.has(D.peerId)).map(D=>D.id),l=Array.from(r.values()).filter(D=>this.participants.joined.has(D.peerId)).map(D=>D.peerId);l=QC(l),l==null||l.forEach(D=>{var U;const L=this.participants.joined.get(D);if(!L){this.logger.warn(`Peer with ${D} doesn't exist in joined list but producers of it are being consumed.`);return}(U=L.producers)!=null&&U.length&&L.producers.forEach(B=>{const z=B.consumer&&r.has(B.consumer.id);!e.has(B.producerId)&&(i.has(B.producerId)||z)&&c.push(B)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${a.length} [${a.map(D=>D.producerId).join(", ")}], RemoveProducers: ${c.length} [${c.map(D=>D.producerId).join(", ")}], RemoveStaleConsumers: ${d.length} [${d.join(", ")}]`.substring(0,5e3));const u=35,p=35;a.length>u&&(this.logger.warn(`syncConsumers: Too many remote producers to create consumers: ${a.length}. Only adding ${u} in this run.`),a=a.slice(0,u),this.scheduleSyncConsumers({source:"SOFT_CAPPED_CREATE_CONSUMERS"}));const f=d.length+c.length;f>p&&(this.logger.warn(`syncConsumers: Too many remote consumers to close: ${f}. Only removing ${p} in this run.`),d=d.slice(0,p),c=c.slice(0,p-d.length),this.scheduleSyncConsumers({source:"SOFT_CAPPED_REMOVE_CONSUMERS"}));try{a.length>0||c.length>0||d.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${a.length}, removing ${c.length}, and removing ${d.length} stale consumers.`),await this.updateConsumers(a,c,d),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(D){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:D})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),m(this,is,!1),(V=s==null?void 0:s.socketState)!=null&&V.state&&s.socketState.state!=="connected"&&m(this,Lr,!0)}n(this,Lr)&&(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=rT.formatSocketPeerMessage(s);return new or(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onParticipantMediaJoined(s,t){if(!this.mediaJoined||s===this.self.id)return;const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info("PEER_INFO:::SOCKET_ON_MEDIA_JOIN",{participant:{id:e.id,maskedName:[...(e==null?void 0:e.name)||""].map((r,i)=>i%2?"*":r).join("")}}),this.logger.info(`onParticipantMediaJoined: peer ${s} has joined media room. Processing.`),t.forEach(r=>{r.kind===ir.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===ir.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===ir.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType})}),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${s}`),this.context.getValue("peerSessionStore").emit(_.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)})}handleProducerHandover(s){const{oldPeerId:t,newPeerId:e,producerIds:r}=s;if(typeof t!="string"||typeof e!="string"||t===e||!Array.isArray(r)||r.length===0||r.some(u=>typeof u!="string")||e===this.self.id)return;const i=this.participants.joined.get(t),a=this.participants.joined.get(e);if(!i||!a||!i.userId||i.userId!==a.userId){this.logger.warn(`ParticipantController::producerHandover::participant validation failed from ${t} to ${e}`);return}this.selectedPeers.reassignPeer(t,e,this.context);const o=this.context.getValue("audioPlayback");o==null||o.reassignParticipantTrack(t,e),o==null||o.reassignParticipantTrack(`screenshare-${t}`,`screenshare-${e}`);const c=new Set(r),d=i.producers.filter(({producerId:u})=>c.has(u));if(d.length===0)return;d.some(u=>u.kind==="audio"&&!u.screenShare)&&(i.setAudioEnabled(!1),i.audioTrack=void 0),d.some(u=>u.screenShare)&&(i.setScreenShareEnabled(!1),i.screenShareTracks={audio:void 0,video:void 0}),a.manualProducerConfig={...i.manualProducerConfig},this.participants.videoSubscribed.has(t)&&(this.participants.videoSubscribed.delete(t),this.participants.videoSubscribed.add(a),this.participants.videoSubscribed.emit("participantsUpdate")),this.participants.audioSubscribed.has(t)&&(this.participants.audioSubscribed.delete(t,!1),this.participants.audioSubscribed.add(a,!1),this.participants.audioSubscribed.emit("participantsUpdate")),this.participants.pinned.has(t)&&(i.setIsPinned(!1),a.setIsPinned(!0),this.participants.pinned.delete(t),this.participants.pinned.add(a),this.participants.pinned.emit("participantsUpdate")),i.producers=i.producers.filter(({producerId:u})=>!c.has(u)),d.forEach(u=>{if(a.producers.some(({producerId:f})=>f===u.producerId))return;const p={...u};delete p.consumer,this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:e,producer:{...p,producingPeerId:e}})}),this.roomNodeClient.handoverPeerProducers(e,r).forEach(u=>{u.kind==="video"&&u.appData.screenShare!==!0&&this.videoPeerConsumerMap.get(t)===u.id&&(this.videoPeerConsumerMap.delete(t),this.updatePipSource(t,!1)),this.context.getValue("peerSessionStore").emit(_.NEW_CONSUMER_CREATED,{id:u.id,appData:u.appData,peerId:e})})}setupEventsGlobal(){this.roomSocketHandler.on(x.joinRoom,({peer:s})=>{s.waitlisted||(this.logger.info("Processing socket join",{peers:s.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),this.logger.info("Processed socket join",{peers:s.peerId}))}),this.roomSocketHandler.on(x.leaveRoom,async s=>{const{peerId:t}=s.peer;this.logger.info(`peer ${t} left the meeting. Removing it from selected peers`),this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(_.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(_.SOCKET_SERVICE_DISCONNECTED,()=>{m(this,Lr,!0),this.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),this.context.getValue("peerSessionStore").on(_.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(_.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(_.NEW_CONSUMER_CREATED,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(_.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(_.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(_.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(_.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(_.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(_.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(_.UPDATE_ACTIVE,({viewMode:s,page:t,createAllConsumers:e}={})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${n(this,jt).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(_.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(_.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){this.logger.info(`peer ${s} has left. Deleting peer from maps and closing consumers.`);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.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage}),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(_.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(_.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(_.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 u=i;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),this.logger.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:d,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:d,producerId:o}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track: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(_.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 u=this.participants.joined.get(e);if(!u)return;const p=u.producers.find(v=>v.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(_.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:d,track:a}),i.screenShare){r==="video"?u.screenShareTracks.video=a:r==="audio"&&(u.screenShareTracks.audio=a),u.setScreenShareEnabled(!0),(f=this.context)==null||f.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=a,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=a,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:a,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:a,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(p=>p.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:a,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(l.videoTrack=r,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1})):e==="audio"&&(l.audioTrack=r,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:l.audioEnabled}))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:i,appData:a,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:a,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(p=>p.producerId===o);if(u&&(u.consumer={id:s,peerId:t,kind:e,appData:a,paused:r,producerId:o,rtpReceiver:c,localId:d}),a.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),a.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:a,producerId:o}});return}e==="video"?(l.videoTrack=i,r||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!r})):e==="audio"&&(l.audioTrack=i,r||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!r})),!r&&a.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i}),this.context.getValue("peerSessionStore").emit(_.ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER,{appData:a,peerId:l.id})}static formatSocketPeerMessage(s){var e,r,i,a,o,c;if(!s)return;const t=qh(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(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},jt=new WeakMap,is=new WeakMap,Lr=new WeakMap,Wg);let pr=rT;on([y.trace("ParticipantController.setupEvents")],pr.prototype,"setupEvents",1);on([y.trace("ParticipantController.setupEvents")],pr.prototype,"setupEventsGlobal",1);on([y.trace("ParticipantController.processMedia")],pr.prototype,"processMedia",1);on([y.trace("ParticipantController.processConsumerClosed")],pr.prototype,"processConsumerClosed",1);on([y.trace("ParticipantController.processConsumerResumed")],pr.prototype,"processConsumerResumed",1);on([y.trace("ParticipantController.processConsumerPaused")],pr.prototype,"processConsumerPaused",1);on([y.trace("ParticipantController.processNewConsumer")],pr.prototype,"processNewConsumer",1);const Ee=ws($h().permissions);var J,Kn,zn,Jd,at,Pt;const Kd=class extends Nt{constructor(e,r,i,a=!1){const o=e.getValue("logger");super(o);g(this,at);g(this,J,void 0);g(this,Kn,void 0);g(this,zn,void 0);g(this,Jd,e=>{var l,u,p;const{chat:r,connectedMeetings:i,plugins:a,polls:o,media:c,...d}=e;if(r&&(r.private&&mr(n(this,J).chat.private,r.private),r.public&&mr(n(this,J).chat.public,r.public),this.emit("chatUpdate")),i&&mr(n(this,J).connectedMeetings,i),c){const f=E=>{switch(E){case Wr.NONE:return q.Allowed;case Wr.ALLOWED:return q.Allowed;case Wr.NOT_ALLOWED:return q.NotAllowed;case Wr.CAN_REQUEST:return q.CanRequest;default:return}},v={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(v.audio={canProduce:f(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(v.video={canProduce:f(c.video.canProduce)}),(p=c.screenshare)!=null&&p.canProduce&&(v.screenshare={canProduce:f(c.screenshare.canProduce)}),mr(n(this,J).media,v)}a&&(mr(n(this,J).plugins,a),this.emit("pluginsUpdate")),o&&(mr(n(this,J).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&mr(n(this,J),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.","0904");m(this,zn,e),m(this,Kn,i),m(this,J,r),a&&this.setupEvents()}setupEvents(){n(this,zn).getValue("peerSessionStore").on(_.UPDATE_PERMISSIONS,n(this,Jd))}static init(e,r,i){let a;return i?a=new Kd(e,i,r,!0):a=new Kd(e,Ee,r),a}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=n(this,J))==null?void 0:e.stageEnabled)||n(this,Kn)===rr.Webinar||n(this,Kn)===rr.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=n(this,J))==null?void 0:e.acceptStageRequests)||((r=n(this,J))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=n(this,J))==null?void 0:e.stageAccess)===q.NotAllowed?q.NotAllowed:((r=n(this,J))==null?void 0:r.stageAccess)===q.CanRequest?q.CanRequest:((i=n(this,J))==null?void 0:i.stageAccess)===q.Allowed||n(this,J).media.audio.canProduce===q.Allowed||n(this,J).media.video.canProduce===q.Allowed||n(this,J).media.screenshare.canProduce===q.Allowed?q.Allowed:n(this,J).media.audio.canProduce===q.CanRequest||n(this,J).media.video.canProduce===q.CanRequest||n(this,J).media.screenshare.canProduce===q.CanRequest?q.CanRequest:q.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=n(this,J))==null?void 0:e.acceptWaitingRequests)!=null?r:Ee.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=n(this,J))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===q.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=n(this,J))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===q.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=n(this,J))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===q.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=n(this,J))==null?void 0:e.disableParticipantAudio)!=null?r:Ee.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=n(this,J))==null?void 0:e.canAcceptProductionRequests)!=null?r:Ee.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=n(this,J))==null?void 0:e.disableParticipantVideo)!=null?r:Ee.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=n(this,J))==null?void 0:e.kickParticipant)!=null?r:Ee.kickParticipant}get pinParticipant(){var e,r;return(r=(e=n(this,J))==null?void 0:e.pinParticipant)!=null?r:Ee.pinParticipant}get canRecord(){var e,r;return(r=(e=n(this,J))==null?void 0:e.canRecord)!=null?r:Ee.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=n(this,J))==null?void 0:e.waitingRoomType)!=null?r:Ee.waitingRoomType}get plugins(){var e,r;return(r=(e=n(this,J))==null?void 0:e.plugins)!=null?r:Ee.plugins}get polls(){var e,r;return(r=(e=n(this,J))==null?void 0:e.polls)!=null?r:Ee.polls}get canProduceVideo(){var r;const e=(r=n(this,J).media.video.canProduce)!=null?r:Ee.media.video.canProduce;return this.stageEnabled&&(n(this,at,Pt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,at,Pt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(n(this,at,Pt)==="OFF_STAGE"||n(this,at,Pt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=n(this,J).media.screenshare.canProduce)!=null?r:Ee.media.screenshare.canProduce;return this.stageEnabled&&(n(this,at,Pt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,at,Pt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(n(this,at,Pt)==="OFF_STAGE"||n(this,at,Pt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get canProduceAudio(){var r;const e=(r=n(this,J).media.audio.canProduce)!=null?r:Ee.media.audio.canProduce;return this.stageEnabled&&(n(this,at,Pt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,at,Pt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(n(this,at,Pt)==="OFF_STAGE"||n(this,at,Pt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=n(this,J))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:Ee.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=n(this,J))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:Ee.chat.private}get connectedMeetings(){var e,r;return(r=(e=n(this,J))==null?void 0:e.connectedMeetings)!=null?r:Ee==null?void 0:Ee.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=n(this,J))==null?void 0:e.hiddenParticipant)!=null?r:Ee.hiddenParticipant}get showParticipantList(){var e;return(e=n(this,J).showParticipantList)!=null?e:Ee.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=n(this,J))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Ee.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=n(this,J).canEditDisplayName)!=null?e:!1}get isRecorder(){return n(this,J).isRecorder}get canSpotlight(){return n(this,J).canSpotlight}get canLivestream(){return n(this,J).canLivestream}get transcriptionEnabled(){return n(this,J).transcriptionEnabled}};let zu=Kd;J=new WeakMap,Kn=new WeakMap,zn=new WeakMap,Jd=new WeakMap,at=new WeakSet,Pt=function(){return n(this,zn).getValue("stageStatus")};var Rt;class iT extends Nt{constructor(e,r){super(r);h(this,"localMediaHandler");g(this,Rt,void 0);m(this,Rt,e)}async updatePermission(){var d,l;const e=(u,p)=>{this.mediaPermissions[u]=p;const f={message:this.mediaPermissions[u],kind:u};p==="DENIED"?n(this,Rt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_ERROR,f):n(this,Rt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,f)};if(me.getName()==="firefox")return;const r="microphone",i="camera",a=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),o=await((l=navigator==null?void 0:navigator.permissions)==null?void 0:l.query({name:i})),c=(u,p)=>{switch(p){case"granted":e(u,"ACCEPTED");break;case"denied":e(u,"DENIED");break;case"prompt":e(u,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};a&&(a.onchange=()=>c("audio",a.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,a,o,c;switch(r){case"audio":{(i=n(this,Rt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(a=n(this,Rt))==null||a.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=n(this,Rt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=n(this,Rt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=n(this,Rt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var a,o,c,d,l,u,p;if(me.init(),i&&m(this,Rt,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:v}=navigator;this.localMediaHandler=await v.init(e)}else this.localMediaHandler=new yt(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(_.MEDIA_PERMISSION_UPDATE,async v=>{if(this.populateMediaPermissionsInCallstats({message:v.message,kind:v.kind}),v.message==="NOT_REQUESTED")switch(v==null?void 0:v.kind){case"audio":this.rawAudioTrack&&(this.logger.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(this.logger.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",v)}),i==null||i.getValue("peerSessionStore").on(_.MEDIA_PERMISSION_ERROR,async v=>{const{kind:E,message:R,constraints:A}=v;this.populateMediaPermissionsInCallstats({message:R,kind:E}),E==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):E==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:R},constraints:A,mediaPermissionsErrors:{kind:E,message:R}}),this.emit("mediaPermissionError",v),this.emit("mediaPermissionUpdate",{message:R,kind:E})}),f){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const v=this.localMediaHandler.setupStreams({video:(u=e==null?void 0:e.video)!=null?u:!0,audio:(p=e==null?void 0:e.audio)!=null?p:!0});r||await v}}catch(f){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:f.name,message:f.message}})}}set context(e){m(this,Rt,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})}}Rt=new WeakMap;var wD=Object.defineProperty,RD=Object.getOwnPropertyDescriptor,pt=(s,t,e,r)=>{for(var i=r>1?void 0:r?RD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&wD(t,e,i),i},Yn,ot,Qn,Ve,qs,ii,xe,Ye,Xn,ud,Ae,Ie,Zn,ea,Yo,Yu,Jg;let je=(Jg=class extends iT{constructor(t,e,r,i,a){const o=t.getValue("logger");super(t,o);g(this,qs);g(this,xe);g(this,Xn);g(this,Ae);g(this,Yo);h(this,"name");h(this,"picture");h(this,"customParticipantId");h(this,"waitlistStatus");g(this,Yn,void 0);g(this,ot,void 0);g(this,Qn,void 0);h(this,"role");h(this,"userId");h(this,"organizationId");h(this,"supportsRemoteControl",!1);h(this,"device");g(this,Ve,void 0);h(this,"hidden",!1);h(this,"presetName");h(this,"roomState","init");g(this,Zn,new Set);g(this,ea,new Set);m(this,Ve,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",m(this,ot,r),m(this,Yn,i),this.hidden=!1,m(this,Qn,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=me.isElectron(),this.device=me.getDeviceInfo(),this.presetName=a,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),I(this,Yo,Yu).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,xe,Ye).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,v,E,R,A,b;let c=(v=(f=t.getValue("defaults"))==null?void 0:f.audio)!=null?v:!0,d=(R=(E=t.getValue("defaults"))==null?void 0:E.video)!=null?R:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new je(t,e,r,i,a),u=V0(i.mediaConstraints);mr(u,(A=t.getValue("defaults"))==null?void 0:A.mediaConfiguration);const p=(b=t.getValue("defaults"))==null?void 0:b.mediaHandler;return p&&(p.context=t),await l.init({audio:c,video:d,constraints:u},o,t),l.setupEvents(),l}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),n(this,ot).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",I(this,Yo,Yu));const t=n(this,Xn,ud);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...ci(this)}),n(this,Ae,Ie)&&this.audioEnabled)try{await n(this,xe,Ye).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",{...ci(this)}),n(this,Ae,Ie)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&n(this,Ae,Ie))try{await n(this,xe,Ye).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,Xn,ud))==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,Ae,Ie)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await n(this,xe,Ye).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",{...ci(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",{...ci(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,Ae,Ie)&&await n(this,xe,Ye).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=n(this,Ve))==null||e.getValue("callstats").videoOff()}),n(this,ot).on("permissionsUpdate",e=>{var r,i,a;(r=e==null?void 0:e.media)!=null&&r.audio&&n(this,ot).canProduceAudio!==q.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,ot).canProduceVideo!==q.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,ot).canProduceScreenshare!==q.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return n(this,ot)}get config(){return n(this,Yn)}get roomJoined(){var t;return n(this,Yn).viewType===rr.Livestream&&this.stageStatus!=="ON_STAGE"?((t=n(this,Ve).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:n(this,Ae,Ie)}setName(t){if(!t)throw new C("Name cannot be empty.","1103");this.name=t}async setupTracks(t={}){t.forceReset,await this.disableAudio(),await this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&await this.enableAudio(),t.video&&await this.enableVideo()}async destructMediaHandler(){return this.localMediaHandler.destruct()}async removeDocumentEventListeners(){return this.localMediaHandler.removeDocumentEventListeners()}async enableAudio(t){var e;if(this.permissions.canProduceAudio!==q.NotAllowed&&!(n(this,ot).canProduceAudio===q.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,Ae,Ie)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await n(this,xe,Ye).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,ot).canProduceVideo!==q.NotAllowed&&!(n(this,ot).canProduceVideo===q.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,Ae,Ie)&&this.stageStatus==="ON_STAGE")try{await n(this,xe,Ye).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",{...ci(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!n(this,Ae,Ie))throw new C("Can`t enable screenshare without joining room","1105");if(n(this,ot).canProduceScreenshare!==q.NotAllowed&&!(n(this,ot).canProduceScreenshare===q.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,xe,Ye).shareScreen(this.screenShareTracks)}catch(t){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),n(this,Ae,Ie)&&n(this,xe,Ye).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,Ae,Ie)&&await n(this,xe,Ye).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,Ae,Ie)&&await n(this,xe,Ye).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;m(this,Qn,t);const r=t?"pinned":"unpinned";(i=n(this,qs,ii))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return n(this,Qn)}async pin(){if(!n(this,Ae,Ie))throw new C("Can`t pin participants without joining room","1105");return this.show(),n(this,xe,Ye).pinPeer(this.id)}async unpin(){if(!n(this,Ae,Ie))throw new C("Can`t unpin participants without joining room","1105");return n(this,xe,Ye).pinPeer(null)}async hide(){if(!n(this,Ae,Ie))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!n(this,Ae,Ie))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,a;if(!t)throw new C("No device selected","1104");const e=this.getCurrentDevices();switch(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((i=e==null?void 0:e.video)==null?void 0:i.deviceId)===t.deviceId||((a=e==null?void 0:e.speaker)==null?void 0:a.deviceId)===t.deviceId)&&this.logger.warn("Self.setDevice.setting_to_in_use_device",{devices:[t]}),t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){n(this,Ae,Ie)&&await n(this,xe,Ye).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,Ae,Ie)&&await n(this,xe,Ye).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,Xn,ud))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?n(this,Zn).add(t):n(this,ea).add(t),this.updateVideo(t),e||(i=n(this,qs,ii))==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,qs,ii).removeSource(this.id);return}t.srcObject=void 0,e?n(this,Zn).delete(t):(n(this,ea).delete(t),n(this,qs,ii).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,qs,ii))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(a=n(this,qs,ii))==null||a.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Yn=new WeakMap,ot=new WeakMap,Qn=new WeakMap,Ve=new WeakMap,qs=new WeakSet,ii=function(){return n(this,Ve).getValue("pip")},xe=new WeakSet,Ye=function(){return n(this,Ve).getValue("roomNodeClient")},Xn=new WeakSet,ud=function(){return n(this,Ve).getValue("audioPlayback")},Ae=new WeakSet,Ie=function(){var t;return((t=n(this,Ve).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Zn=new WeakMap,ea=new WeakMap,Yo=new WeakSet,Yu=function(){Array.from(n(this,ea)).forEach(t=>this.updateVideo(t,!1)),Array.from(n(this,Zn)).forEach(t=>this.updateVideo(t,!0))},Jg);pt([y.trace("Self.cleanupEvents")],je.prototype,"cleanupEvents",1);pt([y.trace("Self.setupEvents")],je.prototype,"setupEvents",1);pt([y.trace("Self.setupTracks")],je.prototype,"setupTracks",1);pt([y.trace("Self.destructMediaHandler")],je.prototype,"destructMediaHandler",1);pt([y.trace("Self.removeDocumentEventListeners")],je.prototype,"removeDocumentEventListeners",1);pt([hr.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.enableAudio")],je.prototype,"enableAudio",1);pt([hr.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.enableVideo")],je.prototype,"enableVideo",1);pt([y.trace("Self.updateVideoConstraints")],je.prototype,"updateVideoConstraints",1);pt([y.trace("Self.enableScreenShare"),hr.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],je.prototype,"enableScreenShare",1);pt([y.trace("Self.updateScreenshareConstraints")],je.prototype,"updateScreenshareConstraints",1);pt([hr.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.disableAudio")],je.prototype,"disableAudio",1);pt([hr.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.disableVideo")],je.prototype,"disableVideo",1);pt([hr.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),y.trace("Self.disableScreenShare")],je.prototype,"disableScreenShare",1);pt([y.trace("Self.setDevice")],je.prototype,"setDevice",1);je=pt([et("1100")],je);class Yh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Yh)}}class Qh extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Qh)}}var Qo;class Qu{constructor(t,e=!1){h(this,"pendingTasks",new Map);h(this,"nextTaskId",0);h(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 Yh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new Qh)}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;class _o extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,_o):this.stack=new Error(t).stack}}class vt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,vt):this.stack=new Error(t).stack}}class Er extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,vt):this.stack=new Error(t).stack}}const Pg=s=>new Promise(t=>setTimeout(t,s));async function nT(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:a,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=p=>{l=!0,r(p)};for(;c<a;){try{const p=await s(c,u);return e(p)}catch(p){if(d=p,l)break;if(c<a)i==="linear"?await Pg(o*(c+1)):i==="exponential"&&await Pg(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function bD(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function kD(s){return s.map(t=>({uri:t.uri}))}function sd(s){return{codecs:bD(s.codecs),headerExtensions:kD(s.headerExtensions?s.headerExtensions:[])}}function AD(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:sd(t),video:sd(e)};return{sender:{audio:sd(r),video:sd(i)},receiver:a}}var Xo;class Yl extends ht.EventEmitter{constructor(e){super();g(this,Xo,void 0);m(this,Xo,e),this.setMaxListeners(1/0)}get logger(){return n(this,Xo).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)}})}}Xo=new WeakMap;function MD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}var Zo,Mi,fs,zd,Ts,Tr,ec,Xu,Yd,aT,Qd,oT;class ID extends Yl{constructor(e,r){var i;super(e);g(this,Ts);g(this,ec);g(this,Yd);g(this,Qd);h(this,"rtpReceiver");h(this,"id");h(this,"localId");h(this,"producerId");h(this,"producingTransportId");h(this,"mimeType");h(this,"track");h(this,"peerId");h(this,"appData");h(this,"transceiver");g(this,Zo,void 0);g(this,Mi,void 0);g(this,fs,void 0);g(this,zd,void 0);this.id=r.id,this.localId=r.localId,m(this,Zo,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,m(this,fs,!1),this.producerId=r.producerId,this.track=r.track,m(this,Mi,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,I(this,Yd,aT).call(this),m(this,zd,e)}get closed(){return n(this,fs)}get kind(){return this.track.kind}get paused(){return n(this,Mi)}reassignPeer(e){this.peerId=e}close(e,r){n(this,fs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,n(this,Ts,Tr)),m(this,fs,!0),r&&(I(this,Qd,oT).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(n(this,fs))throw new vt("closed");return n(this,Zo).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",n(this,Ts,Tr)),n(this,fs)){this.logger.error("consumer::pause() | Consumer closed",n(this,Ts,Tr));return}m(this,Mi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",n(this,Ts,Tr)),n(this,fs)){this.logger.error("Consumer::resume() | Consumer closed",n(this,Ts,Tr));return}m(this,Mi,!1),this.track.enabled=!0,this.safeEmit("resume")}}Zo=new WeakMap,Mi=new WeakMap,fs=new WeakMap,zd=new WeakMap,Ts=new WeakSet,Tr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},ec=new WeakSet,Xu=function(){this.logger.debug('Consumer::track "ended" event',n(this,Ts,Tr)),this.safeEmit("trackended")},Yd=new WeakSet,aT=function(){this.track.addEventListener("ended",I(this,ec,Xu).bind(this))},Qd=new WeakSet,oT=function(){try{this.track.removeEventListener("ended",I(this,ec,Xu)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...n(this,Ts,Tr),error:e})}};var ns,ta,sa,Ii,Gt,Ke,Vr,ra,Xd,bt,Xt;class DD extends Yl{constructor(e,r){var i,a;super(e);g(this,bt);h(this,"id");h(this,"localId");g(this,ns,void 0);h(this,"kind");h(this,"appData");h(this,"rtpSender");g(this,ta,void 0);g(this,sa,void 0);g(this,Ii,void 0);g(this,Gt,!1);g(this,Ke,void 0);g(this,Vr,void 0);g(this,ra,void 0);g(this,Xd,void 0);this.id=r.id,this.localId=r.localId,m(this,Ke,r.track),this.kind=(i=r.track)==null?void 0:i.kind,m(this,Vr,r.disableTrackOnPause?!((a=r.track)!=null&&a.enabled):!1),m(this,ra,void 0),m(this,ta,r.stopTracks),m(this,sa,r.disableTrackOnPause),m(this,Ii,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),m(this,ns,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),m(this,Xd,e)}get closed(){return n(this,Gt)}get track(){return n(this,Ke)}get paused(){return n(this,Vr)}get maxSpatialLayer(){return n(this,ra)}async close(e){if(n(this,Gt))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,n(this,bt,Xt)),m(this,Gt,!0),this._destroyTrack(),e===Ad){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await n(this,ns).stopSending(this.localId),{answer:a}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(a)}async getStats(){if(n(this,Gt))throw new vt("closed");return n(this,ns).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",n(this,bt,Xt)),n(this,Gt)&&this.logger.error("Producer::pause() | Producer closed",n(this,bt,Xt)),m(this,Vr,!0),n(this,Ke)&&n(this,sa)&&(n(this,Ke).enabled=!1),n(this,Ii)&&n(this,ns).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",n(this,bt,Xt)),n(this,Gt)){this.logger.error("Producer::resume() | Producer closed",n(this,bt,Xt));return}m(this,Vr,!1),n(this,Ke)&&n(this,sa)&&(n(this,Ke).enabled=!0),n(this,Ii)&&n(this,ns).replaceTrack(this.localId,n(this,Ke)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,n(this,bt,Xt)),n(this,Gt)){if(e&&n(this,ta))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...n(this,bt,Xt),error:r})}throw new vt("closed")}else if(e&&e.readyState==="ended")throw new vt("track ended");if(e===n(this,Ke)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,n(this,bt,Xt));return}(!n(this,Ii)||!n(this,Vr))&&await n(this,ns).replaceTrack(this.localId,e),this._destroyTrack(),m(this,Ke,e),this._handleTrack()}async setMaxSpatialLayer(e){if(n(this,Gt))throw new vt("closed");if(this.kind!=="video")throw new _o("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await n(this,ns).setMaxSpatialLayer(this.localId,e),m(this,ra,e)}async setRtpEncodingParameters(e){if(n(this,Gt))throw new vt("closed");if(typeof e!="object")throw new TypeError("invalid params");await n(this,ns).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,n(this,bt,Xt)),this.safeEmit("trackended",this.track.id)}_handleTrack(){n(this,Ke)&&n(this,Ke).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(n(this,Ke))try{n(this,Ke).removeEventListener("ended",this._onTrackEnded),n(this,ta)&&n(this,Ke).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...n(this,bt,Xt),error:r})}}}ns=new WeakMap,ta=new WeakMap,sa=new WeakMap,Ii=new WeakMap,Gt=new WeakMap,Ke=new WeakMap,Vr=new WeakMap,ra=new WeakMap,Xd=new WeakMap,bt=new WeakSet,Xt=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};const Ad="transport closed";var ia;const Sn=class extends Yl{constructor(e,{id:r,direction:i,handlerFactory:a,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:p}){var R,A,b;super(e);h(this,"awaitQueue");h(this,"observer");h(this,"id");h(this,"serverId");h(this,"direction");h(this,"maxSctpMessageSize");h(this,"handler");h(this,"connectionState","new");h(this,"producers");h(this,"consumers");h(this,"connected",!1);h(this,"transportConnectionPromise");h(this,"consumerTrackEvents");h(this,"unknownTracksMap");h(this,"appData");g(this,ia,void 0);m(this,ia,e);const f=e.getValue("logger");f.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const v=MD(l,{});delete v.iceServers,delete v.iceTransportPolicy,delete v.bundlePolicy,delete v.rtcpMuxPolicy,delete v.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Qu(f,!0),this.handler=a(),this.handler.enableHighBitrate=(R=p==null?void 0:p.enableHighBitrate)!=null?R:!1,this.handler.enableStereo=(A=p==null?void 0:p.enableStereo)!=null?A:!1,this.handler.enableDtx=(b=p==null?void 0:p.enableDtx)!=null?b:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const E=3e4;this.transportConnectionPromise=new Promise(V=>{const D=setTimeout(()=>{f.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),V(!1)},E);this.once("connected",()=>{clearTimeout(D),V(!0)}),this.once("disconnect",()=>{clearTimeout(D),V(!1)}),this.once("close",()=>{clearTimeout(D),V(!1)})}),this.handler.on("@connectionstatechange",V=>{V!==this.connectionState&&(this.logger.debug(`connection state changed to ${V}`),this.connectionState=V,V==="connected"&&(this.connected=!0,this.emit("connected")),V==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(V==="failed"||V==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",V))}),this.handler.on("@icecandidate",({candidate:V})=>{this.closed||this.safeEmit("icecandidate",V)})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId!==e&&(this.serverId=e,this.emit("serveridchange",e))}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(Ad).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Ad)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new vt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:a,answer:o}=await e(r);this.setServerId(a),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new vt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new _o("not a sending Transport");if(r.readyState==="ended")throw new vt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Er("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:a,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:p={}}=e;this.logger.debug(`produce() [track:${a.id}]`);const{producerId:f,localId:v,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:R,callback:A,sender:b,mid:V}=await this.handler.send({track:a,encodings:o,codecOptions:c,screenShare:p==null?void 0:p.screenShare}),{answer:D,producerId:L}=await r({offer:R,kind:a.kind,paused:l?!a.enabled||Object.hasOwn(a,"fakeTracks"):!1,appData:{...p||{},mid:V},codecOptions:c,producingTransportId:this.serverId}),U=await A(D);return{producerId:L,localId:U,rtpSender:b}},"Transport.produce");return this.createProducerObject({id:f,localId:v,track:a,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:p,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new DD(n(this,ia),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new vt("closed");if(this.direction!=="recv")throw new _o("not a receiving transport");if(!await this.transportConnectionPromise)throw new Er("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const a={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,p)=>{a[p]=this.createConsumerObjectAndWaitForTrack({...u,producerId:p})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(a).map(([u,p])=>p.then(f=>l.push(f)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=Zt.parse(e.sdp),a={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(a[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),a}static setCodecAndFmtpMappings(e,r,i){const a=Zt.parse(e.sdp);return a.media=a.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:Zt.write(a)}}static parseHeaderExtensionMappings(e){const r=Zt.parse(e.sdp),i={};return r.media.forEach(a=>{i[a.mid]=a.ext}),i}static setHeaderExtensionMappings(e,r){const i=Zt.parse(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:Zt.write(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),a=Sn.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Sn.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=Sn.setCodecAndFmtpMappings(c,i,a),c=Sn.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=Zt.parse(r.sdp);return i.media=i.media.map(a=>{if(a.type==="audio"){const o={...a},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return a}),r.sdp=Zt.write(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const a=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(a)});const o=this.consumerTrackEvents.get(a);o?(o(r,i),this.consumerTrackEvents.delete(a)):(this.logger.warn(`track event handler not found ${a}`),this.unknownTracksMap.set(a,e))}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:a,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:p,mimeType:f}=e,v=`${c}:${p}`,E={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(R,A)=>{const b=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${v} producingPeerId: ${a}`),this.consumerTrackEvents.delete(v),E.isTimedout=!0,A(E)},5e3),V=(L,U)=>{try{if(L.readyState==="ended")clearTimeout(b),A(E);else{const B=L;B.enabled=!0,this.handler.midTransceiverMap.set(U.mid,U);const z=new ID(n(this,ia),{id:r,localId:U.mid,transceiver:U,track:B,paused:d,producerId:i,producingPeerId:a,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:a},rtpReceiver:U.receiver,mimeType:f});this.consumers.set(r,z),z.once("close",()=>{this.consumers.delete(z.id),this.handler.midTransceiverMap.delete(U.mid)}),this.logger.info(`consumer created for peerId: ${a} of kind: ${p} with screenShare: ${l}`,{consumer:{id:r,kind:p,appData:{screenShare:l},peerId:a,producerId:i}}),this.emit("newconsumer",z),clearTimeout(b),R(z)}}catch(B){this.logger.warn("error while creating consumer:",B),clearTimeout(b),A(E)}},D=this.unknownTracksMap.get(v);D?(this.logger.info(`track event already received [trackId: ${D.track.id}] [mid: ${D.transceiver.mid}]`),this.unknownTracksMap.delete(v),V(D.track,D.transceiver)):(this.logger.info(`Registering onTrack handler for key ${v} [producingPeerId: ${a}]`),this.consumerTrackEvents.set(v,V))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}};let Zu=Sn;ia=new WeakMap;var Ue;class OD{constructor(t){g(this,Ue,void 0);h(this,"events");m(this,Ue,t),this.events=ds}async joinRoom(t,e,r,i=!1){const a={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await n(this,Ue).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:aR.toBinary(a),timeout:5e3})).payload}async connectTransport(t){const e=(await n(this,Ue).sendMessagePromise(this.events.createWebRTCTransport,Nw.toBinary(t))).payload,{transportId:r,description:i,producerIds:a}=ff.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,Ue).sendMessagePromise(this.events.produce,ER.toBinary(t))).payload,r=sb.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,Ue).sendMessagePromise(this.events.consume,mR.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=eb.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await n(this,Ue).sendMessagePromise(this.events.closeProducer,kR.toBinary(t))).payload,{description:r}=db.fromBinary(e);return r}async closeConsumer(t){return(await n(this,Ue).sendMessagePromise(this.events.closeConsumer,MR.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await n(this,Ue).sendMessagePromise(this.events.updateConsumersSimulcastConfig,vR.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await n(this,Ue).sendMessagePromise(this.events.hostControlPeer,VR.toBinary(r))).payload;if(!i)return!1;const{status:a}=fb.fromBinary(i);return a==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await n(this,Ue).sendMessagePromise(this.events.hostControlAllPeers,UR.toBinary(e))).payload;if(!r)return!1;const{status:i}=Sb.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};n(this,Ue).sendMessagePromise(x.kickAll,yf.toBinary(t))}async kickPeer(t){n(this,Ue).sendMessagePromise(x.kick,wf.toBinary(t))}async changeDisplayName(t){const e=(await n(this,Ue).sendMessagePromise(this.events.changeDisplayName,NR.toBinary(t))).payload;if(!e)return!1;const{status:r}=yb.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await n(this,Ue).sendMessagePromise(this.events.selfJoinComplete,cR.toBinary(t))).payload;return Au.fromBinary(e)}async audioActivity(t){n(this,Ue).sendMessage(this.events.audioActivity,Vw.toBinary(t))}}Ue=new WeakMap;var Pr=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Pr||{});class Xh extends Yl{constructor(){super(...arguments);h(this,"_sendWebStream",new MediaStream);h(this,"_sendScreenShareStream",new MediaStream);h(this,"_direction");h(this,"pc");h(this,"_transportReady",!1);h(this,"_mapMidTransceiver",new Map);h(this,"enableHighBitrate",!1);h(this,"enableStereo",!1);h(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(this.logger.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){this.logger.error(`${this.name}::pc.close()`,{error:e})}}async restartIce(){this.logger.debug(`${this.name}::restartIce()`);const e=await this.pc.createOffer({iceRestart:!0});return this.logger.debug(`[SDP] ${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`[SDP] ${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:a,proprietaryConstraints:o,onTrackHandler:c}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},o),c&&this.pc.addEventListener("track",d=>{c(d)}),this._addEventListeners()}async connect(){this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly",...this._direction==="send"?{sendEncodings:[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]}:{}});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`[SDP] connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`[SDP] ${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}async getTransportStats(){return this.pc.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}async stopSending(e){this._assertSendDirection(),this.logger.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this.pc.removeTrack(r.sender),r.direction="inactive";const i=await this.pc.createOffer();return this.logger.debug(`[SDP] stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`[SDP] stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(o)}]`),await this.pc.setRemoteDescription(o),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");await i.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters();a.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(a)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters();a.encodings.forEach((o,c)=>{a.encodings[c]={...o,...r}}),await i.sender.setParameters(a)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class Zh extends Xh{static createFactory(t){return()=>new Zh(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:a,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},a),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const a=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const d=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`senders available params: ${JSON.stringify(d)}`);const l=[];r&&r.length&&r.forEach(u=>{var f;const p=d.codecs.find(v=>v.mimeType.includes(u.name));if(u.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(u.parameters)}`);const v=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];v.push(...u.parameters);const E=Array.from(new Set(v).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,u=this.enableHighBitrate?l?128e3:64e3:l?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${d?"usedtx=1;":""}${l?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${u}`),o.sdp+=`a=rtcp-fb:111 nack\r
|
|
9
|
-
`}this.midTransceiverMap.set(a.mid,a);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),a.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:a.sender,mid:a.mid}}}class Md extends Xh{constructor(e,r){super(e);h(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Md(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:a}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[a?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const p=c.sender.getParameters();p.encodings=r,await c.sender.setParameters(p)}const d=(p,f)=>{var D;const v=Zt.parse(p),E=v.media[v.media.length-1],R=E.rtp.filter(L=>f.some(U=>U.name===L.codec)),A=E.fmtp.filter(L=>R.some(U=>U.payload===L.payload)),b=(D=E.rtcpFb)==null?void 0:D.filter(L=>R.some(U=>U.payload===L.payload)),V=R.map(L=>L.payload);return v.media[v.media.length-1].rtp=R,v.media[v.media.length-1].fmtp=A,v.media[v.media.length-1].rtcpFb=b,v.media[v.media.length-1].payloads=V.join(" "),Zt.write(v)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:p,enableStereo:f}=this,v=this.enableHighBitrate?f?128e3:64e3:f?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${f?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async p=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(p)}]`),await this.pc.setRemoteDescription(p),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters(),o=a.encodings.length-1-r;a.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(a)}}class ep extends Xh{static createFactory(t){return()=>new ep(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const a=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var f;const p=o.codecs.find(v=>v.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const v=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];v.push(...u.parameters);const E=[...new Set(v).values()];p.sdpFmtpLine=E.join(";")}c.push(p)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),a.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:p}=this,f=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${f}`)}return this.midTransceiverMap.set(a.mid,a),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),a.mid),sender:a.sender,mid:a.mid}}}function ND(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Qg.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}var js,Di;class LD{constructor(t,{handlerName:e,handlerFactory:r}={}){h(this,"handlerFactory");g(this,js,void 0);g(this,Di,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),m(this,js,t),m(this,Di,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)n(this,Di).debug(`Device::constructor() | handler given: ${e}`);else if(e=ND(n(this,Di)),e)n(this,Di).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Zh.createFactory(n(this,js));break;case"Safari12":this.handlerFactory=ep.createFactory(n(this,js));break;case"Firefox60":this.handlerFactory=Md.createFactory(n(this,js),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Md.createFactory(n(this,js),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=Qr.v4();return new Zu(n(this,js),{id:e,...t,handlerFactory:this.handlerFactory})}}js=new WeakMap,Di=new WeakMap;const VD=2e3;var na,$e,He,tc,sc,Oi,aa,rc,oa,Ni,Ss,ca,hd,ic,eh,Zd,cT,nc,th,el,dT,tl,lT,sl,uT,rl,hT,il,pT,ac,sh,xr,pn;class xD extends ht.EventEmitter{constructor(e,r){super();g(this,ca);g(this,ic);g(this,Zd);g(this,nc);g(this,el);g(this,tl);g(this,sl);g(this,rl);g(this,il);g(this,ac);g(this,xr);h(this,"context");g(this,na,void 0);g(this,$e,void 0);g(this,He,void 0);g(this,tc,void 0);g(this,sc,void 0);g(this,Oi,void 0);g(this,aa,void 0);g(this,rc,void 0);g(this,oa,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,Ni,void 0);g(this,Ss,"all");this.context=e,m(this,Oi,r),m(this,na,new LD(e)),m(this,aa,new OD(r)),m(this,rc,ds),n(this,ca,hd).mediaState={send:{state:Pr.NEW},recv:{state:Pr.NEW}},Eo(this.context,"forceRelay")&&m(this,Ss,"relay"),this.logger.info(`ICE Transport Policy initially set to ${n(this,Ss)}`),I(this,ic,eh).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return n(this,Oi)}get socketHandler(){return n(this,aa)}get sendTransport(){return n(this,$e)}get recvTransport(){return n(this,He)}get events(){return n(this,rc)}set sendTransportConnectedCallback(e){m(this,tc,e)}set recvTransportConnectedCallback(e){m(this,sc,e)}async setupTransports(e){await I(this,Zd,cT).call(this,e);let r,i;e.send&&(r=I(this,nc,th).call(this,n(this,$e)).then(a=>{try{n(this,tc).call(this,a)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=I(this,nc,th).call(this,n(this,He)).then(a=>{try{n(this,sc).call(this,a)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,$e);this.logger.info("Closing send transport",{transport:{id:a,serverId:o,type:c}}),n(this,$e).close(),n(this,$e).removeAllListeners(),m(this,$e,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,He);this.logger.info("Closing recv transport",{transport:{id:a,serverId:o,type:c}}),(r=n(this,He))==null||r.close(),(i=n(this,He))==null||i.removeAllListeners(),m(this,He,void 0)}I(this,ic,eh).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}na=new WeakMap,$e=new WeakMap,He=new WeakMap,tc=new WeakMap,sc=new WeakMap,Oi=new WeakMap,aa=new WeakMap,rc=new WeakMap,oa=new WeakMap,Ni=new WeakMap,Ss=new WeakMap,ca=new WeakSet,hd=function(){return this.context.getValue("connectionHandler")},ic=new WeakSet,eh=function(){m(this,Ni,{send:void 0,recv:void 0})},Zd=new WeakSet,cT=async function(e){var o,c,d,l,u,p,f,v;Eo(this.context,"forceRelay")&&m(this,Ss,"relay"),this.logger.info(`ICE Transport Policy set to ${n(this,Ss)}`);const a=await It().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&I(this,tl,lT).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(f=(p=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:p.enableStereo)!=null?f:!1,enableDtx:!1},iceTransportPolicy:n(this,Ss)}),e.recv&&I(this,sl,uT).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(v=this.context.getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:n(this,Ss)})},nc=new WeakSet,th=async function(e){const{id:r,serverId:i,direction:a}=e;I(this,rl,hT).call(this,e);try{return await nT(async(c,d)=>{c>0&&this.logger.info(`Retrying ${a} transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:a}});try{if(e.closed)throw new Er("Cannot reconnect closed transport");await I(this,el,dT).call(this,e)}catch(l){if(l instanceof Er){this.logger.error(`Failed to connect ${a} transport. It will not be retried.`,{transport:e,error:l}),d(l);return}throw this.logger.error(`Failed to connect ${a} transport, retrying`,{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect ${a} transport after retries: ${e.id}. Transport reconnection will not be retried.`,{error:o,transport:{id:r,serverId:i,type:a}}),e.close(),e.removeAllListeners(),o}},el=new WeakSet,dT=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!n(this,Oi).isConnected)throw new Er("Socket is not connected");if(e.connectionState==="closed")throw new Er("Transport is closed");try{await e.connect(a=>I(this,il,pT).call(this,i,a)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(a){throw n(this,oa).transportFailureCount[i]+=1,a.message==="ice connection failed"?new Er(a.message):a}},tl=new WeakSet,lT=function(e){var r,i;if(n(this,$e)&&n(this,$e).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=n(this,$e))==null?void 0:r.id,serverId:(i=n(this,$e))==null?void 0:i.serverId,type:"send"}});return}m(this,$e,n(this,na).createTransport({...e,direction:"send"})),I(this,xr,pn).call(this,{state:Pr.NEW,direction:"send",sfuSessionId:n(this,$e).serverId}),this.context.getValue("callstats").configureSendTransport(n(this,$e))},sl=new WeakSet,uT=function(e){var r,i;if(n(this,He)&&n(this,He).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=n(this,He))==null?void 0:r.id,serverId:(i=n(this,He))==null?void 0:i.serverId,type:"recv"}});return}m(this,He,n(this,na).createTransport({...e,direction:"recv"})),I(this,xr,pn).call(this,{state:Pr.NEW,direction:"recv",sfuSessionId:n(this,He).serverId}),this.context.getValue("callstats").configureRecvTransport(n(this,He))},rl=new WeakSet,hT=function(e){const{direction:r,id:i}=e;e.on("serveridchange",a=>{I(this,xr,pn).call(this,{state:e.connectionState,direction:r,sfuSessionId:a})}),e.on("connectionstatechange",async a=>{I(this,xr,pn).call(this,{state:a,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:a}});const o=()=>{const c=n(this,Ni)[r];c!==void 0&&(clearTimeout(c),n(this,Ni)[r]=void 0)};switch(a){case"connected":o(),n(this,oa).lastConnectionTime=performance.now();break;case"disconnected":n(this,Ni)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await I(this,ac,sh).call(this,e.direction)},VD);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await I(this,ac,sh).call(this,e.direction);break}}),e.on("icecandidate",async a=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:a})})},il=new WeakSet,pT=async function(e,r){const i=e==="recv";try{const{sdp:a,type:o}=r,c={consuming:i,description:{sdp:a,type:o,target:i?ar.SUBSCRIBER:ar.PUBLISHER},producers:[]};return n(this,aa).connectTransport(c)}catch(a){throw this.logger.error(`Error in ${e} transport connection:`,{error:a}),a}},ac=new WeakSet,sh=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),n(this,Oi).isConnected&&n(this,oa).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),m(this,Ss,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:n(this,$e)}),this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:n(this,He)}),this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?n(this,$e):n(this,He);I(this,xr,pn).call(this,{state:Pr.CONNECTED,direction:e,sfuSessionId:r.serverId})},xr=new WeakSet,pn=function(e){const{state:r,direction:i,sfuSessionId:a}=e;n(this,ca,hd).mediaState[i]={state:r,sfuSessionId:a},this.context.getValue("peerSessionStore").emit(_.TRANSPORT_STATE_UPDATE,{transport:i,...n(this,ca,hd).mediaState[i]})};var nl,Wt;class UD{constructor(t,e,r,i,a){g(this,nl,void 0);g(this,Wt,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=a,m(this,nl,t),m(this,Wt,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:p}=d,f={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:p,...f})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),a=new Map;t.forEach(d=>a.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=a.get(d);if(!u)return;if(l.errorCode){n(this,Wt).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let p={};try{p=JSON.parse(l.producerState.appData)}catch(f){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:p})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{n(this,Wt).info("Negotiating socket consumer",{transport:this.recvTransport}),n(this,Wt).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:ar.SUBSCRIBER}};return n(this,Wt).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,$w.toBinary(r)),n(this,Wt).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){n(this,Wt).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return;const e=async(r,i)=>{const a=r.map(l=>l.localId);n(this,Wt).info(`Closing consumers: ${JSON.stringify(a)}`);const o={description:{sdp:i.sdp,type:i.type,target:ar.SUBSCRIBER},consumerIds:a,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=ub.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"SocketConsumerStrategy.close",{consumersLength:t.length})}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(a=>a&&a.id);i.forEach(({id:a,producingTransportId:o,localId:c})=>{r.requests.push({producerId:a,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),n(this,Wt).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:a})=>a)})}}nl=new WeakMap,Wt=new WeakMap;class tp{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return Zt.parse(t).media.filter(a=>e==="video"?a.type==="video":a.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:a,producingTransportId:o}){var p,f;const c=tp.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:ar.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(p=i.screenShare)!=null?p:!1,mimeType:`${e}/${(f=a[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function $D(s){try{const t=JSON.parse(s.message);if(typeof t!="object"||t===null)return{};const{errorCode:e,errorDescription:r}=t;return{...typeof e=="string"&&{errorCode:e},...typeof r=="string"&&{errorDescription:r}}}catch(t){return{}}}var Li,Ur,da,oc,vs,al,Gs,la,cc,rh,ol,gT,cl,mT,dl,fT,ll,TT;class HD extends xD{constructor(e,r){super(e,r);g(this,cc);g(this,ol);g(this,cl);g(this,dl);g(this,ll);g(this,Li,void 0);g(this,Ur,void 0);g(this,da,void 0);g(this,oc,void 0);g(this,vs,void 0);g(this,al,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,Gs,[]);g(this,la,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{m(this,oc,new tp(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{n(this,da).clear(),m(this,vs,new UD(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return n(this,Li)}get consumers(){return n(this,Ur)}get producerIdToConsumerIdMap(){return n(this,da)}get logger(){return this.context.getValue("logger")}reset(){m(this,Li,new Map),m(this,Ur,new Map),m(this,da,new Map)}async createProducer(e,r){var i,a;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,I(this,ol,gT).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,o),I(this,cl,mT).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((a=e==null?void 0:e.track)==null?void 0:a.kind)||"unknown"} producer`,{error:o}),n(this,al).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var a;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),(a=this.context.getValue("modules").e2ee)!=null&&a.enabled&&this.context.getValue("peerSessionStore").emit(_.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}}closeAllProducers(){return Promise.all(Array.from(n(this,Li).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){n(this,la)||clearTimeout(n(this,la)),m(this,Gs,n(this,Gs).concat(e)),await I(this,cc,rh).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!n(this,vs))return;const r=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);r.length!==0&&await n(this,vs).close(r)}closeAllConsumers(){return this.closeConsumers(Array.from(n(this,Ur).keys()))}async switchConsumersToLayer(e,r){n(this,vs).switchConsumersToLayer(e,r)}}Li=new WeakMap,Ur=new WeakMap,da=new WeakMap,oc=new WeakMap,vs=new WeakMap,al=new WeakMap,Gs=new WeakMap,la=new WeakMap,cc=new WeakSet,rh=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=n(this,Gs).splice(0,n(this,Gs).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),a=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(a.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(a,I(this,dl,fT).bind(this),n(this,vs).negotiate.bind(n(this,vs)));if(o.forEach(I(this,ll,TT).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);m(this,Gs,n(this,Gs).concat(d)),m(this,la,setTimeout(I(this,cc,rh).bind(this),e))}}catch(i){const a=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:a});const{errorCode:o,errorDescription:c}=$D(a);if(o==="internal_error"&&c==="Backend error"||o==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:o,message:c}});try{this.stopTransports({recv:!0})}catch(d){}await this.setupTransports({recv:!0})}}},ol=new WeakSet,gT=function(e){return n(this,oc).create(e)},cl=new WeakSet,mT=function(e,r){e.on("close",async(i,a)=>{const{reason:o}=i,{offer:c}=i;if(this.logger.info("producer::closing",{debuggingHint:o,producer:{...e,status:"closing"}}),o!==Ad){const d={producerId:e.id,description:{sdp:c.sdp,type:c.type,target:ar.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),a({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),n(this,Li).set(e.id,e)},dl=new WeakSet,fT=async function(e){try{return await this.recvTransport.canConsume(),await n(this,vs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},ll=new WeakSet,TT=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),n(this,Ur).delete(e.id),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:e.id})}),n(this,Ur).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(_.NEW_CONSUMER_CREATED,{id:e.id,appData:e.appData,peerId:e.peerId})};var dc,lc,uc,ua,ha,pa,hc,pc,ga,mt,as,os,Vi,xi,Ws,gc,ul,ST,hl,vT,pl,yT,gl,ET;const ml=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:a=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,ul);g(this,hl);g(this,dc,void 0);g(this,lc,void 0);g(this,uc,void 0);g(this,ua,void 0);g(this,ha,void 0);g(this,pa,void 0);g(this,hc,void 0);g(this,pc,void 0);g(this,ga,void 0);g(this,mt,void 0);g(this,as,void 0);g(this,os,!1);g(this,Vi,0);g(this,xi,0);g(this,Ws,[]);g(this,gc,void 0);m(this,ua,t),m(this,mt,t),m(this,dc,e),m(this,lc,r),m(this,uc,i),m(this,ha,a),m(this,pa,o),m(this,hc,c),m(this,pc,d),m(this,ga,l),m(this,gc,u),m(this,as,t/2)}get voiceDetected(){return n(this,os)}processAudioChunk(t){var o,c;const e=I(o=ml,pl,yT).call(o,t),r=I(c=ml,gl,ET).call(c,t);return I(this,ul,ST).call(this,e),e/n(this,as)>n(this,ga)&&e>n(this,mt)&&r>n(this,dc)?(m(this,Vi,n(this,Vi)+1),m(this,xi,n(this,uc)),n(this,Vi)>=n(this,lc)&&m(this,os,!0)):(m(this,Vi,0),n(this,xi)>0?m(this,xi,n(this,xi)-1):n(this,os)&&m(this,os,!1),n(this,os)||I(this,hl,vT).call(this,e)),{energy:e,isVoice:n(this,os)}}reset(){m(this,os,!1),m(this,Vi,0),m(this,xi,0),m(this,mt,n(this,ua)),m(this,as,n(this,ua)/2),m(this,Ws,[])}getThresholdInfo(){return{currentEnergyThreshold:n(this,mt),backgroundNoiseEnergy:n(this,as),energyRatioThreshold:n(this,ga)}}};let Xa=ml;dc=new WeakMap,lc=new WeakMap,uc=new WeakMap,ua=new WeakMap,ha=new WeakMap,pa=new WeakMap,hc=new WeakMap,pc=new WeakMap,ga=new WeakMap,mt=new WeakMap,as=new WeakMap,os=new WeakMap,Vi=new WeakMap,xi=new WeakMap,Ws=new WeakMap,gc=new WeakMap,ul=new WeakSet,ST=function(t){n(this,os)?m(this,mt,n(this,pa)*n(this,mt)+(1-n(this,pa))*t):m(this,mt,n(this,ha)*n(this,mt)+(1-n(this,ha))*n(this,as)),m(this,mt,Math.max(n(this,hc),Math.min(n(this,pc),n(this,mt))))},hl=new WeakSet,vT=function(t){if(t<n(this,mt)*1.2)if(n(this,Ws).push(t),n(this,Ws).length>n(this,gc)&&n(this,Ws).shift(),n(this,Ws).length>=10){const e=[...n(this,Ws)].sort((i,a)=>i-a),r=Math.floor(e.length/2);m(this,as,e[r])}else m(this,as,.95*n(this,as)+.05*t)},pl=new WeakSet,yT=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},gl=new WeakSet,ET=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},g(Xa,pl),g(Xa,gl);var mc;class _g{constructor(t){h(this,"RNAudioSampleHandler");g(this,mc,void 0);m(this,mc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return n(this,mc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}mc=new WeakMap;var fc;class Cg{constructor(t){h(this,"audioContext");h(this,"analyser");g(this,fc,void 0);m(this,fc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return n(this,fc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}fc=new WeakMap;class PT{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const BD=60,FD=400;var Js,Ks,zs,Tc,ma,fa,$r,Ui,Ta,$i,Ys,ys,Sc,ih,fl,_T,vc,nh,yc,ah,Tl,CT;const go=class{constructor(t,e){g(this,Sc);g(this,fl);g(this,yc);g(this,Js,void 0);g(this,Ks,void 0);g(this,zs,void 0);g(this,Tc,void 0);g(this,ma,void 0);g(this,fa,void 0);g(this,$r,void 0);g(this,Ui,void 0);g(this,Ta,void 0);g(this,$i,void 0);g(this,Ys,void 0);g(this,ys,void 0);this.reportRequest=e,m(this,$i,t),m(this,fa,new Xa);const{isReactNative:r}=navigator;m(this,Ys,r?new _g(n(this,$i)):new Cg(n(this,$i))),m(this,ys,r?PT:io)}get logger(){return n(this,$i).getValue("logger")}set producerId(t){m(this,zs,t)}set audioTrack(t){m(this,Tc,t),n(this,Ys)instanceof Cg&&(n(this,Ys).audioTrack=t)}start(t=!1){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${n(this,zs)}`),n(this,Js)&&n(this,ys).clearInterval(n(this,Js)),m(this,Js,n(this,ys).setInterval(I(this,Sc,ih).bind(this),BD)),n(this,Ks)&&n(this,ys).clearInterval(n(this,Ks)),m(this,Ks,n(this,ys).setInterval(I(this,yc,ah).bind(this),FD)),t&&(I(this,Sc,ih).call(this),I(this,yc,ah).call(this))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${n(this,zs)}`),n(this,Js)&&(n(this,ys).clearInterval(n(this,Js)),m(this,Js,void 0)),n(this,Ks)&&(n(this,ys).clearInterval(n(this,Ks)),m(this,Ks,void 0))}catch(t){}n(this,fa).reset(),n(this,Ys)instanceof _g&&n(this,Ys).stop()}};let Za=go;Js=new WeakMap,Ks=new WeakMap,zs=new WeakMap,Tc=new WeakMap,ma=new WeakMap,fa=new WeakMap,$r=new WeakMap,Ui=new WeakMap,Ta=new WeakMap,$i=new WeakMap,Ys=new WeakMap,ys=new WeakMap,Sc=new WeakSet,ih=function(){var i;if(!n(this,Tc)||!n(this,zs))return;const{energy:t}=I(this,fl,_T).call(this),e=I(i=go,vc,nh).call(i,t);let r=.9;n(this,Ta)!==e&&n(this,Ta)?r=.9:e?r=.3:r=.5,m(this,ma,(n(this,ma)||0)*(1-r)+t*r)},fl=new WeakSet,_T=function(){var o;const{samples:t}=n(this,Ys),{energy:e,isVoice:r}=n(this,fa).processAudioChunk(t),i=I(o=go,Tl,CT).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,$r)||i<n(this,$r))&&m(this,$r,i),(!n(this,Ui)||i>n(this,Ui))&&m(this,Ui,i),{energy:(i-n(this,$r))/(n(this,Ui)-n(this,$r))*10||0,isVoice:r})},vc=new WeakSet,nh=function(t){return t<5},yc=new WeakSet,ah=function(t=n(this,ma)){var r;if(!n(this,zs)||!t)return;const e={producerId:n(this,zs),energy:Math.round(t),silent:I(r=go,vc,nh).call(r,t)};m(this,Ta,e.silent),this.reportRequest(e)},Tl=new WeakSet,CT=function(t){const e=Math.log10(t);return Math.round(e)},g(Za,vc),g(Za,Tl);var qD=Object.defineProperty,jD=Object.getOwnPropertyDescriptor,ie=(s,t,e,r)=>{for(var i=r>1?void 0:r?jD(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&&qD(t,e,i),i},Ec,Pc,Ze,H,Sl,ct,Hi,Bi,Fi,_c,kt,Qs,dt,ft,Xs,ni,vl,wT,yl,RT,El,bT,Cc,oh,Pl,kT,_l,AT,ze,st,qi,eo,Cl,MT,wl,IT,Rl,DT,bl,OT;class se{constructor(t,e){g(this,Xs);g(this,vl);g(this,yl);g(this,El);g(this,Cc);g(this,Pl);g(this,_l);g(this,ze);g(this,qi);g(this,Cl);g(this,wl);g(this,Rl);g(this,bl);h(this,"context");h(this,"authToken");h(this,"e2ee");g(this,Ec,void 0);g(this,Pc,void 0);g(this,Ze,void 0);g(this,H,void 0);g(this,Sl,void 0);g(this,ct,void 0);g(this,Hi,void 0);g(this,Bi,void 0);g(this,Fi,void 0);g(this,_c,void 0);g(this,kt,null);g(this,Qs,void 0);g(this,dt,void 0);g(this,ft,void 0);var i,a;this.context=t;const{socket:r}=e;this.mediaJoined=!1,m(this,Ze,r),m(this,Hi,!1),m(this,H,new HD(t,r)),m(this,ct,n(this,H).events),m(this,Qs,new Set),m(this,dt,new Map),m(this,Bi,!1),m(this,Fi,new Qu(t.getValue("logger"))),m(this,ft,new Za(this.context,n(this,H).socketHandler.audioActivity.bind(n(this,H).socketHandler))),this.e2ee=(a=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?a:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,_c,xh(async()=>{if(!n(this,Xs,ni).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(n(this,Pc),n(this,Ec),!0);o&&(this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(_.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,Xs,ni).mediaJoined}set mediaJoined(t){n(this,Xs,ni).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),n(this,H).closeAllProducers(),n(this,H).closeAllConsumers(),n(this,dt).clear(),n(this,Qs).clear(),m(this,kt,null),t&&n(this,Fi).stop(),n(this,H).stopAllTransports(),n(this,H).reset(),t&&m(this,Fi,new Qu)}async joinRoom(t,e,r=!1,i={}){n(this,Xs,ni).mediaJoinAttempted=!0,m(this,Hi,!0);try{return await n(this,Fi).push(()=>I(this,vl,wT).call(this,t,e,r,i),"joinRoom")}catch(a){return this.logger.error("Error in room joining process",{error:a}),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_FAILED),{roomJoined:!1,error:a}}}async initializeConnection(t,e,r=!1,i={}){return n(this,kt)?n(this,kt):(m(this,kt,(async()=>{try{await I(this,Cc,oh).call(this,t,e,r,i)}catch(a){throw m(this,kt,null),a}})()),n(this,kt))}getConsumers(){return n(this,H).consumers}getProducers(){return n(this,H).producers}handoverPeerProducers(t,e){const r=new Set(e);return Array.from(n(this,H).consumers.values()).filter(i=>r.has(i.producerId)?(i.reassignPeer(t),!0):!1)}async leaveRoom(){n(this,H).stopAllTransports(),m(this,Bi,!1),n(this,Xs,ni).mediaJoinAttempted=!1;const t={closeRoom:!1};try{n(this,Ze).sendMessage(n(this,ct).leaveRoom,lR.toBinary(t))||this.logger.warn("MediaNodeClient.leaveRoom: media leave was not sent")}catch(r){this.logger.error("MediaNodeClient.leaveRoom: media leave failed",{error:r})}this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(r=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:r})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():n(this,H).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const a=n(this,H).producerIdToConsumerIdMap.get(i.producerId);return a?(r.push(a),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await this.closeConsumersById(e)}async closeConsumersById(t){t.length&&await n(this,H).closeConsumers(t)}async _shareWebcam(t){var u,p,f,v;const e=Te.WEBCAM,r=I(this,ze,st).call(this,e);if(r){const E=await r;if(n(this,H).producers.has(E)){const R=n(this,H).producers.get(E);if(!R.closed)return await R.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=I(this,bl,OT).call(this,t),a=Eo(this.context,"disableSimulcast"),o=(p=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:p.simulcastConfig;a||o&&o.disable||!((v=(f=this.context)==null?void 0:f.getValue("theme"))!=null&&v.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=N0(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,dt).delete(e)},l=n(this,H).createProducer(i,d);return I(this,qi,eo).call(this,e,l.then(E=>E.id)),l.then(E=>E.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i=await I(this,ze,st).call(this,Te.SCREENSHARE_VIDEO),a=await I(this,ze,st).call(this,Te.SCREENSHARE_AUDIO),o=n(this,H).producers.get(i),c=n(this,H).producers.get(a),d=[];if(o&&!o.closed)d.push(o.replaceTrack({track:e}));else{const l={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:me.isElectron()},stopTracks:!1},u=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,dt).delete(Te.SCREENSHARE_VIDEO),n(this,dt).delete(Te.SCREENSHARE_AUDIO)},p=n(this,H).createProducer(l,u);I(this,qi,eo).call(this,Te.SCREENSHARE_VIDEO,p.then(f=>f.id)),d.push(p)}if(r)if(c&&!c.closed)d.push(c.replaceTrack({track:r}));else{const l={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:me.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},u=()=>{},p=n(this,H).createProducer(l,u);I(this,qi,eo).call(this,Te.SCREENSHARE_AUDIO,p.then(f=>f.id)),d.push(p)}await Promise.all(d),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new vt("track undefined");const e=I(this,ze,st).call(this,Te.MIC);if(e){const o=await e;if(n(this,H).producers.has(o)){const c=n(this,H).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),n(this,ft)&&(n(this,ft).audioTrack=t,n(this,ft).producerId=o,n(this,ft).start(!0));return}await n(this,H).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=I(this,Rl,DT).call(this,t),i=()=>{n(this,dt).delete(Te.MIC)},a=n(this,H).createProducer(r,i);I(this,qi,eo).call(this,Te.MIC,a.then(o=>o.id)),await a.then(o=>{n(this,ft)&&(n(this,ft).audioTrack=o.track,n(this,ft).producerId=o.id,n(this,ft).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await I(this,ze,st).call(this,Te.MIC),e=n(this,H).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=n(this,ft))==null||i.stop();const r={producerId:e.id,pause:!0};n(this,Ze).sendMessage(n(this,ct).toggleProducer,Qc.toBinary(r))}async pauseWebcam(){const t=await I(this,ze,st).call(this,Te.WEBCAM),e=n(this,H).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};n(this,Ze).sendMessage(n(this,ct).toggleProducer,Qc.toBinary(r))}async resumeMic(){const t=await I(this,ze,st).call(this,Te.MIC),e=n(this,H).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,Ze).sendMessage(n(this,ct).toggleProducer,Qc.toBinary(r))}async resumeWebcam(t=Te.WEBCAM){const e=await I(this,ze,st).call(this,t),r=n(this,H).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};n(this,Ze).sendMessage(n(this,ct).toggleProducer,Qc.toBinary(i))}async disableWebcam(){const t=Te.WEBCAM,e=await I(this,ze,st).call(this,t);I(this,Cl,MT).call(this,t),e&&await n(this,H).closeProducer(e)}async disableMic(){var e;const t=await I(this,ze,st).call(this,Te.MIC);t&&await n(this,H).closeProducer(t),(e=n(this,ft))==null||e.stop(),n(this,dt).delete(Te.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await I(this,ze,st).call(this,Te.SCREENSHARE_VIDEO),e=await I(this,ze,st).call(this,Te.SCREENSHARE_AUDIO);t&&await n(this,H).closeProducer(t),e&&await n(this,H).closeProducer(e),n(this,Qs).clear(),n(this,dt).delete(Te.SCREENSHARE_VIDEO),n(this,dt).delete(Te.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await I(this,ze,st).call(this,Te.WEBCAM);await n(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await I(this,ze,st).call(this,Te.SCREENSHARE_VIDEO);await n(this,H).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await n(this,H).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};n(this,H).socketHandler.kickPeer(e)}kickAll(){n(this,H).socketHandler.kickAll()}async muteAll(t){if(!await n(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await n(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await n(this,H).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await n(this,H).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await n(this,Ze).sendMessagePromise(n(this,ct).globalPinPeer,CR.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&n(this,H).producers.get(t.producerId)&&n(this,Qs).add(t.consumerPeerId),n(this,Qs).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));n(this,H).switchConsumersToLayer(r,e)}async handleSocketEvents(){n(this,Ze).on(n(this,ct).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{I(this,wl,IT).call(this,bb.fromBinary(t))}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),n(this,Ze).on(n(this,ct).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const e=tg.fromBinary(t),{participantId:r,initiatorParticipantId:i,producerState:{kind:a,pause:o,producerId:c,screenShare:d}}=e;if(d)return;const l=a===ir.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${r}, producerId: ${c}, kind:${l}, paused:${o} payload: ${tg.toJsonString(e)}`),r===this.peerId&&i!==this.peerId&&o&&this.context.getValue("peerSessionStore").emit(l==="audio"?_.MUTE_SELF:_.MUTE_SELF_VIDEO),r===this.peerId)return;this.context.getValue("peerSessionStore").emit(_.PRODUCER_TOGGLE,{peerId:r,producerId:c,paused:o,kind:l}),Array.from(this.getConsumers().values()).filter(p=>p.producerId===c).forEach(p=>{p.kind==="video"&&o||p.paused!==o&&(this.logger.debug(`consumer state mismatched for ${p.id}. updating consumer pause state ${p.paused} to ${o}`),o?(p.pause(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_PAUSED,{id:p.id})):(p.resume(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_RESUMED,{id:p.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),n(this,Ze).on(n(this,ct).peerLeaveBroadcast,async({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Mu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),n(this,Qs).delete(e),n(this,H).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(_.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),n(this,Ze).on(n(this,ct).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=Mb.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(_.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=n(this,H).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),n(this,H).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),n(this,H).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:i})}).catch(a=>{this.logger.error("error closing consumer",{error:a})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),n(this,Ze).on(n(this,ct).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,Hi)&&!n(this,Bi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_DISCONNECTED),n(this,_c).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=n(this,H).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(_.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(n(this,H).producers.values()).find(a=>a.id===r);i&&this.context.getValue("peerSessionStore").emit(_.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}Ec=new WeakMap,Pc=new WeakMap,Ze=new WeakMap,H=new WeakMap,Sl=new WeakMap,ct=new WeakMap,Hi=new WeakMap,Bi=new WeakMap,Fi=new WeakMap,_c=new WeakMap,kt=new WeakMap,Qs=new WeakMap,dt=new WeakMap,ft=new WeakMap,Xs=new WeakSet,ni=function(){return this.context.getValue("connectionHandler")},vl=new WeakSet,wT=async function(t,e,r,i){var o;m(this,Pc,t);let a=!1;if(r){const{recv:c,send:d}=(o=n(this,Xs,ni).mediaState)!=null?o:{};(d==null?void 0:d.state)===Pr.CONNECTED&&(c==null?void 0:c.state)===Pr.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — preserving all producers for ownership handover"),m(this,kt,null),a=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{n(this,kt)?await n(this,kt):await I(this,Cc,oh).call(this,t,e,r,i,a),I(this,El,bT).call(this,e);const{joined:c,error:d}=await I(this,yl,RT).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{m(this,kt,null)}},yl=new WeakSet,RT=async function(){try{this.mediaJoined=!0;const{roomState:t}=await n(this,H).socketHandler.notifySelfJoinComplete();return m(this,Ec,t.roomUuid),m(this,Bi,!0),m(this,Hi,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},El=new WeakSet,bT=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...me.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Cc=new WeakSet,oh=async function(t,e,r,i,a=!1){try{const o=I(this,Pl,kT).call(this);await I(this,_l,AT).call(this,t,e,r,o),a?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await n(this,H).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},Pl=new WeakSet,kT=function(){const t=AD("video/VP8");return m(this,Sl,t),t},_l=new WeakSet,AT=async function(t,e,r,i){await nT(async(a,o)=>{if(!n(this,Ze).isConnected){o(new Error("Socket is not connected"));return}a>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${a}`});try{await n(this,H).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},ze=new WeakSet,st=function(t){return n(this,dt).get(t)},qi=new WeakSet,eo=function(t,e){return n(this,dt).set(t,e)},Cl=new WeakSet,MT=function(t){return n(this,dt).delete(t)},wl=new WeakSet,IT=function({participantId:t,producerState:e,producerHandoverFromPeerId:r}){var o;const i=r;if(i&&i!==t&&(e!=null&&e.producerId)&&(this.logger.info(`Producer handover detected from ${i} to ${t} for producer id ${e.producerId}`),this.context.getValue("peerSessionStore").emit(_.PRODUCER_HANDOVER,{oldPeerId:i,newPeerId:t,producerIds:[e.producerId]})),t===this.peerId||!e)return;const a=(o=e.mimeType)!=null?o:e.kind===ir.AUDIO?"audio/opus":"video/VP8";this.logger.info(`producer created broadcast: ${t}, producer state: ${e}`),this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:t,producer:{...e,mimeType:a,kind:e.kind===ir.AUDIO?"audio":"video",producingPeerId:t}})},Rl=new WeakSet,DT=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},bl=new WeakSet,OT=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};ie([y.trace("MediaNodeClient.reset")],se.prototype,"reset",1);ie([y.trace("MediaNodeClient.joinRoom")],se.prototype,"joinRoom",1);ie([y.trace("MediaNodeClient.leaveRoom")],se.prototype,"leaveRoom",1);ie([y.trace("MediaNodeClient.activatePeers")],se.prototype,"activatePeers",1);ie([y.trace("MediaNodeClient.createConsumers")],se.prototype,"createConsumers",1);ie([y.trace("MediaNodeClient.closeConsumers")],se.prototype,"closeConsumers",1);ie([y.trace("MediaNodeClient.closeConsumersById")],se.prototype,"closeConsumersById",1);ie([y.trace("MediaNodeClient._shareWebcam")],se.prototype,"_shareWebcam",1);ie([y.trace("MediaNodeClient.shareWebcam")],se.prototype,"shareWebcam",1);ie([y.trace("MediaNodeClient.shareScreen")],se.prototype,"shareScreen",1);ie([y.trace("MediaNodeClient.shareMic")],se.prototype,"shareMic",1);ie([y.trace("MediaNodeClient.pauseMic")],se.prototype,"pauseMic",1);ie([y.trace("MediaNodeClient.pauseWebcam")],se.prototype,"pauseWebcam",1);ie([y.trace("MediaNodeClient.resumeMic")],se.prototype,"resumeMic",1);ie([y.trace("MediaNodeClient.resumeWebcam")],se.prototype,"resumeWebcam",1);ie([y.trace("MediaNodeClient.disableWebcam")],se.prototype,"disableWebcam",1);ie([y.trace("MediaNodeClient.disableMic")],se.prototype,"disableMic",1);ie([y.trace("MediaNodeClient.disableScreenShare")],se.prototype,"disableScreenShare",1);ie([y.trace("MediaNodeClient.muteSelf")],se.prototype,"muteSelf",1);ie([y.trace("MediaNodeClient.resetVideoProducers")],se.prototype,"resetVideoProducers",1);ie([y.trace("MediaNodeClient.changeDisplayName")],se.prototype,"changeDisplayName",1);ie([y.trace("MediaNodeClient.kickPeer")],se.prototype,"kick",1);ie([y.trace("MediaNodeClient.kickAllPeers")],se.prototype,"kickAll",1);ie([y.trace("MediaNodeClient.muteAll")],se.prototype,"muteAll",1);ie([y.trace("MediaNodeClient.muteAllVideo")],se.prototype,"muteAllVideo",1);ie([y.trace("MediaNodeClient.disableAudio")],se.prototype,"disableAudio",1);ie([y.trace("MediaNodeClient.disableVideo")],se.prototype,"disableVideo",1);ie([y.trace("MediaNodeClient.pinPeer")],se.prototype,"pinPeer",1);ie([y.trace("MediaNodeClient.validateScreenShare")],se.prototype,"validateScreenShare",1);function NT(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 se(s,t);return s.setValue("roomNodeClient",r),r}function GD(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 WD=Object.defineProperty,JD=Object.getOwnPropertyDescriptor,cn=(s,t,e,r)=>{for(var i=r>1?void 0:r?JD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&WD(t,e,i),i},wc,Jt,X,Tt,xt,Kg;const LT=(Kg=class{constructor(s,t,e,r){g(this,Tt);h(this,"self");h(this,"authToken");g(this,wc,void 0);h(this,"viewType");g(this,Jt,void 0);g(this,X,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,X,s),this.viewType=r,this.authToken=a,m(this,wc,i),m(this,Jt,e),this.setupEvents()}get peerId(){return n(this,X).getValue("peerId")}get telemetry(){return n(this,X).getValue("telemetry")}get logger(){return n(this,X).getValue("logger")}get mediaJoined(){return n(this,X).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=It(),o=!!s.getValue("cachedUserDetails"),c=await je.__init__(s,e,r,i,i.name,o);s.setValue("self",c);const d=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const u=await c.getAllDevices();d.info("populated_full_device_list",{devices:JSON.stringify(u)}),s.getValue("callstats").devices("AUDIO",u==null?void 0:u.filter(p=>p.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",u==null?void 0:u.filter(p=>p.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",u==null?void 0:u.filter(p=>p.kind==="audiooutput")),d.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:s.getValue("peerId"),engineName:me.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:d,apiHostnames:sw(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),t.socket.updateCallstatsPeerId(s.getValue("peerId")),d.info("Callstats:: initialized")}catch(p){d.error("Callstats:: initialization failed",{error:p})}},0):d.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new LT(s,c,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===q.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await n(this,Tt,xt).shareMic(s),this.self.audioEnabled||n(this,Tt,xt).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===q.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await n(this,Tt,xt).shareWebcam(t),this.self.videoEnabled||n(this,Tt,xt).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===q.Allowed&&a){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=n(this,Tt,xt))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){n(this,X).getValue("callstats").callEnded(),s?(this.logger.info("Resetting Self post reconnect. Peer has earlier tried joining the meeting. State cleanup will be done during room rejoin."),await this.joinRoom(s)):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),n(this,Tt,xt).reset({resetTransportQueue:!0}))}setupEvents(){n(this,X).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&await this.shareMediaTracks()}),n(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s).catch(t=>{this.logger.error("Failed to reset self after socket reconnection",{error:t})})}),n(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_FAILED,()=>{this.logger.error("Socket reconnection failed after exhausting all attempts. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Jt).on(x.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,Jt).on(ad.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,X).getValue("peerSessionStore").emit(_.UPDATE_PERMISSIONS,t.patch)})}),n(this,Jt).on(x.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,Jt).on(x.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,Jt).on(x.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,X).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,X).getValue("peerSessionStore").on(_.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,X).getValue("peerSessionStore").on(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,X).getValue("callstats").audioOff())}),n(this,X).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,X).getValue("callstats").videoOff())}),n(this,X).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,X).getValue("peerSessionStore").on(_.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{this.logger.info("Joining socket room.");const{peer:t}=await n(this,Jt).joinRoom(this.self);this.logger.info("Joined socket room."),n(this,Jt).socket.flush();const e=qh(t.stageType);if(n(this,X).setValue("stageStatus",e,!1),t.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new C("Check the network and try again.","0002")}try{this.logger.info("Joining media room."),await this.joinMediaRoom(s),this.logger.info("Joined media room."),n(this,X).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof Er&&t.message==="ice connection failed"?new C("A firewall or network restriction may be blocking the connection.","0014"):new C("Check the network and try again.","0014")}}async leaveRoom(s="left"){var e;if(this.logger.info(`Leaving room with state: ${s}`),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}if(this.self.setIsPinned(!1),n(this,X).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,X).setValue("roomNodeClient",void 0),n(this,X).notify("stageStatus"),n(this,X).getValue("connectionHandler").socketJoined)try{n(this,Jt).leaveRoom(this.self)||this.logger.warn("SelfController.leaveRoom: socket leave was not sent")}catch(r){this.logger.error("SelfController.leaveRoom: socket leave failed",{error:r})}(e=n(this,X).getValue("roomSocketHandler"))==null||e.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,X).getAllValues();try{if(e===rr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}NT(n(this,X),{socket:n(this,wc),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:p}=(o=await((a=n(this,Tt,xt))==null?void 0:a.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw p!=null?p:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=n(this,X).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===rr.Webinar)&&n(this,Tt,xt)&&(n(this,Tt,xt).mediaJoined&&s!=="disconnected"&&await n(this,Tt,xt).leaveRoom(),!(s==="stageLeft"&&t===rr.Livestream)&&(n(this,Tt,xt).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()}},wc=new WeakMap,Jt=new WeakMap,X=new WeakMap,Tt=new WeakSet,xt=function(){return n(this,X).getValue("roomNodeClient")},Kg);let si=LT;cn([y.trace("SelfController.resetSelf")],si.prototype,"resetSelf",1);cn([y.trace("SelfController.setupEvents")],si.prototype,"setupEvents",1);cn([y.trace("SelfController.joinRoom")],si.prototype,"joinRoom",1);cn([y.trace("SelfController.leaveRoom")],si.prototype,"leaveRoom",1);cn([y.trace("SelfController.joinMediaRoom")],si.prototype,"joinMediaRoom",1);cn([y.trace("SelfController.leaveMediaRoom")],si.prototype,"leaveMediaRoom",1);cn([y.trace("SelfController.init")],si,"init",1);var Rc;class KD{constructor(t){g(this,Rc,void 0);m(this,Rc,t)}on(t,e){let r;t===x.roomPeerCount?r=ig.fromBinary.bind(ig):r=hg.fromBinary.bind(hg),n(this,Rc).on(t,({payload:i})=>{if(t===x.roomPeerCount&&!i)return;const a=r(i);e(a)})}}Rc=new WeakMap;var bc,kc;class zD{constructor(t,e){g(this,bc,void 0);g(this,kc,void 0);m(this,bc,e),m(this,kc,t)}get logger(){return n(this,kc).getValue("logger")}on(t,e){let r,i;switch(t){case x.transcript:{r=du.fromBinary.bind(du),i=du.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,bc).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)})}}bc=new WeakMap,kc=new WeakMap;var YD=Object.defineProperty,QD=Object.getOwnPropertyDescriptor,sp=(s,t,e,r)=>{for(var i=r>1?void 0:r?QD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&YD(t,e,i),i},Zs,Sa;class Ql{constructor(t,e){g(this,Zs,void 0);g(this,Sa,void 0);m(this,Zs,e),m(this,Sa,t)}get logger(){return n(this,Sa).getValue("logger")}get telemetry(){return n(this,Sa).getValue("telemetry")}getPolls(){return n(this,Zs).sendMessagePromise(Os.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,Zs).sendMessage(Os.createPoll,oI.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,Zs).sendMessage(Os.votePoll,dI.toBinary(r))}on(t,e){let r,i;switch(t){case Os.updatePoll:case Os.createPoll:case Os.votePoll:{r=mu.fromBinary.bind(mu),i=mu.create();break}}n(this,Zs).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,Zs).removeListeners(t)}}Zs=new WeakMap,Sa=new WeakMap;sp([y.trace("PollSocketHandler.getPolls")],Ql.prototype,"getPolls",1);sp([y.trace("PollSocketHandler.createPoll")],Ql.prototype,"createPoll",1);sp([y.trace("PollSocketHandler.votePoll")],Ql.prototype,"votePoll",1);var XD=Object.defineProperty,ZD=Object.getOwnPropertyDescriptor,eO=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZD(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&&XD(t,e,i),i},At;class VT{constructor(t,e){h(this,"socket");g(this,At,void 0);m(this,At,t),this.socket=e,this.handleSocketEvents(),n(this,At).setValue("roomSocketHandler",this)}get telemetry(){return n(this,At).getValue("telemetry")}get logger(){return n(this,At).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(x.joinRoom,ok.toBinary(e));try{const{peer:a}=ln.fromBinary((await r).payload);n(this,At).getValue("connectionHandler").socketJoined=!0,n(this,At).getValue("peerSessionStore").emit(_.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,At).getValue("peerSessionStore").emit(_.ROOM_STATE,d),n(this,At).getValue("peerSessionStore").emit(_.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),a}}async getAllAddedParticipants(){try{return Gk.fromBinary((await this.socket.sendMessagePromise(x.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(x.getRoomPeersInfo,Qb.toBinary(a));i=lu.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(x.getRoomPeersInfo);t=lu.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(x.getRoomPeersInfo);t=lu.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(x.getPeerInfo,_f.toBinary({peerId:t}));e=ln.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=ng.create();try{const e=await this.socket.sendMessagePromise(x.getRoomInfo);t=ng.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=dg.create();try{const e=await this.socket.sendMessagePromise(x.getRoomStageState);t=dg.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(x.broadcastMessage,Ga.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(x.broadcastToEntity,Ga.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(x.broadcastToEntity,Ga.toBinary(i))}leaveRoom(t){this.socket.joinAttempted=!1;const e={peer:{peerId:t.peerId,userId:t.userId,displayName:t.name,waitlisted:t.waitlistStatus==="waiting"}};return this.socket.sendMessage(x.leaveRoom,dk.toBinary(e))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(x.kick,wf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(x.kickAll,yf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(x.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.acceptWaitingRoomRequests,Qk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.denyWaitingRoomRequests,Zk.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(ad.updateUserPreset,kA.toBinary(r))}handleSocketEvents(){this.socket.on(x.broadcastMessage,({payload:t})=>{try{const e=Ga.fromBinary(t);n(this,At).getValue("peerSessionStore").emit(_.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(x.broadcastToEntity,({payload:t})=>{try{const e=Ga.fromBinary(t);n(this,At).getValue("peerSessionStore").emit(_.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 x.joinRoom:case x.leaveRoom:case x.kick:case x.kickAll:{r=ln.fromBinary.bind(ln),i=ln.create();break}case x.getWaitingRoomRequests:{r=(a,o)=>a?cg.fromBinary(a,o):{requests:[]},i=cg.create();break}case x.recordingPaused:case x.recordingStarted:case x.recordingStopped:{r=mg.fromBinary.bind(mg);break}case ad.updateUserPreset:{r=lg.fromBinary.bind(lg);break}case ds.peerJoinedBroadcast:case yr.peerJoinedBroadcast:{r=Zp.fromBinary.bind(Zp);break}case ds.selfJoinComplete:case yr.selfJoinComplete:{r=Au.fromBinary.bind(Au);break}case ds.globalPeerPinBroadcast:case yr.globalPeerPinBroadcast:{r=sg.fromBinary.bind(sg);break}case ds.selectedPeer:case yr.selectedPeer:{r=ku.fromBinary.bind(ku);break}case ds.selectedPeerDiff:case yr.selectedPeerDiff:{r=Xp.fromBinary.bind(Xp);break}case ds.leaveRoom:case yr.leaveRoom:{r=Mu.fromBinary.bind(Mu);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(ad.getUserPresets,EA.toBinary(e)),i=wA.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}}}At=new WeakMap;eO([y.trace("RoomSocketHandler.joinRoom")],VT.prototype,"joinRoom",1);var St;class tO{constructor(t){g(this,St,void 0);m(this,St,t)}async getStageRequests(){const{payload:t}=await n(this,St).sendMessagePromise(x.getStageRequests);return t?gu.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,St).sendMessage(x.requestStageAccess)}cancelRequestAccess(){n(this,St).sendMessage(x.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,St).sendMessage(x.grantStageAccess,QM.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,St).sendMessage(x.denyStageAccess,ZM.toBinary(e))}joinStage(){return n(this,St).sendMessagePromise(x.joinStage,void 0,void 0,x.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,St).sendMessagePromise(x.leaveStage,gg.toBinary(e),void 0,x.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,St).sendMessagePromise(x.leaveStage,gg.toBinary(e))}on(t,e){let r;switch(t){case x.grantStageAccess:case x.denyStageAccess:{r=void 0;break}case x.getStagePeers:{r=pg.fromBinary.bind(pg);break}case x.getStageRequests:case x.requestStageAccess:case x.cancelStageRequest:{r=gu.fromBinary.bind(gu);break}case x.peerStageStatusUpdate:{r=rg.fromBinary.bind(rg);break}}n(this,St).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,St).sendMessagePromise(x.getPeerInfo,_f.toBinary({peerId:t}));return ln.fromBinary(e.payload)}}St=new WeakMap;var Hr,va;class sO{constructor(t,e){g(this,Hr,void 0);g(this,va,void 0);m(this,Hr,e),m(this,va,t)}get logger(){return n(this,va).getValue("logger")}get peerId(){return n(this,va).getValue("peerId")}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,Hr).sendMessage(Ds.storeInsertKeys,IM.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,Hr).sendMessage(Ds.storeGetKeys,OM.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,Hr).sendMessage(Ds.storeDeleteKeys,LM.toBinary(a),i)}on(t,e){const r=ug.fromBinary.bind(ug);n(this,Hr).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}Hr=new WeakMap,va=new WeakMap;var rO=Object.defineProperty,iO=(s,t,e)=>t in s?rO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,nO=(s,t,e)=>(iO(s,typeof t!="symbol"?t+"":t,e),e),rp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(rp(s,t,"read from private field"),e?e.call(s):t.get(s)),ne=(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)},ee=(s,t,e,r)=>(rp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),te=(s,t,e)=>(rp(s,t,"access private method"),e),Id={},aO={get exports(){return Id},set exports(s){Id=s}},En=typeof Reflect=="object"?Reflect:null,wg=En&&typeof En.apply=="function"?En.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},pd;En&&typeof En.ownKeys=="function"?pd=En.ownKeys:Object.getOwnPropertySymbols?pd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:pd=function(s){return Object.getOwnPropertyNames(s)};function oO(s){console&&console.warn&&console.warn(s)}var xT=Number.isNaN||function(s){return s!==s};function ce(){ce.init.call(this)}aO.exports=ce;Id.once=uO;ce.EventEmitter=ce;ce.prototype._events=void 0;ce.prototype._eventsCount=0;ce.prototype._maxListeners=void 0;var Rg=10;function Xl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ce,"defaultMaxListeners",{enumerable:!0,get:function(){return Rg},set:function(s){if(typeof s!="number"||s<0||xT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Rg=s}});ce.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};ce.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||xT(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 UT(s){return s._maxListeners===void 0?ce.defaultMaxListeners:s._maxListeners}ce.prototype.getMaxListeners=function(){return UT(this)};ce.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")wg(c,this,t);else for(var d=c.length,l=qT(c,d),e=0;e<d;++e)wg(l[e],this,t);return!0};function $T(s,t,e,r){var i,a,o;if(Xl(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=UT(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,oO(c)}return s}ce.prototype.addListener=function(s,t){return $T(this,s,t,!1)};ce.prototype.on=ce.prototype.addListener;ce.prototype.prependListener=function(s,t){return $T(this,s,t,!0)};function cO(){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 HT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=cO.bind(r);return i.listener=e,r.wrapFn=i,i}ce.prototype.once=function(s,t){return Xl(t),this.on(s,HT(this,s,t)),this};ce.prototype.prependOnceListener=function(s,t){return Xl(t),this.prependListener(s,HT(this,s,t)),this};ce.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Xl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():dO(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ce.prototype.off=ce.prototype.removeListener;ce.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 BT(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?lO(i):qT(i,i.length)}ce.prototype.listeners=function(s){return BT(this,s,!0)};ce.prototype.rawListeners=function(s){return BT(this,s,!1)};ce.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):FT.call(s,t)};ce.prototype.listenerCount=FT;function FT(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}ce.prototype.eventNames=function(){return this._eventsCount>0?pd(this._events):[]};function qT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function dO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function lO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function uO(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))}jT(s,t,a,{once:!0}),t!=="error"&&hO(s,i,{once:!0})})}function hO(s,t,e){typeof s.on=="function"&&jT(s,"error",t,e)}function jT(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 pO extends T.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 bg=new pO;class GT{static encode(t){return bg.toBinary(t)}static decode(t){return bg.fromBinary(new Uint8Array(t))}}function gO(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Sr;class mO{constructor(t={}){nO(this,"opts"),ne(this,Sr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ee(this,Sr,0)}async wait(){ee(this,Sr,M(this,Sr)+1);const t=gO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,Sr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,Sr)}reset(){ee(this,Sr,0)}}Sr=new WeakMap;const gr={debug:0,info:1,warn:2,error:3};var ai,oi;class fO{constructor(t){ne(this,ai,void 0),ne(this,oi,void 0),ee(this,ai,console),ee(this,oi,t)}debug(...t){gr[M(this,oi)]>gr.debug||M(this,ai).debug("[Sockrates]:",...t)}info(...t){gr[M(this,oi)]>gr.info||M(this,ai).info("[Sockrates]:",...t)}warn(...t){gr[M(this,oi)]>gr.warn||M(this,ai).warn("[Sockrates]:",...t)}error(...t){gr[M(this,oi)]>gr.error||M(this,ai).error("[Sockrates]:",...t)}}ai=new WeakMap,oi=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 kg="2",Ag="3";var we,gn,ae,ve,vr,qe,tr,Jr,cs,mn,fn,Is,ch,JT,to,gd,dh,KT,md,Su,Dd,lh,uh,zT,co,fd,Pn,lo,Od,hh,_n,uo,ph,YT,ho,Td,po,Nd;class TO{constructor(t,e){var E,R,A,b,V,D,L,U,B,z,Q,Ge;ne(this,ch),ne(this,to),ne(this,dh),ne(this,md),ne(this,Dd),ne(this,uh),ne(this,co),ne(this,Pn),ne(this,Od),ne(this,_n),ne(this,ph),ne(this,ho),ne(this,po),ne(this,we,void 0),ne(this,gn,void 0),ne(this,ae,void 0),ne(this,ve,void 0),ne(this,vr,void 0),ne(this,qe,void 0),ne(this,tr,void 0),ne(this,Jr,void 0),ne(this,cs,void 0),ne(this,mn,void 0),ne(this,fn,void 0),ne(this,Is,void 0);var r,i,a,o,c,d,l,u,p,f,v;ee(this,gn,t),ee(this,vr,[]),ee(this,qe,new Id),ee(this,tr,!0),ee(this,cs,!1),ee(this,ae,e!=null?e:{}),(E=(r=M(this,ae)).autoReconnect)!=null||(r.autoReconnect=!0),(R=(i=M(this,ae)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(A=(a=M(this,ae)).pingTimeout)!=null||(a.pingTimeout=3e4),(b=(o=M(this,ae)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(V=(c=M(this,ae)).debug)!=null||(c.debug=!0),(D=(d=M(this,ae)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(L=(l=M(this,ae)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(U=(u=M(this,ae)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(B=(p=M(this,ae)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),(z=(f=M(this,ae)).clientInitiatedPings)!=null||(f.clientInitiatedPings=!1),(Q=(v=M(this,ae)).clientInitiatedPingInterval)!=null||(v.clientInitiatedPingInterval=3e4),ee(this,Jr,{code:void 0,reason:void 0}),ee(this,ve,(Ge=M(this,ae).logger)!=null?Ge:new fO(M(this,ae).debug?"debug":"info")),ee(this,Is,new mO)}get readyState(){var t;return(t=M(this,we))==null?void 0:t.readyState}get url(){return M(this,gn)}updateURL(t){ee(this,gn,t),te(this,uh,zT).call(this)}get config(){return M(this,ae)}get sendQueue(){return M(this,vr)}flush(){if(!M(this,ae).queueOnDisconnect)return!1;const t=[];return M(this,vr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ee(this,vr,t),M(this,vr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,ve).debug("Websocket was already connecting or connected.");return}if(M(this,tr)!==!1)return new Promise((e,r)=>{te(this,_n,uo).call(this),te(this,po,Nd).call(this);try{ee(this,we,new WebSocket(te(this,ch,JT).call(this,M(this,gn)))),M(this,we).binaryType="arraybuffer",M(this,ve).debug("Connecting");const i=setTimeout(()=>{M(this,ve).debug("Connection timeout. Closing socket"),ee(this,tr,!0),te(this,po,Nd).call(this),M(this,we).close(3001,"Connection Timeout"),M(this,ae).autoReconnect&&!M(this,cs)&&(M(this,qe).emit("reconnecting"),te(this,co,fd).call(this)),r(new Error("Connection timed out!"))},M(this,ae).connectionTimeout);M(this,we).onopen=()=>{M(this,ve).debug(`Ready State: ${WT[M(this,we).readyState]}`),i&&clearTimeout(i),te(this,Od,hh).call(this),te(this,ph,YT).call(this),ee(this,Jr,{code:void 0,reason:void 0}),M(this,qe).emit("connected"),M(this,ae).flushOnReconnect&&this.flush(),e()},M(this,we).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),M(this,ve).debug("Socket closed. Close event:",{event:a}),M(this,ve).debug(`Connection closed code: ${o}`),M(this,ve).debug(`Connection closed reason: ${c}`),M(this,cs)||te(this,Dd,lh).call(this,o,c)}catch(o){te(this,to,gd).call(this,o)}},M(this,we).onerror=a=>{te(this,to,gd).call(this,a)},M(this,we).onmessage=a=>te(this,dh,KT).call(this,a)}catch(i){te(this,to,gd).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(M(this,ae).queueOnDisconnect&&(!M(this,we)||M(this,we).readyState!==1))return M(this,ve).debug("Queuing message since socket is not connected!",a),M(this,vr).push(a),!1;const o=GT.encode(a);return te(this,Pn,lo).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return te(this,Pn,lo).call(this,t)}receive(t,e){return M(this,qe).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,qe).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,qe).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,qe).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,qe).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ee(this,tr,!1),te(this,_n,uo).call(this),te(this,ho,Td).call(this),this.removeAllListeners(),ee(this,Jr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,we).close(1e3,"Sockrates disconnect method called.")}}we=new WeakMap,gn=new WeakMap,ae=new WeakMap,ve=new WeakMap,vr=new WeakMap,qe=new WeakMap,tr=new WeakMap,Jr=new WeakMap,cs=new WeakMap,mn=new WeakMap,fn=new WeakMap,Is=new WeakMap,ch=new WeakSet,JT=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)://.")},to=new WeakSet,gd=function(s,t){M(this,ve).error("Error:",{error:s}),M(this,qe).emit("errored",{error:s}),t==null||t(s)},dh=new WeakSet,KT=function(s){if(te(this,Od,hh).call(this),s.data===kg){M(this,ve).debug("Received ping from server"),te(this,Pn,lo).call(this,Ag);return}if(s.data===Ag){M(this,ve).debug("Received pong from server");return}const t=GT.decode(s.data),{id:e,payload:r}=t;M(this,ve).debug("Received message",{event:t.event,messageID:e}),M(this,qe).emit(t.event.toString(),{id:e,payload:r})},md=new WeakSet,Su=function(){return M(this,we).readyState===1},Dd=new WeakSet,lh=function(s,t){ee(this,Jr,{reason:t,code:s}),M(this,qe).emit("disconnected",{code:s,reason:t})},uh=new WeakSet,zT=function(){const{reason:s,code:t}=M(this,Jr);t&&t!==1e3&&M(this,tr)&&M(this,ae).autoReconnect&&!M(this,cs)&&(M(this,ve).debug(`Triggering reconnection due to ${s}.`),M(this,qe).emit("reconnecting"),te(this,co,fd).call(this))},co=new WeakSet,fd=async function(s=!0){if(s&&M(this,cs)){M(this,ve).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,cs)||M(this,Is).reset(),M(this,ae).maxReconnectionAttempts!==null&&M(this,Is).getAttempts()>=M(this,ae).maxReconnectionAttempts){M(this,qe).emit("failed"),ee(this,cs,!1);return}ee(this,cs,!0),te(this,po,Nd).call(this),te(this,_n,uo).call(this);try{if(await M(this,Is).wait(),M(this,tr)===!1)return;if(M(this,ve).debug(`Reconnection attempt ${M(this,Is).getAttempts()}`),M(this,qe).emit("reconnectAttempt",{attempt:M(this,Is).getAttempts()}),await this.connect(),!te(this,md,Su).call(this))throw Error("Reconnect Failed");ee(this,cs,!1),ee(this,Jr,{code:void 0,reason:void 0}),M(this,qe).emit("reconnected")}catch(t){M(this,ve).debug("Failed to reconnect."),M(this,qe).emit("reconnectFailure",{attempt:M(this,Is).getAttempts()}),te(this,co,fd).call(this,!1)}},Pn=new WeakSet,lo=function(s){try{return M(this,we).send(s),!0}catch(t){return M(this,ve).error(t.message),!1}},Od=new WeakSet,hh=function(){this.config.disconnectOnPingTimeout&&(M(this,ve).debug("Resetting ping timeout"),te(this,_n,uo).call(this),ee(this,mn,setTimeout(()=>{var s;M(this,ve).debug("Disconnecting the socket due to ping timeout"),ee(this,tr,!0);const t=3002,e="Ping timeout";(s=M(this,we))==null||s.close(t,e),te(this,Dd,lh).call(this,t,e)},M(this,ae).pingTimeout)))},_n=new WeakSet,uo=function(){M(this,mn)&&(clearTimeout(M(this,mn)),ee(this,mn,void 0))},ph=new WeakSet,YT=function(){te(this,ho,Td).call(this),M(this,ae).clientInitiatedPings&&ee(this,fn,setInterval(()=>{te(this,md,Su).call(this)&&(M(this,ve).debug("Sending client-initiated ping"),te(this,Pn,lo).call(this,kg))},M(this,ae).clientInitiatedPingInterval))},ho=new WeakSet,Td=function(){M(this,fn)&&(clearInterval(M(this,fn)),ee(this,fn,void 0))},po=new WeakSet,Nd=function(){te(this,ho,Td).call(this),M(this,we)&&(M(this,we).onopen=void 0,M(this,we).onerror=void 0,M(this,we).onmessage=void 0,M(this,we).onclose=void 0)};function QT(s){return`${s.slice(0,10)}...${s.slice(-10)}`}function SO(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=di.baseURI.prod;t&&(a=t);const o=`https://${Cd({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}var vO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,Zl=(s,t,e,r)=>{for(var i=r>1?void 0:r?yO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vO(t,e,i),i};const Mg=65535,EO=3,PO=15e3,_O=8e3,CO=50,wO=1e3,RO=1e4;var Es,ya,Se,Be,Qe,ji,Br,Gi,Wi,Fr,Ps,_s,qr,Ji,lt,jr,ut,Oe,Ac,gh,kl,ZT,Al,eS,Ml,tS,Mc,mh,Ic,fh,Ki,so,Il,vu,sS,Dl,rS,Dc,Th,Oc,Sh,Nc,vh,Ol,iS,Lc,yh,Vc,Eh;const XT=(vu=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Be);g(this,Ac);g(this,kl);g(this,Al);g(this,Ml);g(this,Mc);g(this,Ic);g(this,Ki);g(this,Dl);g(this,Dc);g(this,Oc);g(this,Nc);g(this,Ol);g(this,Lc);g(this,Vc);g(this,Es,void 0);g(this,ya,void 0);g(this,Se,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");g(this,ji,[]);g(this,Br,void 0);g(this,Gi,!1);g(this,Wi,void 0);g(this,Fr,void 0);g(this,Ps,void 0);g(this,_s,void 0);g(this,qr,void 0);g(this,Ji,void 0);g(this,lt,0);g(this,jr,void 0);g(this,ut,!0);g(this,Oe,void 0);if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");m(this,Oe,s),m(this,_s,navigator.isReactNative?PT:io),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,Es,I(this,Ac,gh).call(this,t)),m(this,ya,t);const a=i.includes("PING");m(this,Se,new TO(n(this,Es),{autoReconnect:!1,disconnectOnPingTimeout:a,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!a,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,Be,Qe).socketJoinAttempted}set joinAttempted(s){n(this,Be,Qe).socketJoinAttempted=s}get telemetry(){return n(this,Oe).getValue("telemetry")}get logger(){return n(this,Oe).getValue("logger")}get peerId(){return n(this,Oe).getValue("peerId")}updateCallstatsPeerId(s){const t=n(this,Oe).getValue("callstats");t.peerId=s,t.backend&&(t.backend.peerId=s,t.backend.eventHandler&&Object.assign(t.backend.eventHandler,{peerId:s}))}updateURL(s){var t;m(this,Es,I(this,Ac,gh).call(this,s)),m(this,ya,s),n(this,Oe).getValue("telemetry").resetPeerId(s),(t=n(this,Oe).getValue("apiClient"))==null||t.setHeader("tracing-id",s),this.updateCallstatsPeerId(s),zr.remapContext(s,n(this,Oe)),this.logger.info(`Attempting websocket connection with URL: ${n(this,Ki,so)}`),n(this,Se).updateURL(n(this,Es))}get url(){return n(this,Es)}async connect(){var t;const s=n(this,lt)+1;m(this,lt,s),I(this,Dc,Th).call(this),n(this,Be,Qe).socketJoinAttempted=!0,m(this,ut,!0),I(this,Ml,tS).call(this);try{if(await n(this,Se).connect(),!n(this,ut)||s!==n(this,lt))throw new Error("Socket connection was canceled");I(this,Ic,fh).call(this,this.peerId),(t=n(this,Ps))!=null||m(this,Ps,this.peerId),n(this,Be,Qe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}catch(e){throw this.logger.error(`Websocket connection failed with URL: ${n(this,Ki,so)}`,{error:e}),n(this,ut)&&s===n(this,lt)&&I(this,Nc,vh).call(this,s),e}}disconnect(){n(this,Be,Qe).socketJoinAttempted=!1,m(this,lt,n(this,lt)+1),m(this,ut,!1),I(this,Dc,Th).call(this),I(this,Mc,mh).call(this),m(this,Ps,void 0),n(this,Se).disconnect(),n(this,Be,Qe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,Se).readyState===1}catch(s){return!1}}sendMessage(s,t,e){if(!n(this,Lc,yh))return!1;const r={};return n(this,Oe).getValue("telemetry").injectContext(r),n(this,Se).send(s,e!=null?e:I(this,Vc,Eh).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){if(!n(this,Lc,yh))return Promise.reject(new Error("Socket is not connected for the current peer ID"));const a=i!=null?i:s;return new Promise((o,c)=>{let d;const l=(A,b)=>{d&&clearTimeout(d),n(this,Se).removeListener(a,A),n(this,Se).removeListener(Mg,b),n(this,Se).removeListener(yr.errorResponse,b),n(this,Se).removeListener(ds.errorResponse,b)},u=r!=null?r:I(this,Vc,Eh).call(this),p={};n(this,Oe).getValue("telemetry").injectContext(p);const v=({id:A,payload:b})=>{if(u===A){let V;try{const D=FR.fromBinary(b);V=new Error(D.errorMessage)}catch(D){V=new Error("failed to parse error message",{cause:D});try{const L=jb.fromBinary(b);V=new Error(L.message)}catch(L){V=new Error("failed to parse error message",{cause:L})}}c(V),l(E,v)}},E=({id:A,payload:b})=>{u===A&&(o({id:A,payload:b}),l(E,v))};n(this,Se).on(a,E),n(this,Se).on(Mg,v),n(this,Se).on(yr.errorResponse,v),n(this,Se).on(ds.errorResponse,v),d=setTimeout(()=>{l(E,v),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,Se).send(s,u,e,new TextEncoder().encode(JSON.stringify(p)))||(l(E,v),c(new Error("Socket message could not be sent for the current peer ID")))})}on(s,t){n(this,Se).on(s,t)}onStateEvent(s,t){n(this,Se).on(s,t)}removeListener(s,t){n(this,Se).removeListener(s,t)}removeListeners(s){n(this,Se).removeListeners(s)}flush(){return n(this,Se).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{var s;this.logger.info(`Websocket connected with URL: ${n(this,Ki,so)}`),(s=n(this,Ps))!=null||m(this,Ps,this.peerId),n(this,Be,Qe).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{!n(this,ut)||n(this,jr)===n(this,lt)||(this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}}),n(this,Be,Qe).updateSocketConnectionState("disconnected"),n(this,Oe).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Be,Qe).joinAttempted}),I(this,Nc,vh).call(this,n(this,lt)))})}},Es=new WeakMap,ya=new WeakMap,Se=new WeakMap,Be=new WeakSet,Qe=function(){return n(this,Oe).getValue("connectionHandler")},ji=new WeakMap,Br=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,Fr=new WeakMap,Ps=new WeakMap,_s=new WeakMap,qr=new WeakMap,Ji=new WeakMap,lt=new WeakMap,jr=new WeakMap,ut=new WeakMap,Oe=new WeakMap,Ac=new WeakSet,gh=function(s){let t=Uh({servicePrefix:"ws",baseURI:n(this,Oe).getValue("baseURI")});const e=Eo(n(this,Oe),"socket_server_base");if(typeof e=="string"){const a=/^(http|ws):\/\//i.test(e),o=e.replace(/^(https?|wss?):\/\//i,"").replace(/\/+$/,"");t=`${a?"ws":"wss"}://${o}/ws`}const r=new URL(t),i={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n(this,ji).length>0&&{oldPeerIds:n(this,ji).join(",")},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>wd[a]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0,apiVersion:"23-09-2026"};return Object.entries(i).forEach(([a,o])=>{r.searchParams.append(a,o.toString())}),r.href},kl=new WeakSet,ZT=function(){if(!n(this,Ps))return;const s=new URL(n(this,Es));return s.protocol=s.protocol==="ws:"?"http:":"https:",s.pathname=`${s.pathname.replace(/\/+$/,"")}/ping`,s.search="",s.searchParams.set("peerId",n(this,Ps)),s.href},Al=new WeakSet,eS=async function(){const s=I(this,kl,ZT).call(this);if(!s||n(this,Gi))return;const t={},e=typeof AbortController=="function"?new AbortController:void 0;let r;m(this,Gi,!0),m(this,Fr,t),m(this,Wi,e);try{e&&(r=n(this,_s).setTimeout(()=>e.abort(),_O));const i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${this.authToken}`},...e&&{signal:e.signal}});i.ok||this.logger.warn("SocketService::API ping request failed",{networkCall:{status:i.status,url:s}})}catch(i){n(this,Fr)===t&&this.logger.warn("SocketService::API ping request failed",{error:i,networkCall:{url:s}})}finally{r!==void 0&&n(this,_s).clearTimeout(r),n(this,Fr)===t&&(m(this,Gi,!1),m(this,Fr,void 0),m(this,Wi,void 0))}},Ml=new WeakSet,tS=function(){n(this,Br)===void 0&&m(this,Br,n(this,_s).setInterval(()=>I(this,Al,eS).call(this),PO))},Mc=new WeakSet,mh=function(){var s;n(this,Br)!==void 0&&n(this,_s).clearInterval(n(this,Br)),(s=n(this,Wi))==null||s.abort(),m(this,Br,void 0),m(this,Gi,!1),m(this,Fr,void 0),m(this,Wi,void 0)},Ic=new WeakSet,fh=function(s){m(this,ji,[s,...n(this,ji).filter(t=>t!==s)].slice(0,EO))},Ki=new WeakSet,so=function(){const s=new URL(n(this,Es)),t=s.searchParams.get("authToken");return t&&s.searchParams.set("authToken",QT(t)),s.href},Il=new WeakSet,sS=function(s){const t=Math.min(RO,wO*2**(s-1));return Math.floor(Math.random()*(t+1))},Dl=new WeakSet,rS=function(s){return new Promise(t=>{var e;m(this,Ji,t),m(this,qr,n(this,_s).setTimeout(()=>{m(this,qr,void 0),m(this,Ji,void 0),t()},I(e=XT,Il,sS).call(e,s)))})},Dc=new WeakSet,Th=function(){var s;n(this,qr)!==void 0&&(n(this,_s).clearTimeout(n(this,qr)),m(this,qr,void 0)),(s=n(this,Ji))==null||s.call(this),m(this,Ji,void 0)},Oc=new WeakSet,Sh=function(s,t){!n(this,ut)||s!==n(this,lt)||(t&&this.logger.error("SocketService::Reconnect loop failed",{error:t}),m(this,ut,!1),I(this,Mc,mh).call(this),m(this,Ps,void 0),n(this,Be,Qe).updateSocketConnectionState("failed"),n(this,Oe).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_FAILED))},Nc=new WeakSet,vh=function(s){!n(this,ut)||n(this,jr)===s||(m(this,jr,s),n(this,Be,Qe).updateSocketConnectionState("reconnecting"),I(this,Ol,iS).call(this,s).catch(t=>I(this,Oc,Sh).call(this,s,t)))},Ol=new WeakSet,iS=async function(s){try{for(let t=1;t<=CO;t+=1){if(!n(this,ut)||s!==n(this,lt)||(await I(this,Dl,rS).call(this,t),!n(this,ut)||s!==n(this,lt)))return;this.updateURL(Qr.v4()),this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:t}}),n(this,Be,Qe).updateSocketConnectionState("reconnectAttempt",t);try{if(await n(this,Se).connect(!0),!n(this,ut)||s!==n(this,lt))return;if(!this.isConnected)throw new Error("Reconnect failed");I(this,Ic,fh).call(this,this.peerId),m(this,Ps,this.peerId),n(this,Be,Qe).updateSocketConnectionState("reconnected"),n(this,Oe).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,Be,Qe).mediaJoinAttempted});return}catch(e){if(!n(this,ut)||s!==n(this,lt))return;this.logger.error(`Websocket connection retry attempt ${t} failed with URL: ${n(this,Ki,so)}`,{error:e,socket:{retryAttempt:t}}),n(this,Be,Qe).updateSocketConnectionState("reconnectFailure",t)}}I(this,Oc,Sh).call(this,s)}finally{n(this,jr)===s&&m(this,jr,void 0)}},Lc=new WeakSet,yh=function(){return this.isConnected&&n(this,ya)===this.peerId},Vc=new WeakSet,Eh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},g(vu,Il),vu);let Jc=XT;Zl([y.trace("SocketService.connect")],Jc.prototype,"connect",1);Zl([y.trace("SocketService.disconnect")],Jc.prototype,"disconnect",1);Zl([y.trace("SocketService.sendMessagePromise")],Jc.prototype,"sendMessagePromise",1);Zl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Jc.prototype,"sendMessagePromiseWithTimeout",1);class bO{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=Tk.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=qk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Cf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return og.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(x.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(x.createConnectedRooms,Ek.toBinary({payloads:t}));return og.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(x.deleteConnectedRooms,Ik.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(x.movePeers,$k.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 kO=Object.defineProperty,AO=Object.getOwnPropertyDescriptor,MO=(s,t,e,r)=>{for(var i=r>1?void 0:r?AO(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&&kO(t,e,i),i},Mt;class nS extends Nt{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);g(this,Mt,void 0);m(this,Mt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=n(this,Mt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=n(this,Mt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const a=n(this,Mt).getValue("userId");if(!(r.length===1&&r[0]===a))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await n(this,Mt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await n(this,Mt).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await n(this,Mt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(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,Mt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,Mt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,Mt).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})}}Mt=new WeakMap;MO([Lt({maxInvocations:60,period:60})],nS.prototype,"getConnectedMeetings",1);var IO=Object.defineProperty,DO=Object.getOwnPropertyDescriptor,ip=(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&&IO(t,e,i),i},ue,zg;const aS=(zg=class{constructor(s){h(this,"connectedMeetings");g(this,ue,void 0);m(this,ue,s),this.connectedMeetings=new nS(s)}get telemetry(){return n(this,ue).getValue("telemetry")}get logger(){return n(this,ue).getValue("logger")}static init(s){const t=new aS(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.transferPeer,this.handleTransferPeer.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.movedPeer,this.handleMovedPeer.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,ue).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,a,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:n(this,ue).getValue("self").videoEnabled,audio:n(this,ue).getValue("self").audioEnabled};try{n(this,ue).getValue("self").cleanupEvents(),await n(this,ue).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,ue).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 cS.init({...n(this,ue).getValue("options"),cachedUserDetails:null,defaults:{...n(this,ue).getValue("options").defaults,...e,mediaHandler:n(this,ue).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,ue).getValue("self");r.self.setName(n(this,ue).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,ue).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,ue).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,ue).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,ue).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})}},ue=new WeakMap,zg);let eu=aS;ip([y.trace("ConnectedMeetingsController.getConnectedMeetings")],eu.prototype,"getConnectedMeetings",1);ip([y.trace("ConnectedMeetingsController.setupEvents")],eu.prototype,"setupEvents",1);ip([y.trace("ConnectedMeetingsController.switchMeeting")],eu.prototype,"switchMeeting",1);var OO=Object.defineProperty,NO=Object.getOwnPropertyDescriptor,np=(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&&OO(t,e,i),i};const ro=class{constructor(s,t,e){h(this,"apiBase");h(this,"selfController");h(this,"pollController");h(this,"chatController");h(this,"metaController");h(this,"storesManager");h(this,"stageController");h(this,"pluginController");h(this,"internalsController");h(this,"recordingController");h(this,"livestreamController");h(this,"participantController");h(this,"connectedMeetingsController");h(this,"telemetry");h(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 D,L;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(GD(s),me.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=UI(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 y0(s);s.setValue("connectionHandler",l);let u="",p=null;c.info("CF SFU is being used.");const f=ro.createSocketService(s),v=f.connect();v.catch(()=>{});const E=d.getUserDetails();try{p=await E,u=((D=p.meeting)==null?void 0:D.title)||"",s.setValue("presetName",p.preset.name)}catch(U){throw c.error("Failed to get user details",{error:U}),f.disconnect(),U instanceof Rd?U.status===401?new C("Unauthorized. The auth token may be invalid or expired. (401)","0004"):U.status===403?new C("Access denied. Insufficient permissions to join the meeting. (403)","0004"):U.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new C("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004")):U.status>=500?new C(`The server encountered an error. Try again. (${U.status})`,"0001"):U.isHttpError?new C(`Request rejected by the server. (${U.status})`,"0001"):U.isTimeout?new C("Connection timed out. Check the network and try again.","0001"):new C("Unable to connect to the server. Check the internet connection.","0001"):new C((U==null?void 0:U.message)||"Failed to initialize.","0001")}try{await v}catch(U){c.error("[Controller]: Failed to connect to socket server:",{error:U})}const R=Gu.init(p.preset,!s.getValue("modules").theme);s.setValue("theme",R);const A=zu.init(s,R.viewType,p.preset.permissions),b=ro.setupControllers(f,s,p,u,R,A);c0(R)&&((L=ro.createRoomNodeClient(s,f).initializeConnection(p.participant.name,i,!1,A))==null||L.catch(B=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:B})}));const{controllers:V}=await b;return _w(),new ro(e,V,s)}static async setupControllers(s,t,e,r,i,a){var ye,N,w;const o=t.getValue("modules"),{participant:c}=e,d=t.getValue("defaults"),l=t.getValue("logger"),{viewType:u,mediaConstraints:{audio:p}}=i;t.setValue("viewType",u),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(ye=p.enableHighBitrate)!=null?ye:!1,enableStereo:(N=p.enableStereo)!=null?N:!1}},...d}),t.setValue("maxPreferredStreams",me.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let f,v,E,R,A,b,V,D,L;const U=new zD(t,s),B=new bO(s);t.setValue("connectedMeetingsSocketHandler",B);const z=new Ql(t,s),Q=new lr(t,s),Ge=new tO(s),tt=new VT(t,s),Et=new sO(t,s),k=new KD(s),S=await si.init(t,tt,c,a,i);t.setValue("selfController",S);const P=await $f.init(t,S.self,tt,U,r);o.participant&&(D=new pr(t,S.self,tt)),(w=o.e2ee)!=null&&w.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(v=await oo.init(t,Q,S.self,D.participants)),o.internals&&(A=await Wh.init(t)),o.livestream&&i.viewType===rr.Livestream&&(V=new Yf(t,S.self,k)),o.poll&&(f=await Lf.init(t,S.self,z)),o.recording&&(b=new Gf(t,S.self,tt)),o.stage&&(E=new Hf(t,Ge,tt,S.self,D.participants));const $=new hD(t,Et);if(o.plugin){if(!D)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Re=d.plugins||[];R=await jf.init(t,Re,S.self,$)}if(o.connectedMeetings&&(L=await eu.init(t)),o.pip){const Re=await bu._init(t,S.self);t.setValue("pip",Re)}return{theme:i,permissions:a,controllers:{storesManager:$,pollController:f,selfController:S,metaController:P,chatController:v,stageController:E,pluginController:R,recordingController:b,internalsController:A,livestreamController:V,participantController:D,connectedMeetingsController:L}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return NT(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=[];return s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(i)}`),new Jc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let tu=ro;np([y.trace("Controller.init")],tu,"init",1);np([y.trace("Controller.createRoomNodeClient")],tu,"createRoomNodeClient",1);np([y.trace("Controller.createSocketService")],tu,"createSocketService",1);class LO{constructor(){h(this,"battery");h(this,"logger");h(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)}});h(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});h(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});h(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 Ig=new LO;var Gr,zi,Yi,xc,Nl,oS;class VO{constructor(){g(this,Nl);g(this,Gr,new Audio);g(this,zi,new MediaStream);g(this,Yi,new Map);g(this,xc,void 0);n(this,Gr).srcObject=n(this,zi),n(this,Gr).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,Yi).has(e.id)||(n(this,zi).addTrack(e),n(this,Yi).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,Gr).setSinkId(t)}removeTrack(t){const e=n(this,Yi).get(t);e&&(n(this,zi).removeTrack(e),n(this,Yi).delete(t))}async play(){return n(this,Gr).srcObject=n(this,zi),n(this,Gr).play().catch(t=>{I(this,Nl,oS).call(this,t)})}onError(t){m(this,xc,t)}}Gr=new WeakMap,zi=new WeakMap,Yi=new WeakMap,xc=new WeakMap,Nl=new WeakSet,oS=function(t){var e;(e=n(this,xc))==null||e.call(this,t)};var Cs;class xO extends VO{constructor(){super();g(this,Cs,void 0);m(this,Cs,new Map)}addParticipantTrack(e,r){n(this,Cs).set(e,r.id),this.playTracks([r])}reassignParticipantTrack(e,r){const i=n(this,Cs).get(e);i&&(n(this,Cs).delete(e),n(this,Cs).set(r,i))}removeParticipantTrack(e){const r=n(this,Cs).get(e);r&&this.removeTrack(r),n(this,Cs).delete(e)}}Cs=new WeakMap;var UO=Object.defineProperty,$O=Object.getOwnPropertyDescriptor,su=(s,t,e,r)=>{for(var i=r>1?void 0:r?$O(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},Me,Qi,Yg;let Xr=(Yg=class{constructor(t,e){g(this,Me,void 0);g(this,Qi,void 0);m(this,Qi,t),m(this,Me,e)}get peerId(){return n(this,Qi).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Qr.v4(),a=zr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new iT(a,o);return await c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,v,E,R,A,b,V;me.init();const e=(v=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?v:Qr.v4(),{authToken:r,baseURI:i}=t,{meetingId:a,...o}=SO(r,i);if((E=o.baseURI)!=null&&E.includes("dyte.io"))throw new C("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Xr.setupContext(e,t,a,o),d=c.getValue("telemetry"),l=c.getValue("logger");mS(l),Ig.init(l),d.init(c,{roomName:a,userId:o.participantId,organizationId:o.orgId,peerId:e},(A=(R=t.modules)==null?void 0:R.tracing)!=null?A:!0,(V=(b=t==null?void 0:t.modules)==null?void 0:b.devTools)==null?void 0:V.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:QT(t.authToken)}});const u=await tu.init(c),p=new Xr(c,u);return c.setValue("meeting",p),p}static setupContext(t,e,r,i){var d,l;const a=zr.createContext(t,e),o={...ew,...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",tw({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",ws(e.cachedUserDetails)),a.setValue("sdkVersion","2.0.3-staging.8"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new xO),a}async join(){const{selfController:t}=n(this,Me);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;Ig.cleanup(),n(this,Qi).getValue("peerSessionStore").reset(),(r=n(this,Me).pluginController)==null||r.cleanup();const{selfController:e}=n(this,Me);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,Me).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,Me).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,Me).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,Me).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,Me).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,Me).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,Me).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,Me).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,Me).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,Me).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,Me).stageController)==null?void 0:t.stage}get stores(){return n(this,Me).storesManager}get audio(){return n(this,Qi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,Me).internalsController)==null?void 0:t.internals}},Me=new WeakMap,Qi=new WeakMap,Yg);su([et("0002"),hr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Xr.prototype,"join",1);su([et("0003")],Xr.prototype,"leave",1);su([et("0001"),hr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Xr,"init",1);Xr=su([et("0000")],Xr);const cS=Xr;module.exports=cS;
|
|
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 Wm extends ft{constructor(e){super();h(this,"call");h(this,"timeOut");this.call=new pr(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 nv=8,av=1/1e3;class ov extends Wm{constructor(e){super(e);h(this,"senderChannel");h(this,"recieveChannel");h(this,"startTime");h(this,"lastBitrateMeasureTime");h(this,"sentPayloadBytes",0);h(this,"recievedPayloadBytes",0);h(this,"lastReceivedPayloadBytes",0);h(this,"stopSending",!1);h(this,"testProgress",0);h(this,"samplePacket","");h(this,"finalBitrateSum",0);h(this,"bitRateSampels",0);h(this,"maxNumberOfPacketsToSend",0);h(this,"bytesToKeepBuffered",0);h(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(pr.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)*nv/(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*av)})}}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 Fh extends Wm{constructor(e,r=pr.noFilter){super(e);h(this,"ch1");h(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 cv extends Fh{constructor(t){super(t,pr.isHost)}}class dv extends Fh{constructor(t){super(t,pr.isRelay)}}class lv extends Fh{constructor(t){super(t,pr.isReflexive)}}class uv{constructor(){h(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=ri(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=ri(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 Jm=new uv,Mp=[{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 Ap(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class Km{constructor(){h(this,"transport");h(this,"candidatePair");h(this,"outboundVideoRtp",new Map);h(this,"inboundVideoRtp",new Map);h(this,"outboundAudioRtp",new Map);h(this,"inboundAudioRtp",new Map);h(this,"remoteInboundRtp",new Map);h(this,"producerStreamMap",new Map);h(this,"consumerStreamMap",new Map);h(this,"staleProducerStreamMap",!1);h(this,"staleConsumerStreamMap",!1)}}class zm extends ft{constructor(){super();h(this,"observer");h(this,"outboundProducerMap",new Map);h(this,"inboundConsumerMap",new Map);h(this,"consumerPeerIdMap",new Map);h(this,"pausedConsumerMap",new Map);h(this,"pausedProducerMap",new Map);h(this,"overallProducingTransportsStatsMap",{});h(this,"overallConsumingTransportsStatsMap",{});h(this,"overallConsumersStatsMap",{});h(this,"overallProducersStatsMap",{});h(this,"videoProducerToStatsMap",new Map);h(this,"audioProducerToStatsMap",new Map);h(this,"videoConsumerToStatsMap",new Map);h(this,"audioConsumerToStatsMap",new Map);h(this,"consumerIdsWithFreezedVideo",new Set);h(this,"consumerIdsWithFreezedAudio",new Set);h(this,"producerIdsWithFreezedVideo",new Set);h(this,"producerIdsWithFreezedAudio",new Set);h(this,"freezedProducingTransportIds",new Set);h(this,"freezedConsumingTransportIds",new Set);h(this,"screenShareProducers",new Set);h(this,"screenShareConsumers",new Set);h(this,"ipDetails");h(this,"callStatsInstance");this.observer=new ft}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 u;const a=((u=this==null?void 0:this.callStatsInstance)==null?void 0:u.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,u)=>l||u.audio||u.video||u.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 R,I,D,A,x,$,U,z,ee,H,X,pe,et;const c=e,d=new Km,l=r.length?new Set(r):void 0,u=[],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":{u.push(this.getIceCandidateStats(k));break}case"remote-candidate":{p.push(this.getIceCandidateStats(k));break}case"candidate-pair":{const{nominated:S}=k,{selected:P}=k,L=k,se={nominated:S!=null?S:P,currentRoundTripTime:L.currentRoundTripTime,totalRoundTripTime:L.totalRoundTripTime,bytesReceived:L.bytesReceived,bytesSent:L.bytesSent,availableOutgoingBitrate:L.availableOutgoingBitrate,availableIncomingBitrate:L.availableIncomingBitrate,lastPacketReceivedTimestamp:L.lastPacketReceivedTimestamp,lastPacketSentTimestamp:L.lastPacketSentTimestamp,localCandidateId:L.localCandidateId,remoteCandidateId:L.remoteCandidateId,bytesDiscardedOnSend:L.bytesDiscardedOnSend,packetsSent:L.packetsSent,packetsReceived:L.packetsReceived,packetsDiscardedOnSend:L.packetsDiscardedOnSend};f.push(se),(k.nominated===!0||k.selected===!0)&&(d.candidatePair=se);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 L=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,L,P)}if(o.consuming){const L=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,L,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),L=this.pausedProducerMap.get(P);if(L){if(L.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const se=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 ae=this.callStatsInstance.producers.get(P);if(((R=ae==null?void 0:ae.track)==null?void 0:R.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const N={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 _=S,ke={frameHeight:_.frameHeight,frameWidth:_.frameWidth,framesEncoded:_.framesEncoded,framesDropped:_.framesDropped,framesPerSecond:_.framesPerSecond,framesSent:_.framesSent,keyFramesEncoded:_.keyFramesEncoded,firCount:_.firCount,encoderImplementation:_.encoderImplementation,hugeFramesSent:_.hugeFramesSent,pliCount:_.pliCount,qpSum:_.qpSum,qualityLimitationDurations:_.qualityLimitationDurations,qualityLimitationReason:_.qualityLimitationReason,qualityLimitationResolutionChanges:_.qualityLimitationResolutionChanges,totalEncodeTime:_.targetBitrate,totalPacketSendDelay:_.totalPacketSendDelay,retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,scalabilityMode:_.scalabilityMode,powerEfficientEncoder:_.powerEfficientEncoder,...N};d.outboundVideoRtp.set(k.id,ke),d.producerStreamMap.get(P).outboundVideoRtpId.push(k.id),this.processOutboundProducerVideoStats(P,se,ke)}else if(S.mediaType==="audio"||S.kind==="audio"){const _=S,ke={retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,...N};d.outboundAudioRtp.set(k.id,ke),d.producerStreamMap.get(P).outboundAudioRtpId.push(k.id),this.processOutboundProducerAudioStats(P,se,ke)}}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),L=this.pausedConsumerMap.get(P);if(L){if(L.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 se=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 ae={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 N=S,_={frameHeight:N.frameHeight,frameWidth:N.frameWidth,framesDecoded:N.framesDecoded,framesDropped:N.framesDropped,framesPerSecond:N.framesPerSecond,framesReceived:N.framesReceived,keyFramesDecoded:N.keyFramesDecoded,firCount:N.firCount,decoderImplementation:N.decoderImplementation,pliCount:N.pliCount,totalProcessingDelay:N.totalProcessingDelay,qpSum:N.qpSum||0,totalAssemblyTime:N.totalAssemblyTime||0,totalDecodeTime:N.totalDecodeTime||0,totalFreezesDuration:N.totalFreezesDuration||0,totalInterFrameDelay:N.totalInterFrameDelay||0,totalPausesDuration:N.totalPausesDuration||0,totalSquaredInterFrameDelay:N.totalSquaredInterFrameDelay||0,freezeCount:N.freezeCount||0,pauseCount:N.pauseCount||0,powerEfficientDecoder:N.powerEfficientDecoder,...ae};_.score=Gm({frameWidth:_.frameWidth||0,framesDecoded:(_.framesDecoded||0)-(((I=this.videoConsumerToStatsMap.get(P))==null?void 0:I.framesDecoded)||0),framesPerSecond:_.framesPerSecond||0,packetsLost:(_.packetsLost||0)-(((D=this.videoConsumerToStatsMap.get(P))==null?void 0:D.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((A=this.videoConsumerToStatsMap.get(P))==null?void 0:A.packetsReceived)||0),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(_.score*10).toFixed(),frameWidth:_.frameWidth||0,frameHeight:_.frameHeight||0,framesPerSecond:_.framesPerSecond||0,packetsLostPercentage:Id({packetsLost:(_.packetsLost||0)-(((x=this.videoConsumerToStatsMap.get(P))==null?void 0:x.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((_.bytesReceived||0)-(((U=this.videoConsumerToStatsMap.get(P))==null?void 0:U.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,_),d.inboundVideoRtp.set(k.id,_),d.consumerStreamMap.get(P).inboundVideoRtpId.push(k.id),this.processInboundConsumerVideoStats(P,se,_)}else if(S.mediaType==="audio"||S.kind==="audio"){const N=S,_={audioLevel:N.audioLevel,concealedSamples:N.concealedSamples,concealmentEvents:N.concealmentEvents,totalAudioEnergy:N.totalAudioEnergy,totalSamplesDuration:N.totalSamplesDuration,totalSamplesReceived:N.totalSamplesReceived,fecPacketsDiscarded:N.fecPacketsDiscarded||0,fecPacketsReceived:N.fecPacketsReceived||0,insertedSamplesForDeceleration:N.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:N.removedSamplesForAcceleration||0,silentConcealedSamples:N.silentConcealedSamples||0,playoutId:N.playoutId,...ae};_.score=qm({concealmentEvents:(_.concealmentEvents||0)-(((z=this.audioConsumerToStatsMap.get(P))==null?void 0:z.concealmentEvents)||0),packetsLost:(_.packetsLost||0)-(((ee=this.audioConsumerToStatsMap.get(P))==null?void 0:ee.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((H=this.audioConsumerToStatsMap.get(P))==null?void 0:H.packetsReceived)||0),jitter:_.jitter||0}),E.set(P,{score:+(_.score*10).toFixed(),packetsLostPercentage:Id({packetsLost:(_.packetsLost||0)-(((X=this.audioConsumerToStatsMap.get(P))==null?void 0:X.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((pe=this.audioConsumerToStatsMap.get(P))==null?void 0:pe.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((_.bytesReceived||0)-(((et=this.audioConsumerToStatsMap.get(P))==null?void 0:et.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,_),d.inboundAudioRtp.set(k.id,_),d.consumerStreamMap.get(P).inboundAudioRtpId.push(k.id),this.processInboundConsumerAudioStats(P,se,_)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((k,S)=>{var P,L,se,ae,N,_,ke,Na,La,Va,$a,xa,Ua,Ha,Ba,Fa,ja,qa,Ga,Wa,Ja,Ka,za;if(k.outboundVideoRtpId.length>0){const he=[];k.outboundVideoRtpId.forEach(vu=>{he.push(d.outboundVideoRtp.get(vu))});const Q=this.getWorkingSimulcastVideoStats(he);Q.score=Fm({frameWidth:Q.frameWidth||0,framesPerSecond:Q.framesPerSecond||0,jitter:((P=Q.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(Q.packetsSent||0)-(((L=this.videoProducerToStatsMap.get(S))==null?void 0:L.packetsSent)||0),packetsLost:(((se=Q.remoteData)==null?void 0:se.packetsLost)||0)-(((N=(ae=this.videoProducerToStatsMap.get(S))==null?void 0:ae.remoteData)==null?void 0:N.packetsLost)||0),framesEncoded:(Q.framesEncoded||0)-(((_=this.videoProducerToStatsMap.get(S))==null?void 0:_.framesEncoded)||0)}),T.set(S,{score:+(Q.score*10).toFixed(),frameWidth:Q.frameWidth||0,frameHeight:Q.frameHeight||0,framesPerSecond:Q.framesPerSecond||0,jitter:((ke=Q.remoteData)==null?void 0:ke.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:kd({packetsSent:(Q.packetsSent||0)-(((Na=this.videoProducerToStatsMap.get(S))==null?void 0:Na.packetsSent)||0),packetsLost:(((La=Q.remoteData)==null?void 0:La.packetsLost)||0)-((($a=(Va=this.videoProducerToStatsMap.get(S))==null?void 0:Va.remoteData)==null?void 0:$a.packetsLost)||0)}),bitrate:((Q.bytesSent||0)-(((xa=this.videoProducerToStatsMap.get(S))==null?void 0:xa.bytesSent)||0))*8/7,cpuLimitations:Q.qualityLimitationReason==="cpu",bandwidthLimitations:Q.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,Q)}else if(k.outboundAudioRtpId.length>0){const he=d.outboundAudioRtp.get(k.outboundAudioRtpId[0]);he.score=Bm({packetsSent:(he.packetsSent||0)-(((Ua=this.audioProducerToStatsMap.get(S))==null?void 0:Ua.packetsSent)||0),packetsLost:(((Ha=he.remoteData)==null?void 0:Ha.packetsLost)||0)-(((Fa=(Ba=this.audioProducerToStatsMap.get(S))==null?void 0:Ba.remoteData)==null?void 0:Fa.packetsLost)||0),jitter:((ja=he.remoteData)==null?void 0:ja.jitter)||0}),T.set(S,{score:+(he.score*10).toFixed(),bitrate:((he.bytesSent||0)-(((qa=this.audioProducerToStatsMap.get(S))==null?void 0:qa.bytesSent)||0))*8/7,packetsLostPercentage:kd({packetsSent:(he.packetsSent||0)-(((Ga=this.audioProducerToStatsMap.get(S))==null?void 0:Ga.packetsSent)||0),packetsLost:(((Wa=he.remoteData)==null?void 0:Wa.packetsLost)||0)-(((Ka=(Ja=this.audioProducerToStatsMap.get(S))==null?void 0:Ja.remoteData)==null?void 0:Ka.packetsLost)||0)}),jitter:((za=he.remoteData)==null?void 0:za.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,he)}}),f.forEach(k=>{const S=u.find(L=>L.id===k.localCandidateId?(k.localCandidateId=L.id,L):null),P=p.find(L=>L.id===k.remoteCandidateId?(k.remoteCandidateId=L.id,L):null);S&&(k.localCandidateType=S.type,k.localCandidateAddress=ri(S.address),k.localCandidatePort=S.port,k.localCandidateProtocol=S.protocol,k.localCandidateUrl=S.url,k.localCandidateNetworkType=S.networkType,k.localCandidateRelatedAddress=ri(S.relatedAddress),k.localCandidateRelatedPort=S.relatedPort),P&&(k.remoteCandidateType=P.type,k.remoteCandidateAddress=ri(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,L)=>{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},u=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),p=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:u,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||Mp},i=new Promise((u,p)=>{try{const f=new cv(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),a=new Promise((u,p)=>{try{const f=new dv(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),o=new Promise((u,p)=>{try{const f=new lv(r);f.addListener("done",u),f.addListener("failed",()=>{u({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||Mp},d=new ov(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 Jm.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?Ap(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?Ap(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 hv extends zm{}class Ym extends zm{constructor(){super(...arguments);h(this,"producerMap",new Map);h(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 R,I,D,A,x,$,U,z,ee,H,X,pe,et;const c=e,d=new Km,l=r.length?new Set(r):void 0,u=[],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":{u.push(this.getIceCandidateStats(k));break}case"remote-candidate":{p.push(this.getIceCandidateStats(k));break}case"candidate-pair":{const{nominated:S}=k,{selected:P}=k,L=k,se={nominated:S!=null?S:P,currentRoundTripTime:L.currentRoundTripTime,totalRoundTripTime:L.totalRoundTripTime,bytesReceived:L.bytesReceived,bytesSent:L.bytesSent,availableOutgoingBitrate:L.availableOutgoingBitrate,availableIncomingBitrate:L.availableIncomingBitrate,lastPacketReceivedTimestamp:L.lastPacketReceivedTimestamp,lastPacketSentTimestamp:L.lastPacketSentTimestamp,localCandidateId:L.localCandidateId,remoteCandidateId:L.remoteCandidateId,bytesDiscardedOnSend:L.bytesDiscardedOnSend,packetsSent:L.packetsSent,packetsReceived:L.packetsReceived,packetsDiscardedOnSend:L.packetsDiscardedOnSend};f.push(se),(k.nominated===!0||k.selected===!0)&&(d.candidatePair=se);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 L=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,L,P)}if(o.consuming){const L=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,L,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),L=this.pausedProducerMap.get(P);if(L){if(L.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const se=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 ae=this.callStatsInstance.producers.get(P);if(((R=ae==null?void 0:ae.track)==null?void 0:R.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const N={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 _=S,ke={frameHeight:_.frameHeight,frameWidth:_.frameWidth,framesEncoded:_.framesEncoded,framesDropped:_.framesDropped?_.framesDropped:_.droppedFrames,framesPerSecond:_.framesPerSecond?_.framesPerSecond:_.framerateMean,framesSent:_.framesSent,keyFramesEncoded:_.keyFramesEncoded,firCount:_.firCount,encoderImplementation:_.encoderImplementation,hugeFramesSent:_.hugeFramesSent,pliCount:_.pliCount,qpSum:_.qpSum,qualityLimitationReason:_.qualityLimitationReason,qualityLimitationDurations:_.qualityLimitationDurations,qualityLimitationResolutionChanges:_.qualityLimitationResolutionChanges,totalEncodeTime:_.totalEncodeTime,totalPacketSendDelay:_.totalEncodeTime,retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,scalabilityMode:_.scalabilityMode,powerEfficientEncoder:_.powerEfficientEncoder,...N};d.outboundVideoRtp.set(k.id,ke),d.producerStreamMap.get(P).outboundVideoRtpId.push(k.id),this.processOutboundProducerVideoStats(P,se,ke)}else if(S.mediaType==="audio"||S.kind==="audio"){const _=S,ke={retransmittedBytesSent:_.retransmittedBytesSent,retransmittedPacketsSent:_.retransmittedPacketsSent,...N};d.outboundAudioRtp.set(k.id,ke),d.producerStreamMap.get(P).outboundAudioRtpId.push(k.id),this.processOutboundProducerAudioStats(P,se,ke)}}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),L=this.pausedConsumerMap.get(P);if(L){if(L.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 se=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 ae={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 N=S,_={frameHeight:N.frameHeight,frameWidth:N.frameWidth,framesDecoded:N.framesDecoded,framesDropped:N.framesDropped?N.framesDropped:N.droppedFrames,framesPerSecond:N.framesPerSecond?N.framesPerSecond:N.framerateMean,framesReceived:N.framesReceived,keyFramesDecoded:N.keyFramesDecoded,firCount:N.firCount,decoderImplementation:N.decoderImplementation,pliCount:N.pliCount,totalProcessingDelay:N.totalProcessingDelay,qpSum:N.qpSum||0,totalAssemblyTime:N.totalAssemblyTime||0,totalDecodeTime:N.totalDecodeTime||0,totalFreezesDuration:N.totalFreezesDuration||0,totalInterFrameDelay:N.totalInterFrameDelay||0,totalPausesDuration:N.totalPausesDuration||0,totalSquaredInterFrameDelay:N.totalSquaredInterFrameDelay||0,freezeCount:N.freezeCount||0,pauseCount:N.pauseCount||0,powerEfficientDecoder:N.powerEfficientDecoder,...ae};_.score=Gm({frameWidth:_.frameWidth||0,framesDecoded:(_.framesDecoded||0)-(((I=this.videoConsumerToStatsMap.get(P))==null?void 0:I.framesDecoded)||0),framesPerSecond:_.framesPerSecond||0,packetsLost:(_.packetsLost||0)-(((D=this.videoConsumerToStatsMap.get(P))==null?void 0:D.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((A=this.videoConsumerToStatsMap.get(P))==null?void 0:A.packetsReceived)||0),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(_.score*10).toFixed(),frameWidth:_.frameWidth||0,frameHeight:_.frameHeight||0,framesPerSecond:_.framesPerSecond||0,packetsLostPercentage:Id({packetsLost:(_.packetsLost||0)-(((x=this.videoConsumerToStatsMap.get(P))==null?void 0:x.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((_.bytesReceived||0)-(((U=this.videoConsumerToStatsMap.get(P))==null?void 0:U.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,_),d.inboundVideoRtp.set(k.id,_),d.consumerStreamMap.get(P).inboundVideoRtpId.push(k.id),this.processInboundConsumerVideoStats(P,se,_)}else if(S.mediaType==="audio"||S.kind==="audio"){const N=S,_={audioLevel:N.audioLevel,concealedSamples:N.concealedSamples,concealmentEvents:N.concealmentEvents,totalAudioEnergy:N.totalAudioEnergy,totalSamplesDuration:N.totalSamplesDuration,totalSamplesReceived:N.totalSamplesReceived,fecPacketsDiscarded:N.fecPacketsDiscarded||0,fecPacketsReceived:N.fecPacketsReceived||0,insertedSamplesForDeceleration:N.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:N.removedSamplesForAcceleration||0,silentConcealedSamples:N.silentConcealedSamples||0,playoutId:N.playoutId,...ae};_.score=qm({concealmentEvents:(_.concealmentEvents||0)-(((z=this.audioConsumerToStatsMap.get(P))==null?void 0:z.concealmentEvents)||0),packetsLost:(_.packetsLost||0)-(((ee=this.audioConsumerToStatsMap.get(P))==null?void 0:ee.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((H=this.audioConsumerToStatsMap.get(P))==null?void 0:H.packetsReceived)||0),jitter:_.jitter||0}),E.set(P,{score:+(_.score*10).toFixed(),packetsLostPercentage:Id({packetsLost:(_.packetsLost||0)-(((X=this.audioConsumerToStatsMap.get(P))==null?void 0:X.packetsLost)||0),packetsReceived:(_.packetsReceived||0)-(((pe=this.audioConsumerToStatsMap.get(P))==null?void 0:pe.packetsReceived)||0)}),jitter:_.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((_.bytesReceived||0)-(((et=this.audioConsumerToStatsMap.get(P))==null?void 0:et.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,_),d.inboundAudioRtp.set(k.id,_),d.consumerStreamMap.get(P).inboundAudioRtpId.push(k.id),this.processInboundConsumerAudioStats(P,se,_)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((k,S)=>{var P,L,se,ae,N,_,ke,Na,La,Va,$a,xa,Ua,Ha,Ba,Fa,ja,qa,Ga,Wa,Ja,Ka,za;if(k.outboundVideoRtpId.length>0){const he=[];k.outboundVideoRtpId.forEach(vu=>{he.push(d.outboundVideoRtp.get(vu))});const Q=this.getWorkingSimulcastVideoStats(he);Q.score=Fm({frameWidth:Q.frameWidth||0,framesPerSecond:Q.framesPerSecond||0,jitter:((P=Q.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(Q.packetsSent||0)-(((L=this.videoProducerToStatsMap.get(S))==null?void 0:L.packetsSent)||0),packetsLost:(((se=Q.remoteData)==null?void 0:se.packetsLost)||0)-(((N=(ae=this.videoProducerToStatsMap.get(S))==null?void 0:ae.remoteData)==null?void 0:N.packetsLost)||0),framesEncoded:(Q.framesEncoded||0)-(((_=this.videoProducerToStatsMap.get(S))==null?void 0:_.framesEncoded)||0)}),T.set(S,{score:+(Q.score*10).toFixed(),frameWidth:Q.frameWidth||0,frameHeight:Q.frameHeight||0,framesPerSecond:Q.framesPerSecond||0,jitter:((ke=Q.remoteData)==null?void 0:ke.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:kd({packetsSent:(Q.packetsSent||0)-(((Na=this.videoProducerToStatsMap.get(S))==null?void 0:Na.packetsSent)||0),packetsLost:(((La=Q.remoteData)==null?void 0:La.packetsLost)||0)-((($a=(Va=this.videoProducerToStatsMap.get(S))==null?void 0:Va.remoteData)==null?void 0:$a.packetsLost)||0)}),bitrate:((Q.bytesSent||0)-(((xa=this.videoProducerToStatsMap.get(S))==null?void 0:xa.bytesSent)||0))*8/7,cpuLimitations:Q.qualityLimitationReason==="cpu",bandwidthLimitations:Q.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,Q)}else if(k.outboundAudioRtpId.length>0){const he=d.outboundAudioRtp.get(k.outboundAudioRtpId[0]);he.score=Bm({packetsSent:(he.packetsSent||0)-(((Ua=this.audioProducerToStatsMap.get(S))==null?void 0:Ua.packetsSent)||0),packetsLost:(((Ha=he.remoteData)==null?void 0:Ha.packetsLost)||0)-(((Fa=(Ba=this.audioProducerToStatsMap.get(S))==null?void 0:Ba.remoteData)==null?void 0:Fa.packetsLost)||0),jitter:((ja=he.remoteData)==null?void 0:ja.jitter)||0}),T.set(S,{score:+(he.score*10).toFixed(),bitrate:((he.bytesSent||0)-(((qa=this.audioProducerToStatsMap.get(S))==null?void 0:qa.bytesSent)||0))*8/7,packetsLostPercentage:kd({packetsSent:(he.packetsSent||0)-(((Ga=this.audioProducerToStatsMap.get(S))==null?void 0:Ga.packetsSent)||0),packetsLost:(((Wa=he.remoteData)==null?void 0:Wa.packetsLost)||0)-(((Ka=(Ja=this.audioProducerToStatsMap.get(S))==null?void 0:Ja.remoteData)==null?void 0:Ka.packetsLost)||0)}),jitter:((za=he.remoteData)==null?void 0:za.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,he)}}),f.forEach(k=>{const S=u.find(L=>L.id===k.localCandidateId?(k.localCandidateId=L.id,L):null),P=p.find(L=>L.id===k.remoteCandidateId?(k.remoteCandidateId=L.id,L):null);S&&(k.localCandidateType=S.type,k.localCandidateAddress=ri(S.address),k.localCandidatePort=S.port,k.localCandidateProtocol=S.protocol,k.localCandidateUrl=S.url,k.localCandidateNetworkType=S.networkType,k.localCandidateRelatedAddress=ri(S.relatedAddress),k.localCandidateRelatedPort=S.relatedPort),P&&(k.remoteCandidateType=P.type,k.remoteCandidateAddress=ri(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,L)=>{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(u=>{const p=e.outboundVideoRtp.get(u);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(u=>e.outboundAudioRtp.get(u))};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(u=>{const f=this.consumerMap.get(i).track.getSettings(),T=e.inboundVideoRtp.get(u);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(u=>e.inboundAudioRtp.get(u))}}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 pv extends Ym{}function Md(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 Dp(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=>{Md(this,t,e,o)}):a}catch(a){Md(this,t,e,a)}return null},s}const K=(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=>{Md(this,s,t,d)}):c}catch(c){Md(this,s,t,c)}return null},i},gv=(s,t)=>(e,r,i)=>{if(i)return Dp(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,Dp(o,s,t))}};var G=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 W=console;let F=class extends ft{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Nm.PROD,a,o,c,d,l){super();h(this,"observer");h(this,"eventHandler");h(this,"measurements");h(this,"producingTransport");h(this,"consumingTransport");h(this,"producers",new Map);h(this,"consumers",new Map);h(this,"iceServers");h(this,"connectionInfoPromise");h(this,"pingStatsTimeout");h(this,"logger");h(this,"env");h(this,"apiHostnames");h(this,"peerId");h(this,"consumerSharedMediaStatesMap",new Map);h(this,"currentUserMediaStates",{});if(!l)throw Error("authToken is missing but required to initialize CallStats!");switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new XT({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new hv;break;case"Gecko":this.measurements=new Ym;break;case"WebKit":this.measurements=new pv;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 ft,this.measurements.observer.on("consumer_score",u=>{o.debug(`callStats::consumer_score ${[...u.entries()]}`),this.eventHandler.emit("consumer_score",u)}),this.measurements.observer.on("producer_score",u=>{o.debug(`callStats::producer_score ${[...u.entries()]}`),this.eventHandler.emit("producer_score",u)})}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:O.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:O.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?O.SCREENSHARE_STARTED:O.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:O.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:O.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===Bt.AUDIO&&O.AUDIO_DEVICES_UPDATES||e===Bt.VIDEO&&O.VIDEO_DEVICES_UPDATES||e===Bt.SPEAKER&&O.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===Bt.AUDIO&&O.SELECTED_MICROHPONE_UPDATE||e===Bt.VIDEO&&O.SELECTED_CAMERA_UPDATE||e===Bt.SPEAKER&&O.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:O.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===Bt.AUDIO&&O.AUDIO_PLAY_FAILED||e===Bt.VIDEO&&O.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===Bt.AUDIO&&O.AUDIO_TRACK_MUTED||e===Bt.VIDEO&&O.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:O.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:O.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:O.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:O.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:O.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:O.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:O.NET_QUALITY_TEST_END,timestamp:r,metaData:a})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:O.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:O.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=O.AUDIO_ON:i=O.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=O.VIDEO_ON:i=O.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:O.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:O.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:O.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:O.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:O.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:O.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:O.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:O.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:O.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:O.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:O.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:O.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:O.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerIceServers",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerConsumer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerProducer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendConsumerSharedMediaStateEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerProducingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerConsumingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"deRegisterConsumer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"deRegisterProducer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"disconnectConsumingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"disconnectProducingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPreCallTestBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendScreenShareToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendScreenShareRequestedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendActiveSpeakerEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"devices",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"selectedDevice",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaPermission",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaPlaybackFailed",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaTrackMuted",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"tabChanged",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"browserBackgrounded",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"browserForegrounded",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"legacySwitch",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"getPreCallTestResults",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendCallJoinBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendNetworkQualityTestBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendWebSocketConnectedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendTransportConnectedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendAudioToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendVideoToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendParticipantRoleToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"startPingStats",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"stopPingStats",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPingStatsEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerRebufferEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerAudioBlockEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerInitializedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerWorkerErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerRecoverableErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerAnalyticsEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerQualityChanged",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPlayerLiveLatency",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendDisconnectEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendReconnectEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"expectedVideoResolution",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"expectedScreenshareResolution",null);F=G([gv(TypeError,(s,t)=>W.error(t,s))],F);const mv=F;class Qm extends ft{constructor(){super(...arguments);h(this,"stats");h(this,"peerId");h(this,"backend");h(this,"iceServers");h(this,"initialized",!1);h(this,"stalled",!1);h(this,"ipInformation");h(this,"logger")}async initialize({peerId:e,engineName:r,env:i=Nm.PROD,iceServers:a,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:p}){var f,T,E;try{if(this.peerId=e,this.logger=d,!p){this.logger.error("callStats::initialize",{event:"auth_token_missing",peerId:this.peerId}),this.stallCallStats();return}this.ipInformation=await Jm.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new mv(o,r,i,c,d,e,l,p),this.iceServers=a,(f=this.backend)==null||f.registerIceServers(this.iceServers),this.initialized=!0,(E=(T=this.backend)==null?void 0:T.eventHandler)==null||E.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(R){this.logger.error("callStats::CallStatsIntegration",{peerId:this.peerId,error:R instanceof Error?R.message:String(R),stack:R instanceof Error?R.stack:void 0}),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,u,p,f,T,E,R;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":(u=this.backend)==null||u.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":(R=this.backend)==null||R.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 fv=new Qm;fv.setMaxListeners(30);var Do;class Sv{constructor(){g(this,Do,void 0)}get telemetry(){var t;return(t=n(this,Do))==null?void 0:t.getValue("telemetry")}init(t){m(this,Do,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)}}Do=new WeakMap;function Op(s,t,e,r){try{t==null||t.error(`EventEmitter listener error on event ${e.toString()}`,{error:r,eventListener:{eventName:e.toString(),listenerCount:s.listenerCount(e)}});return}catch(i){return}}function _o(s,t,e,r){const i=s.rawListeners(t);return i.forEach(a=>{try{const o=Reflect.apply(a,s,e);o&&typeof o.then=="function"&&Promise.resolve(o).catch(c=>Op(s,r,t,c))}catch(o){Op(s,r,t,o)}}),i.length>0}class Ma extends ft.EventEmitter{constructor(e){super();h(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return _o(this,"*",[e,...r],this.logger),_o(this,e,r,this.logger)}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 xt extends ft.EventEmitter{constructor(e){super();h(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return _o(this,"*",[e,...r],this.logger),_o(this,e,r,this.logger)}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)}}var Fs,js;class Tv extends ft.EventEmitter{constructor(e){super();g(this,Fs,void 0);g(this,js,void 0);h(this,"asyncPromiseTimeout");h(this,"logger");this.logger=e,m(this,Fs,new Map),m(this,js,new Map),this.asyncPromiseTimeout=8e3}emit(e,...r){return _o(this,e,r,this.logger)}async emitAsync(e,...r){n(this,Fs).set(e,[]);const i=n(this,js).get(e).map(()=>new Promise(a=>{n(this,Fs).get(e).push(a)}));this.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,js).get(e)||n(this,js).set(e,[]),n(this,js).get(e).push(a),super.on(e,a)}reset(){m(this,Fs,new Map),m(this,js,new Map),super.removeAllListeners()}}Fs=new WeakMap,js=new WeakMap;var vv=typeof global=="object"&&global&&global.Object===Object&&global;const Xm=vv;var yv=typeof self=="object"&&self&&self.Object===Object&&self,Ev=Xm||yv||Function("return this")();const gs=Ev;var Pv=gs.Symbol;const Ns=Pv;var Zm=Object.prototype,wv=Zm.hasOwnProperty,_v=Zm.toString,Ya=Ns?Ns.toStringTag:void 0;function Cv(s){var t=wv.call(s,Ya),e=s[Ya];try{s[Ya]=void 0;var r=!0}catch(a){}var i=_v.call(s);return r&&(t?s[Ya]=e:delete s[Ya]),i}var Rv=Object.prototype,bv=Rv.toString;function kv(s){return bv.call(s)}var Iv="[object Null]",Mv="[object Undefined]",Np=Ns?Ns.toStringTag:void 0;function ln(s){return s==null?s===void 0?Mv:Iv:Np&&Np in Object(s)?Cv(s):kv(s)}function Ls(s){return s!=null&&typeof s=="object"}var Av="[object Symbol]";function tu(s){return typeof s=="symbol"||Ls(s)&&ln(s)==Av}function Dv(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 Ov=Array.isArray;const Vt=Ov;var Nv=1/0,Lp=Ns?Ns.prototype:void 0,Vp=Lp?Lp.toString:void 0;function ef(s){if(typeof s=="string")return s;if(Vt(s))return Dv(s,ef)+"";if(tu(s))return Vp?Vp.call(s):"";var t=s+"";return t=="0"&&1/s==-Nv?"-0":t}var Lv=/\s/;function Vv(s){for(var t=s.length;t--&&Lv.test(s.charAt(t)););return t}var $v=/^\s+/;function xv(s){return s&&s.slice(0,Vv(s)+1).replace($v,"")}function Zt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var $p=0/0,Uv=/^[-+]0x[0-9a-f]+$/i,Hv=/^0b[01]+$/i,Bv=/^0o[0-7]+$/i,Fv=parseInt;function xp(s){if(typeof s=="number")return s;if(tu(s))return $p;if(Zt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Zt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=xv(s);var e=Hv.test(s);return e||Bv.test(s)?Fv(s.slice(2),e?2:8):Uv.test(s)?$p:+s}function jh(s){return s}var jv="[object AsyncFunction]",qv="[object Function]",Gv="[object GeneratorFunction]",Wv="[object Proxy]";function qh(s){if(!Zt(s))return!1;var t=ln(s);return t==qv||t==Gv||t==jv||t==Wv}var Jv=gs["__core-js_shared__"];const Eu=Jv;var Up=function(){var s=/[^.]+$/.exec(Eu&&Eu.keys&&Eu.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function Kv(s){return!!Up&&Up in s}var zv=Function.prototype,Yv=zv.toString;function un(s){if(s!=null){try{return Yv.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var Qv=/[\\^$.*+?()[\]{}|]/g,Xv=/^\[object .+?Constructor\]$/,Zv=Function.prototype,ey=Object.prototype,ty=Zv.toString,sy=ey.hasOwnProperty,ry=RegExp("^"+ty.call(sy).replace(Qv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function iy(s){if(!Zt(s)||Kv(s))return!1;var t=qh(s)?ry:Xv;return t.test(un(s))}function ny(s,t){return s==null?void 0:s[t]}function hn(s,t){var e=ny(s,t);return iy(e)?e:void 0}var ay=hn(gs,"WeakMap");const Vu=ay;var Hp=Object.create,oy=function(){function s(){}return function(t){if(!Zt(t))return{};if(Hp)return Hp(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const cy=oy;function dy(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 ly(){}function tf(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var uy=800,hy=16,py=Date.now;function gy(s){var t=0,e=0;return function(){var r=py(),i=hy-(r-e);if(e=r,i>0){if(++t>=uy)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function my(s){return function(){return s}}var fy=function(){try{var s=hn(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const Ad=fy;var Sy=Ad?function(s,t){return Ad(s,"toString",{configurable:!0,enumerable:!1,value:my(t),writable:!0})}:jh;const Ty=Sy;var vy=gy(Ty);const yy=vy;function Ey(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function Py(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 wy(s){return s!==s}function _y(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function Cy(s,t,e){return t===t?_y(s,t,e):Py(s,wy,e)}function Ry(s,t){var e=s==null?0:s.length;return!!e&&Cy(s,t,0)>-1}var by=9007199254740991,ky=/^(?:0|[1-9]\d*)$/;function Gh(s,t){var e=typeof s;return t=t==null?by:t,!!t&&(e=="number"||e!="symbol"&&ky.test(s))&&s>-1&&s%1==0&&s<t}function Wh(s,t,e){t=="__proto__"&&Ad?Ad(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function Kc(s,t){return s===t||s!==s&&t!==t}var Iy=Object.prototype,My=Iy.hasOwnProperty;function sf(s,t,e){var r=s[t];(!(My.call(s,t)&&Kc(r,e))||e===void 0&&!(t in s))&&Wh(s,t,e)}function zc(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?Wh(e,c,d):sf(e,c,d)}return e}var Bp=Math.max;function Ay(s,t,e){return t=Bp(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,a=Bp(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),dy(s,this,c)}}function Dy(s,t){return yy(Ay(s,t,jh),s+"")}var Oy=9007199254740991;function Jh(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=Oy}function Yc(s){return s!=null&&Jh(s.length)&&!qh(s)}function Ny(s,t,e){if(!Zt(e))return!1;var r=typeof t;return(r=="number"?Yc(e)&&Gh(t,e.length):r=="string"&&t in e)?Kc(e[t],s):!1}function Ly(s){return Dy(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&&Ny(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 Vy=Object.prototype;function su(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||Vy;return s===e}function $y(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var xy="[object Arguments]";function Fp(s){return Ls(s)&&ln(s)==xy}var rf=Object.prototype,Uy=rf.hasOwnProperty,Hy=rf.propertyIsEnumerable,By=Fp(function(){return arguments}())?Fp:function(s){return Ls(s)&&Uy.call(s,"callee")&&!Hy.call(s,"callee")};const Co=By;function Fy(){return!1}var nf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,jp=nf&&typeof module=="object"&&module&&!module.nodeType&&module,jy=jp&&jp.exports===nf,qp=jy?gs.Buffer:void 0,qy=qp?qp.isBuffer:void 0,Gy=qy||Fy;const ba=Gy;var Wy="[object Arguments]",Jy="[object Array]",Ky="[object Boolean]",zy="[object Date]",Yy="[object Error]",Qy="[object Function]",Xy="[object Map]",Zy="[object Number]",eE="[object Object]",tE="[object RegExp]",sE="[object Set]",rE="[object String]",iE="[object WeakMap]",nE="[object ArrayBuffer]",aE="[object DataView]",oE="[object Float32Array]",cE="[object Float64Array]",dE="[object Int8Array]",lE="[object Int16Array]",uE="[object Int32Array]",hE="[object Uint8Array]",pE="[object Uint8ClampedArray]",gE="[object Uint16Array]",mE="[object Uint32Array]",Te={};Te[oE]=Te[cE]=Te[dE]=Te[lE]=Te[uE]=Te[hE]=Te[pE]=Te[gE]=Te[mE]=!0;Te[Wy]=Te[Jy]=Te[nE]=Te[Ky]=Te[aE]=Te[zy]=Te[Yy]=Te[Qy]=Te[Xy]=Te[Zy]=Te[eE]=Te[tE]=Te[sE]=Te[rE]=Te[iE]=!1;function fE(s){return Ls(s)&&Jh(s.length)&&!!Te[ln(s)]}function Kh(s){return function(t){return s(t)}}var af=typeof exports=="object"&&exports&&!exports.nodeType&&exports,go=af&&typeof module=="object"&&module&&!module.nodeType&&module,SE=go&&go.exports===af,Pu=SE&&Xm.process,TE=function(){try{var s=go&&go.require&&go.require("util").types;return s||Pu&&Pu.binding&&Pu.binding("util")}catch(t){}}();const ka=TE;var Gp=ka&&ka.isTypedArray,vE=Gp?Kh(Gp):fE;const ru=vE;var yE=Object.prototype,EE=yE.hasOwnProperty;function of(s,t){var e=Vt(s),r=!e&&Co(s),i=!e&&!r&&ba(s),a=!e&&!r&&!i&&ru(s),o=e||r||i||a,c=o?$y(s.length,String):[],d=c.length;for(var l in s)(t||EE.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||a&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||Gh(l,d)))&&c.push(l);return c}function cf(s,t){return function(e){return s(t(e))}}var PE=cf(Object.keys,Object);const wE=PE;var _E=Object.prototype,CE=_E.hasOwnProperty;function df(s){if(!su(s))return wE(s);var t=[];for(var e in Object(s))CE.call(s,e)&&e!="constructor"&&t.push(e);return t}function iu(s){return Yc(s)?of(s):df(s)}function RE(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var bE=Object.prototype,kE=bE.hasOwnProperty;function IE(s){if(!Zt(s))return RE(s);var t=su(s),e=[];for(var r in s)r=="constructor"&&(t||!kE.call(s,r))||e.push(r);return e}function Qc(s){return Yc(s)?of(s,!0):IE(s)}var ME=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,AE=/^\w*$/;function zh(s,t){if(Vt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||tu(s)?!0:AE.test(s)||!ME.test(s)||t!=null&&s in Object(t)}var DE=hn(Object,"create");const Ro=DE;function OE(){this.__data__=Ro?Ro(null):{},this.size=0}function NE(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var LE="__lodash_hash_undefined__",VE=Object.prototype,$E=VE.hasOwnProperty;function xE(s){var t=this.__data__;if(Ro){var e=t[s];return e===LE?void 0:e}return $E.call(t,s)?t[s]:void 0}var UE=Object.prototype,HE=UE.hasOwnProperty;function BE(s){var t=this.__data__;return Ro?t[s]!==void 0:HE.call(t,s)}var FE="__lodash_hash_undefined__";function jE(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=Ro&&t===void 0?FE:t,this}function cn(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])}}cn.prototype.clear=OE;cn.prototype.delete=NE;cn.prototype.get=xE;cn.prototype.has=BE;cn.prototype.set=jE;function qE(){this.__data__=[],this.size=0}function nu(s,t){for(var e=s.length;e--;)if(Kc(s[e][0],t))return e;return-1}var GE=Array.prototype,WE=GE.splice;function JE(s){var t=this.__data__,e=nu(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():WE.call(t,e,1),--this.size,!0}function KE(s){var t=this.__data__,e=nu(t,s);return e<0?void 0:t[e][1]}function zE(s){return nu(this.__data__,s)>-1}function YE(s,t){var e=this.__data__,r=nu(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,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=qE;fr.prototype.delete=JE;fr.prototype.get=KE;fr.prototype.has=zE;fr.prototype.set=YE;var QE=hn(gs,"Map");const bo=QE;function XE(){this.size=0,this.__data__={hash:new cn,map:new(bo||fr),string:new cn}}function ZE(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function au(s,t){var e=s.__data__;return ZE(t)?e[typeof t=="string"?"string":"hash"]:e.map}function eP(s){var t=au(this,s).delete(s);return this.size-=t?1:0,t}function tP(s){return au(this,s).get(s)}function sP(s){return au(this,s).has(s)}function rP(s,t){var e=au(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function Sr(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])}}Sr.prototype.clear=XE;Sr.prototype.delete=eP;Sr.prototype.get=tP;Sr.prototype.has=sP;Sr.prototype.set=rP;var iP="Expected a function";function Yh(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(iP);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(Yh.Cache||Sr),e}Yh.Cache=Sr;var nP=500;function aP(s){var t=Yh(s,function(r){return e.size===nP&&e.clear(),r}),e=t.cache;return t}var oP=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,cP=/\\(\\)?/g,dP=aP(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(oP,function(e,r,i,a){t.push(i?a.replace(cP,"$1"):r||e)}),t});const lP=dP;function uP(s){return s==null?"":ef(s)}function lf(s,t){return Vt(s)?s:zh(s,t)?[s]:lP(uP(s))}var hP=1/0;function ou(s){if(typeof s=="string"||tu(s))return s;var t=s+"";return t=="0"&&1/s==-hP?"-0":t}function uf(s,t){t=lf(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[ou(t[e++])];return e&&e==r?s:void 0}function pP(s,t,e){var r=s==null?void 0:uf(s,t);return r===void 0?e:r}function hf(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var gP=cf(Object.getPrototypeOf,Object);const Qh=gP;var mP="[object Object]",fP=Function.prototype,SP=Object.prototype,pf=fP.toString,TP=SP.hasOwnProperty,vP=pf.call(Object);function yP(s){if(!Ls(s)||ln(s)!=mP)return!1;var t=Qh(s);if(t===null)return!0;var e=TP.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&pf.call(e)==vP}function EP(){this.__data__=new fr,this.size=0}function PP(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function wP(s){return this.__data__.get(s)}function _P(s){return this.__data__.has(s)}var CP=200;function RP(s,t){var e=this.__data__;if(e instanceof fr){var r=e.__data__;if(!bo||r.length<CP-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new Sr(r)}return e.set(s,t),this.size=e.size,this}function ps(s){var t=this.__data__=new fr(s);this.size=t.size}ps.prototype.clear=EP;ps.prototype.delete=PP;ps.prototype.get=wP;ps.prototype.has=_P;ps.prototype.set=RP;function bP(s,t){return s&&zc(t,iu(t),s)}function kP(s,t){return s&&zc(t,Qc(t),s)}var gf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Wp=gf&&typeof module=="object"&&module&&!module.nodeType&&module,IP=Wp&&Wp.exports===gf,Jp=IP?gs.Buffer:void 0,Kp=Jp?Jp.allocUnsafe:void 0;function mf(s,t){if(t)return s.slice();var e=s.length,r=Kp?Kp(e):new s.constructor(e);return s.copy(r),r}function MP(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 ff(){return[]}var AP=Object.prototype,DP=AP.propertyIsEnumerable,zp=Object.getOwnPropertySymbols,OP=zp?function(s){return s==null?[]:(s=Object(s),MP(zp(s),function(t){return DP.call(s,t)}))}:ff;const Xh=OP;function NP(s,t){return zc(s,Xh(s),t)}var LP=Object.getOwnPropertySymbols,VP=LP?function(s){for(var t=[];s;)hf(t,Xh(s)),s=Qh(s);return t}:ff;const Sf=VP;function $P(s,t){return zc(s,Sf(s),t)}function Tf(s,t,e){var r=t(s);return Vt(s)?r:hf(r,e(s))}function $u(s){return Tf(s,iu,Xh)}function xP(s){return Tf(s,Qc,Sf)}var UP=hn(gs,"DataView");const xu=UP;var HP=hn(gs,"Promise");const Uu=HP;var BP=hn(gs,"Set");const Rn=BP;var Yp="[object Map]",FP="[object Object]",Qp="[object Promise]",Xp="[object Set]",Zp="[object WeakMap]",eg="[object DataView]",jP=un(xu),qP=un(bo),GP=un(Uu),WP=un(Rn),JP=un(Vu),li=ln;(xu&&li(new xu(new ArrayBuffer(1)))!=eg||bo&&li(new bo)!=Yp||Uu&&li(Uu.resolve())!=Qp||Rn&&li(new Rn)!=Xp||Vu&&li(new Vu)!=Zp)&&(li=function(s){var t=ln(s),e=t==FP?s.constructor:void 0,r=e?un(e):"";if(r)switch(r){case jP:return eg;case qP:return Yp;case GP:return Qp;case WP:return Xp;case JP:return Zp}return t});const Ia=li;var KP=Object.prototype,zP=KP.hasOwnProperty;function YP(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&zP.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var QP=gs.Uint8Array;const Dd=QP;function Zh(s){var t=new s.constructor(s.byteLength);return new Dd(t).set(new Dd(s)),t}function XP(s,t){var e=t?Zh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var ZP=/\w*$/;function ew(s){var t=new s.constructor(s.source,ZP.exec(s));return t.lastIndex=s.lastIndex,t}var tg=Ns?Ns.prototype:void 0,sg=tg?tg.valueOf:void 0;function tw(s){return sg?Object(sg.call(s)):{}}function vf(s,t){var e=t?Zh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var sw="[object Boolean]",rw="[object Date]",iw="[object Map]",nw="[object Number]",aw="[object RegExp]",ow="[object Set]",cw="[object String]",dw="[object Symbol]",lw="[object ArrayBuffer]",uw="[object DataView]",hw="[object Float32Array]",pw="[object Float64Array]",gw="[object Int8Array]",mw="[object Int16Array]",fw="[object Int32Array]",Sw="[object Uint8Array]",Tw="[object Uint8ClampedArray]",vw="[object Uint16Array]",yw="[object Uint32Array]";function Ew(s,t,e){var r=s.constructor;switch(t){case lw:return Zh(s);case sw:case rw:return new r(+s);case uw:return XP(s,e);case hw:case pw:case gw:case mw:case fw:case Sw:case Tw:case vw:case yw:return vf(s,e);case iw:return new r;case nw:case cw:return new r(s);case aw:return ew(s);case ow:return new r;case dw:return tw(s)}}function yf(s){return typeof s.constructor=="function"&&!su(s)?cy(Qh(s)):{}}var Pw="[object Map]";function ww(s){return Ls(s)&&Ia(s)==Pw}var rg=ka&&ka.isMap,_w=rg?Kh(rg):ww;const Cw=_w;var Rw="[object Set]";function bw(s){return Ls(s)&&Ia(s)==Rw}var ig=ka&&ka.isSet,kw=ig?Kh(ig):bw;const Iw=kw;var Mw=1,Aw=2,Dw=4,Ef="[object Arguments]",Ow="[object Array]",Nw="[object Boolean]",Lw="[object Date]",Vw="[object Error]",Pf="[object Function]",$w="[object GeneratorFunction]",xw="[object Map]",Uw="[object Number]",wf="[object Object]",Hw="[object RegExp]",Bw="[object Set]",Fw="[object String]",jw="[object Symbol]",qw="[object WeakMap]",Gw="[object ArrayBuffer]",Ww="[object DataView]",Jw="[object Float32Array]",Kw="[object Float64Array]",zw="[object Int8Array]",Yw="[object Int16Array]",Qw="[object Int32Array]",Xw="[object Uint8Array]",Zw="[object Uint8ClampedArray]",e_="[object Uint16Array]",t_="[object Uint32Array]",fe={};fe[Ef]=fe[Ow]=fe[Gw]=fe[Ww]=fe[Nw]=fe[Lw]=fe[Jw]=fe[Kw]=fe[zw]=fe[Yw]=fe[Qw]=fe[xw]=fe[Uw]=fe[wf]=fe[Hw]=fe[Bw]=fe[Fw]=fe[jw]=fe[Xw]=fe[Zw]=fe[e_]=fe[t_]=!0;fe[Vw]=fe[Pf]=fe[qw]=!1;function mo(s,t,e,r,i,a){var o,c=t&Mw,d=t&Aw,l=t&Dw;if(e&&(o=i?e(s,r,i,a):e(s)),o!==void 0)return o;if(!Zt(s))return s;var u=Vt(s);if(u){if(o=YP(s),!c)return tf(s,o)}else{var p=Ia(s),f=p==Pf||p==$w;if(ba(s))return mf(s,c);if(p==wf||p==Ef||f&&!i){if(o=d||f?{}:yf(s),!c)return d?$P(s,kP(o,s)):NP(s,bP(o,s))}else{if(!fe[p])return i?s:{};o=Ew(s,p,c)}}a||(a=new ps);var T=a.get(s);if(T)return T;a.set(s,o),Iw(s)?s.forEach(function(I){o.add(mo(I,t,e,I,s,a))}):Cw(s)&&s.forEach(function(I,D){o.set(D,mo(I,t,e,D,s,a))});var E=l?d?xP:$u:d?Qc:iu,R=u?void 0:E(s);return Ey(R||s,function(I,D){R&&(D=I,I=s[D]),sf(o,D,mo(I,t,e,D,s,a))}),o}var s_=4;function r_(s){return mo(s,s_)}var i_=1,n_=4;function ep(s){return mo(s,i_|n_)}var a_="__lodash_hash_undefined__";function o_(s){return this.__data__.set(s,a_),this}function c_(s){return this.__data__.has(s)}function ko(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new Sr;++t<e;)this.add(s[t])}ko.prototype.add=ko.prototype.push=o_;ko.prototype.has=c_;function d_(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 _f(s,t){return s.has(t)}var l_=1,u_=2;function Cf(s,t,e,r,i,a){var o=e&l_,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=a.get(s),u=a.get(t);if(l&&u)return l==t&&u==s;var p=-1,f=!0,T=e&u_?new ko:void 0;for(a.set(s,t),a.set(t,s);++p<c;){var E=s[p],R=t[p];if(r)var I=o?r(R,E,p,t,s,a):r(E,R,p,s,t,a);if(I!==void 0){if(I)continue;f=!1;break}if(T){if(!d_(t,function(D,A){if(!_f(T,A)&&(E===D||i(E,D,e,r,a)))return T.push(A)})){f=!1;break}}else if(!(E===R||i(E,R,e,r,a))){f=!1;break}}return a.delete(s),a.delete(t),f}function h_(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function tp(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var p_=1,g_=2,m_="[object Boolean]",f_="[object Date]",S_="[object Error]",T_="[object Map]",v_="[object Number]",y_="[object RegExp]",E_="[object Set]",P_="[object String]",w_="[object Symbol]",__="[object ArrayBuffer]",C_="[object DataView]",ng=Ns?Ns.prototype:void 0,wu=ng?ng.valueOf:void 0;function R_(s,t,e,r,i,a,o){switch(e){case C_:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case __:return!(s.byteLength!=t.byteLength||!a(new Dd(s),new Dd(t)));case m_:case f_:case v_:return Kc(+s,+t);case S_:return s.name==t.name&&s.message==t.message;case y_:case P_:return s==t+"";case T_:var c=h_;case E_:var d=r&p_;if(c||(c=tp),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=g_,o.set(s,t);var u=Cf(c(s),c(t),r,i,a,o);return o.delete(s),u;case w_:if(wu)return wu.call(s)==wu.call(t)}return!1}var b_=1,k_=Object.prototype,I_=k_.hasOwnProperty;function M_(s,t,e,r,i,a){var o=e&b_,c=$u(s),d=c.length,l=$u(t),u=l.length;if(d!=u&&!o)return!1;for(var p=d;p--;){var f=c[p];if(!(o?f in t:I_.call(t,f)))return!1}var T=a.get(s),E=a.get(t);if(T&&E)return T==t&&E==s;var R=!0;a.set(s,t),a.set(t,s);for(var I=o;++p<d;){f=c[p];var D=s[f],A=t[f];if(r)var x=o?r(A,D,f,t,s,a):r(D,A,f,s,t,a);if(!(x===void 0?D===A||i(D,A,e,r,a):x)){R=!1;break}I||(I=f=="constructor")}if(R&&!I){var $=s.constructor,U=t.constructor;$!=U&&"constructor"in s&&"constructor"in t&&!(typeof $=="function"&&$ instanceof $&&typeof U=="function"&&U instanceof U)&&(R=!1)}return a.delete(s),a.delete(t),R}var A_=1,ag="[object Arguments]",og="[object Array]",id="[object Object]",D_=Object.prototype,cg=D_.hasOwnProperty;function O_(s,t,e,r,i,a){var o=Vt(s),c=Vt(t),d=o?og:Ia(s),l=c?og:Ia(t);d=d==ag?id:d,l=l==ag?id:l;var u=d==id,p=l==id,f=d==l;if(f&&ba(s)){if(!ba(t))return!1;o=!0,u=!1}if(f&&!u)return a||(a=new ps),o||ru(s)?Cf(s,t,e,r,i,a):R_(s,t,d,e,r,i,a);if(!(e&A_)){var T=u&&cg.call(s,"__wrapped__"),E=p&&cg.call(t,"__wrapped__");if(T||E){var R=T?s.value():s,I=E?t.value():t;return a||(a=new ps),i(R,I,e,r,a)}}return f?(a||(a=new ps),M_(s,t,e,r,i,a)):!1}function cu(s,t,e,r,i){return s===t?!0:s==null||t==null||!Ls(s)&&!Ls(t)?s!==s&&t!==t:O_(s,t,e,r,cu,i)}var N_=1,L_=2;function V_(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],u=c[1];if(o&&c[2]){if(l===void 0&&!(d in s))return!1}else{var p=new ps;if(r)var f=r(l,u,d,s,t,p);if(!(f===void 0?cu(u,l,N_|L_,r,p):f))return!1}}return!0}function Rf(s){return s===s&&!Zt(s)}function $_(s){for(var t=iu(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,Rf(i)]}return t}function bf(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function x_(s){var t=$_(s);return t.length==1&&t[0][2]?bf(t[0][0],t[0][1]):function(e){return e===s||V_(e,s,t)}}function U_(s,t){return s!=null&&t in Object(s)}function H_(s,t,e){t=lf(t,s);for(var r=-1,i=t.length,a=!1;++r<i;){var o=ou(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&&Jh(i)&&Gh(o,i)&&(Vt(s)||Co(s)))}function B_(s,t){return s!=null&&H_(s,t,U_)}var F_=1,j_=2;function q_(s,t){return zh(s)&&Rf(t)?bf(ou(s),t):function(e){var r=pP(e,s);return r===void 0&&r===t?B_(e,s):cu(t,r,F_|j_)}}function G_(s){return function(t){return t==null?void 0:t[s]}}function W_(s){return function(t){return uf(t,s)}}function J_(s){return zh(s)?G_(ou(s)):W_(s)}function K_(s){return typeof s=="function"?s:s==null?jh:typeof s=="object"?Vt(s)?q_(s[0],s[1]):x_(s):J_(s)}function z_(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 Y_=z_();const Q_=Y_;var X_=function(){return gs.Date.now()};const _u=X_;var Z_="Expected a function",eC=Math.max,tC=Math.min;function sp(s,t,e){var r,i,a,o,c,d,l=0,u=!1,p=!1,f=!0;if(typeof s!="function")throw new TypeError(Z_);t=xp(t)||0,Zt(e)&&(u=!!e.leading,p="maxWait"in e,a=p?eC(xp(e.maxWait)||0,t):a,f="trailing"in e?!!e.trailing:f);function T(z){var ee=r,H=i;return r=i=void 0,l=z,o=s.apply(H,ee),o}function E(z){return l=z,c=setTimeout(D,t),u?T(z):o}function R(z){var ee=z-d,H=z-l,X=t-ee;return p?tC(X,a-H):X}function I(z){var ee=z-d,H=z-l;return d===void 0||ee>=t||ee<0||p&&H>=a}function D(){var z=_u();if(I(z))return A(z);c=setTimeout(D,R(z))}function A(z){return c=void 0,f&&r?T(z):(r=i=void 0,o)}function x(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function $(){return c===void 0?o:A(_u())}function U(){var z=_u(),ee=I(z);if(r=arguments,i=this,d=z,ee){if(c===void 0)return E(d);if(p)return clearTimeout(c),c=setTimeout(D,t),T(d)}return c===void 0&&(c=setTimeout(D,t)),o}return U.cancel=x,U.flush=$,U}function Hu(s,t,e){(e!==void 0&&!Kc(s[t],e)||e===void 0&&!(t in s))&&Wh(s,t,e)}function sC(s){return Ls(s)&&Yc(s)}function Bu(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function rC(s){return zc(s,Qc(s))}function iC(s,t,e,r,i,a,o){var c=Bu(s,e),d=Bu(t,e),l=o.get(d);if(l){Hu(s,e,l);return}var u=a?a(c,d,e+"",s,t,o):void 0,p=u===void 0;if(p){var f=Vt(d),T=!f&&ba(d),E=!f&&!T&&ru(d);u=d,f||T||E?Vt(c)?u=c:sC(c)?u=tf(c):T?(p=!1,u=mf(d,!0)):E?(p=!1,u=vf(d,!0)):u=[]:yP(d)||Co(d)?(u=c,Co(c)?u=rC(c):(!Zt(c)||qh(c))&&(u=yf(d))):p=!1}p&&(o.set(d,u),i(u,d,r,a,o),o.delete(d)),Hu(s,e,u)}function kf(s,t,e,r,i){s!==t&&Q_(t,function(a,o){if(i||(i=new ps),Zt(a))iC(s,t,o,e,kf,r,i);else{var c=r?r(Bu(s,o),a,o+"",s,t,i):void 0;c===void 0&&(c=a),Hu(s,o,c)}},Qc)}function nC(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 aC="[object Map]",oC="[object Set]",cC=Object.prototype,dC=cC.hasOwnProperty;function lC(s){if(s==null)return!0;if(Yc(s)&&(Vt(s)||typeof s=="string"||typeof s.splice=="function"||ba(s)||ru(s)||Co(s)))return!s.length;var t=Ia(s);if(t==aC||t==oC)return!s.size;if(su(s))return!df(s).length;for(var e in s)if(dC.call(s,e))return!1;return!0}function uC(s,t){return cu(s,t)}var hC=Ly(function(s,t,e){kf(s,t,e)});const wr=hC;var pC=1/0,gC=Rn&&1/tp(new Rn([,-0]))[1]==pC?function(s){return new Rn(s)}:ly;const mC=gC;var fC=200;function SC(s,t,e){var r=-1,i=Ry,a=s.length,o=!0,c=[],d=c;if(e)o=!1,i=nC;else if(a>=fC){var l=t?null:mC(s);if(l)return tp(l);o=!1,i=_f,d=new ko}else d=t?[]:c;e:for(;++r<a;){var u=s[r],p=t?t(u):u;if(u=e||u!==0?u:0,o&&p===p){for(var f=d.length;f--;)if(d[f]===p)continue e;t&&d.push(p),c.push(u)}else i(d,p,e)||(d!==c&&d.push(p),c.push(u))}return c}function TC(s,t){return s&&s.length?SC(s,K_(t)):[]}function gd(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 vC={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},dg={STAGING:"staging",PROD:"prod"},yC={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 Io(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function EC({baseURI:s}){return s.includes("staging.realtime")?dg.STAGING:dg.PROD}function Od({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function rp({servicePrefix:s,baseURI:t}){const e=s==="ws"?"wss":"https",r=Od({servicePrefix:"api",baseURI:t});return`${e}://${r}/${s}`}function PC(s){const t=s.getValue("baseURI");return{location:Od({servicePrefix:"location",baseURI:t}),locationLegacy:Od({servicePrefix:"location-legacy",baseURI:t}),daCollector:rp({servicePrefix:"telemetry",baseURI:t}).replace("https://","")}}const wC='<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>',_C='<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>',nd=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})},fi={logs:"https://api.realtime.cloudflare.com/logs",mock:{url:"https://api.realtime.cloudflare.com/mock",domain:"mock.realtime.cloudflare.com",app:"https://examples.realtime.cloudflare.com/meeting",stagingApp:"https://examples.staging.realtime.cloudflare.com/meeting"},apiBase:{prod:"https://api.realtime.cloudflare.com",staging:"https://api.staging.realtime.cloudflare.com",prodAlternate:"https://api.realtime.cloudflare.com"},baseURI:{prod:"realtime.cloudflare.com",staging:"staging.realtime.cloudflare.com"}},CC=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/,Fu="__rtk_plugins__",RC=[Fu];function If(s){var r,i,a;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(fi.baseURI.staging)),e=!!((a=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&a.logs);return t||e}function bC(s,t){var r;const e=(r=s==null?void 0:s.getValue("telemetry"))==null?void 0:r.logLevel;if(e==="off")return!1;if(e!=="all"){const i=["debug","log","info","warn","error"],a=i.indexOf(t.toLowerCase()),o=i.indexOf(e);if(a<o)return!1}return!0}function Mf(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"?Mf(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function lg(s,t,e={},r=""){const i={};try{const a=JSON.stringify(e),o=JSON.parse(a),c=Mf(o,r),d=JSON.stringify(c);if(!(t==null?void 0:t.startsWith("[SDP]"))&&d.length>5e3){const u=`Log named: "${t}" is trying to log an flattened object of size
|
|
5
|
+
${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw If(s)&&console.error(u,{log:e,flattened:d}),new Error(u)}return JSON.parse(d)}catch(a){const o=gd(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}class y{constructor(){h(this,"logsCache",[]);h(this,"logsProcessorTimer");h(this,"compressionSupported",null);h(this,"tracingEnabled",!0);h(this,"initialized",!1);h(this,"logLevel","log");h(this,"logsProcessingInterval",7e3);h(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"]);h(this,"meetingMetadata",{})}isCompressionSupported(){if(this.compressionSupported===null)try{this.compressionSupported=typeof CompressionStream!="undefined"&&typeof Blob!="undefined"&&typeof Blob.prototype.stream=="function"&&typeof Response!="undefined"}catch(t){this.compressionSupported=!1,this.addLogInCurrentSpan("warn","Compression feature detection failed, using uncompressed logs",{error:t})}return this.compressionSupported}get logsEndpoint(){const t=ii.getContext(this.meetingMetadata.peerId);return rp({servicePrefix:"logs",baseURI:t.getValue("baseURI")})}get logsBatchSize(){return this.isCompressionSupported()?50:25}resetPeerId(t){this.meetingMetadata.peerId=t}init(t,e,r,i){this.tracingEnabled=!0,this.initialized=!1,i&&(this.logLevel=i),this.logsCache=[];const a=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=a,this.meetingMetadata.sdkVersion=t.getValue("sdkVersion");const{RNDeviceInfoImpl:o}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?o==null?void 0:o.getDeviceInfo():ve.getDeviceInfo(),this.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,this.logsProcessorTimer=setInterval(()=>this.processCachedLogs().catch(()=>{}),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){const l=this==null?void 0:this.telemetry;if(!l||!l.initialized||navigator.isReactNative||!l.tracingEnabled)return o.apply(this,d);l.addLogInCurrentSpan("info",t,e);const u=performance.now(),p=o.apply(this,d);return Promise.resolve(p).then(()=>{const f=performance.now();f-u>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:f-u})}).catch(()=>{const f=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:f-u})}),p},a}}injectContext(t){var i;const e=hr.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:gd(r.error)});const a=ii.getContext(this.meetingMetadata.peerId);if(If(a)&&(lC(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!bC(a,t))try{const c=lg(a,e,r,"metadata"),d=new Date,l={message:e,level:t,...c,loggedAt:d.toISOString(),loggedAtTzOffset:d.getTimezoneOffset()};i?this.sendOtelLogsToNewRelic([l],{isInDestructionMode:!1}).catch(()=>{}):this.logsCache.push(l)}catch(c){this.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:gd(c)})}}async sendOtelLogsToNewRelic(t,{isInDestructionMode:e=!1}={isInDestructionMode:!1}){const r=new AbortController,i=setTimeout(()=>r.abort("Logs request timed out after 8 seconds"),8e3);try{const a=ii.getContext(this.meetingMetadata.peerId),o=JSON.stringify({meetingMetadata:lg(a,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:a.getValue("sdkName"),logs:t});let c;const d={Authorization:`Bearer ${a.getValue("authToken")}`};if(this.isCompressionSupported()){const l=new Blob([o]).stream().pipeThrough(new CompressionStream("gzip"));c=await new Response(l).arrayBuffer(),d["Content-Type"]="application/gzip",d["Content-Encoding"]="gzip"}else c=o,d["Content-Type"]="application/json";await fetch(this.logsEndpoint,{method:"POST",headers:d,body:c,signal:r.signal,keepalive:!!e})}catch(a){e||(this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:gd(a)}),this.logsCache.push(...t))}finally{clearTimeout(i)}}async processCachedLogs({isInDestructionMode:t=!1}={isInDestructionMode:!1}){const e=this.logsCache.splice(0,this.logsBatchSize);e!=null&&e.length&&await this.sendOtelLogsToNewRelic(e,{isInDestructionMode:t})}async destruct(){for(clearInterval(this.logsProcessorTimer);this.logsCache.length;)await this.processCachedLogs({isInDestructionMode:!0})}}function kC(s){const t={...s},e=new Map,r=(l,u)=>(e.has(l)||e.set(l,new Set),e.get(l).add(u),()=>{var p;return(p=e.get(l))==null?void 0:p.delete(u)}),i=(l,u)=>{var p;(p=e.get(l))==null||p.delete(u)},a=l=>{var u;(u=e.get(l))==null||u.forEach(p=>{try{p(t[l])}catch(f){}})};return{subscribe:r,unsubscribe:i,notify:a,setValue:(l,u,p=!0)=>{t[l]=u,p&&a(l)},getValue:l=>t[l],getAllValues:()=>t}}class IC{constructor(){h(this,"contexts",new Map);h(this,"mostRecentPeerId",null)}createContext(t,e){if(this.contexts.has(t))return this.contexts.get(t);const r=new y,i=new Sv;this.contexts.set(t,kC(e)),this.contexts.get(t).setValue("peerSessionStore",new Tv(i));const a=new Qm;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.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 ii=new IC,MC={"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"},md={"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","0014":"Failed to establish media connection.","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","0604":"Active plugins store is not available yet","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(md).forEach(s=>{md[s]=`{${MC[s.slice(0,2)]}} ${md[s]}`});class C extends Error{constructor(e,r,i=void 0,a=!1){super(e);h(this,"code");this.code=r,this.name="ClientError";const o=this.code?`[ERR${this.code}]`:"[ERR]",c=this.code?md[this.code]:"";this.message=`${o}: ${c}
|
|
6
|
+
${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=ii.getContext(ii.getMostRecentPeerId());if(l){const u=l.getValue("onError");try{u(this)}catch(p){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(d){}}}function ad(s,t,e,r){if(r instanceof C)throw r;if(r instanceof t){const i=new C(r.message,e);throw i.stack=r.stack,i}else throw r}function ug(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){ad(this,t,e,o)}}),a&&(s.set=function(o){try{return a.apply(this,[o])}catch(c){ad(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=>{ad(this,t,e,o)}):a}catch(a){ad(this,t,e,a)}},s}function AC(s,t){return(e,r,i)=>{if(i)return ug(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,ug(o,s,t))}}}const rt=s=>AC(Error,s);var hs=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(hs||{}),j=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(j||{}),Xg;typeof process!="undefined"&&(Xg=process==null?void 0:process.env)!=null&&Xg.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var Af=[-2,-1,0,1,2],DC=[0,1,2,3,4];function OC(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 NC=(s,t,e)=>{let r,i,a;if(t==0)r=i=a=e;else{const o=(l,u,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?l+(u-l)*6*p:p<.5?u:p<.6666666666666666?l+(u-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)]},LC=(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]},VC=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},Df=(s,t=Af,e=.4)=>{const r=[],[i,a,o]=OC(s),[c,d,l]=LC(i,a,o),u=Math.round(l*100);u>70?e=.8:u>60?e=.9:u<10?e=.075:u<42&&(e=.3);const p=t.findIndex(I=>I===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-u)/f,R=u/T;for(const I of t){let D;I<0?D=u+I*R*e:I>0?D=u+I*E*e:D=u;const[A,x,$]=NC(c,d,D/100);r.push(VC(A,x,$))}return r},hg={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"}},$C=s=>{const[t,e,r,i,a]=Df(s,Af);return{300:t,400:e,500:r,600:i,700:a}},xC=s=>{if(s==="#FFFFFF")return hg.light.background;if(s==="#000000")return hg.dark.background;const[t,e,r,i,a]=Df(s,DC);return{1e3:t,900:e,800:r,700:i,600:a}},UC={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:$C("#2160FD"),background:xC("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Of(){return ep(UC)}var HC={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:Of(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function BC(){return ep(HC)}var FC={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:Of(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function ip(){return ep(FC)}function jC(){ve.isElectron()&&window.electronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.electronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(a=>{var o;return(o=a.id)==null?void 0:o.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var w=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.PRODUCER_HANDOVER="PRODUCER_HANDOVER",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.MEDIA_ROOM_JOIN_FAILED="MEDIA_ROOM_JOIN_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.NEW_CONSUMER_CREATED="NEW_CONSUMER_CREATED",s.PRODUCER_CLOSED="websocket/producer-closed",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="cf/producer-toggle",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="cf/reset-producer-state",s.ROOM_STATE="sockethub/room-state",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER="ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(w||{});const pg=(s,t)=>!s.includes("currentColor")||!t?s:s.replace(/currentColor/g,t);function qC(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 gg=1080,mg=1920,GC=(s,t,e,r,i,a)=>{let o=.5,c=.5;const d=i,l=a,u=Math.min(e/d,r/l);let p=d*u,f=l*u,T,E,R,I,D=1;return p<e&&(D=e/p),Math.abs(D-1)<1e-14&&f<r&&(D=r/f),p*=D,f*=D,R=d/(p/e),I=l/(f/r),T=(d-R)*o,E=(l-I)*c,T<0&&(T=0),E<0&&(E=0),R>d&&(R=d),I>l&&(I=l),[T,E,R,I,s,t,e,r]};var Tt,Dr,st,jt,_e,qt,qs,Ne,Ie,Mn,An,Dn,Gs,On,Gd,Oo;const Cp=class extends xt{constructor(e,r,i,a){const o=e.getValue("logger");super(o);g(this,Tt,void 0);g(this,Dr,void 0);g(this,st,void 0);g(this,jt,void 0);g(this,_e,{height:gg,width:mg});g(this,qt,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,qs,void 0);g(this,Ne,{});g(this,Ie,void 0);g(this,Mn,void 0);g(this,An,void 0);g(this,Dn,void 0);g(this,Gs,void 0);g(this,On,!1);g(this,Gd,e=>{const r=n(this,Mn);if(m(this,Mn,e),!r||r===e)return;const i=n(this,Ne)[r];i&&(delete n(this,Ne)[r],!n(this,Ne)[e]&&(n(this,Ne)[e]={...i,id:e}))});h(this,"cleanupEventListeners",()=>{n(this,Dr).unsubscribe("stageStatus",this.handlePipMediaControls),n(this,Ie).removeListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,Ie).removeListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,Ie).removeListener("roomLeft",n(this,Oo))});g(this,Oo,({state:e})=>{e!=="disconnected"&&this.disable()});h(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});h(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});h(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});h(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});h(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,Dr).getValue("peerSessionStore").emit(w.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});h(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});h(this,"animate",()=>{if(!this.isActive&&n(this,Gs)==="active"){this.disable(!0);return}n(this,Ne)!==void 0&&this.paintCanvas(),n(this,qs)!==void 0&&m(this,qs,requestAnimationFrame(()=>this.animate()))});h(this,"disable",(e=!1)=>{m(this,Gs,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(n(this,qs)),e!==!0&&document.body.removeChild(n(this,st)),m(this,qs,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});m(this,Dr,e),m(this,Gs,"idle"),m(this,Ie,r),m(this,Mn,e.getValue("peerId")),n(this,Dr).subscribe("peerId",n(this,Gd)),m(this,qt,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),a&&this.setupIcon("handRaise",a)}static async _init(e,r){var o,c,d;let i,a;try{const l=(d=(c=(o=r.config)==null?void 0:o.designTokens)==null?void 0:c.colors)==null?void 0:d.textOnBrand;i=await nd(pg(wC,l)),a=await nd(pg(_C,l))}catch(l){}return new Cp(e,r,i,a)}async setupIcon(e,r){switch(e){case"handRaise":m(this,Dn,r);break;case"pin":m(this,An,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":m(this,Dn,await nd(r));break;case"pin":m(this,An,await nd(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),a=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(a)},r.src=a})}createVideoContainer(){m(this,st,document.createElement("div")),n(this,st).style.width="0.1px",n(this,st).style.height="0.1px",n(this,st).style.overflow="hidden",n(this,st).style.position="absolute",n(this,st).style.bottom="0",n(this,st).style.right="0",n(this,st).style.opacity="0",n(this,st).appendChild(n(this,jt))}setupEventListeners(){n(this,Dr).subscribe("stageStatus",this.handlePipMediaControls),n(this,Ie).addListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,Ie).addListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,Ie).addListener("roomLeft",n(this,Oo))}createCanvas(){const e=document.createElement("canvas");e.height=n(this,_e).height,e.width=n(this,_e).width,m(this,Tt,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,Ne)).reduce((i,a)=>(i[a.pinned?"pinned":"regular"].push(a),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,a){if(n(this,Tt)===void 0)return;const o=n(this,Tt).getContext("2d"),c=n(this,Tt).width,d=0,l=0,u=r-d*2,p=i-d*2,f=Math.floor(c/u),T=Math.floor(e/f),R=e%f*(u+d)+d,I=T*(p+d)+d,{displayText:D,image:A}=a!=null?a:{};o.fillStyle=D||A?n(this,qt).videoBackground:n(this,qt).background,o.strokeStyle=n(this,qt).brand,o.beginPath(),o.moveTo(R+l,I),o.arcTo(R+u,I,R+u,I+l,l),o.arcTo(R+u,I+p,R+u-l,I+p,l),o.arcTo(R,I+p,R,I+p-l,l),o.arcTo(R,I,R+l,I,l),o.closePath(),o.fill(),o.stroke();const x=u/6,$=u/2+R,U=p/2+I;o.save(),(D||A)&&(o.beginPath(),o.arc($,U,x,0,Math.PI*2),o.fillStyle=n(this,qt).brand,o.fill(),A?(o.clip(),o.drawImage(A,$-x,U-x,x*2,x*2),o.restore()):D&&(o.fillStyle=n(this,qt).textOnBrand,o.font=`${x/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(D,$,U)),this.drawIcons(a,R,I,Math.max(u,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 u=i+c,p=f=>{const T=n(this,Tt).getContext("2d");T.save(),T.fillStyle=n(this,qt).background,T.beginPath(),T.moveTo(l+d,u),T.arcTo(l+o,u,l+o,u+d,d),T.arcTo(l+o,u+o,l+o-d,u+o,d),T.arcTo(l,u+o,l,u+o-d,d),T.arcTo(l,u,l+d,u,d),T.closePath(),T.fill(),typeof f=="string"?(T.font=`${o/1.5}px sans-serif`,T.fillStyle=n(this,qt).text,T.textAlign="center",T.textBaseline="top",T.fillText(f,o/2+l,u+c)):T.drawImage(f,l+c,u+c,o-c*2,o-c*2),l+=o+c,T.restore()};e.pinned&&p(n(this,An)),e.handRaised&&p(n(this,Dn)),e.reaction&&p(e.reaction)}drawTile(e,r,i){var l,u;if(n(this,Tt)===void 0)return;const a=n(this,Tt).getContext("2d");a.fillStyle=n(this,qt).background,a.fillRect(0,0,n(this,Tt).width,n(this,Tt).height);const 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,R,I,D,A,x,$]=GC(p,c,e,r,f.videoWidth,f.videoHeight);((u=f==null?void 0:f.classList)==null?void 0:u.contains("mirror"))?(a.save(),a.scale(-1,1),a.drawImage(f,T,E,R,I,-1*D,A,-1*x,$),a.restore()):a.drawImage(f,T,E,R,I,D,A,x,$),this.drawIcons(o[d],D,A,Math.max(x,$))}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,On,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),n(this,st))try{document.body.removeChild(n(this,st))}catch(e){}this.removeAllSources(),m(this,Tt,void 0),m(this,jt,void 0),m(this,qs,void 0)}init({height:e,width:r}={}){if(!this.isSupported())throw this.logger.error("Pip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(n(this,On))return;m(this,On,!0),this.createCanvas();const i=document.createElement("video");m(this,_e,{height:e!=null?e:gg,width:r!=null?r:mg}),i.height=n(this,_e).height,i.width=n(this,_e).width,i.autoplay=!0,i.muted=!0,i.srcObject=n(this,Tt).captureStream(24),m(this,jt,i),n(this,jt).onloadedmetadata=()=>{try{this.emit("pipStarted"),n(this,jt).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(a){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){n(this,Ne)[e]!==void 0&&(n(this,Ne)[e].enabled=!0)}disableSource(e){n(this,Ne)[e]!==void 0&&(n(this,Ne)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const a=await(await fetch(r)).blob(),o=window.URL.createObjectURL(a);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(a){this.logger.error("Pip::GenerateAvatar",{error:a})}}addSource(e,r,i,a=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),n(this,Ne)[e]={id:e,element:r,enabled:i,pinned:a,displayText:o?qC(o):void 0,imageUrl:c,handRaised:d},c&&this.generateAvatar(e,c)}updateSource(e,r){this.logger.info("Pip::UpdateSource",{pip:{id:e,handRaised:r.handRaised,reaction:r.reaction}});const i=n(this,Ne)[e];i&&(n(this,Ne)[e]={...i,...r})}removeSource(e){delete n(this,Ne)[e]}removePinnedSource(){Object.values(n(this,Ne)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){m(this,Ne,{})}enable(){m(this,Gs,"activating"),this.setupEventListeners(),this.setupMediaSessionEvents(),this.updateMediaSession("CAMERA",n(this,Ie).videoEnabled),this.updateMediaSession("MIC",n(this,Ie).audioEnabled),document.body.appendChild(n(this,st)),m(this,qs,requestAnimationFrame(()=>this.animate())),n(this,jt).onloadedmetadata=()=>{n(this,jt).requestPictureInPicture().then(()=>{m(this,Gs,"active")})},n(this,jt).readyState===4&&n(this,jt).requestPictureInPicture().then(()=>{m(this,Gs,"active")})}};let ju=Cp;Tt=new WeakMap,Dr=new WeakMap,st=new WeakMap,jt=new WeakMap,_e=new WeakMap,qt=new WeakMap,qs=new WeakMap,Ne=new WeakMap,Ie=new WeakMap,Mn=new WeakMap,An=new WeakMap,Dn=new WeakMap,Gs=new WeakMap,On=new WeakMap,Gd=new WeakMap,Oo=new WeakMap;var gr;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(gr||(gr={}));var Ds;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Ds||(Ds={}));class WC 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 Nf=new WC;class JC 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 KC=new JC;class zC extends v.MessageType{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new zC;class YC extends v.MessageType{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",gr]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const ms=new YC;class QC 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 XC=new QC;class ZC extends v.MessageType{constructor(){super("media.CreateTransportRequest",[{no:1,name:"consuming",kind:"scalar",T:8},{no:2,name:"force_tcp",kind:"scalar",opt:!0,T:8},{no:3,name:"description",kind:"message",T:()=>ms},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>XC}])}}const eR=new ZC;class tR 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 sR=new tR;class rR extends v.MessageType{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ms},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Lf=new rR;class iR extends v.MessageType{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ms}])}}const nR=new iR;class aR extends v.MessageType{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ms}])}}new aR;class oR 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 cR=new oR;class dR 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 lR=new dR;class uR 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 uR;class hR 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 hR;class pR extends v.MessageType{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Ds]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"codec",kind:"message",T:()=>Nf}])}}const Xc=new pR;class gR extends v.MessageType{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Xc},{no:3,name:"producer_track",kind:"message",T:()=>lR},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const mR=new gR;class fR extends v.MessageType{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>mR}}])}}const Vf=new fR;class SR extends v.MessageType{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Sg},{no:2,name:"receiver",kind:"message",T:()=>Sg}])}}const $f=new SR;class TR extends v.MessageType{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Nf},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>KC}])}}const fg=new TR;class vR extends v.MessageType{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>fg},{no:2,name:"video",kind:"message",T:()=>fg}])}}const Sg=new vR;class yR 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 ER=new yR;class PR 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 xf=new PR;class wR 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 _R=new wR;class CR 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:()=>_R},{no:9,name:"capabilities",kind:"message",T:()=>$f}])}}const RR=new CR;class bR extends v.MessageType{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const kR=new bR;class IR extends v.MessageType{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const MR=new IR;class AR extends v.MessageType{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new AR;class DR 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:()=>ER},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>xf}])}}const OR=new DR;class NR extends v.MessageType{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>OR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const LR=new NR;class VR extends v.MessageType{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>xf},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const $R=new VR;class xR extends v.MessageType{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>$R},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const UR=new xR;class HR extends v.MessageType{constructor(){super("media.edge.ProducerCreateRequest",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"description",kind:"message",T:()=>ms},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const BR=new HR;class FR extends v.MessageType{constructor(){super("media.edge.SelectedPeersRequest",[])}}new FR;class jR extends v.MessageType{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const qR=new jR;class GR 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 od=new GR;class WR 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 WR;class JR extends v.MessageType{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ms},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const KR=new JR;class zR extends v.MessageType{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>ms},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const YR=new zR;class QR extends v.MessageType{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new QR;class XR extends v.MessageType{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Uf=new XR;class ZR 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 eb=new ZR;class tb 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 sb=new tb;class rb 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 ib=new rb;class nb 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 ab=new nb;class ob 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 cb=new ob;class db extends v.MessageType{constructor(){super("media.edge.EmptyResponse",[])}}new db;class lb 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:()=>Xc},{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:()=>$f}])}}const Hf=new lb;class ub 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 qu=new ub;class hb 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 pb=new hb;class gb extends v.MessageType{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>pb}])}}const Tg=new gb;class mb extends v.MessageType{constructor(){super("media.edge.PeerJoinResponse",[])}}new mb;class fb extends v.MessageType{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>ab},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Hf},{no:3,name:"selected_peers",kind:"message",T:()=>qu},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Gu=new fb;class Sb extends v.MessageType{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}new Sb;class Tb 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:()=>Vf}])}}new Tb;class vb 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:()=>Vf},{no:3,name:"description",kind:"message",T:()=>ms}])}}const yb=new vb;class Eb extends v.MessageType{constructor(){super("media.edge.ProducerCreateResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"producer_id",kind:"scalar",T:9},{no:4,name:"description",kind:"message",T:()=>ms}])}}const Pb=new Eb;class wb extends v.MessageType{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>cR}])}}new wb;class _b 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 _b;class Cb extends v.MessageType{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new Cb;class Rb extends v.MessageType{constructor(){super("media.edge.ProducerToggleResponse",[])}}new Rb;class bb extends v.MessageType{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new bb;class kb extends v.MessageType{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ms}])}}const Ib=new kb;class Mb extends v.MessageType{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ms}])}}const Ab=new Mb;class Db extends v.MessageType{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new Db;class Ob extends v.MessageType{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new Ob;class Nb extends v.MessageType{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new Nb;class Lb extends v.MessageType{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Vb=new Lb;class $b extends v.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const xb=new $b;class Ub extends v.MessageType{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Hb=new Ub;class Bb extends v.MessageType{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Hf},{no:2,name:"producer_handover_from_peer_id",kind:"scalar",opt:!0,T:9}])}}const vg=new Bb;class Fb 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 yg=new Fb;class jb extends v.MessageType{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>yg},{no:3,name:"screenshare",kind:"message",T:()=>yg}])}}const qb=new jb;class Gb 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:()=>Lf},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>qb}])}}new Gb;class Wb 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:()=>Xc},{no:3,name:"producer_handover_from_peer_id",kind:"scalar",opt:!0,T:9}])}}const Jb=new Wb;class Kb 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:()=>Xc},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Eg=new Kb;class zb 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:()=>Xc}])}}const Yb=new zb;class Qb extends v.MessageType{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Wu=new Qb;class Xb extends v.MessageType{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Pg=new Xb;class Zb extends v.MessageType{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Zb;class ek extends v.MessageType{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new ek;class tk extends v.MessageType{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new tk;class sk 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 sk;class rk extends v.MessageType{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new rk;class ik extends v.MessageType{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new ik;class nk extends v.MessageType{constructor(){super("socket.ai.TranscriptSpeaker",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"participant_id",kind:"scalar",T:9},{no:3,name:"custom_participant_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9}])}}const ak=new nk;class ok extends v.MessageType{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8},{no:4,name:"sentence",kind:"scalar",T:9},{no:5,name:"speaker",kind:"message",T:()=>ak},{no:6,name:"started_at",kind:"scalar",T:4,L:2},{no:7,name:"ended_at",kind:"scalar",T:4,L:2},{no:8,name:"confidence",kind:"scalar",T:2}])}}const Cu=new ok;class ck 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 ck;class dk 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 lk=new dk;var nn;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(nn||(nn={}));var dr;(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"})(dr||(dr={}));var Ju;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(Ju||(Ju={}));var Ku;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(Ku||(Ku={}));var Nd;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Nd||(Nd={}));class uk 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 hk=new uk;class pk 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",dr,"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:()=>hk}])}}const du=new pk;class gk extends v.MessageType{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>du}])}}const Sn=new gk;class mk 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",dr,"STAGE_TYPE_"]}])}}const wg=new mk;class fk 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 Sk=new fk;class Tk extends v.MessageType{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>du}])}}const Ru=new Tk;class vk extends v.MessageType{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const _g=new vk;class yk 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:()=>Pk},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Bf=new yk;class Ek 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",nn]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const Pk=new Ek;class wk extends v.MessageType{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Bf}])}}const Cg=new wk;class _k extends v.MessageType{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Ff=new _k;class Ck 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 Ck;class Rk extends v.MessageType{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>du},{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",Nd,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const bk=new Rk;class kk extends v.MessageType{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>du},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const Ik=new kk;class Mk extends v.MessageType{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Bf}])}}new Mk;class Ak extends v.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new Ak;class Dk 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 np=new Dk;class Ok 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 Nk=new Ok;class Lk 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:()=>Nk}])}}const Rg=new Lk;class Vk extends v.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>Rg},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>Rg}])}}const $k=new Vk;class xk extends v.MessageType{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const Uk=new xk;class Hk extends v.MessageType{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Uk}])}}const Bk=new Hk;class Fk 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:()=>np}])}}const jk=new Fk;class qk extends v.MessageType{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>jk}])}}const bg=new qk;class Gk 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 Wk=new Gk;class Jk extends v.MessageType{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Wk}])}}new Jk;class Kk extends v.MessageType{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const zk=new Kk;class Yk extends v.MessageType{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>zk}])}}const Qk=new Yk;class Xk extends v.MessageType{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>tI}])}}const Zk=new Xk;class eI 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:()=>np}])}}const tI=new eI;class sI 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 rI=new sI;class iI 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:()=>rI}])}}const nI=new iI;class aI 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:()=>np}])}}const jf=new aI;class oI extends v.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>jf}])}}new oI;class cI 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 dI=new cI;class lI extends v.MessageType{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>pI}])}}const uI=new lI;class hI 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 pI=new hI;class gI extends v.MessageType{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const qf=new gI;class mI 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",Ku,"BROADCAST_TYPE_"]}])}}const Qa=new mI;class fI extends v.MessageType{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const SI=new fI;class TI extends v.MessageType{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const vI=new TI;class yI 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 EI=new yI;class PI extends v.MessageType{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>EI}])}}const kg=new PI;class wI 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 Ig=new wI;var zu;(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"})(zu||(zu={}));var ti;(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"})(ti||(ti={}));class _I 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 CI=new _I;class RI 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 bI=new RI;class kI 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 II=new kI;class MI 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 AI=new MI;class DI extends v.MessageType{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>II},{no:2,name:"private",kind:"message",T:()=>AI}])}}const OI=new DI;class NI 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 LI=new NI;class VI extends v.MessageType{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",ti,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",ti,"STREAM_PERMISSION_TYPE_"]}])}}const bu=new VI;class $I extends v.MessageType{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>bu},{no:2,name:"audio",kind:"message",T:()=>bu},{no:3,name:"screenshare",kind:"message",T:()=>bu}])}}const xI=new $I;class UI extends v.MessageType{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>CI},{no:2,name:"plugins",kind:"message",T:()=>bI},{no:3,name:"chat",kind:"message",T:()=>OI},{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",zu,"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",Ju,"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:()=>LI},{no:23,name:"media",kind:"message",T:()=>xI}])}}const ap=new UI;class HI extends v.MessageType{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const BI=new HI;class FI 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 jI=new FI;class qI extends v.MessageType{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>jI}])}}const GI=new qI;class WI extends v.MessageType{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>ap}])}}const Gf=new WI;class JI extends v.MessageType{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Gf}])}}const KI=new JI;class zI extends v.MessageType{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Gf}])}}const Mg=new zI;class YI 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 QI=new YI;class XI extends v.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>QI},{no:2,name:"patch",kind:"message",T:()=>ap}])}}new XI;class ZI extends v.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>ap}])}}new ZI;class eM extends v.MessageType{constructor(){super("socket.chat.ChatMessage",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"user_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9},{no:5,name:"pinned",kind:"scalar",T:8},{no:6,name:"is_edited",kind:"scalar",T:8},{no:7,name:"payload_type",kind:"scalar",T:5},{no:8,name:"payload",kind:"scalar",T:9},{no:10,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:11,name:"created_at",kind:"scalar",T:4,L:2},{no:12,name:"created_at_ms",kind:"scalar",opt:!0,T:4,L:2},{no:13,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:14,name:"channel_index",kind:"scalar",opt:!0,T:9}])}}const ai=new eM;class tM 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 sM=new tM;class rM 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:()=>sM}])}}const iM=new rM;class nM extends v.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>ai},{no:2,name:"next",kind:"scalar",T:8}])}}const aM=new nM;class oM extends v.MessageType{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>ai}])}}const Wf=new oM;class cM 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 dM=new cM;class lM extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>ai}])}}const ku=new lM;class uM 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 hM=new uM;class pM extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>ai}])}}const Iu=new pM;class gM 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 gM;class mM extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>ai}])}}new mM;class fM 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 SM=new fM;class TM 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 vM=new TM;class yM extends v.MessageType{constructor(){super("socket.chat.PinChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:4,name:"message",kind:"message",T:()=>ai}])}}const cd=new yM;class EM extends v.MessageType{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>ai}])}}const dd=new EM;class PM 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 wM=new PM;class _M 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 ld=new _M;class CM 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 RM=new CM;class bM 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 bM;class kM extends v.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new kM;class IM 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 IM;class MM 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 MM;class AM extends v.MessageType{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new AM;class DM extends v.MessageType{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new DM;class OM extends v.MessageType{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>ai},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const NM=new OM;class LM 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:()=>NM},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const VM=new LM;class $M extends v.MessageType{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>VM}])}}new $M;class xM 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 UM=new xM;class HM extends v.MessageType{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>UM}])}}new HM;class BM extends v.MessageType{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new BM;class FM extends v.MessageType{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new FM;class jM extends v.MessageType{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new jM;class qM extends v.MessageType{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new qM;class GM extends v.MessageType{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}new GM;class WM extends v.MessageType{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}new WM;class JM extends v.MessageType{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new JM;class KM extends v.MessageType{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}new KM;class zM 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 op=new zM;class YM 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:()=>op}])}}const QM=new YM;class XM 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:()=>op}])}}const ZM=new XM;class eA 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:()=>op}])}}const tA=new eA;class sA extends v.MessageType{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}new sA;class rA 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 iA=new rA;class nA extends v.MessageType{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>iA}])}}new nA;class aA extends v.MessageType{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}new aA;class oA 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 oA;class dA 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 Ag=new dA;class lA extends v.MessageType{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new lA;class uA extends v.MessageType{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9},{no:10,name:"manual_ingest",kind:"scalar",opt:!0,T:8}])}}const Dg=new uA;class hA extends v.MessageType{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Og=new hA;class pA 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 gA=new pA;class mA extends v.MessageType{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>gA}])}}const Mu=new mA;class fA extends v.MessageType{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const SA=new fA;class TA extends v.MessageType{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const vA=new TA;class yA extends v.MessageType{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Ng=new yA;class EA 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:()=>wA},{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 Jf=new EA;class PA 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:()=>CA}])}}const wA=new PA;class _A 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 CA=new _A;class RA 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 bA=new RA;class kA 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 IA=new kA;class MA extends v.MessageType{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Jf}])}}const Au=new MA;class AA extends v.MessageType{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Jf}])}}const DA=new AA;class OA 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",nn]}])}}const Lg=new OA;class NA 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 NA;class LA 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 Yu=new LA;class VA extends v.MessageType{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Yu}])}}new VA;class $A extends v.MessageType{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>Yu},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>Yu}])}}new $A;const xA=0,UA=1,HA=2,BA=3,FA=5,jA={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},qA={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},GA={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},WA={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Kf={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},JA={getUserPresets:0,updateUserPreset:1};function Zc(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function zf(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const V=Zc(xA,jA),We=Zc(UA,qA),Hs=Zc(HA,GA),Bs=Zc(BA,WA),Mr=zf(Kf,16777216),us=zf(Kf,50331648),fd=Zc(FA,JA);var KA=Object.defineProperty,zA=Object.getOwnPropertyDescriptor,oi=(s,t,e,r)=>{for(var i=r>1?void 0:r?zA(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&&KA(t,e,i),i},Xt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(Xt||{}),bt,Nn;class Tr{constructor(t,e){g(this,bt,void 0);g(this,Nn,void 0);m(this,bt,e),m(this,Nn,t)}get telemetry(){return n(this,Nn).getValue("telemetry")}get logger(){return n(this,Nn).getValue("logger")}getChatMessages(){return n(this,bt).sendMessagePromise(We.getMessages)}async getChatMessagesPaginated(t,e,r,i){const a={timeStamp:t,size:e,from:0,reversed:r,...i&&{filters:{filters:i}}},o=await n(this,bt).sendMessagePromise(We.getPaginatedMessages,iM.toBinary(a));return o.payload?aM.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};n(this,bt).sendMessage(We.sendMessageToRoom,dM.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};n(this,bt).sendMessage(We.sendMessageToPeers,hM.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,bt).sendMessagePromise(We.editMessage,SM.toBinary(a));return dd.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await n(this,bt).sendMessagePromise(We.deleteMessage,wM.toBinary(e));return{id:ld.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,bt).sendMessagePromise(We.searchChannelMessages,RM.toBinary(r));return Wf.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await n(this,bt).sendMessagePromise(We.pinMessage,vM.toBinary(r));return cd.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case We.sendMessageToRoom:{r=ku.fromBinary.bind(ku),i=ku.create();break}case We.sendMessageToPeers:{r=Iu.fromBinary.bind(Iu),i=Iu.create();break}case We.editMessage:{r=dd.fromBinary.bind(dd),i=dd.create();break}case We.pinMessage:{r=cd.fromBinary.bind(cd),i=cd.create();break}case We.deleteMessage:{r=ld.fromBinary.bind(ld),i=ld.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}n(this,bt).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)})}}bt=new WeakMap,Nn=new WeakMap;oi([y.trace("SocketService.getChatMessages")],Tr.prototype,"getChatMessages",1);oi([y.trace("SocketService.getChatMessagesPaginated")],Tr.prototype,"getChatMessagesPaginated",1);oi([y.trace("SocketService.sendMessageToRoom")],Tr.prototype,"sendMessageToRoom",1);oi([y.trace("SocketService.sendMessageToPeers")],Tr.prototype,"sendMessageToPeers",1);oi([y.trace("SocketService.sendMessage")],Tr.prototype,"sendMessage",1);oi([y.trace("SocketService.editMessage")],Tr.prototype,"editMessage",1);oi([y.trace("SocketService.deleteMessage")],Tr.prototype,"deleteMessage",1);oi([y.trace("SocketService.searchMessages")],Tr.prototype,"searchMessages",1);function YA(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Os(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Os(e));const t={};return Object.keys(s).forEach(e=>{const r=hr.validate(e)?e:YA(e);t[r]=Os(s[e])}),t}function QA(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Yf(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Yf(e));const t={};return Object.keys(s).forEach(e=>{const r=hr.validate(e)?e:QA(e);t[r]=s[e]}),t}class Ld extends Error{constructor(e){const r=e instanceof Error?e.message:`Request failed with status ${e.status}`;super(r);h(this,"status");h(this,"response");h(this,"isTimeout");e instanceof Error?(this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(this.status=e.status,this.response=e,this.isTimeout=!1),this.name="RequestError"}get isHttpError(){return this.status!==void 0}get isNetworkError(){return this.status===void 0&&!this.isTimeout}}class Vg{constructor(t){h(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,u=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 R=null;const I=E.headers.get("content-type");I&&I.includes("application/json")?R=await E.json():R=await E.text();const D={};E.headers.forEach((x,$)=>{D[$]=x});const A={data:R,status:E.status,statusText:E.statusText,headers:D,config:t};if(!E.ok)throw A;return A}catch(f){if(f instanceof Error&&l>0)return await new Promise(T=>setTimeout(T,u)),this.defaults.baseURL===fi.apiBase.prod?this.defaults.baseURL=fi.apiBase.prodAlternate:this.defaults.baseURL===fi.apiBase.prodAlternate&&(this.defaults.baseURL=fi.apiBase.prod),this.request({...t,retry:l-1});throw f}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const XA=3,ZA=30,e0=8e3;class t0{constructor(t,e){h(this,"fetchClient");h(this,"requests");h(this,"roomName");h(this,"roomUUID");h(this,"authToken");h(this,"organizationId");h(this,"iceServers");h(this,"userDetails");h(this,"roomDetails");h(this,"context");this.context=t;const{timeout:r=e0,retry:i=XA,retryDelay:a=ZA,baseURL:o=fi.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new Vg({baseURL:o,timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.fetchClient=new Vg({baseURL:"",timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var f,T,E,R,I,D;const p=t.getValue("telemetry");try{p.injectContext(this.requests.defaults.headers.common);const A=await l(u);return u.url!==p.logsEndpoint&&this.logger.debug(`XHR - Fetched ${u.method}:${u.url} with status ${A.status}`,{networkCall:{status:A.status,statusText:A.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),A}catch(A){if(!A)throw new C("Unknown network error occurred","0011");if(A instanceof C||A instanceof Ld)throw A;((f=A.config)==null?void 0:f.url)!==p.logsEndpoint&&this.logger.error(`XHR - Fetch failed on ${u.method}:${u.url} with status ${A.status}. Retry: ${(T=A.config)==null?void 0:T.retry}`,{error:A,networkCall:{status:A.status,statusText:A.statusText,baseURL:((E=A.config)==null?void 0:E.baseURL)||this.requests.defaults.baseURL,url:(R=A.config)==null?void 0:R.url,retries:(I=A.config)==null?void 0:I.retry,method:(D=A.config)==null?void 0:D.method,isOnline:navigator.onLine?"online":"offline"}});const x=A instanceof Error&&A.message||"Network request failed";throw new C(x,"0011"),new Ld(A)}}}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 s0=Object.defineProperty,r0=Object.getOwnPropertyDescriptor,vr=(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};class Vs extends t0{constructor(e,r){super(e,r);h(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(await this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r}async getPresignedUrls(e){const r=Io(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof r=="number"?r:void 0},{get_location:a,put_location:o}=(await this.requests.post("/v2/meetings/chat-upload",i)).data.data;return{getLocation:a,putLocation:o}}async uploadFile(e,r){if(navigator.isReactNative&&"uri"in e)try{await fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){this.logger.error(`sendFileMessage::${i}`)}else await this.fetchClient.put(r,e,{headers:{"Content-Type":e.type}})}async startLivestreaming({manualIngestion:e}){const r=Os(await this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!e})).data.data;return{playbackUrl:r.playbackUrl,status:r.status,manualIngest:r.manualIngest,ingestionCredentials:r.streamKey?{ingestionServer:r.ingestServer,streamKey:r.streamKey}:null}}async stopLivestreaming(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)}async getActiveLivestream(){const e=Os((await this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{playbackUrl:e.playbackUrl,status:e.status,manualIngest:e.manualIngest,ingestionCredentials:e.streamKey?{ingestionServer:e.ingestServer,streamKey:e.streamKey}:null}}async getUserDetails(){if(this.userDetails)return this.userDetails;const e=(await this.requests.get("v2/internals/participant-details")).data.data;return Os(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...Yf(e),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r})).data.data.id}async updateRecording(e,r){return this.requests.put(`v2/recordings/${e}`,{action:r})}async getActiveRecording(){const{status:e,id:r}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}}async getActiveTranscript(){const{transcript_download_url:e}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.fetchClient.get(e)).data}}catch(r){throw new C("Cant fetch transcript s3 url","1801")}}}vr([y.trace("APIClient.getICEServers")],Vs.prototype,"getICEServers",1);vr([y.trace("APIClient.startLivestreaming")],Vs.prototype,"startLivestreaming",1);vr([y.trace("APIClient.stopLivestreaming")],Vs.prototype,"stopLivestreaming",1);vr([y.trace("APIClient.getActiveLivestream")],Vs.prototype,"getActiveLivestream",1);vr([y.trace("APIClient.getUserDetails")],Vs.prototype,"getUserDetails",1);vr([y.trace("APIClient.startRecording")],Vs.prototype,"startRecording",1);vr([y.trace("APIClient.stopRecording")],Vs.prototype,"updateRecording",1);vr([y.trace("APIClient.getActiveRecording")],Vs.prototype,"getActiveRecording",1);vr([y.trace("APIClient.getActiveTranscript")],Vs.prototype,"getActiveTranscript",1);let Qu;function i0(s,t){return Qu=new Vs(s,t),Qu}function Lt(){return Qu}const Aa={maxInvocations:5,period:1};function Ut(s,t){return function(e,r,i){const a=i.value;let o=0,c=Date.now();return i.value=function(...d){const l=Date.now(),u=t?this[t]:s;if(l-c>u.period*1e3&&(c=l,o=0),o>=u.maxInvocations)throw new C(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,a.apply(this,d)},i}}var n0=Object.defineProperty,a0=Object.getOwnPropertyDescriptor,$s=(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&&n0(t,e,i),i};const o0=["text","image","file","custom","poll"],Sd={maxInvocations:180,period:60};var Z,Si,ze,Ln,Wd,Qf,No,Xu,Zg;let es=(Zg=class extends xt{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,Wd);g(this,No);h(this,"messages");g(this,Z,void 0);g(this,Si,void 0);g(this,ze,void 0);g(this,Ln,void 0);h(this,"maxTextLimit",2e3);m(this,Ln,t),m(this,ze,e),m(this,Z,r),m(this,Si,i),this.messages=[]}get telemetry(){return n(this,Ln).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e){switch(t.type){case"text":{await this.sendTextMessageInternal(t.message,e);break}case"image":await this.sendImageMessageInternal(t.image,e);break;case"file":await this.sendFileMessageInternal(t.file,e);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e){var i,a,o,c,d,l;if(t.length>this.maxTextLimit)throw new C("Max character limit breached","0503");if(e&&e.length>0){if(!((i=n(this,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 C("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 C("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new C("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(n(this,Z).id),r=n(this,Si).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(n(this,Z).userId)),n(this,ze).sendMessage(t,Xt.TEXT,e)}async sendImageMessageInternal(t,e){var i,a,o,c,d,l;if(e&&e.length>0){if(!((i=n(this,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 u=Lt(),{getLocation:p,putLocation:f}=await u.getPresignedUrls(t.name);await u.uploadFile(t,f);let T=[];e&&e.length>0&&(e.push(n(this,Z).id),T=n(this,Si).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),T.push(n(this,Z).userId)),n(this,ze).sendMessage(p,Xt.IMAGE,e)}catch(u){throw new C("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,a,o,c,d;if(e&&e.length>0){if(!((r=n(this,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=Lt(),{getLocation:u,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,Si).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),f.push(n(this,Z).userId));const T=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});n(this,ze).sendMessage(T,Xt.FILE,e)}catch(l){throw new C("Error sending file message.","0500",this.logger)}}get rateLimits(){return Sd}updateRateLimits(t,e){Sd.maxInvocations=t,Sd.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var a,o,c,d,l,u,p,f,T,E,R,I,D,A,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=(u=n(this,Z).permissions)==null?void 0:u.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 $=>{try{if(typeof $=="string")return{link:$};const U=Lt(),{getLocation:z,putLocation:ee}=await U.getPresignedUrls($.name);return await U.uploadFile($,ee),{link:z,type:$.type,name:$.name,size:$.size}}catch(U){throw new C("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((R=(E=t.files)!=null?E:[])==null?void 0:R.map(async $=>r($))),images:await Promise.all((D=(I=t.images)!=null?I:[])==null?void 0:D.map(async $=>r($))),videos:await Promise.all((x=(A=t.videos)!=null?A:[])==null?void 0:x.map(async $=>r($)))};n(this,ze).sendMessage(JSON.stringify(i),Xt.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e){var r,i,a,o;if(!((i=(r=n(this,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,ze).editMessage(t,e,Xt.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=Lt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),n(this,ze).editMessage(t,l,Xt.IMAGE)}catch(d){throw new C("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,a,o;if(!((i=(r=n(this,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=Lt(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),n(this,ze).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),Xt.FILE)}catch(c){throw new C("Error editing file message.","0500",this.logger)}}async editMessage(t,e){switch(e.type){case"text":{this.editTextMessage(t,e.message);break}case"image":{this.editImageMessage(t,e.image);break}case"file":{this.editFileMessage(t,e.file);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t){n(this,ze).deleteMessage(t)}async pin(t){if(!n(this,No,Xu))throw new C("Can`t pin message without joining room","0505");try{await n(this,ze).setPinState(t,!0)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!n(this,No,Xu))throw new C("Can`t unpin message without joining room","0505");try{await n(this,ze).setPinState(t,!1)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,ze).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>fo.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await n(this,ze).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>fo.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,ze).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>fo.formatSocketPeerMessage(o))}},Z=new WeakMap,Si=new WeakMap,ze=new WeakMap,Ln=new WeakMap,Wd=new WeakSet,Qf=function(){return n(this,Ln).getValue("connectionHandler")},No=new WeakSet,Xu=function(){return n(this,Wd,Qf).socketJoined===!0},Zg);$s([y.trace("Chat.sendTextMessage"),Ut(Sd)],es.prototype,"sendTextMessage",1);$s([y.trace("Chat.sendImageMessage"),Ut({maxInvocations:20,period:60})],es.prototype,"sendImageMessage",1);$s([y.trace("Chat.sendFileMessage"),Ut({maxInvocations:20,period:60})],es.prototype,"sendFileMessage",1);$s([y.trace("Chat.sendMessage"),Ut({maxInvocations:180,period:60})],es.prototype,"sendMessage",1);$s([y.trace("Chat.editTextMessage")],es.prototype,"editTextMessage",1);$s([y.trace("Chat.editImageMessage")],es.prototype,"editImageMessage",1);$s([y.trace("Chat.editFileMessage")],es.prototype,"editFileMessage",1);$s([y.trace("Chat.editMessage")],es.prototype,"editMessage",1);$s([y.trace("Chat.deleteMessage")],es.prototype,"deleteMessage",1);es=$s([rt("0500")],es);var c0=Object.defineProperty,d0=Object.getOwnPropertyDescriptor,l0=(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},Ti,em;const _r=(em=class{constructor(s,t,e,r){h(this,"chat");h(this,"chatSocketHandler");h(this,"self");g(this,Ti,void 0);m(this,Ti,s),this.chatSocketHandler=t,this.chat=new es(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return n(this,Ti).getValue("telemetry")}get logger(){return n(this,Ti).getValue("logger")}static async init(s,t,e,r){return new _r(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:o0[s.type]}}static formatSocketPeerMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case Xt.TEXT:{e.message=s.payload;break}case Xt.IMAGE:{e.link=s.payload;break}case Xt.FILE:{const{link:r,name:i,size:a}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=a;break}case Xt.CUSTOM:{const{html:r,images:i,message:a,videos:o,files:c}=JSON.parse(s.payload);e.message=a,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return _r.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=Wf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>_r.formatSocketPeerMessage(e))}setupEvents(){n(this,Ti).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(We.sendMessageToRoom,s=>{if(!s.message)return;const t=_r.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(We.sendMessageToPeers,s=>{const t=_r.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(We.editMessage,s=>{if(!s.message)return;const t=_r.formatSocketPeerMessage(s.message),e=this.chat.messages.findIndex(r=>r.id===t.id);e!==-1&&(this.chat.messages[e]=t),this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(We.deleteMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);let e={id:s.chatId};t!==-1&&([e]=this.chat.messages.splice(t,1)),this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(We.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=_r.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})})}},Ti=new WeakMap,em);let fo=_r;l0([y.trace("ChatController.setupEvents")],fo.prototype,"setupEvents",1);var u0=Object.defineProperty,h0=Object.getOwnPropertyDescriptor,p0=(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&&u0(t,e,i),i},Jd,Xf,Kd,Zf,Vn,$n,Lo,tm;let Zu=(tm=class extends xt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Jd);g(this,Kd);h(this,"items");g(this,Vn,void 0);g(this,$n,void 0);g(this,Lo,void 0);m(this,Lo,t),m(this,Vn,e),m(this,$n,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!n(this,Kd,Zf))throw new C("Can't create polls without joining room","0705");if(!n(this,Vn).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,$n).createPoll(t,e,r,i)}async vote(t,e){if(!n(this,Vn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await n(this,$n).votePoll(t,e)}},Jd=new WeakSet,Xf=function(){return n(this,Lo).getValue("connectionHandler")},Kd=new WeakSet,Zf=function(){var t;return((t=n(this,Jd,Xf))==null?void 0:t.socketJoined)===!0},Vn=new WeakMap,$n=new WeakMap,Lo=new WeakMap,tm);Zu=p0([rt("0700")],Zu);var g0=Object.defineProperty,m0=Object.getOwnPropertyDescriptor,f0=(s,t,e,r)=>{for(var i=r>1?void 0:r?m0(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&&g0(t,e,i),i},Or,xn,vi,sm;const Tn=(sm=class{constructor(s,t,e){h(this,"polls");g(this,Or,void 0);g(this,xn,void 0);g(this,vi,void 0);this.polls=new Zu(s,t,e),m(this,xn,t),m(this,Or,s),m(this,vi,e),this.setupEvents()}get telemetry(){return n(this,Or).getValue("telemetry")}get logger(){return n(this,Or).getValue("logger")}static async init(s,t,e){return new Tn(s,t,e)}canViewPolls(){return n(this,xn).permissions.polls.canView}setupEvents(){const s={[Bs.createPoll]:r=>{r.poll&&this.updatePoll(Tn.formatSocketServicePoll(r.poll))},[Bs.updatePoll]:r=>{r.poll&&this.updatePoll(Tn.formatSocketServicePoll(r.poll))},[Bs.votePoll]:r=>{r.poll&&this.updatePoll(Tn.formatSocketServicePoll(r.poll))}},t=()=>{n(this,Or).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,vi).on(r,s[r])})},e=()=>{n(this,Or).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,vi).removeListeners(r)})};n(this,xn).permissions.on("permissionsUpdate",async r=>{var i;r!=null&&r.polls&&((i=r==null?void 0:r.polls)!=null&&i.canView?(await this.getPolls(),t()):(this.polls.items=[],e()))}),this.canViewPolls()&&t()}updatePoll(s){if(!this.canViewPolls())return;const t=this.polls.items.findIndex(e=>e.id===s.id);if(t>-1){const e=JSON.stringify(this.polls.items[t]);this.polls.items[t]=s,e!==JSON.stringify(s)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,s],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}async getPolls(){const s=await n(this,vi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=DA.fromBinary(s.payload);this.polls.items=t.map(e=>Tn.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}}},Or=new WeakMap,xn=new WeakMap,vi=new WeakMap,sm);let eS=Tn;f0([y.trace("PollController.setupEvents")],eS.prototype,"setupEvents",1);var S0=Object.defineProperty,T0=Object.getOwnPropertyDescriptor,v0=(s,t,e,r)=>{for(var i=r>1?void 0:r?T0(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},tS=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(tS||{}),Un,Vo,th,yi,$o,rm;let eh=(rm=class extends xt{constructor(t,e,r,i,a){const o=t.getValue("logger");super(o);g(this,Vo);h(this,"selfActiveTab");h(this,"broadcastTabChanges");g(this,Un,void 0);g(this,yi,void 0);g(this,$o,void 0);h(this,"viewType");h(this,"meetingStartedTimestamp");h(this,"meetingTitle");h(this,"sessionId");m(this,Un,t),m(this,yi,e),this.viewType=r,m(this,$o,i),this.meetingTitle=a,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return n(this,Vo,th).socketState}get mediaState(){return n(this,Vo,th).mediaState}get meetingId(){return n(this,Un).getValue("meetingId")}setBroadcastTabChanges(t){if(!n(this,yi).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new C("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;this.logger.info("Spotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=n(this,yi).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){n(this,$o).broadcastMessage("spotlight",{userId:n(this,yi).userId,currentTab:this.selfActiveTab})}},Un=new WeakMap,Vo=new WeakSet,th=function(){return n(this,Un).getValue("connectionHandler")},yi=new WeakMap,$o=new WeakMap,rm);eh=v0([rt("0800")],eh);function y0(s){let t="",e=[""];const r=[e];let i=0,a=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
|
|
7
|
+
`&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++a]=[c=""],i=0):e[i]+=c,t=c;return r}var E0=Object.defineProperty,P0=Object.getOwnPropertyDescriptor,sS=(s,t,e,r)=>{for(var i=r>1?void 0:r?P0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&E0(t,e,i),i},xo,im;let an=(im=class extends xt{constructor(t){const e=t.getValue("logger");super(e);h(this,"transcripts");g(this,xo,void 0);m(this,xo,t),this.transcripts=[]}get telemetry(){return n(this,xo).getValue("telemetry")}static async init(t,e){const r=new an(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]]=y0(t);return{id:hr.v4(),name:c,peerId:i,userId:a,customParticipantId:o,transcript:d,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
|
|
8
|
+
`).map(e=>an.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=Lt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=an.parseTranscripts(e)}catch(t){}}async onTranscript(t){var r;const e=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((r=e==null?void 0:e.at(-1))!=null&&r.isPartialTranscript){const i=e.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)}},xo=new WeakMap,im);sS([y.trace("Ai.getActiveTranscript")],an.prototype,"getActiveTranscript",1);an=sS([rt("0000")],an);var w0=Object.defineProperty,_0=Object.getOwnPropertyDescriptor,C0=(s,t,e,r)=>{for(var i=r>1?void 0:r?_0(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&&w0(t,e,i),i},Nr,Hn,kt,nm;const sh=(nm=class{constructor(s,t,e,r,i,a){h(this,"meta");h(this,"ai");g(this,Nr,void 0);g(this,Hn,void 0);h(this,"aiSocketHandler");g(this,kt,void 0);m(this,kt,s),this.meta=new eh(s,t,t.config.viewType,e,a),this.ai=r,m(this,Nr,t),m(this,Hn,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return n(this,kt).getValue("telemetry")}get logger(){return n(this,kt).getValue("logger")}static async init(s,t,e,r,i){const a=await an.init(s,t.permissions.transcriptionEnabled);return new sh(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,tS.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){n(this,kt).getValue("peerSessionStore").on(w.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),n(this,kt).getValue("peerSessionStore").on(w.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),n(this,kt).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,kt).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),n(this,Nr).permissions.canSpotlight&&this.meta.selfActiveTab&&(this.logger.info("Asserting Spotlight status to other peers."),n(this,Hn).broadcastMessage("spotlight",{userId:n(this,Nr).userId,currentTab:this.meta.selfActiveTab})),n(this,kt).getValue("peerSessionStore").on(w.PEER_JOINED_INTERNAL,async s=>{n(this,Nr).permissions.canSpotlight&&this.meta.selfActiveTab&&n(this,Hn).broadcastToPeers("spotlight",[s.id],{userId:n(this,Nr).userId,currentTab:this.meta.selfActiveTab})}),n(this,kt).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,kt).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(V.transcript,s=>{let t;try{t=sh.extractSocketTranscript(s)}catch(e){this.logger.error("Failed to parse transcript socket message.",{error:e});return}if(!t){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(t)})}static extractSocketTranscript(s){return s?{id:hr.v4(),name:s.speaker.displayName,peerId:s.speaker.peerId,userId:s.speaker.participantId,customParticipantId:s.speaker.customParticipantId,transcript:s.sentence,isPartialTranscript:s.isPartial||!1,date:new Date(s.startedAt*1e3)}:void 0}},Nr=new WeakMap,Hn=new WeakMap,kt=new WeakMap,nm);let rS=sh;C0([y.trace("MetaController.setupEvents")],rS.prototype,"setupEvents",1);const Xa={},yr={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,a)=>{const o=a.value;return a.value=function(...d){var E,R;const l=(R=(this==null?void 0:this.peerId)||((E=d[0])==null?void 0:E.authToken))!=null?R:"",u=`${t}-${l}`,p=this==null?void 0:this.logger;if(Xa[u]){const I=new Error(`Unsupported concurrent calls on method: ${s}.`);throw I.name="UnsupportedConcurrentMethodExecution",p==null||p.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:I.stack},locker:{methodName:s,lockName:u}}),I}Xa[u]=!0;const f=setTimeout(()=>delete Xa[u],e),T=o.apply(this,d);return Promise.resolve(T).then(()=>{delete Xa[u],clearTimeout(f)}).catch(()=>{delete Xa[u],clearTimeout(f)}),T},a}}};var R0=Object.defineProperty,b0=Object.getOwnPropertyDescriptor,pn=(s,t,e,r)=>{for(var i=r>1?void 0:r?b0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&R0(t,e,i),i},Gt,zd,ie,Uo,Ss,$e,Ho,rh,Bn,Td;class ci extends xt{constructor(e,r,i,a,o){const c=e.getValue("logger");super(c);g(this,Ho);g(this,Bn);g(this,Gt,void 0);g(this,zd,void 0);g(this,ie,void 0);g(this,Uo,void 0);g(this,Ss,void 0);g(this,$e,void 0);m(this,$e,e),m(this,Gt,a),m(this,zd,o),m(this,ie,r),m(this,Uo,i),m(this,Ss,[]),this.setupEvents()}get telemetry(){return n(this,$e).getValue("telemetry")}get status(){return n(this,$e).getValue("stageStatus")}setupEvents(){const e={[w.GET_STAGE_REQUESTS]:async a=>{m(this,Ss,a)},[w.UPDATE_STAGE_REQUESTS]:async({add:a})=>{const o=n(this,Ss).length,{stageRequests:c}=this.getAccessRequests();(a||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([a,o])=>{n(this,$e).getValue("peerSessionStore").onAsync(a,o)})},i=()=>{Object.entries(e).forEach(([a,o])=>{n(this,$e).getValue("peerSessionStore").removeListener(a,o)})};n(this,ie).permissions.on("permissionsUpdate",a=>{const{canAcceptProductionRequests:o}=a;o!==void 0&&(n(this,ie).permissions.acceptStageRequests?(r(),n(this,Gt).getStageRequests()):(i(),m(this,Ss,[]),this.emit("stageAccessRequestUpdate",n(this,Ss))))}),n(this,ie).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ie).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new C("You do not have permission to perform this action","2001");const e=n(this,Uo).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return m(this,Ss,e),{stageRequests:n(this,Ss)}}async requestAccess(){if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new C(`Unable to request access you are currently ${this.status}`,"2006");if(n(this,ie).permissions.stageAccess===j.Allowed){b(this,Bn,Td).call(this,"ACCEPTED_TO_JOIN_STAGE");return}n(this,Gt).requestAccess(),b(this,Bn,Td).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");n(this,Gt).cancelRequestAccess(),b(this,Bn,Td).call(this,"OFF_STAGE")}grantAccess(e){if(!n(this,ie).roomJoined)throw new C("Can`t grant for participant without joining room");if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ie).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new C("You do not have permission to perform this action","2001");return n(this,Gt).grantAccess(e)}denyAccess(e){if(!n(this,ie).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ie).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new C("You do not have permission to perform this action","2001");return n(this,Gt).denyAccess(e)}get peerId(){return n(this,$e).getValue("peerId")}async join(){const e=n(this,$e).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||n(this,ie).permissions.stageAccess===j.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`,"2006");if(n(this,$e).setValue("stageStatus","ON_STAGE",!1),await n(this,Gt).joinStage(),e===hs.Livestream){await n(this,$e).getValue("selfController").joinRoom();return}n(this,$e).notify("stageStatus"),n(this,ie).audioEnabled&&n(this,Ho,rh).shareMic(n(this,ie).audioTrack),n(this,ie).videoEnabled&&n(this,Ho,rh).shareWebcam(n(this,ie).videoTrack)}async leave(){if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new C(`Unable to leave stage you are currently ${this.status}`,"2006");n(this,ie).setIsPinned(!1),n(this,$e).setValue("stageStatus","OFF_STAGE",!1),await n(this,Gt).leaveStage(n(this,ie).userId);try{await n(this,$e).getValue("peerSessionStore").emitAsync(w.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}n(this,$e).notify("stageStatus")}async kick(e){if(!n(this,ie).roomJoined)throw new C("Can`t kick participant without joining room","2005");if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ie).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new C("You do not have permissions for kick","2001");return n(this,Gt).kick(e)}}Gt=new WeakMap,zd=new WeakMap,ie=new WeakMap,Uo=new WeakMap,Ss=new WeakMap,$e=new WeakMap,Ho=new WeakSet,rh=function(){return n(this,$e).getValue("roomNodeClient")},Bn=new WeakSet,Td=async function(e){this.status!==e&&n(this,$e).setValue("stageStatus",e)};pn([y.trace("Stage.getStageRequests")],ci.prototype,"getAccessRequests",1);pn([y.trace("Stage.requestAccess")],ci.prototype,"requestAccess",1);pn([y.trace("Stage.cancelRequestAccess")],ci.prototype,"cancelRequestAccess",1);pn([y.trace("Stage.grantAccess")],ci.prototype,"grantAccess",1);pn([y.trace("Stage.denyAccess")],ci.prototype,"denyAccess",1);pn([yr.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),y.trace("Stage.joinStage")],ci.prototype,"join",1);pn([y.trace("Stage.leaveStage")],ci.prototype,"leave",1);function k0(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function cp(s){switch(s){case dr.UNSPECIFIED:return"OFF_STAGE";case dr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case dr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case dr.OFF_STAGE:return"OFF_STAGE";case dr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var I0=Object.defineProperty,M0=Object.getOwnPropertyDescriptor,A0=(s,t,e,r)=>{for(var i=r>1?void 0:r?M0(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},Lr,is,Vr,Bo,at;class iS{constructor(t,e,r,i,a){h(this,"stage");g(this,Lr,void 0);g(this,is,void 0);g(this,Vr,void 0);g(this,Bo,0);g(this,at,void 0);m(this,at,t),this.stage=new ci(t,i,a,e,r),m(this,Vr,e),m(this,Lr,i),m(this,is,a),this.setupEvents()}get telemetry(){return n(this,at).getValue("telemetry")}get logger(){return n(this,at).getValue("logger")}setupEvents(){n(this,at).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),n(this,Vr).on(V.grantStageAccess,()=>{n(this,Lr).permissions.stageAccess!==j.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),n(this,Vr).on(V.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===n(this,Lr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),n(this,Vr).on(V.denyStageAccess,()=>{n(this,Lr).permissions.stageAccess!==j.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),n(this,Vr).on(V.getStageRequests,async t=>{var r;if(n(this,Lr).permissions.stageAccess!==j.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await n(this,at).getValue("peerSessionStore").emitAsync(w.GET_STAGE_REQUESTS,e),n(this,Bo)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),m(this,Bo,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return n(this,is).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&n(this,at).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=cp(t.stageType),r=n(this,at).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:n(this,at).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,at).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=n(this,is).joined.get(t.peerId),r=n(this,is).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&n(this,at).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:n(this,is).viewMode,page:n(this,is).currentPage});break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&n(this,at).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:n(this,is).viewMode,page:n(this,is).currentPage});break}n(this,at).getValue("peerSessionStore").emit(w.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}Lr=new WeakMap,is=new WeakMap,Vr=new WeakMap,Bo=new WeakMap,at=new WeakMap;A0([y.trace("Stage.setupEvents")],iS.prototype,"setupEvents",1);var D0=Object.defineProperty,O0=Object.getOwnPropertyDescriptor,dp=(s,t,e,r)=>{for(var i=r>1?void 0:r?O0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&D0(t,e,i),i},Ei,Ws,Fo,jo,Pi,am;let Mo=(am=class extends Ma{constructor(t,e,r,i){const a=t.getValue("logger");super(a);h(this,"name");h(this,"icon");h(this,"id");h(this,"permissions");g(this,Ei,void 0);g(this,Ws,void 0);g(this,Fo,void 0);g(this,jo,void 0);g(this,Pi,void 0);h(this,"active");h(this,"enabledBy");m(this,Fo,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,m(this,jo,e.component),this.permissions=e.permissions,m(this,Ei,i),m(this,Ws,r),this.active=!1,this.enabledBy=""}get component(){return n(this,jo)}get telemetry(){return n(this,Fo).getValue("telemetry")}set activePluginsStore(t){m(this,Ws,t)}activateForSelf(){m(this,Pi,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){m(this,Pi,void 0),this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("closed")}async activate(){var t;if(!this.active&&(t=this.permissions)!=null&&t.canActivate){if(!n(this,Ws))throw new C("Cannot activate plugin: active plugins store is not available yet.","0604");await n(this,Ws).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:n(this,Ei).id}),this.enabledBy=n(this,Ei).id,this.activateForSelf(),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}})}}async deactivate(){var e;if(!this.active||!((e=this.permissions)!=null&&e.canDeactivate)&&this.enabledBy!==n(this,Ei).id)return;if(!n(this,Ws))throw new C("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=n(this,Pi)?new Date().getTime()-n(this,Pi).getTime():0;await n(this,Ws).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},Ei=new WeakMap,Ws=new WeakMap,Fo=new WeakMap,jo=new WeakMap,Pi=new WeakMap,am);dp([y.trace("Plugin.activatePlugin")],Mo.prototype,"activate",1);dp([y.trace("Plugin.deactivatePlugin")],Mo.prototype,"deactivate",1);Mo=dp([rt("0600")],Mo);var Me,wi;class nS extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:a,onClearEvent:o}=e;super();g(this,Me,void 0);g(this,wi,void 0);h(this,"onAddEvent");h(this,"onDeleteEvent");h(this,"onClearEvent");m(this,Me,new Ma(r)),this.onAddEvent=i,this.onDeleteEvent=a,this.onClearEvent=o,m(this,wi,new Map)}emit(e,...r){return n(this,Me).emit(e,...r)}on(e,r){return n(this,Me).on(e,r)}addListener(e,r){return n(this,Me).addListener(e,r)}off(e,r){return n(this,Me).off(e,r)}once(e,r){return n(this,Me).once(e,r)}prependListener(e,r){return n(this,Me).prependListener(e,r)}prependOnceListener(e,r){return n(this,Me).prependOnceListener(e,r)}removeListener(e,r){return n(this,Me).removeListener(e,r)}removeAllListeners(e){return n(this,Me).removeAllListeners(e)}listeners(e){return n(this,Me).listeners(e)}listenerCount(e){return n(this,Me).listenerCount(e)}getMaxListeners(){return n(this,Me).getMaxListeners()}setMaxListeners(e){return n(this,Me).setMaxListeners(e)}eventNames(){return n(this,Me).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,wi).set(e,o),r.on("*",o),i&&n(this,Me).emit(this.onAddEvent,r),a}delete(e,r=!0,i=!1){const a=this.get(e);if(!a)return!1;a.removeListener("*",n(this,wi).get(e));const o=super.delete(e);return i&&a.removeAllListeners(),r&&n(this,Me).emit(this.onDeleteEvent,a),o}clear(e=!0,r=!1){this.forEach(a=>{a.removeListener("*",n(this,wi).get(a.id)),r&&a.removeAllListeners()});const i=super.clear();return e&&n(this,Me).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Me=new WeakMap,wi=new WeakMap;class $g extends nS{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 N0=Object.defineProperty,L0=Object.getOwnPropertyDescriptor,V0=(s,t,e,r)=>{for(var i=r>1?void 0:r?L0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&N0(t,e,i),i};let ih=class{constructor(s){h(this,"all");h(this,"active");this.all=new $g(s),this.active=new $g(s)}};ih=V0([rt("0600")],ih);var $0=Object.defineProperty,x0=Object.getOwnPropertyDescriptor,U0=(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&&$0(t,e,i),i},ns,Fn,$r,_i,Yd,oS,qo,nh,Go,ah,Wo,oh,om;const aS=(om=class{constructor(s,t,e,r){g(this,Yd);g(this,qo);g(this,Go);g(this,Wo);h(this,"plugins");g(this,ns,void 0);g(this,Fn,void 0);g(this,$r,void 0);g(this,_i,null);m(this,$r,s),this.plugins=t,m(this,Fn,e),m(this,ns,r),this.setupEvents()}get telemetry(){return n(this,$r).getValue("telemetry")}get logger(){return n(this,$r).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),a=s.getValue("connectionHandler"),o=new ih(i);let c;a.socketState.state==="connected"?(i.info("Creating active plugins store immediately. Socket is already connected."),c=await r.create(Fu,!0)):i.info("Deferring active plugins store creation until socket connects."),t.forEach(p=>{const f=new Mo(s,p,c,e);o.all.add(f)});const d=new aS(s,o,r,c);return c?b(l=d,Wo,oh).call(l):b(u=d,Yd,oS).call(u),d}cleanup(){b(this,qo,nh).call(this)}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),n(this,$r).getValue("peerSessionStore").onAsync(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{var t,e;if(((e=(t=this.plugins.active)==null?void 0:t.toArray())!=null?e:[]).forEach(r=>{r.deactivateForSelf()}),!n(this,ns)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await b(this,Go,ah).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},ns=new WeakMap,Fn=new WeakMap,$r=new WeakMap,_i=new WeakMap,Yd=new WeakSet,oS=function(){const s=n(this,$r).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!n(this,ns))try{m(this,ns,await n(this,Fn).create(Fu,!0)),b(this,qo,nh).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=n(this,ns)}),b(this,Wo,oh).call(this),this.logger.info("Active plugins store created after socket connected"),await b(this,Go,ah).call(this)}catch(r){this.logger.error("Failed to create active plugins store after socket connected, will retry on next reconnect",{error:r})}};s.on(w.SOCKET_STATE_UPDATE,t),m(this,_i,()=>{s.off(w.SOCKET_STATE_UPDATE,t)})},qo=new WeakSet,nh=function(){n(this,_i)&&(n(this,_i).call(this),m(this,_i,null))},Go=new WeakSet,ah=async function(){try{await n(this,Fn).refresh(n(this,ns).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=n(this,ns).getAll();Object.entries(s).forEach(([t,e])=>{if(!e)return;const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store entry.`);return}r.active||(r.enabledBy=e.enabledBy,r.activateForSelf())})},Wo=new WeakSet,oh=function(){n(this,ns).subscribe("*",s=>{Object.entries(s).forEach(([t,e])=>{const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store update.`);return}!e&&r.active&&r.deactivateForSelf(),e&&!r.active&&(r.enabledBy=e.enabledBy,r.activateForSelf())})})},om);let cS=aS;U0([y.trace("PluginController.setupEvents")],cS.prototype,"setupEvents",1);var Jo;class H0{constructor(t){h(this,"mediaJoined");h(this,"socketJoined");h(this,"socketJoinAttempted");h(this,"mediaJoinAttempted");h(this,"socketState");h(this,"mediaState");g(this,Jo,void 0);this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0},m(this,Jo,t)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(t,e){let r;const{reconnected:i}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:i,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}r&&(this.socketState=r,n(this,Jo).getValue("peerSessionStore").emit(w.SOCKET_STATE_UPDATE,r))}}Jo=new WeakMap;var B0=Object.defineProperty,F0=Object.getOwnPropertyDescriptor,ed=(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&&B0(t,e,i),i};const xg="Cannot start recording: another recording is already in progress.";var jn,qn,Gn,vd,cm;let dn=(cm=class extends xt{constructor(t,e){const r=t.getValue("logger");super(r);g(this,Gn);g(this,jn,void 0);g(this,qn,void 0);h(this,"recordingPeerIds",[]);h(this,"recordings",[]);m(this,qn,t),m(this,jn,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,qn).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!n(this,jn).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new C("User does not have permission to start recording","1001");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw this.logger.error("Recording::start::recording_in_progress",{recording:{state:this.recordingState}}),new C(xg,"1005");try{const e=Lt(),{recording:r={}}=n(this,qn).getValue("defaults"),i=await e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw this.logger.error("Recording::start::recording_failed_to_start",{error:e}),e instanceof Ld&&e.status===409?new C(xg,"1005"):new C("Error while starting recording","1000",this.logger)}}async stop(t){await b(this,Gn,vd).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await b(this,Gn,vd).call(this,"pause",["RECORDING"],t)}async resume(t){await b(this,Gn,vd).call(this,"resume",["PAUSED"],t)}},jn=new WeakMap,qn=new WeakMap,Gn=new WeakSet,vd=async function(t,e,r){if(!n(this,jn).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new C("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const a=this.recordings.find(o=>o.id===r);if(a===void 0)throw new C("Could not find the specified recording","1004");if(e.includes(a.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:a.state}});return}i.push(a)}else i=this.recordings.filter(a=>e.includes(a.state));i.forEach(async a=>{const o=a.state;t==="stop"&&(a.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await Lt().updateRecording(a.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),a.state!==o&&(a.state=o,this.emit("recordingUpdate",o)),new C("Error while stopping recording","1000",this.logger)}})},cm);ed([y.trace("Recording.start")],dn.prototype,"start",1);ed([y.trace("Recording.stop")],dn.prototype,"stop",1);ed([y.trace("Recording.stop")],dn.prototype,"pause",1);ed([y.trace("Recording.stop")],dn.prototype,"resume",1);dn=ed([rt("1000")],dn);var j0=Object.defineProperty,q0=Object.getOwnPropertyDescriptor,G0=(s,t,e,r)=>{for(var i=r>1?void 0:r?q0(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},Ci;class dS{constructor(t,e,r){h(this,"recording");h(this,"room");g(this,Ci,void 0);m(this,Ci,t),this.recording=new dn(t,e),this.room=r,this.setupEvents()}get telemetry(){return n(this,Ci).getValue("telemetry")}get logger(){return n(this,Ci).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case nn.BROWSER:e="BROWSER";break;case nn.COMPOSITE:e="COMPOSITE";break;case nn.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){n(this,Ci).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(V.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(V.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(V.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}Ci=new WeakMap;G0([y.trace("RecordingController.setupEvents")],dS.prototype,"setupEvents",1);var Ri;class W0{constructor(t){g(this,Ri,void 0);m(this,Ri,t)}hasFeature(t){return n(this,Ri).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return n(this,Ri).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return n(this,Ri).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}Ri=new WeakMap;class lp{constructor(t,e,r,i){h(this,"authToken");h(this,"logger");h(this,"features");h(this,"browserSpecs");h(this,"callStats");this.authToken=t,this.logger=e,this.features=r,this.browserSpecs=ve,this.callStats=i}static init(t){return new lp(t.getValue("authToken"),t.getValue("logger"),new W0(t),t.getValue("callstats"))}}class up{constructor(t){h(this,"internals");this.internals=t}static async init(t){const e=lp.init(t);return new up(e)}}var J0=Object.defineProperty,K0=Object.getOwnPropertyDescriptor,Ht=(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},Le,Se,ge,Js,Wt,Ko,Ce;class _t extends Ma{constructor(e,r,i=Vd,a=!0){const o=e.getValue("logger");super(o);g(this,Le,void 0);g(this,Se,void 0);g(this,ge,void 0);g(this,Js,void 0);g(this,Wt,void 0);g(this,Ko,void 0);g(this,Ce,void 0);h(this,"audioUpdateInProgress");h(this,"videoUpdateInProgress");m(this,Ce,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,m(this,Le,new lS(e,r)),m(this,Se,new SD(e,n(this,Le),void 0,i)),m(this,ge,new _D(e,n(this,Le),void 0,i)),m(this,Wt,new ED(n(this,Ce),n(this,Le))),m(this,Js,new vD(e,n(this,Le))),m(this,Ko,a),n(this,Se).on("trackMuted",this.onAudioTrackMuted.bind(this)),n(this,Se).on("trackChanged",this.onAudioTrackChanged.bind(this)),n(this,ge).on("trackChanged",this.onVideoTrackChanged.bind(this)),n(this,ge).on("trackEnded",this.onVideoTrackEnded.bind(this)),n(this,Wt).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return n(this,Ce).getValue("telemetry")}set context(e){m(this,Ce,e)}async onVisibilityChange(){n(this,Ce).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?n(this,Ce).getValue("callstats").browserBackgrounded():(n(this,Ce).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?n(this,Ce).getValue("callstats").audioOn():n(this,Ce).getValue("callstats").audioOff(),r?n(this,Ce).getValue("callstats").videoOn():n(this,Ce).getValue("callstats").videoOff();let i,a;if(e&&r)try{const c=await n(this,Le).getAudioAndVideoTrack(n(this,Se).userSelectedDevice,n(this,ge).userSelectedDevice);i=c.audioTrack,a=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await n(this,Le).getAudioTrack(!1,n(this,Se).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!a&&r)try{a=await n(this,Le).getVideoTrack(n(this,ge).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&n(this,Ce).getValue("callstats").audioOff(),r&&!a&&n(this,Ce).getValue("callstats").videoOff(),await n(this,Se).setMediaTrack(i),await n(this,ge).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,Js).currentDevice)!=null&&o.deviceId&&n(this,Ce).getValue("callstats").selectedDevice("SPEAKER",n(this,Js).currentDevice),n(this,Le).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:n(this,Se).currentDevice,video:n(this,ge).currentDevice,speaker:n(this,Js).currentDevice}}get permissions(){return n(this,Le).permissions}getAllDevices(){return n(this,Le).getAvailableDevices()}getDeviceById(e,r){return n(this,Le).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return n(this,Se).mediaTrack}get audioTrack(){return n(this,Se).transformedMediaTrack}get audioEnabled(){return n(this,Se).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await n(this,Se).enableTrack(!1,e):await n(this,Se).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){n(this,Se).mediaTrack&&!n(this,Se).isCustomTrack?n(this,Se).muteTrack():n(this,Se).disableTrack()}getAudioDevices(e){return n(this,Le).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await n(this,Se).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,Ce).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await n(this,Js).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,Js).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,ge).mediaTrack}get videoTrack(){return n(this,ge).transformedMediaTrack}get videoEnabled(){return n(this,ge).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await n(this,ge).enableTrack(!1,e):await n(this,ge).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){n(this,ge).disableTrack()}getVideoDevices(e){return n(this,Le).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await n(this,ge).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,ge).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:n(this,Wt).audioMediaTrack,video:n(this,Wt).videoMediaTrack}}get screenShareEnabled(){return n(this,Wt).trackEnabled}async enableScreenShare(){await n(this,Wt).enableScreenShare()}async disableScreenShare(){n(this,Wt).disableScreenShare()}async updateScreenshareConstraints(e){await n(this,Wt).updateConstraints(e)}getSpeakerDevices(e){return n(this,Le).getAudioOutputDevices(e)}addAudioMiddleware(e){return n(this,Se).addMiddleware(e)}removeAudioMiddleware(e){return n(this,Se).removeMiddleware(e)}removeAllAudioMiddlewares(){return n(this,Se).removeAllMiddlewares()}addVideoMiddleware(e){return n(this,ge).addMiddleware(e)}removeVideoMiddleware(e){return n(this,ge).removeMiddleware(e)}removeAllVideoMiddlewares(){return n(this,ge).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return n(this,ge).setVideoMiddlewareGlobalConfig(e)}destruct(){n(this,Se).disableTrack(),n(this,ge).disableTrack(),n(this,ge).terminateMiddlewareWebWorker(),n(this,Wt).disableScreenShare(),n(this,Le).destruct()}async onDeviceChange(e,r){var a,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!n(this,Ko))return;let i=!1;(a=e==null?void 0:e.added)==null||a.reverse().forEach(async c=>{var d;c&&!Vd(c)&&(c.kind==="audioinput"&&((d=this.audioTrack)==null?void 0:d.enabled)===!0?await this.setAudioDevice(c,{saveDevicePreference:!1}):c.kind==="audiooutput"&&(i=!0,await this.setSpeakerDevice(c,{saveDevicePreference:!1})))}),i||(o=e==null?void 0:e.removed)==null||o.forEach(async c=>{var d;if(c.kind==="audiooutput"&&((d=this.getCurrentDevices().speaker)==null?void 0:d.deviceId)===c.deviceId){const l=await this.getSpeakerDevices();(l==null?void 0:l.length)>0&&await this.setSpeakerDevice(l[0],{saveDevicePreference:!1})}})}removeAllTracks(){this.destruct()}removeAudioTrack(){n(this,Se).disableTrack()}removeVideoTrack(){n(this,ge).disableTrack(),n(this,ge).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Le=new WeakMap,Se=new WeakMap,ge=new WeakMap,Js=new WeakMap,Wt=new WeakMap,Ko=new WeakMap,Ce=new WeakMap;Ht([y.trace("MediaHandler.setupStreams")],_t.prototype,"setupStreams",1);Ht([y.trace("MediaHandler.enableAudio")],_t.prototype,"enableAudio",1);Ht([y.trace("MediaHandler.disableAudio")],_t.prototype,"disableAudio",1);Ht([y.trace("MediaHandler.setAudioDevice")],_t.prototype,"setAudioDevice",1);Ht([y.trace("MediaHandler.enableVideo")],_t.prototype,"enableVideo",1);Ht([y.trace("MediaHandler.disableVideo")],_t.prototype,"disableVideo",1);Ht([y.trace("MediaHandler.setVideoDevice")],_t.prototype,"setVideoDevice",1);Ht([y.trace("MediaHandler.updateVideoConstraints")],_t.prototype,"updateVideoConstraints",1);Ht([y.trace("MediaHandler.enableScreenShare")],_t.prototype,"enableScreenShare",1);Ht([y.trace("MediaHandler.disableScreenShare")],_t.prototype,"disableScreenShare",1);Ht([y.trace("MediaHandler.updateScreenshareConstraints")],_t.prototype,"updateScreenshareConstraints",1);Ht([y.trace("MediaHandler.destruct")],_t.prototype,"destruct",1);Ht([y.trace("MediaHandler.onDeviceChange")],_t.prototype,"onDeviceChange",1);function ud(s,t,e){switch(!0){case ve.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case ve.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case ve.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 z0=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function Vd(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=ve._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:z0.some(i=>t==null?void 0:t.includes(i))}async function Y0(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,a=await Promise.all(t==null?void 0:t.map(d=>d(i))),o=i.createMediaStreamSource(new MediaStream([e])),c=i.createMediaStreamDestination();try{let d=o;for(let l=0;l<a.length;l+=1)d.connect(a[l]),d=a[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}var bi,zo;class Q0{constructor(t){g(this,bi,void 0);g(this,zo,void 0);m(this,zo,t)}get logger(){return n(this,zo).getValue("logger")}terminateMiddlewareWebWorker(){if(n(this,bi))try{po.clearInterval(n(this,bi)),m(this,bi,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),a=await Promise.all(t==null?void 0:t.map(f=>f({canvas:i,WorkerTimers:po})));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,bi,po.setInterval(l,50))},!1);const p=i.captureStream().getVideoTracks()[0];return Object.defineProperty(p,"originalSettings",{value:e.getSettings()}),p}}bi=new WeakMap,zo=new WeakMap;const X0={qvga:{width:{ideal:320},height:{ideal:240},frameRate:{ideal:30}},vga:{width:{ideal:640},height:{ideal:480},frameRate:{ideal:30}},hd:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},fhd:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},uhd:{width:{ideal:3840},height:{ideal:2160},frameRate:{ideal:30}}},Z0=[[320,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[640,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[1280,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[1920,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[3840,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]]],eD=(s,t)=>{var d,l,u;const e=(d=s==null?void 0:s.getValue("overrides"))==null?void 0:d.simulcastConfig;if((l=e==null?void 0:e.encodings)!=null&&l.length)return e.encodings;const r="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((u=t.originalSettings)==null?void 0:u.width),i=Z0,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 ye=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(ye||{});const tD=BC(),fn=Os(tD.config.media);function sD(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 ki,Qd;class rD{constructor(t,e){g(this,ki,void 0);g(this,Qd,void 0);h(this,"getScreenShareConstraints",()=>{var l,u,p,f,T,E,R,I,D;const t=(l=n(this,ki))==null?void 0:l.screenshare,e=(p=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?p:1920,r=(T=(f=t==null?void 0:t.height)==null?void 0:f.max)!=null?T:1080,i=(R=(E=t==null?void 0:t.frameRate)==null?void 0:E.max)!=null?R:5,a=(D=(I=t==null?void 0:t.frameRate)==null?void 0:I.ideal)!=null?D:5,o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;let d={width:{max:e},height:{max:r},frameRate:{ideal:a,max:i}};return o!==void 0&&["monitor","browser","window"].includes(o)&&(d={...d,displaySurface:o}),c!==void 0&&(d={...d,selfBrowserSurface:c}),{audio:!0,video:d}});h(this,"getAudioConstraints",t=>{var a,o,c,d,l,u,p;const e={},r=(a=n(this,ki))==null?void 0:a.audio,i=r!=null&&r.enableStereo?2:1;return ve.isFirefox()||ve.isWebKitBased()?(e.audio={deviceId:t,autoGainControl:(o=r==null?void 0:r.autoGainControl)!=null?o:!0,echoCancellation:(c=r==null?void 0:r.echoCancellation)!=null?c:!0,noiseSuppression:(d=r==null?void 0:r.noiseSupression)!=null?d:!0,channelCount:i},e):(e.audio={autoGainControl:(l=r==null?void 0:r.autoGainControl)!=null?l:!0,echoCancellation:(u=r==null?void 0:r.echoCancellation)!=null?u:!0,noiseSuppression:(p=r==null?void 0:r.noiseSupression)!=null?p:!0,channelCount:i},t&&(e.audio.deviceId={exact:t}),e)});h(this,"getVideoConstraints",t=>{var o,c,d;const e={},r=(o=n(this,ki))==null?void 0:o.video,i=r_(X0);let a=i.vga;if(typeof r=="string"){const l=i[r];l&&(a=l)}else r!==void 0&&(a.height.ideal=r.height.ideal,a.width.ideal=r.width.ideal,a.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=a,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});m(this,Qd,t),m(this,ki,e)}getUpdatedVideoConstraints(t){return t}}ki=new WeakMap,Qd=new WeakMap;class Du extends Error{constructor(e,r,i){super(r);h(this,"constraints");h(this,"name");this.name=e,this.constraints=i}}class iD{constructor(){h(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 nD=Object.defineProperty,aD=Object.getOwnPropertyDescriptor,fs=(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},Wn,Jt,xe,dm;let $t=(dm=class extends iD{constructor(t,e){super();g(this,Wn,void 0);g(this,Jt,void 0);g(this,xe,void 0);m(this,xe,t),m(this,Jt,new rD(t,e)),m(this,Wn,new AbortController)}get telemetry(){return n(this,xe).getValue("telemetry")}get logger(){return n(this,xe).getValue("logger")}get constraintsBuilder(){return n(this,Jt)}async destruct(){var t;(t=n(this,Wn))==null||t.abort()}handlePermissionErrors(t,e){const r=ud(t,e.name,e.message);return this.permissions[t]=r,n(this,xe).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,a,o;try{const c=await this.getAudioInputDevices(),d=await this.getVideoInputDevices(),l=!!(c!=null&&c.find(D=>D.deviceId===t));let u;t&&l?u=t:c&&((r=c[0])!=null&&r.deviceId)&&(u=(i=c[0])==null?void 0:i.deviceId);const p=!!(d!=null&&d.find(D=>D.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,Jt).getAudioConstraints(u).audio,video:n(this,Jt).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 R=E.getAudioTracks()[0];let I=E.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",I.label.includes("OBS Virtual")){const A=(await this.getVideoInputDevices()).find(x=>x.label.includes("OBS Virtual"));I=await this.getVideoTrack(A.deviceId)}return n(this,xe).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),n(this,xe).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:R,videoTrack:I}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new C("Couldnt fetch audio and video track","1605")}}async getAudioTrack(t,e){var c,d;let r=await this.getAudioInputDevices();if(!(r!=null&&r.length))throw this.permissions.audio="NO_DEVICES_AVAILABLE",n(this,xe).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new C("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let a;e&&i?a=e:(c=r[0])!=null&&c.deviceId&&(a=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(f=>f.deviceId!==l),u=n(this,Jt).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[p]=(await navigator.mediaDevices.getUserMedia(u)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),p}catch(p){const f=ud("audio",p.name,p.message),T=new Du(p.name,p.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw T;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const R=n(this,Jt).getAudioConstraints(E.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(R)}),o(E.deviceId)}throw T}};try{const l=await o(a);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",n(this,xe).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new C(l.message,"1601")}}async getVideoTrack(t){var c,d,l;const e=(c=await this.getCurrentDeviceLabel(t))==null?void 0:c.includes("OBS Virtual"),r=await this.getVideoInputDevices();if(!(r!=null&&r.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",n(this,xe).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new C("No video devices available","1607");const i=!!(r!=null&&r.find(u=>u.deviceId===t));let a;t&&i?a=t:(d=r[0])!=null&&d.deviceId&&(a=(l=r[0])==null?void 0:l.deviceId);const o=async u=>{try{let p=u;const{video:f}=p;e&&typeof f!="boolean"&&(p={video:{deviceId:f.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(p)});const[T]=(await navigator.mediaDevices.getUserMedia(p)).getVideoTracks();if(e&&typeof f!="boolean"&&typeof f.width=="object"){const{width:E,height:R}=T.getSettings(),{ideal:I}=f.width;T.applyConstraints({width:{ideal:I},height:{ideal:Math.floor(R*I/E)},frameRate:f.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(p)}),T}catch(p){const f=ud("video",p.name,p.message),T=new Du(p.name,p.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw T;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const R=n(this,Jt).getVideoConstraints(E.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(R)}),o({video:R.video})}throw T}};try{const u=n(this,Jt).getVideoConstraints(a),p=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",n(this,xe).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),p}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new C(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),n(this,xe).getValue("callstats").screenShareRequested();const r=await navigator.mediaDevices.getDisplayMedia(e);return this.logger.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const i=ud("video",r.name,r.message),a=new Du(r.name,r.message,e),o={video:!0};if(uC(e,o))throw a;if(i==="COULD_NOT_START")return t(o);throw a}};try{const e=n(this,Jt).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",n(this,xe).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new C(e.message,"1612")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async enumerateDevicesWithExternalFirst(){const t=await navigator.mediaDevices.enumerateDevices(),e=i=>{var o;const a=((o=i.label)==null?void 0:o.toLowerCase())||"";return Vd(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 u,p;const o=e(i),c=e(a);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=a.deviceId==="default"||((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 C("Failed to get available devices by kind","1609")}}async getDevice(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(r=>r.deviceId===t)[0]}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get device","1609")}}async onDeviceChange(t){if(ve.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,u;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||(u=d.removed)!=null&&u.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,xe).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(f=>f.kind==="audioinput")),p.some(f=>f.kind==="videoinput")&&n(this,xe).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(f=>f.kind==="videoinput")),p.some(f=>f.kind==="audiooutput")&&n(this,xe).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(f=>f.kind==="audiooutput")),t(r,d,!1)}},{signal:n(this,Wn).signal})}}},Wn=new WeakMap,Jt=new WeakMap,xe=new WeakMap,dm);fs([y.trace("WebMediaInterface.destruct")],$t.prototype,"destruct",1);fs([y.trace("WebMediaInterface.handlePermissionErrors")],$t.prototype,"handlePermissionErrors",1);fs([y.trace("WebMediaInterface.getAudioAndVideoTrack")],$t.prototype,"getAudioAndVideoTrack",1);fs([y.trace("WebMediaInterface.getAudioTrack")],$t.prototype,"getAudioTrack",1);fs([y.trace("WebMediaInterface.getVideoTrack")],$t.prototype,"getVideoTrack",1);fs([y.trace("WebMediaInterface.getScreenShareTracks")],$t.prototype,"getScreenShareTracks",1);fs([y.trace("WebMediaInterface.getAvailableDevices")],$t.prototype,"getAvailableDevices",1);fs([y.trace("WebMediaInterface.getAvailableDevicesByKind")],$t.prototype,"getAvailableDevicesByKind",1);fs([y.trace("WebMediaInterface.getDevice")],$t.prototype,"getDevice",1);fs([y.trace("WebMediaInterface.onDeviceChange")],$t.prototype,"onDeviceChange",1);$t=fs([rt("1600")],$t);const lS=$t,on={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}},oD=(s=0)=>new Promise(t=>setTimeout(t,s)),cD=(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):oD().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},dD=typeof AudioContext!="undefined"?AudioContext:null;class hp{constructor(t){h(this,"_AudioContext");h(this,"audioContext");h(this,"_audioContextRefContainers");const e={AudioContext:dD,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:hp}})}getOrCreate(t){if(!this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.add(t),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(e){}return this.audioContext}release(t){this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.delete(t),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const Ug=new hp,lD=3,uD=250;function hD(s){const t={},e=Ug.getOrCreate(t);let r=lD;function i(){return r-=1,cD(e,s.srcObject,uD).then(a=>a?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Ug.release(t)})}async function Hg(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const a=e.play();a&&await a,i=await hD(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 pD=Object.defineProperty,gD=Object.getOwnPropertyDescriptor,uS=(s,t,e,r)=>{for(var i=r>1?void 0:r?gD(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&&pD(t,e,i),i};let $d=class extends Ma{constructor(t,e,r,i){var o;const a=t.getValue("logger");super(a);h(this,"constructorName",this.constructor.name);h(this,"userSelectedDevice");h(this,"mediaInterface");h(this,"isNonPreferredDevice");h(this,"_mediaTrack");h(this,"transformedMediaTrack");h(this,"middlewares",[]);h(this,"currentDevice");h(this,"userPreferredDeviceKey",`Realtimekit::${this.constructorName}::UserDeviceID`);h(this,"setUserPreferredDevice",t=>on.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>on.getItem(this.userPreferredDeviceKey,this.logger));h(this,"isCustomTrack",!1);h(this,"context");this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(o=this.getUserPreferredDevice())!=null?o:void 0,this.isNonPreferredDevice=i,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}get telemetry(){return this.context.getValue("telemetry")}disableTrack(){var t,e;this.removeMediaTrackListeners(),this.isCustomTrack||(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}async setMediaTrack(t,e=!1){const r=i=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){r(i)}this._mediaTrack=await this.conditionallyChangeTrack(t,e),await this.setTransformedTrack();try{this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){r(i)}}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){this.logger.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}async unmuteTrack(){try{this.mediaTrack?this.mediaTrack.enabled=!0:await this.enableTrack(!1)}catch(t){throw this.logger.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new C("Failed to unmute track","1611")}}getCurrentDeviceId(){var e;const{kind:t}=this.mediaTrack;switch(t){case"audio":{const{deviceId:r}=this.mediaTrack.getSettings();if(r)return r;const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(i&&typeof i.deviceId=="object"&&"exact"in i.deviceId?i.deviceId.exact:i.deviceId)||((e=i==null?void 0:i.advanced)==null?void 0:e[0].deviceId)||"default":this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}async setCurrentDevice(){var e;if(!this.mediaTrack){this.currentDevice=void 0;return}const t=this.getCurrentDeviceId();((e=this.currentDevice)==null?void 0:e.deviceId)!==t&&(this.currentDevice=await this.mediaInterface.getDevice(t))}async setDevice(t,{saveDevicePreference:e}){if(!t)throw this.logger.warn(`${this.constructorName}.setDevice No device received`),new C("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(ve.isWebKitBased()&&!(ve.isSafari()&&CC.test(ve.getVersion())))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&await this.setTransformedTrack(),{success:!0,message:"Successfully added the middleware."}}catch(e){return this.logger.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}}async removeMiddleware(t){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return this.logger.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}}async removeAllMiddlewares(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return this.logger.error("While removing all the middlewares",{error:e}),{success:!1,message:e==null?void 0:e.message}}return{success:!1,message:"No middlewares were found. Skipping."}}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.logger.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};uS([y.trace("BaseMediaHandler.unmuteTrack")],$d.prototype,"unmuteTrack",1);$d=uS([rt("1600")],$d);const hS=$d;var mD=Object.defineProperty,fD=Object.getOwnPropertyDescriptor,pp=(s,t,e,r)=>{for(var i=r>1?void 0:r?fD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mD(t,e,i),i};const Ou="[Realtimekit]nonSilentDeviceLabels";class lu extends hS{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new C("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new C("Non audio device received while setting device!","1603");try{const e=this.trackEnabled;this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getAudioTrack(!e,this.userSelectedDevice))}catch(e){throw this.logger.error("AudioMediaHandler.setDevice.error",{error:e}),this.disableTrack(),new C(e.message,"1604")}}async enableTrack(t,e){if(this.trackEnabled){this.logger.warn("AudioMediaHandler.enableTrack Track already enabled!");return}if(e){this.isCustomTrack=!0,await this.setMediaTrack(e,!0);return}this.isCustomTrack=!1;const r=await this.mediaInterface.getAudioTrack(t,this.userSelectedDevice);await this.setMediaTrack(r)}async setTransformedTrack(t){var e;if(!t&&!((e=this.middlewares)!=null&&e.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await Y0(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(on.getItem(Ou,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await Hg(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return on.setItem(Ou,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return a.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await Hg(this.logger,r)){const p=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return on.setItem(Ou,JSON.stringify({devices:p}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}pp([y.trace("AudioMediaHandler.setTransformedTrack")],lu.prototype,"setTransformedTrack",1);pp([y.trace("AudioMediaHandler.onTrackEnded")],lu.prototype,"onTrackEnded",1);pp([y.trace("AudioMediaHandler.conditionallyChangeTrack")],lu.prototype,"conditionallyChangeTrack",1);const SD=lu;var Ii;class TD{constructor(t,e){g(this,Ii,void 0);h(this,"currentDevice");h(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");h(this,"logger");h(this,"setUserPreferredDevice",t=>on.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>on.getItem(this.userPreferredDeviceKey,this.logger));m(this,Ii,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await n(this,Ii).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,Ii)instanceof lS))return;let r=t;if(t||([r]=(await n(this,Ii).getAvailableDevicesByKind("audiooutput")).filter(d=>!Vd(d))),!r)throw new C("No speaker found","1608");if(((a=this.currentDevice)==null?void 0:a.deviceId)===r.deviceId)return;e&&this.setUserPreferredDevice(r.deviceId),this.currentDevice=r;const i=document.querySelectorAll("audio");(o=i[0])!=null&&o.setSinkId&&i.forEach(async c=>{if(typeof c.sinkId!="undefined"&&this.currentDevice.deviceId&&c.sinkId!==this.currentDevice.deviceId)try{await c.setSinkId(this.currentDevice.deviceId)}catch(d){}})}}Ii=new WeakMap;const vD=TD;var Yo;class yD extends Ma{constructor(e,r){const i=e.getValue("logger");super(i);h(this,"mediaInterface");h(this,"audioMediaTrack");h(this,"videoMediaTrack");g(this,Yo,void 0);m(this,Yo,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,Yo).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 C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),ve.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")}}Yo=new WeakMap;const ED=yD;var PD=Object.defineProperty,wD=Object.getOwnPropertyDescriptor,uu=(s,t,e,r)=>{for(var i=r>1?void 0:r?wD(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&&PD(t,e,i),i},Jn,Qo;class td extends hS{constructor(e,r,i,a){super(e,r,i,a);g(this,Jn,void 0);g(this,Qo,{disablePerFrameCanvasRendering:!1});m(this,Jn,new Q0(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new C("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new C("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){this.logger.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C("Failed to change device","1600",this.logger)}}async enableTrack(e,r){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,await this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=await this.mediaInterface.getVideoTrack(this.userSelectedDevice);await this.setMediaTrack(i)}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await n(this,Jn).getTransformedVideoTrack(this.middlewares,this.mediaTrack,n(this,Qo)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){m(this,Qo,e)}async updateConstraints(e){if(!this._mediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}}terminateMiddlewareWebWorker(){n(this,Jn).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}}Jn=new WeakMap,Qo=new WeakMap;uu([y.trace("VideoMediaHandler.setTransformedTrack")],td.prototype,"setTransformedTrack",1);uu([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],td.prototype,"setVideoMiddlewareGlobalConfig",1);uu([y.trace("VideoMediaHandler.onTrackEnded")],td.prototype,"onTrackEnded",1);uu([y.trace("VideoMediaHandler.conditionallyChangeTrack")],td.prototype,"conditionallyChangeTrack",1);const _D=td,Bg=Os(ip());var ot,Mi,Xo,Kn;const wn=class{constructor(t){g(this,ot,void 0);g(this,Mi,void 0);g(this,Xo,void 0);g(this,Kn,void 0);if(!t)throw new C("Could not load preset.","0904");m(this,ot,t.config),m(this,Xo,t.name),m(this,Mi,t.ui||Os(ip().ui)),m(this,Kn,t.permissions.plugins.config)}static fromResponse(t){return new wn(t)}static default(){return new wn(Bg)}static init(t,e=!0){return!t||e?new wn(Bg):new wn(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,Mi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return n(this,ot).viewType}get livestreamViewerQualities(){return n(this,ot).livestreamViewerQualities||[]}get maxVideoStreams(){return n(this,ot).maxVideoStreams}get maxScreenShareCount(){return n(this,ot).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(n(this,Kn)).filter(t=>n(this,Kn)[t].disabled)}get designTokens(){return n(this,Mi).designTokens}get configDiff(){return n(this,Mi).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=n(this,ot))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.simulcast)!=null?i:!1}get mediaConstraints(){var t,e,r,i,a,o,c,d,l,u,p,f,T,E,R,I,D,A,x,$,U,z,ee,H;return{audio:{enableStereo:(i=(r=(e=(t=n(this,ot))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:fn.audio.enableStereo,enableHighBitrate:(d=(c=(o=(a=n(this,ot))==null?void 0:a.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:fn.audio.enableHighBitrate},video:{quality:(f=(p=(u=(l=n(this,ot))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:p.quality)!=null?f:fn.video.quality,frameRate:(I=(R=(E=(T=n(this,ot))==null?void 0:T.media)==null?void 0:E.video)==null?void 0:R.frameRate)!=null?I:fn.video.frameRate},screenshare:{quality:($=(x=(A=(D=n(this,ot))==null?void 0:D.media)==null?void 0:A.screenshare)==null?void 0:x.quality)!=null?$:fn.screenshare.quality,frameRate:(H=(ee=(z=(U=n(this,ot))==null?void 0:U.media)==null?void 0:z.screenshare)==null?void 0:ee.frameRate)!=null?H:fn.screenshare.frameRate}}}get name(){return n(this,Xo)}};let ch=wn;ot=new WeakMap,Mi=new WeakMap,Xo=new WeakMap,Kn=new WeakMap;var CD=Object.defineProperty,RD=Object.getOwnPropertyDescriptor,pS=(s,t,e,r)=>{for(var i=r>1?void 0:r?RD(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&&CD(t,e,i),i},zn,Zo;class gp extends xt{constructor(e,r){const i=e.getValue("logger");super(i);g(this,zn,void 0);h(this,"state","IDLE");h(this,"playbackUrl");h(this,"ingestionCredentials");h(this,"viewerCount");g(this,Zo,void 0);m(this,zn,r),m(this,Zo,e),this.viewerCount=0}get telemetry(){return n(this,Zo).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(e={manualIngestion:!1}){if(!n(this,zn).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new C("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=Lt(),{playbackUrl:i,ingestionCredentials:a}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=a,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("Recording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new C("Error while starting livestream","1900",this.logger)}}async stop(){if(!n(this,zn).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new C("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw this.logger.error("Livestream::stop::inconsistent_state"),new C("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await Lt().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new C("Error while stopping livestream","1900",this.logger)}}}zn=new WeakMap,Zo=new WeakMap;pS([y.trace("livestream.start")],gp.prototype,"start",1);pS([y.trace("livestream.stop")],gp.prototype,"stop",1);var bD=Object.defineProperty,kD=Object.getOwnPropertyDescriptor,ID=(s,t,e,r)=>{for(var i=r>1?void 0:r?kD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&bD(t,e,i),i},Yn,Qn,Ks,Ts;class gS{constructor(t,e,r){h(this,"livestream");g(this,Yn,void 0);g(this,Qn,void 0);g(this,Ks,void 0);g(this,Ts,void 0);m(this,Ts,t),m(this,Qn,e),this.livestream=new gp(t,e),m(this,Ks,r),this.setupEvents()}get logger(){return n(this,Ts).getValue("logger")}get telemetry(){return n(this,Ts).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=Lt(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:a}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=a,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){n(this,Ks).on(V.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{n(this,Qn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),n(this,Ks).on(V.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{n(this,Qn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),n(this,Ks).on(V.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),n(this,Ks).on(V.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),n(this,Ks).on(V.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),n(this,Ts).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,Yn,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),n(this,Ts).getValue("peerSessionStore").on(w.PEER_CLOSED,t=>{t.id===n(this,Yn)&&(m(this,Yn,void 0),this.livestream.setLivestreamState("IDLE"))}),n(this,Ts).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,Ts).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}Yn=new WeakMap,Qn=new WeakMap,Ks=new WeakMap,Ts=new WeakMap;ID([y.trace("LivestreamController.setupEvents")],gS.prototype,"setupEvents",1);var MD=Object.defineProperty,AD=Object.getOwnPropertyDescriptor,sd=(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&&MD(t,e,i),i},Ye,xr,Ur,Xd,mS;class Da{constructor({name:t,socketHandler:e,meetingId:r}){g(this,Xd);h(this,"name","");g(this,Ye,{});g(this,xr,"");g(this,Ur,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});h(this,"listeners",{});this.name=t,m(this,Ur,e),m(this,xr,r)}async set(t,e,r=!0,i=!1){n(this,Ye)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(a=>a({[t]:n(this,Ye)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(a=>a({[t]:n(this,Ye)[t]})))}remoteSet(t,e){n(this,Ur).storeInsertKeys(n(this,xr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{n(this,Ye)[e]=r}),n(this,Ur).storeInsertKeys(n(this,xr),this.name,t)}async update(t,e,r=!0){b(this,Xd,mS).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(n(this,Ye)[t]&&delete n(this,Ye)[t],e)return n(this,Ur).storeDeleteKeys(n(this,xr),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(i=>i({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{n(this,Ye)[e]&&delete n(this,Ye)[e]}),n(this,Ur).storeDeleteKeys(n(this,xr),this.name,t)}get(t){if(n(this,Ye)[t])return n(this,Ye)[t]}getAll(){return n(this,Ye)}clear(){m(this,Ye,{})}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(i=>i!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){m(this,Ye,t)}}Ye=new WeakMap,xr=new WeakMap,Ur=new WeakMap,Xd=new WeakSet,mS=function(t,e,r=!0){let i;const a=n(this,Ye)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(a);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...a,...e];break;case"[object Object]":i={...a,...e};break;case"[object Map]":i=new Map([...a,...e]);break;case"[object Set]":i=new Set([...a,...e]);break;default:i=e;break}this.set(t,i,r)};sd([Ut(Aa,"rateLimitConfig")],Da.prototype,"remoteSet",1);sd([Ut(Aa,"bulkRateLimitConfig")],Da.prototype,"bulkSet",1);sd([Ut(Aa,"rateLimitConfig")],Da.prototype,"update",1);sd([Ut(Aa,"rateLimitConfig")],Da.prototype,"delete",1);sd([Ut(Aa,"bulkRateLimitConfig")],Da.prototype,"bulkDelete",1);var Hr,Br,ec,dh,tc,as,Zd,fS;class DD{constructor(t,e){g(this,ec);g(this,Zd);h(this,"stores",new Map);g(this,Hr,void 0);g(this,Br,"");g(this,tc,void 0);g(this,as,new Map);m(this,Hr,e),m(this,Br,t.getValue("meetingId")),m(this,tc,t),b(this,Zd,fS).call(this)}create(t,e=!1){if(RC.includes(t)&&!e)throw new C(`'${t}' is a reserved store name.`,"0601");const r=new Da({name:t,socketHandler:n(this,Hr),meetingId:n(this,Br)});return n(this,Hr).storeGetKeys(n(this,Br),t,[]),new Promise((a,o)=>{const c=setTimeout(()=>{n(this,as).delete(t),o(Error("Failed"))},3e3);n(this,as).set(t,{rejectTimeout:c,resolve:a,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),n(this,Hr).storeGetKeys(n(this,Br),t,[]),new Promise((i,a)=>{const o=setTimeout(()=>{n(this,as).delete(t),a(Error("Store refresh timed out"))},3e3);n(this,as).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}Hr=new WeakMap,Br=new WeakMap,ec=new WeakSet,dh=function(){return n(this,tc).getValue("peerId")},tc=new WeakMap,as=new WeakMap,Zd=new WeakSet,fS=function(){[Hs.storeInsertKeys,Hs.storeGetKeys,Hs.storeDeleteKeys].forEach(t=>{n(this,Hr).on(t,async e=>{var a,o;if(e.pluginId!==n(this,Br))return;const r=(a=e.storeItems)==null?void 0:a.map(c=>{var d;return{timestamp:c.timestamp,peerId:c.peerId,payload:JSON.parse((d=c.payload)!=null&&d.length?new TextDecoder().decode(c.payload):"{}"),key:c.storeKey}});if(t===Hs.storeGetKeys){const c=n(this,as).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(n(this,as).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),n(this,as).delete(e.storeName)),!d)return;r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=n(this,as).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===Hs.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==n(this,ec,dh)&&i.set(c,l,!1,!0)}),t===Hs.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==n(this,ec,dh)&&i.delete(c,!1,!0)}))})})};function mi(s){var t,e,r,i,a,o,c,d,l,u,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=(u=s.screenShareTracks)==null?void 0:u.video)==null?void 0:p.enabled,trackId:(T=(f=s.screenShareTracks)==null?void 0:f.video)==null?void 0:T.id}}}}:{}}var OD=Object.defineProperty,ND=Object.getOwnPropertyDescriptor,Oa=(s,t,e,r)=>{for(var i=r>1?void 0:r?ND(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&&OD(t,e,i),i};const LD=.8,VD=1.2;var Xn,Zn,It,Ai,eo,Fr,vn,Di,to,el,SS,ct,sc,jr,Oi,so,zs,tl,rc,lh,sl,TS,rl,vS,lm;let mr=(lm=class extends xt{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,Ai);g(this,Fr);g(this,Di);g(this,el);g(this,Oi);g(this,rc);g(this,sl);g(this,rl);h(this,"id");h(this,"userId");h(this,"name");h(this,"picture");h(this,"isHost");h(this,"customParticipantId");h(this,"flags");h(this,"device");h(this,"videoTrack");h(this,"audioTrack");h(this,"screenShareTracks");h(this,"videoEnabled");h(this,"audioEnabled");h(this,"screenShareEnabled");h(this,"producers");h(this,"manualProducerConfig");g(this,Xn,void 0);h(this,"supportsRemoteControl",!1);g(this,Zn,void 0);h(this,"presetName");g(this,It,void 0);g(this,ct,void 0);g(this,sc,void 0);g(this,jr,new Map);g(this,zs,1);g(this,tl,sp(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>VD&&n(this,zs)===1?(m(this,zs,0),n(this,It).getValue("peerSessionStore").emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,zs)})):d<LD&&n(this,zs)===0&&(m(this,zs,1),n(this,It).getValue("peerSessionStore").emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,zs)}))},2e3));m(this,It,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:p,flags:f,stageStatus:T,customParticipantId:E,audioMuted:R,audioTrack:I,videoEnabled:D=!1,videoTrack:A,producers:x,metadata:$}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=p,this.flags=f,this.manualProducerConfig=vC,m(this,Zn,T!=null?T:"ON_STAGE"),this.customParticipantId=E,this.audioEnabled=!R,this.audioTrack=I,this.videoEnabled=D,this.videoTrack=A,this.screenShareTracks={audio:void 0,video:void 0},this.producers=x!=null?x:[],this.presetName=$==null?void 0:$.preset_name,m(this,Xn,!1),m(this,ct,r),m(this,sc,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),b(this,rc,lh).call(this)}get stageStatus(){return n(this,Zn)}get telemetry(){return n(this,It).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...mi(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...mi(this)}),this.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",b(this,rc,lh)),n(this,Fr,vn)&&(this.on("audioUpdate",b(this,sl,TS)),this.on("screenShareUpdate",b(this,rl,vS)))}async pin(){if(!n(this,Di,to))throw new C("Can`t pin participant without joining room","1205");if(!n(this,ct).permissions.pinParticipant)throw new C("You do not have permission to pin participants.","1201");return n(this,Ai,eo).pinPeer(this.id)}async unpin(){if(!n(this,Di,to))throw new C("Can`t unpin participant without joining room","1205");if(!n(this,ct).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.","1201");return n(this,Ai,eo).pinPeer(null)}setIsPinned(t,e=!0){var i;m(this,Xn,t);const r=t?"pinned":"unpinned";(i=n(this,Oi,so))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info(`Local peer ${n(this,ct).id} is disabling mic of a remote peer ${t}`),!n(this,Di,to))throw new C("Can`t disable participant audio without joining room","1205");if(n(this,ct).permissions.canDisableParticipantAudio)return n(this,Ai,eo).disableAudio(t);throw this.logger.error(`Local peer ${n(this,ct).id} is not authorized to disable mic of a remote peer ${t}`),new C("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info(`Local peer ${n(this,ct).id} is kicking a remote peer ${t} out of the meeting.`),!n(this,el,SS))throw new C("Can`t kick participant without joining room","1205");if(n(this,ct).permissions.kickParticipant){await n(this,It).getValue("peerSessionStore").emitAsync(w.KICK_PEER,{peerId:t});return}throw this.logger.error(`Local peer ${n(this,ct).id} is not authorized to kick a remote peer ${t} out of the meeting.`),new C("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info(`Local peer ${n(this,ct).id} is disabling webcam of a remote peer ${t}.`),!n(this,Di,to))throw new C("Can`t disable participant video without joining room","1205");if(n(this,ct).permissions.canDisableParticipantVideo)return n(this,Ai,eo).disableVideo(t);throw this.logger.error(`Local peer ${n(this,ct).id} is not authorized to disable webcam of a remote peer ${t}.`),new C("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return n(this,sc).getUserPermissions(this.userId)}setStageStatus(t){m(this,Zn,t),this.emit("stageStatusUpdate",this)}get isPinned(){return n(this,Xn)}registerVideoElement(t){var r,i,a,o;if(!t)return;let e;(i=(r=n(this,jr).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>n(this,tl).call(this,t)),e.observe(t)),n(this,jr).set(t,{observer:e}),this.updateVideo(t),(o=n(this,Oi,so))==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,Oi,so))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=n(this,jr).get(t))==null?void 0:r.observer)==null||i.disconnect(),n(this,jr).delete(t),(a=n(this,Oi,so))==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"}},Xn=new WeakMap,Zn=new WeakMap,It=new WeakMap,Ai=new WeakSet,eo=function(){return n(this,It).getValue("roomNodeClient")},Fr=new WeakSet,vn=function(){return n(this,It).getValue("audioPlayback")},Di=new WeakSet,to=function(){return n(this,It).getValue("connectionHandler").mediaJoined},el=new WeakSet,SS=function(){return n(this,It).getValue("connectionHandler").socketJoined},ct=new WeakMap,sc=new WeakMap,jr=new WeakMap,Oi=new WeakSet,so=function(){return n(this,It).getValue("pip")},zs=new WeakMap,tl=new WeakMap,rc=new WeakSet,lh=function(){Array.from(n(this,jr).keys()).forEach(this.updateVideo)},sl=new WeakSet,TS=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=n(this,Fr,vn))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=n(this,Fr,vn))==null||e.removeParticipantTrack(this.id)},rl=new WeakSet,vS=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=n(this,Fr,vn))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=n(this,Fr,vn))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},lm);Oa([y.trace("Participant.disableAudio")],mr.prototype,"disableAudio",1);Oa([y.trace("Participant.kick")],mr.prototype,"kick",1);Oa([y.trace("Participant.disableVideo")],mr.prototype,"disableVideo",1);Oa([y.trace("Participant.getPermissions")],mr.prototype,"getPermissions",1);Oa([y.trace("Participant.setStageStatus")],mr.prototype,"setStageStatus",1);mr=Oa([rt("1200")],mr);class Za extends nS{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 qr;class $D extends Ma{constructor(e){super(e);g(this,qr,void 0);m(this,qr,new Map)}__set(e,r){return n(this,qr).set(e,r)}__clear(){return n(this,qr).clear()}get(e){return n(this,qr).get(e)}toArray(){return Array.from(n(this,qr).values())}}qr=new WeakMap;class xD{constructor(){h(this,"_orderedArray");h(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 UD{constructor(){h(this,"_activeSpeakerPeers");h(this,"_compulsoryPeers");this._activeSpeakerPeers=new xD,this._compulsoryPeers=new Set}add(t,e,r){if(!t)return-1;if(e<0)return this._compulsoryPeers.add(t),0;const i=r.getValue("logger");if(this.compulsoryPeers.includes(t)&&(e>0||e===246267631)){if(i.info("SelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),e===246267631)return-1}else if(e===229490415)return this.delete(t,r),-1;return this._activeSpeakerPeers.add(t,e)}delete(t,e){const r=e==null?void 0:e.getValue("logger");r==null||r.info("SelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),this._activeSpeakerPeers.delete(t)}reassignPeer(t,e,r){const i=this._activeSpeakerPeers.index(t),a=this._compulsoryPeers.has(t);this.delete(t,r),a&&this.add(e,-1,r),i>=0&&this.add(e,i+1,r)}index(t){return this._activeSpeakerPeers.index(t)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(t){this._compulsoryPeers.delete(t)}}const yS=new UD;var HD=Object.defineProperty,BD=Object.getOwnPropertyDescriptor,xs=(s,t,e,r)=>{for(var i=r>1?void 0:r?BD(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&&HD(t,e,i),i};const FD=["ACTIVE_GRID","PAGINATED","MANUAL"];var Re,ic,uh,Ni,ro,ea,yd,Li,vt,um;let ts=(um=class extends xt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,ic);g(this,Ni);g(this,ea);h(this,"waitlisted");h(this,"joined");h(this,"active");h(this,"videoSubscribed");h(this,"audioSubscribed");h(this,"pinned");h(this,"all");g(this,Re,void 0);g(this,Li,void 0);g(this,vt,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"viewMode");h(this,"currentPage");h(this,"lastActiveSpeaker");h(this,"selectedPeers",yS);m(this,Re,t),m(this,Li,e),m(this,vt,r),this.waitlisted=new Za(i),this.joined=new Za(i),this.videoSubscribed=new Za(i),this.audioSubscribed=new Za(i),this.active=this.videoSubscribed,this.pinned=new Za(i),this.all=new $D(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return n(this,Re).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return n(this,Re).getValue("telemetry")}setupEvents(){n(this,Re).getValue("peerSessionStore").on(w.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=n(this,Re).getValue("modules").e2ee)==null?void 0:r.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${e}, but encryption wasn't enabled in init.defaults`,code:"1702"})});const t=n(this,Re).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=n(this,Re))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24","1203");n(this,Re).setValue("maxPreferredStreams",t),n(this,ea,yd)&&n(this,Re).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var r,i;if(!n(this,Ni,ro))throw new C("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return n(this,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,Ni,ro))throw new C("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;n(this,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=>FD.includes(r))(t))throw this.logger.error("Participants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new C(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){this.logger.info("Participants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,n(this,Re).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,n(this,Re).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,n(this,Re).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)))}),n(this,Re).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!1},i.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(i.id)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!1},i.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(i.id)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1},i.manualProducerConfig.audio||this.audioSubscribed.delete(i.id)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1},i.manualProducerConfig.video||this.videoSubscribed.delete(i.id)))}),n(this,Re).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}getPeerIdsForCurrentPage(){this.logger.info("Participants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(c=>this.joined.has(c)),r=Array.from(this.pinned.keys()).filter(c=>!e.includes(c)),i=Array.from(this.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),a=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),o=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(a,o))}async setPage(t){if(this.logger.info("Participants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw this.logger.error("Participants::invalid_page_number"),new C(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,n(this,Re).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(this.logger.info("Participants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!n(this,ea,yd))throw new C("Can`t disable all audio without joining room","1205");if(n(this,Li).permissions.canAllowParticipantAudio)return n(this,ic,uh).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new C("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!n(this,ea,yd))throw new C("Can`t disable all video without joining room","1205");if(n(this,Li).permissions.canAllowParticipantVideo)return n(this,ic,uh).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.","1201")}async kickAll(){if(this.logger.info("Participants::kick_all"),n(this,Re).getValue("viewType")!=="LIVESTREAM"&&!n(this,Ni,ro))throw new C("Can`t kick all without joining room","1205");if(!n(this,Li).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;n(this,vt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!n(this,Ni,ro))throw new C("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new C("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await n(this,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(Er.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(a=>t.includes(a.id)).map(a=>a.userId),i=[...new Set(r)];if(!i.length)throw new C("Cannot update permissions, no valid userIDs found","1204");n(this,vt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return n(this,vt).getRoomPeersNonPaginated()}},Re=new WeakMap,ic=new WeakSet,uh=function(){return n(this,Re).getValue("roomNodeClient")},Ni=new WeakSet,ro=function(){var t;return((t=n(this,Re).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},ea=new WeakSet,yd=function(){var t;return((t=n(this,Re).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Li=new WeakMap,vt=new WeakMap,um);xs([y.trace("Participants.setViewMode")],ts.prototype,"setViewMode",1);xs([y.trace("Participants.setPage")],ts.prototype,"setPage",1);xs([y.trace("Participants.disableAllAudio")],ts.prototype,"disableAllAudio",1);xs([y.trace("Participants.disableAllVideo")],ts.prototype,"disableAllVideo",1);xs([y.trace("Participants.kickAll")],ts.prototype,"kickAll",1);xs([y.trace("Participants.broadcastMessage"),Ut(Aa,"rateLimitConfig")],ts.prototype,"broadcastMessage",1);xs([y.trace("Participants.getAllJoinedPeers"),Ut({maxInvocations:10,period:60})],ts.prototype,"getAllJoinedPeers",1);xs([y.trace("Participant.updatePermissions"),Ut({maxInvocations:1e3,period:60})],ts.prototype,"updatePermissions",1);xs([y.trace("Participants.getParticipantsInMeetingPreJoin")],ts.prototype,"getParticipantsInMeetingPreJoin",1);ts=xs([rt("1200")],ts);var jD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,gn=(s,t,e,r)=>{for(var i=r>1?void 0:r?qD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&jD(t,e,i),i};const GD=5e3,WD=1e4;var Kt,vs,Gr,Ue,Ys,Vi,$i,no,il,ES,nl,PS,nc,hh,al,wS,ol,_S,cl,hm;const io=(hm=class{constructor(s,t,e){g(this,$i);g(this,il);g(this,nl);g(this,nc);g(this,al);g(this,ol);h(this,"participants");h(this,"self");h(this,"selectedPeers",yS);h(this,"maxSpatialLayerUpdates",new Map);h(this,"consumerPeerMap");h(this,"events");h(this,"roomSocketHandler");h(this,"context");h(this,"videoPeerConsumerMap",new Map);g(this,Kt,{mode:"ACTIVE_GRID",page:0});g(this,vs,!1);g(this,Gr,!1);h(this,"isRebuildingReconnectSnapshot",!1);g(this,Ue,new Map);g(this,Ys,void 0);g(this,Vi,void 0);g(this,cl,({state:s})=>{s==="disconnected"||s==="stageLeft"||(this.isRebuildingReconnectSnapshot=!1,b(this,ol,_S).call(this),n(this,Ue).clear(),m(this,Ys,void 0))});h(this,"updateConsumerSpatialLayers",sp(()=>{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));h(this,"updateConsumers",async(s,t)=>{this.logger.info(`updateConsumers: Starting serialized consumer updates: createProducerIds=[${s.map(({producerId:e})=>e).join(",")}], deleteConsumerIds=[${t.join(",")}], consumersSyncing=${n(this,vs)}.`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for producerIds=[${s.map(({producerId:e})=>e).join(",")}].`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(e){this.logger.error("updateConsumers: Error creating consumers",{error:e})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers after grace period: consumerIds=[${t.join(",")}].`),await this.roomNodeClient.closeConsumersById(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(e){this.logger.error("updateConsumers: Error closing consumers",{error:e})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new ts(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=us,t.config.viewType!=="CHAT"&&(this.setupEventsGlobal(),b(this,al,wS).call(this)),this.setupEvents(),this.self.on("roomLeft",n(this,cl))}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var s;return((s=this.roomNodeClient)==null?void 0:s.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}handleSocketPeers(s){var d;const t=new Set(this.roomSocketHandler.socket.supersededLocalPeerIds),e=(d=s==null?void 0:s.filter(l=>!l.waitlisted&&!t.has(l.peerId)))!=null?d:[],r=new Set(e.map(({peerId:l})=>l)),i=t.size>0||this.participants.joined.size>0,a=this.context.getValue("viewType"),o=this.context.getValue("stageStatus"),c=this.mediaJoined&&(a!==hs.Livestream||o==="ON_STAGE");this.isRebuildingReconnectSnapshot=i&&c,this.isRebuildingReconnectSnapshot||(this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear()),i||(this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID"),this.participants.joined.forEach(({id:l})=>{var u;r.has(l)||(u=this.pip)==null||u.removeSource(l)}),this.participants.joined.clear(),e.forEach(l=>{var p;const u=this.createParticipantObjFromSocketPeer(l);if(this.isRebuildingReconnectSnapshot){const f=(p=this.participants.videoSubscribed.get(l.peerId))!=null?p:this.participants.audioSubscribed.get(l.peerId);f&&(u.manualProducerConfig={...f.manualProducerConfig})}this.logger.debug(`Processing socket join for ${this.self.id===u.id?"local peer":"remote peer"} ${u.id} listed in socket peers.`),this.onParticipantSocketJoined(u),this.logger.debug(`Processed socket join for ${this.self.id===u.id?"local peer":"remote peer"} ${u.id} listed in socket peers.`)})}handlePeerJoinedBroadcast({participant:s,producerHandoverFromPeerId:t}){var i;if(!s)return;const e=s.peerId===this.self.id,r=(i=s.producerStates)!=null?i:[];this.logger.info(`${e?"Local peer":"Remote peer"} ${s.peerId} has joined media room with producerStates: ${JSON.stringify(r)}`),t&&t!==s.peerId&&r.length>0&&(this.logger.info(`Producer handover detected from ${t} to ${s.peerId} for producer ids ${r.map(({producerId:a})=>a).join(",")}`),this.context.getValue("peerSessionStore").emit(w.PRODUCER_HANDOVER,{oldPeerId:t,newPeerId:s.peerId,producerIds:r.map(({producerId:a})=>a)})),this.logger.debug(`Processing media join for newly joined ${e?"local peer":"remote peer"} ${s.peerId}.`),this.onParticipantMediaJoined(s.peerId,r),this.logger.debug(`Processed media join for newly joined ${e?"local peer":"remote peer"} ${s.peerId}.`)}clearParticipantMediaState(s,t,e){const r=s;e?t==="audio"?(r.screenShareTracks.audio=void 0,r.setScreenShareEnabled(r.screenShareEnabled&&r.screenShareTracks.video!==void 0)):(r.setScreenShareEnabled(!1),r.screenShareTracks={audio:void 0,video:void 0}):t==="audio"?(r.setAudioEnabled(!1),r.audioTrack=void 0):(r.setVideoEnabled(!1),this.updatePipSource(r.id,!1),r.videoTrack=void 0)}setupEvents(){this.roomSocketHandler.on(V.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(w.SOCKET_PEERS,this.handleSocketPeers.bind(this)),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,this.handlePeerJoinedBroadcast.bind(this)),this.roomSocketHandler.on(this.events.selfJoinComplete,async({participants:s,selectedPeers:t,roomState:e})=>{this.logger.info(`Local peer has joined media room. Processing media joins for existing ${s==null?void 0:s.length} peers.`),s.forEach(({peerId:a,producerStates:o})=>{this.logger.debug(`Processing media join for ${this.self.peerId===a?"local peer":"existing remote peer"} ${a}.`),this.onParticipantMediaJoined(a,o),this.logger.debug(`Processed media join for ${this.self.peerId===a?"local peer":"existing remote peer"} ${a}.`)}),this.isRebuildingReconnectSnapshot&&this.rewireConsumersOnLocalUserReconnect();const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};this.applyPinnedSnapshot(e.pinnedPeerIds),this.computeActivateParticipants(r!=null?r:[],i),this.participants.viewMode==="PAGINATED"&&(this.participants.currentPage<1||this.participants.currentPage>this.participants.pageCount)&&await this.participants.setViewMode("ACTIVE_GRID"),this.isRebuildingReconnectSnapshot=!1,this.logger.info("Participants reconciliation on local peer's media join is complete. Reconciling consumers."),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}),this.context.getValue("peerSessionStore").on(w.MAX_SPATIAL_LAYER_CHANGE,({peerId:s,maxSpatialLayer:t})=>{const e=this.videoPeerConsumerMap.get(s);e&&(this.maxSpatialLayerUpdates.set(e,t),this.updateConsumerSpatialLayers())}),this.context.getValue("peerSessionStore").on(w.PRODUCER_HANDOVER,s=>this.handleProducerHandover(s)),this.context.getValue("peerSessionStore").on(w.NEW_PRODUCER,({peerId:s,producer:t})=>{if(!t){this.logger.error(`Received new remote producer for peer ${s}. producer is invalid/empty.`);return}const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received new ${t.screenShare?"screenshare":"participant"} ${t.kind} remote producer ${t.producerId} for a non-existent peer ${s}`);return}const r=e.producers.find(({producerId:a})=>a===t.producerId);let i="REPLACED";r?(Object.assign(r,t),i="REPLACED"):(e.producers.push(t),i="INSERTED"),this.logger.info(`Scheduling syncConsumer post upserting (${i}) new producer ${t.producerId} to peer ${s} for ${t.screenShare?"screenshare":"participant"} ${t.kind}`),this.scheduleSyncConsumers({source:"NEW_REMOTE_PRODUCER"})}),this.context.getValue("peerSessionStore").on(w.PRODUCER_CLOSED,({peerId:s,producerId:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received producer closed event for producer ${t} of a peer ${s} that might have already left the meeting.`);return}const r=e.producers.find(i=>i.producerId===t);r?(this.logger.info(`${r.screenShare?"Screenshare":"Participant"} ${r.kind} producer ${t} of peer ${s} has closed. Updating media state and scheduling syncConsumers for reconciliation.`),this.clearParticipantMediaState(e,r.kind,r.screenShare),r.kind==="video"&&!r.screenShare&&this.videoPeerConsumerMap.get(s)===t&&this.videoPeerConsumerMap.delete(s),e.producers=e.producers.filter(i=>i.producerId!==t),this.scheduleSyncConsumers({source:"PRODUCER_CLOSED"})):this.logger.warn(`Received producer closed event for producer ${t} of a peer ${s}. Peer doesn't have the producer associated with it. Ignoring the event.`)}),this.context.getValue("peerSessionStore").on(w.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){const a=i.producers.find(o=>o.producerId===t);if(!a){this.logger.warn(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of peer ${s} however producer is not associated with the peer. Ignoring the event.`);return}if(this.logger.info(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of peer ${s}. Reconciling media states and consumers.`),a.pause=e,r==="audio"&&i.setAudioEnabled(!e),r==="video"){const o=this.roomNodeClient.getConsumers().get(t);e?(i.setVideoEnabled(!1),this.updatePipSource(i.id,!1)):o&&!o.closed&&(i.videoTrack=o.track,i.setVideoEnabled(!0),this.updatePipSource(i.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!e}),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}else this.logger.warn(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of a missing peer ${s}. Ignoring the event.`)}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,s=>{let t;if(s&&(t=s.participantId),!this.mediaJoined)return;const e=t;this.onParticipantPinned(e);const r=this.participants.joined.get(e);r&&(this.logger.info(`globalPeerPinBroadcast: Scheduling audio/video consumer sync for pinned participant ${e} - ProducerCount: ${r.producers.length}, ConsumersSyncing: ${n(this,vs)}, ProducerIds: [${r.producers.map(i=>i.producerId).join(", ")}]`),this.scheduleSyncConsumers({source:"GLOBAL_PEER_PIN"}))}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:s,compulsoryPeers:t})=>{this.mediaJoined&&this.onSelectedPeers(t.concat(s))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:s})=>{if(!this.mediaJoined)return;const t=s.map(e=>({peerId:e.peerId,priority:e.priority}));this.updateActiveParticipantsWithPriorities(t,!0)})}waitingRoomRequestHandler(s){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 mr(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(u=>u.stageStatus==="ON_STAGE").map(u=>(t.set(u.id,!0),u.id))),r=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((u,p)=>(p.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(p.id):u.push(p.id),u),[]),a=this.self.stageStatus==="ON_STAGE"?1:0,o=s-a,c=new Set(r.concat(i).filter(u=>u!==this.self.id&&t.has(u)));let d=Array.from(c);const l=o-c.size;if(l>=0){const u=e.filter(p=>!c.has(p)&&p!==this.self.id).slice(0,l);d=Array.from(c).concat(u)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(s,t){const{page:e}=t!=null?t:{};s&&n(this,Kt).mode!==s&&(n(this,Kt).mode=s),e&&n(this,Kt).page!==e&&(n(this,Kt).page=e);const{mode:r,page:i}=n(this,Kt);switch(r){case"PAGINATED":{if(!i)return;const a=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,a),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:a});break}case"ACTIVE_GRID":{const a=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,a),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":{this.reconcileManualSubscriptionMaps();break}default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=n(this,Kt))==null?void 0:e.mode)==="PAGINATED"&&!n(this,vs)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=n(this,Kt))==null?void 0:r.mode}, ConsumersSyncing: ${n(this,vs)}, Delay: ${t}, Page: ${(i=n(this,Kt))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var I,D,A,x,$,U,z,ee;const s=this.context.getValue("connectionHandler");if((I=s==null?void 0:s.socketState)!=null&&I.state&&s.socketState.state!=="connected"){b(this,$i,no).call(this,"socket not connected"),this.logger.info("syncConsumers: Socket not connected, deferring sync.");return}if(((A=(D=s==null?void 0:s.mediaState)==null?void 0:D.recv)==null?void 0:A.state)!=="connected"){b(this,$i,no).call(this,"Recv transport not connected"),this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(b(this,il,ES).call(this),n(this,vs)){m(this,Gr,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),m(this,vs,!0),m(this,Gr,!1);let t=[];this.participants.videoSubscribed.forEach(H=>{var et,k;const X=this.participants.joined.get(H.id),pe=(k=(et=H.producers)==null?void 0:et.filter(S=>S.kind==="video"))!=null?k:[];X&&(pe!=null&&pe.length)&&pe.forEach(S=>{var se,ae,N,_;const P=((ae=(se=X.manualProducerConfig)==null?void 0:se.video)!=null?ae:!0)&&S.kind==="video"&&!S.screenShare,L=((_=(N=X.manualProducerConfig)==null?void 0:N.screenshareVideo)!=null?_:!0)&&S.kind==="video"&&S.screenShare;(P||L)&&(S.pause||t.push(S))})}),this.participants.audioSubscribed.forEach(H=>{var et,k;const X=this.participants.joined.get(H.id),pe=(k=(et=H.producers)==null?void 0:et.filter(S=>S.kind==="audio"))!=null?k:[];X&&(pe!=null&&pe.length)&&pe.forEach(S=>{var se,ae,N,_;const P=((ae=(se=X.manualProducerConfig)==null?void 0:se.audio)!=null?ae:!0)&&S.kind==="audio"&&!S.screenShare,L=((_=(N=X.manualProducerConfig)==null?void 0:N.screenshareAudio)!=null?_:!0)&&S.kind==="audio"&&S.screenShare;(P||L)&&t.push(S)})}),t=TC(t,H=>H.producerId);const e=new Map;t.forEach(H=>{e.set(H.producerId,H)});const r=($=(x=this.roomNodeClient)==null?void 0:x.getConsumers())!=null?$:new Map,i=[];r.forEach(H=>{H.closed&&i.push(H.id)});const a=(z=(U=this.roomNodeClient)==null?void 0:U.removeClosedConsumers(i))!=null?z:[];a.forEach(H=>{n(this,Ue).delete(H),this.consumerPeerMap.has(H)&&this.processConsumerClosed(H)}),a.length>0&&this.logger.info(`syncConsumers: Removed closed consumers: consumerIds=[${a.join(",")}].`);let o=[];const c=new Set,d=[],l=[];e.forEach(H=>{const X=r.get(H.producerId);if(!X){o.push(H);return}c.add(X.id);const{needsRemap:pe,wasMarkedForDeletion:et}=b(this,nc,hh).call(this,X,H);pe&&l.push(X.id),et&&d.push(X.id)});const u=[];r.forEach(H=>{H.closed||c.has(H.id)||b(this,nl,PS).call(this,H)&&u.push(H.id)});const p=Date.now(),f=[];let T=[];n(this,Ue).forEach((H,X)=>{const pe=r.get(X);if(!pe||pe.closed){n(this,Ue).delete(X);return}if(c.has(X)){n(this,Ue).delete(X);return}p-H>=WD?T.push(X):f.push(X)}),e.size>0&&this.logger.debug(`syncConsumers: Desired producer IDs: [${Array.from(e.keys()).join(",")}].`),r.size>0&&this.logger.debug(`syncConsumers: Current consumer IDs: [${Array.from(r.keys()).join(",")}].`),o.length>0&&this.logger.info(`syncConsumers: Producer IDs requiring consumers: [${o.map(({producerId:H})=>H).join(",")}].`),c.size>0&&this.logger.debug(`syncConsumers: Consumer IDs to keep: [${Array.from(c).join(",")}].`),l.length>0&&this.logger.info(`syncConsumers: Consumer IDs with consumer rewiring: [${l.join(",")}].`),d.length>0&&this.logger.info(`syncConsumers: Consumer IDs revived before deletion: [${d.join(",")}].`),u.length>0&&this.logger.info(`syncConsumers: Newly marked consumer IDs: [${u.join(",")}].`),f.length>0&&this.logger.info(`syncConsumers: Consumer IDs in deletion grace period: [${f.join(",")}].`),T.length>0&&this.logger.info(`syncConsumers: Consumer IDs ready for deletion: [${T.join(",")}].`);const E=35,R=35;o.length>E&&(this.logger.warn(`syncConsumers: Too many remote producers to create consumers: ${o.length}. Only adding ${E} in this run.`),o=o.slice(0,E),this.scheduleSyncConsumers({source:"SOFT_CAPPED_CREATE_CONSUMERS"})),T.length>R&&(this.logger.warn(`syncConsumers: Too many remote consumers ready to close: ${T.length}. Only removing ${R} in this run.`),T=T.slice(0,R),this.scheduleSyncConsumers({source:"SOFT_CAPPED_REMOVE_CONSUMERS"}));try{o.length>0||T.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers: createProducerIds=[${o.map(({producerId:H})=>H).join(",")}], deleteConsumerIds=[${T.join(",")}].`),await this.updateConsumers(o,T),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(H){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:H})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),m(this,vs,!1),(ee=s==null?void 0:s.socketState)!=null&&ee.state&&s.socketState.state!=="connected"&&m(this,Gr,!0)}n(this,Gr)&&(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=io.formatSocketPeerMessage(s);return new mr(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onParticipantMediaJoined(s,t){if(!this.mediaJoined||s===this.self.id)return;const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info(`processing media state of remote producers of peer ${s} with producerStates: ${JSON.stringify(t)}`),t.forEach(r=>{r.kind===Ds.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===Ds.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause));const i={...r,producingTransportId:r.producingTransportId,kind:r.kind===Ds.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType},a=e.producers.find(({producerId:o})=>o===i.producerId);a?Object.assign(a,i):e.producers.push(i)}),this.logger.info(`Reconciling consumers due to media join of peer ${s}. Media join is complete.`),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),i=new Set(t),a=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&a.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=a.shift();e[c]=o}),a.forEach(o=>{e.splice(o,1)}),Array.from(s.keys()).forEach(o=>{s.delete(o,!i.has(o))}),e.forEach(o=>{const c=this.participants.joined.get(o);if(!c)return;const d=r.get(o),l=!d||d!==c;s.add(c,l)}),s.emit("participantsUpdate")}reconcileManualSubscriptionMaps(){const s=Array.from(this.participants.videoSubscribed.keys()),t=Array.from(this.participants.audioSubscribed.keys());this.updateParticipantsMap(this.participants.videoSubscribed,s.filter(e=>this.participants.joined.has(e))),this.updateParticipantsMap(this.participants.audioSubscribed,t.filter(e=>this.participants.joined.has(e)))}updateParticipantsMap(s,t){Array.from(s.keys()).forEach(r=>{t.includes(r)||s.delete(r,!0)}),t.forEach(r=>{const i=s.get(r),a=this.participants.joined.get(r);a&&i!==a&&(i&&s.delete(r,!1),s.add(a,!0))}),s.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}applyPinnedSnapshot(s){const t=s[0];if(this.participants.pinned.forEach(i=>{i.id!==t&&(i.setIsPinned(!1),this.participants.pinned.delete(i.id))}),t===this.self.id){this.self.setIsPinned(!0),this.participants.pinned.emit("participantsUpdate");return}if(this.self.isPinned&&this.self.setIsPinned(!1),!t){this.participants.pinned.emit("participantsUpdate");return}const e=this.participants.joined.get(t),r=this.participants.pinned.get(t);if(!e){r&&this.participants.pinned.delete(t),this.participants.pinned.emit("participantsUpdate");return}r!==e&&(r&&(r.setIsPinned(!1),this.participants.pinned.delete(t,!1)),e.setIsPinned(!0),this.participants.pinned.add(e,!0)),this.participants.pinned.emit("participantsUpdate")}rewireConsumersOnLocalUserReconnect(){this.participants.joined.forEach(s=>{s.producers.forEach(t=>{const e=this.roomNodeClient.getConsumers().get(t.producerId);!e||e.closed||(b(this,nc,hh).call(this,e,t),t.pause&&!t.screenShare&&(t.kind==="audio"?s.setAudioEnabled(!1):(s.setVideoEnabled(!1),this.updatePipSource(s.id,!1))))})})}static replaceParticipantInMap(s,t,e,r){const i=s,a=i.get(t);if(!a)return;const o=new Set,c=Array.from(i.values()).reduce((d,l)=>{const u=l.id===t?e:l;return o.has(u.id)||(o.add(u.id),d.push(u)),d},[]);if(Array.from(i.keys()).forEach(d=>{i.delete(d,!1)}),c.forEach(d=>i.add(d,!1)),r){const d=i.emit.bind(i);d("participantLeft",a),d("participantJoined",e)}i.emit("participantsUpdate")}handleProducerHandover(s){const{oldPeerId:t,newPeerId:e,producerIds:r}=s;if(typeof t!="string"||typeof e!="string"||t===e||!Array.isArray(r)||r.length===0||r.some(u=>typeof u!="string")||e===this.self.id)return;const i=this.participants.joined.get(t),a=this.participants.joined.get(e);if(!i||!a||!i.userId||i.userId!==a.userId){this.logger.warn(`ParticipantController::producerHandover::participant validation failed from ${t} to ${e}`);return}this.selectedPeers.reassignPeer(t,e,this.context);const o=this.context.getValue("audioPlayback");o==null||o.reassignParticipantTrack(t,e),o==null||o.reassignParticipantTrack(`screenshare-${t}`,`screenshare-${e}`);const c=new Set(r),d=i.producers.filter(({producerId:u})=>c.has(u));if(d.length===0)return;d.some(u=>u.kind==="audio"&&!u.screenShare)&&(i.setAudioEnabled(!1),i.audioTrack=void 0),d.some(u=>u.screenShare)&&(i.setScreenShareEnabled(!1),i.screenShareTracks={audio:void 0,video:void 0}),a.manualProducerConfig={...i.manualProducerConfig},i.producers=i.producers.filter(({producerId:u})=>!c.has(u)),d.forEach(u=>{if(a.producers.some(({producerId:f})=>f===u.producerId))return;const p={...u};delete p.consumer,this.context.getValue("peerSessionStore").emit(w.NEW_PRODUCER,{peerId:e,producer:{...p,producingPeerId:e}})}),this.roomNodeClient.handoverPeerProducers(e,r).forEach(u=>{u.kind==="video"&&u.appData.screenShare!==!0&&this.videoPeerConsumerMap.get(t)===u.id&&(this.videoPeerConsumerMap.delete(t),this.updatePipSource(t,!1)),this.context.getValue("peerSessionStore").emit(w.NEW_CONSUMER_CREATED,{id:u.id,appData:u.appData,peerId:e})}),io.replaceParticipantInMap(this.participants.videoSubscribed,t,a,!0),io.replaceParticipantInMap(this.participants.audioSubscribed,t,a,!1),this.participants.pinned.has(t)&&(i.setIsPinned(!1),a.setIsPinned(!0),io.replaceParticipantInMap(this.participants.pinned,t,a,!0)),this.logger.info(`Removing old peer ${t} locally after handover.`),this.onParticipantLeave(t).catch(u=>{this.logger.error("Failed to remove old peer locally after handover",{error:u})})}setupEventsGlobal(){this.roomSocketHandler.on(V.joinRoom,({peer:s})=>{s.waitlisted||(this.logger.info(`Processing socket join for ${this.self.id===s.peerId?"local peer":"remote peer"} ${s.peerId}.`),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),this.logger.info(`Processed socket join for ${this.self.id===s.peerId?"local peer":"remote peer"} ${s.peerId}.`))}),this.roomSocketHandler.on(V.leaveRoom,async s=>{const{peerId:t}=s.peer;this.logger.info(`peer ${t} left the meeting. Removing it from selected peers`),this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",s=>{const{acceptWaitingRequests:t}=s;t!==void 0&&(t?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),this.context.getValue("peerSessionStore").on(w.PEER_CLOSED,({id:s})=>{this.logger.info(`Remote peer ${s} has left media room. Scheduling delayed consumer cleanup.`),this.scheduleSyncConsumers({source:"REMOTE_PEER_CLOSED"})}),this.context.getValue("peerSessionStore").on(w.MEDIA_ROOM_JOIN_FAILED,()=>{this.isRebuildingReconnectSnapshot&&(this.isRebuildingReconnectSnapshot=!1)}),this.context.getValue("peerSessionStore").on(w.SOCKET_SERVICE_DISCONNECTED,()=>{this.isRebuildingReconnectSnapshot=!1,m(this,Gr,!0),b(this,$i,no).call(this,"socket disconnected"),this.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),this.context.getValue("peerSessionStore").on(w.TRANSPORT_STATE_UPDATE,({transport:s,state:t})=>{if(s==="recv"){if(t!=="connected"){b(this,$i,no).call(this,`Recv transport not yet connected. state: ${t}`);return}this.logger.info("Receive transport connected; scheduling consumer reconciliation"),this.scheduleSyncConsumers({source:"RECV_TRANSPORT_CONNECTED"})}}),this.context.getValue("peerSessionStore").on(w.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(w.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(w.NEW_CONSUMER_CREATED,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(w.CONSUMER_CLOSED,({id:s})=>{const t=n(this,Ue).delete(s);this.logger.info(`Consumer closed: consumerId=${s}, wasMarkedForDeletion=${t}.`),this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(w.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(w.MESSAGE,async({payload:s,type:t,timestamp:e})=>{t!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(w.LOW_CONSUMER_SCORE,({peerId:s,score:t,kind:e})=>{const r=this.participants.joined.get(s);r&&(r.emit("poorConnection",{score:t,kind:e}),this.participants.emit("poorConnection",{participantId:s,score:t,kind:e}))}),this.context.getValue("peerSessionStore").on(w.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:i})=>{var c;const a=t==="video"&&((c=e==null?void 0:e.screenShare)!=null?c:!1),o=this.participants.joined.get(r);o&&(o.emit("mediaScoreUpdate",{kind:t,isScreenshare:a,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:a,score:s,participantId:r,scoreStats:i}))}),this.context.getValue("peerSessionStore").onAsync(w.KICK_PEER,async({peerId:s})=>{const t=this.participants.joined.get(s);this.roomNodeClient.kick(s),await this.roomSocketHandler.kick(s),t?t.emit("kicked"):this.participants.joined.emit("kicked",{id:s})}),this.context.getValue("peerSessionStore").on(w.UPDATE_ACTIVE,({viewMode:s,page:t}={})=>{this.isRebuildingReconnectSnapshot||(this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${n(this,Kt).mode}, page: ${t}`),this.updateMediaSubscribedMaps(s,{page:t}),this.scheduleSyncConsumers({source:"UPDATE_ACTIVE"}))})}async onParticipantPinned(s){if(!s){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(s===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const t=this.participants.joined.get(s);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),t.setIsPinned(!0),this.participants.pinned.add(t)}async onParticipantSocketJoined(s){var t,e,r;this.self.id!==s.id&&!((t=s.flags)!=null&&t.recorder)&&!((e=s.flags)!=null&&e.hidden_participant)&&!((r=s.flags)!=null&&r.hiddenParticipant)&&(this.isRebuildingReconnectSnapshot||(this.participants.videoSubscribed.delete(s.id),this.participants.audioSubscribed.delete(s.id)),this.participants.joined.add(s),this.participants.waitlisted.delete(s.id),s.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(w.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){var a;this.logger.info(`peer ${s} has left. Deleting peer from participant maps`);const t=this.participants.joined.get(s);this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),(a=this.pip)==null||a.removeSource(s),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage}),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 u=i;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),this.logger.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:d,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:d,producerId:o,trackId:a==null?void 0:a.id}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:a,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){var l;const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:a,trackId:o}=this.consumerPeerMap.get(s)||{},c=this.participants.joined.get(t);if(this.logger.info("ParticipantController::processConsumerClosed",{consumer:{id:s,peerId:t,appData:r,kind:e,remotelyPaused:i,producerId:a}}),this.consumerPeerMap.delete(s),e==="video"&&(r==null?void 0:r.screenShare)!==!0&&this.videoPeerConsumerMap.get(t)===s&&this.videoPeerConsumerMap.delete(t),r!=null&&r.e2ee&&o&&this.context.getValue("peerSessionStore").emit(w.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:o}),!c)return;r!=null&&r.screenShare?this.context.getValue("callstats").consumerSharedMediaState(s,{screen:!1}):e==="audio"?this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!1}):e==="video"&&this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1});const d=c.producers.find(u=>u.producerId===a);if(((l=d==null?void 0:d.consumer)==null?void 0:l.id)!==s){this.logger.info(`Ignoring stale consumer media cleanup: consumerId=${s}, producerId=${a}, peerId=${t}.`);return}d.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:a,rtpReceiver:void 0,localId:void 0},!(e!=="audio"&&e!=="video")&&this.clearParticipantMediaState(c,e,(r==null?void 0:r.screenShare)===!0)}processConsumerResumed(s){var f;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:a,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const u=this.participants.joined.get(e);if(!u)return;const p=u.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"?u.screenShareTracks.video=a:r==="audio"&&(u.screenShareTracks.audio=a),u.setScreenShareEnabled(!0),(f=this.context)==null||f.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=a,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=a,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:a,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:a,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(p=>p.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:a,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(l.videoTrack=r,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1})):e==="audio"&&(l.audioTrack=r,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:l.audioEnabled}))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:i,appData:a,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:a,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(p=>p.producerId===o);if(u&&(u.consumer={id:s,peerId:t,kind:e,appData:a,paused:r,producerId:o,rtpReceiver:c,localId:d}),a.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),a.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:a,producerId:o}});return}e==="video"?(l.videoTrack=i,r||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!r})):e==="audio"&&(l.audioTrack=i,r||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!r})),!r&&a.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i}),this.context.getValue("peerSessionStore").emit(w.ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER,{appData:a,peerId:l.id})}static formatSocketPeerMessage(s){var e,r,i,a,o,c;if(!s)return;const t=cp(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=s.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(a=s.flags)==null?void 0:a.hiddenParticipant,recorder:((o=s.flags)==null?void 0:o.recorderType)!==void 0&&((c=s.flags)==null?void 0:c.recorderType)!=="NONE"}}}async onSelectedPeers(s,t){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(s,t)}updateActiveParticipantsWithPriorities(s,t=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority,this.context)});const e=this.selectedPeers.activeSpeakerPeers.at(0);e!==void 0&&e!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=e,this.participants.emit("activeSpeaker",{peerId:e,volume:1})),t&&this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},Kt=new WeakMap,vs=new WeakMap,Gr=new WeakMap,Ue=new WeakMap,Ys=new WeakMap,Vi=new WeakMap,$i=new WeakSet,no=function(s){n(this,Ys)===void 0&&(m(this,Ys,Date.now()),this.logger.info(`Consumer deletion aging paused: reason="${s}", consumerIds=[${Array.from(n(this,Ue).keys()).join(",")}].`))},il=new WeakSet,ES=function(){if(n(this,Ys)===void 0)return;const s=Date.now()-n(this,Ys);n(this,Ue).forEach((t,e)=>{n(this,Ue).set(e,t+s)}),m(this,Ys,void 0),this.logger.info(`Consumer deletion aging resumed: pausedDurationMs=${s}, consumerIds=[${Array.from(n(this,Ue).keys()).join(",")}].`)},nl=new WeakSet,PS=function(s){return n(this,Ue).has(s.id)?!1:(n(this,Ue).set(s.id,Date.now()),!0)},nc=new WeakSet,hh=function(s,t){const e=s.peerId,r=!t.consumer||t.consumer.peerId!==t.producingPeerId||e!==t.producingPeerId;s.reassignPeer(t.producingPeerId);const i=n(this,Ue).delete(s.id);return r&&this.processNewConsumer(s.id),{needsRemap:r,wasMarkedForDeletion:i}},al=new WeakSet,wS=function(){m(this,Vi,setInterval(()=>{n(this,Ue).size!==0&&(this.logger.info(`Consumer deletion sweep scheduling reconciliation: consumerIds=[${Array.from(n(this,Ue).keys()).join(",")}].`),this.scheduleSyncConsumers({source:"CONSUMER_DELETION_SWEEP"}))},GD))},ol=new WeakSet,_S=function(){n(this,Vi)!==void 0&&(clearInterval(n(this,Vi)),m(this,Vi,void 0))},cl=new WeakMap,hm);let Er=io;gn([y.trace("ParticipantController.setupEvents")],Er.prototype,"setupEvents",1);gn([y.trace("ParticipantController.setupEvents")],Er.prototype,"setupEventsGlobal",1);gn([y.trace("ParticipantController.processMedia")],Er.prototype,"processMedia",1);gn([y.trace("ParticipantController.processConsumerClosed")],Er.prototype,"processConsumerClosed",1);gn([y.trace("ParticipantController.processConsumerResumed")],Er.prototype,"processConsumerResumed",1);gn([y.trace("ParticipantController.processConsumerPaused")],Er.prototype,"processConsumerPaused",1);gn([y.trace("ParticipantController.processNewConsumer")],Er.prototype,"processNewConsumer",1);const we=Os(ip().permissions);var J,ta,sa,dl,dt,Ct;const ll=class extends xt{constructor(e,r,i,a=!1){const o=e.getValue("logger");super(o);g(this,dt);g(this,J,void 0);g(this,ta,void 0);g(this,sa,void 0);g(this,dl,e=>{var l,u,p;const{chat:r,connectedMeetings:i,plugins:a,polls:o,media:c,...d}=e;if(r&&(r.private&&wr(n(this,J).chat.private,r.private),r.public&&wr(n(this,J).chat.public,r.public),this.emit("chatUpdate")),i&&wr(n(this,J).connectedMeetings,i),c){const f=E=>{switch(E){case ti.NONE:return j.Allowed;case ti.ALLOWED:return j.Allowed;case ti.NOT_ALLOWED:return j.NotAllowed;case ti.CAN_REQUEST:return j.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)}),(u=c.video)!=null&&u.canProduce&&(T.video={canProduce:f(c.video.canProduce)}),(p=c.screenshare)!=null&&p.canProduce&&(T.screenshare={canProduce:f(c.screenshare.canProduce)}),wr(n(this,J).media,T)}a&&(wr(n(this,J).plugins,a),this.emit("pluginsUpdate")),o&&(wr(n(this,J).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&wr(n(this,J),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.","0904");m(this,sa,e),m(this,ta,i),m(this,J,r),a&&this.setupEvents()}setupEvents(){n(this,sa).getValue("peerSessionStore").on(w.UPDATE_PERMISSIONS,n(this,dl))}static init(e,r,i){let a;return i?a=new ll(e,i,r,!0):a=new ll(e,we,r),a}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=n(this,J))==null?void 0:e.stageEnabled)||n(this,ta)===hs.Webinar||n(this,ta)===hs.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=n(this,J))==null?void 0:e.acceptStageRequests)||((r=n(this,J))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=n(this,J))==null?void 0:e.stageAccess)===j.NotAllowed?j.NotAllowed:((r=n(this,J))==null?void 0:r.stageAccess)===j.CanRequest?j.CanRequest:((i=n(this,J))==null?void 0:i.stageAccess)===j.Allowed||n(this,J).media.audio.canProduce===j.Allowed||n(this,J).media.video.canProduce===j.Allowed||n(this,J).media.screenshare.canProduce===j.Allowed?j.Allowed:n(this,J).media.audio.canProduce===j.CanRequest||n(this,J).media.video.canProduce===j.CanRequest||n(this,J).media.screenshare.canProduce===j.CanRequest?j.CanRequest:j.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=n(this,J))==null?void 0:e.acceptWaitingRequests)!=null?r:we.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=n(this,J))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===j.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=n(this,J))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===j.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=n(this,J))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===j.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=n(this,J))==null?void 0:e.disableParticipantAudio)!=null?r:we.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=n(this,J))==null?void 0:e.canAcceptProductionRequests)!=null?r:we.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=n(this,J))==null?void 0:e.disableParticipantVideo)!=null?r:we.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=n(this,J))==null?void 0:e.kickParticipant)!=null?r:we.kickParticipant}get pinParticipant(){var e,r;return(r=(e=n(this,J))==null?void 0:e.pinParticipant)!=null?r:we.pinParticipant}get canRecord(){var e,r;return(r=(e=n(this,J))==null?void 0:e.canRecord)!=null?r:we.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=n(this,J))==null?void 0:e.waitingRoomType)!=null?r:we.waitingRoomType}get plugins(){var e,r;return(r=(e=n(this,J))==null?void 0:e.plugins)!=null?r:we.plugins}get polls(){var e,r;return(r=(e=n(this,J))==null?void 0:e.polls)!=null?r:we.polls}get canProduceVideo(){var r;const e=(r=n(this,J).media.video.canProduce)!=null?r:we.media.video.canProduce;return this.stageEnabled&&(n(this,dt,Ct)==="ACCEPTED_TO_JOIN_STAGE"||n(this,dt,Ct)==="ON_STAGE")&&e===j.CanRequest?j.Allowed:this.stageEnabled&&(n(this,dt,Ct)==="OFF_STAGE"||n(this,dt,Ct)==="REQUESTED_TO_JOIN_STAGE")&&e===j.Allowed?j.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=n(this,J).media.screenshare.canProduce)!=null?r:we.media.screenshare.canProduce;return this.stageEnabled&&(n(this,dt,Ct)==="ACCEPTED_TO_JOIN_STAGE"||n(this,dt,Ct)==="ON_STAGE")&&e===j.CanRequest?j.Allowed:this.stageEnabled&&(n(this,dt,Ct)==="OFF_STAGE"||n(this,dt,Ct)==="REQUESTED_TO_JOIN_STAGE")&&e===j.Allowed?j.NotAllowed:e}get canProduceAudio(){var r;const e=(r=n(this,J).media.audio.canProduce)!=null?r:we.media.audio.canProduce;return this.stageEnabled&&(n(this,dt,Ct)==="ACCEPTED_TO_JOIN_STAGE"||n(this,dt,Ct)==="ON_STAGE")&&e===j.CanRequest?j.Allowed:this.stageEnabled&&(n(this,dt,Ct)==="OFF_STAGE"||n(this,dt,Ct)==="REQUESTED_TO_JOIN_STAGE")&&e===j.Allowed?j.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=n(this,J))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:we.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=n(this,J))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:we.chat.private}get connectedMeetings(){var e,r;return(r=(e=n(this,J))==null?void 0:e.connectedMeetings)!=null?r:we==null?void 0:we.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=n(this,J))==null?void 0:e.hiddenParticipant)!=null?r:we.hiddenParticipant}get showParticipantList(){var e;return(e=n(this,J).showParticipantList)!=null?e:we.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=n(this,J))==null?void 0:e.canChangeParticipantPermissions)!=null?r:we.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=n(this,J).canEditDisplayName)!=null?e:!1}get isRecorder(){return n(this,J).isRecorder}get canSpotlight(){return n(this,J).canSpotlight}get canLivestream(){return n(this,J).canLivestream}get transcriptionEnabled(){return n(this,J).transcriptionEnabled}};let ph=ll;J=new WeakMap,ta=new WeakMap,sa=new WeakMap,dl=new WeakMap,dt=new WeakSet,Ct=function(){return n(this,sa).getValue("stageStatus")};var Mt;class CS extends xt{constructor(e,r){super(r);h(this,"localMediaHandler");g(this,Mt,void 0);m(this,Mt,e)}async updatePermission(){var d,l;const e=(u,p)=>{this.mediaPermissions[u]=p;const f={message:this.mediaPermissions[u],kind:u};p==="DENIED"?n(this,Mt).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_ERROR,f):n(this,Mt).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,f)};if(ve.getName()==="firefox")return;const r="microphone",i="camera",a=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),o=await((l=navigator==null?void 0:navigator.permissions)==null?void 0:l.query({name:i})),c=(u,p)=>{switch(p){case"granted":e(u,"ACCEPTED");break;case"denied":e(u,"DENIED");break;case"prompt":e(u,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};a&&(a.onchange=()=>c("audio",a.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,a,o,c;switch(r){case"audio":{(i=n(this,Mt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(a=n(this,Mt))==null||a.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=n(this,Mt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=n(this,Mt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=n(this,Mt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var a,o,c,d,l,u,p;if(ve.init(),i&&m(this,Mt,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 _t(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:R,constraints:I}=T;this.populateMediaPermissionsInCallstats({message:R,kind:E}),E==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):E==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:R},constraints:I,mediaPermissionsErrors:{kind:E,message:R}}),this.emit("mediaPermissionError",T),this.emit("mediaPermissionUpdate",{message:R,kind:E})}),f){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const T=this.localMediaHandler.setupStreams({video:(u=e==null?void 0:e.video)!=null?u:!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,Mt,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})}}Mt=new WeakMap;var JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,St=(s,t,e,r)=>{for(var i=r>1?void 0:r?KD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&JD(t,e,i),i},ra,lt,ia,He,Qs,ui,Be,tt,na,Ed,Ae,Oe,aa,oa,ac,gh,pm;let Ke=(pm=class extends CS{constructor(t,e,r,i,a){const o=t.getValue("logger");super(t,o);g(this,Qs);g(this,Be);g(this,na);g(this,Ae);g(this,ac);h(this,"name");h(this,"picture");h(this,"customParticipantId");h(this,"waitlistStatus");g(this,ra,void 0);g(this,lt,void 0);g(this,ia,void 0);h(this,"role");h(this,"userId");h(this,"organizationId");h(this,"supportsRemoteControl",!1);h(this,"device");g(this,He,void 0);h(this,"hidden",!1);h(this,"presetName");h(this,"roomState","init");g(this,aa,new Set);g(this,oa,new Set);m(this,He,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",m(this,lt,r),m(this,ra,i),this.hidden=!1,m(this,ia,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=ve.isElectron(),this.device=ve.getDeviceInfo(),this.presetName=a,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),b(this,ac,gh).call(this)}get telemetry(){return n(this,He).getValue("telemetry")}get stageStatus(){return n(this,He).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=n(this,Be,tt).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return n(this,He).getValue("peerId")}static async __init__(t,e,r,i,a,o=!1){var f,T,E,R,I,D;let c=(T=(f=t.getValue("defaults"))==null?void 0:f.audio)!=null?T:!0,d=(R=(E=t.getValue("defaults"))==null?void 0:E.video)!=null?R:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new Ke(t,e,r,i,a),u=sD(i.mediaConstraints);wr(u,(I=t.getValue("defaults"))==null?void 0:I.mediaConfiguration);const p=(D=t.getValue("defaults"))==null?void 0:D.mediaHandler;return p&&(p.context=t),await l.init({audio:c,video:d,constraints:u},o,t),l.setupEvents(),l}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),n(this,lt).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",b(this,ac,gh));const t=n(this,na,Ed);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...mi(this)}),n(this,Ae,Oe)&&this.audioEnabled)try{await n(this,Be,tt).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::VIDEO_TRACK_CHANGE",{...mi(this)}),n(this,Ae,Oe)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&n(this,Ae,Oe))try{await n(this,Be,tt).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.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,na,Ed))==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,Ae,Oe)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await n(this,Be,tt).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",{...mi(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",{...mi(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=n(this,He))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;n(this,Ae,Oe)&&await n(this,Be,tt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=n(this,He))==null||e.getValue("callstats").videoOff()}),n(this,lt).on("permissionsUpdate",e=>{var r,i,a;(r=e==null?void 0:e.media)!=null&&r.audio&&n(this,lt).canProduceAudio!==j.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&n(this,lt).canProduceVideo!==j.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(a=e==null?void 0:e.media)!=null&&a.screenshare&&n(this,lt).canProduceScreenshare!==j.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return n(this,lt)}get config(){return n(this,ra)}get roomJoined(){var t;return n(this,ra).viewType===hs.Livestream&&this.stageStatus!=="ON_STAGE"?((t=n(this,He).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:n(this,Ae,Oe)}setName(t){if(!t)throw new C("Name cannot be empty.","1103");this.name=t}async setupTracks(t={}){t.forceReset,await this.disableAudio(),await this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&await this.enableAudio(),t.video&&await this.enableVideo()}async destructMediaHandler(){return this.localMediaHandler.destruct()}async removeDocumentEventListeners(){return this.localMediaHandler.removeDocumentEventListeners()}async enableAudio(t){var e;if(this.permissions.canProduceAudio!==j.NotAllowed&&!(n(this,lt).canProduceAudio===j.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=n(this,He))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),n(this,Ae,Oe)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await n(this,Be,tt).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(n(this,lt).canProduceVideo!==j.NotAllowed&&!(n(this,lt).canProduceVideo===j.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=n(this,He))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),n(this,Ae,Oe)&&this.stageStatus==="ON_STAGE")try{await n(this,Be,tt).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...mi(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!n(this,Ae,Oe))throw new C("Can`t enable screenshare without joining room","1105");if(n(this,lt).canProduceScreenshare!==j.NotAllowed&&!(n(this,lt).canProduceScreenshare===j.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,Be,tt).shareScreen(this.screenShareTracks)}catch(t){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),n(this,Ae,Oe)&&n(this,Be,tt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=n(this,He))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),n(this,Ae,Oe)&&await n(this,Be,tt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=n(this,He))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),n(this,Ae,Oe)&&await n(this,Be,tt).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;m(this,ia,t);const r=t?"pinned":"unpinned";(i=n(this,Qs,ui))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return n(this,ia)}async pin(){if(!n(this,Ae,Oe))throw new C("Can`t pin participants without joining room","1105");return this.show(),n(this,Be,tt).pinPeer(this.id)}async unpin(){if(!n(this,Ae,Oe))throw new C("Can`t unpin participants without joining room","1105");return n(this,Be,tt).pinPeer(null)}async hide(){if(!n(this,Ae,Oe))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!n(this,Ae,Oe))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,a;if(!t)throw new C("No device selected","1104");const e=this.getCurrentDevices();switch(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((i=e==null?void 0:e.video)==null?void 0:i.deviceId)===t.deviceId||((a=e==null?void 0:e.speaker)==null?void 0:a.deviceId)===t.deviceId)&&this.logger.warn("Self.setDevice.setting_to_in_use_device",{devices:[t]}),t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){n(this,Ae,Oe)&&await n(this,Be,tt).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,Ae,Oe)&&await n(this,Be,tt).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,na,Ed))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?n(this,aa).add(t):n(this,oa).add(t),this.updateVideo(t),e||(i=n(this,Qs,ui))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){n(this,Qs,ui).removeSource(this.id);return}t.srcObject=void 0,e?n(this,aa).delete(t):(n(this,oa).delete(t),n(this,Qs,ui).removeSource(this.id))}updateVideo(t,e=!1){var r,i,a;if(this.videoEnabled){if(this.videoTrack==null)return;const o=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((o==null?void 0:o.id)===this.videoTrack.id)return;const c=new MediaStream;c.addTrack(this.videoTrack),t.srcObject=c,e||(i=n(this,Qs,ui))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(a=n(this,Qs,ui))==null||a.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},ra=new WeakMap,lt=new WeakMap,ia=new WeakMap,He=new WeakMap,Qs=new WeakSet,ui=function(){return n(this,He).getValue("pip")},Be=new WeakSet,tt=function(){return n(this,He).getValue("roomNodeClient")},na=new WeakSet,Ed=function(){return n(this,He).getValue("audioPlayback")},Ae=new WeakSet,Oe=function(){var t;return((t=n(this,He).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},aa=new WeakMap,oa=new WeakMap,ac=new WeakSet,gh=function(){Array.from(n(this,oa)).forEach(t=>this.updateVideo(t,!1)),Array.from(n(this,aa)).forEach(t=>this.updateVideo(t,!0))},pm);St([y.trace("Self.cleanupEvents")],Ke.prototype,"cleanupEvents",1);St([y.trace("Self.setupEvents")],Ke.prototype,"setupEvents",1);St([y.trace("Self.setupTracks")],Ke.prototype,"setupTracks",1);St([y.trace("Self.destructMediaHandler")],Ke.prototype,"destructMediaHandler",1);St([y.trace("Self.removeDocumentEventListeners")],Ke.prototype,"removeDocumentEventListeners",1);St([yr.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.enableAudio")],Ke.prototype,"enableAudio",1);St([yr.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.enableVideo")],Ke.prototype,"enableVideo",1);St([y.trace("Self.updateVideoConstraints")],Ke.prototype,"updateVideoConstraints",1);St([y.trace("Self.enableScreenShare"),yr.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],Ke.prototype,"enableScreenShare",1);St([y.trace("Self.updateScreenshareConstraints")],Ke.prototype,"updateScreenshareConstraints",1);St([yr.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.disableAudio")],Ke.prototype,"disableAudio",1);St([yr.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.disableVideo")],Ke.prototype,"disableVideo",1);St([yr.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),y.trace("Self.disableScreenShare")],Ke.prototype,"disableScreenShare",1);St([y.trace("Self.setDevice")],Ke.prototype,"setDevice",1);Ke=St([rt("1100")],Ke);class mp extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,mp)}}class fp extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,fp)}}var oc;class mh{constructor(t,e=!1){h(this,"pendingTasks",new Map);h(this,"nextTaskId",0);h(this,"stopping",!1);g(this,oc,void 0);this.log=e,m(this,oc,{info:e&&t?t.info:()=>{}})}get size(){return this.pendingTasks.size}async push(t,e,r){if(e=e!=null?e:t.name,typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(i){}return new Promise((i,a)=>{const o={id:this.nextTaskId++,task:t,metadata:r,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),i(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),a(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){this.stopping=!0;for(const t of this.pendingTasks.values())t.reject(new mp);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new fp)}get(t){return Array.from(this.pendingTasks.values())[t]}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=this.pendingTasks.size,r=await t.task(),i=Date.now();n(this,oc).info(`AwaitQueue.push(${t.name})_timings`,{awaitQueueTask:{id:t.id,metadata:t.metadata,queueSizeAtStart:e,execTime:(i-t.executedAt)/1e3,taskStartTime:(t.executedAt-t.enqueuedAt)/1e3}}),t.resolve(r)}catch(e){t.reject(e)}}}oc=new WeakMap;class Ao extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ao):this.stack=new Error(t).stack}}class wt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,wt):this.stack=new Error(t).stack}}class Ar extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,wt):this.stack=new Error(t).stack}}const Fg=s=>new Promise(t=>setTimeout(t,s));async function xd(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:a,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=p=>{l=!0,r(p)};for(;c<a;){try{const p=await s(c,u);return e(p)}catch(p){if(d=p,l)break;if(c<a)i==="linear"?await Fg(o*(c+1)):i==="exponential"&&await Fg(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function zD(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function YD(s){return s.map(t=>({uri:t.uri}))}function hd(s){return{codecs:zD(s.codecs),headerExtensions:YD(s.headerExtensions?s.headerExtensions:[])}}function QD(s){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video");s&&(e.codecs=e.codecs.filter(({mimeType:d})=>s===d),i.codecs=i.codecs.filter(({mimeType:d})=>s===d));const a={audio:hd(t),video:hd(e)};return{sender:{audio:hd(r),video:hd(i)},receiver:a}}var cc;class hu extends ft.EventEmitter{constructor(e){super();g(this,cc,void 0);m(this,cc,e),this.setMaxListeners(1/0)}get logger(){return n(this,cc).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(a){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:a}),Boolean(i)}}async safeEmitAsPromise(e,...r){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)}async safeEmitAsPromiseWithTimeout(e,r,...i){return new Promise((a,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,a,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}cc=new WeakMap;function XD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}var dc,xi,ys,ul,Es,Cr,lc,fh,hl,RS,pl,bS;class ZD extends hu{constructor(e,r){var i;super(e);g(this,Es);g(this,lc);g(this,hl);g(this,pl);h(this,"rtpReceiver");h(this,"id");h(this,"localId");h(this,"producerId");h(this,"producingTransportId");h(this,"mimeType");h(this,"track");h(this,"peerId");h(this,"appData");h(this,"transceiver");g(this,dc,void 0);g(this,xi,void 0);g(this,ys,void 0);g(this,ul,void 0);this.id=r.id,this.localId=r.localId,m(this,dc,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,m(this,ys,!1),this.producerId=r.producerId,this.track=r.track,m(this,xi,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,b(this,hl,RS).call(this),m(this,ul,e)}get closed(){return n(this,ys)}get kind(){return this.track.kind}get paused(){return n(this,xi)}reassignPeer(e){this.peerId=e}close(e,r){n(this,ys)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,n(this,Es,Cr)),m(this,ys,!0),r&&(b(this,pl,bS).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(n(this,ys))throw new wt("closed");return n(this,dc).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",n(this,Es,Cr)),n(this,ys)){this.logger.error("consumer::pause() | Consumer closed",n(this,Es,Cr));return}m(this,xi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",n(this,Es,Cr)),n(this,ys)){this.logger.error("Consumer::resume() | Consumer closed",n(this,Es,Cr));return}m(this,xi,!1),this.track.enabled=!0,this.safeEmit("resume")}}dc=new WeakMap,xi=new WeakMap,ys=new WeakMap,ul=new WeakMap,Es=new WeakSet,Cr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},lc=new WeakSet,fh=function(){this.logger.debug('Consumer::track "ended" event',n(this,Es,Cr)),this.safeEmit("trackended")},hl=new WeakSet,RS=function(){this.track.addEventListener("ended",b(this,lc,fh).bind(this))},pl=new WeakSet,bS=function(){try{this.track.removeEventListener("ended",b(this,lc,fh)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...n(this,Es,Cr),error:e})}};var os,ca,da,Ui,zt,Qe,Wr,la,gl,At,ss;class eO extends hu{constructor(e,r){var i,a;super(e);g(this,At);h(this,"id");h(this,"localId");g(this,os,void 0);h(this,"kind");h(this,"appData");h(this,"rtpSender");g(this,ca,void 0);g(this,da,void 0);g(this,Ui,void 0);g(this,zt,!1);g(this,Qe,void 0);g(this,Wr,void 0);g(this,la,void 0);g(this,gl,void 0);this.id=r.id,this.localId=r.localId,m(this,Qe,r.track),this.kind=(i=r.track)==null?void 0:i.kind,m(this,Wr,r.disableTrackOnPause?!((a=r.track)!=null&&a.enabled):!1),m(this,la,void 0),m(this,ca,r.stopTracks),m(this,da,r.disableTrackOnPause),m(this,Ui,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),m(this,os,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),m(this,gl,e)}get closed(){return n(this,zt)}get track(){return n(this,Qe)}get paused(){return n(this,Wr)}get maxSpatialLayer(){return n(this,la)}async close(e){if(n(this,zt))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,n(this,At,ss)),m(this,zt,!0),this._destroyTrack(),e===Ud){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await n(this,os).stopSending(this.localId),{answer:a}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(a)}async getStats(){if(n(this,zt))throw new wt("closed");return n(this,os).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",n(this,At,ss)),n(this,zt)&&this.logger.error("Producer::pause() | Producer closed",n(this,At,ss)),m(this,Wr,!0),n(this,Qe)&&n(this,da)&&(n(this,Qe).enabled=!1),n(this,Ui)&&n(this,os).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",n(this,At,ss)),n(this,zt)){this.logger.error("Producer::resume() | Producer closed",n(this,At,ss));return}m(this,Wr,!1),n(this,Qe)&&n(this,da)&&(n(this,Qe).enabled=!0),n(this,Ui)&&n(this,os).replaceTrack(this.localId,n(this,Qe)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,n(this,At,ss)),n(this,zt)){if(e&&n(this,ca))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...n(this,At,ss),error:r})}throw new wt("closed")}else if(e&&e.readyState==="ended")throw new wt("track ended");if(e===n(this,Qe)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,n(this,At,ss));return}(!n(this,Ui)||!n(this,Wr))&&await n(this,os).replaceTrack(this.localId,e),this._destroyTrack(),m(this,Qe,e),this._handleTrack()}async setMaxSpatialLayer(e){if(n(this,zt))throw new wt("closed");if(this.kind!=="video")throw new Ao("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await n(this,os).setMaxSpatialLayer(this.localId,e),m(this,la,e)}async setRtpEncodingParameters(e){if(n(this,zt))throw new wt("closed");if(typeof e!="object")throw new TypeError("invalid params");await n(this,os).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,n(this,At,ss)),this.safeEmit("trackended",this.track.id)}_handleTrack(){n(this,Qe)&&n(this,Qe).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(n(this,Qe))try{n(this,Qe).removeEventListener("ended",this._onTrackEnded),n(this,ca)&&n(this,Qe).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...n(this,At,ss),error:r})}}}os=new WeakMap,ca=new WeakMap,da=new WeakMap,Ui=new WeakMap,zt=new WeakMap,Qe=new WeakMap,Wr=new WeakMap,la=new WeakMap,gl=new WeakMap,At=new WeakSet,ss=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};const Ud="transport closed",tO=3e4;var ua;const _n=class extends hu{constructor(e,{id:r,direction:i,handlerFactory:a,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:p}){var R,I,D;super(e);h(this,"awaitQueue");h(this,"observer");h(this,"id");h(this,"serverId");h(this,"direction");h(this,"maxSctpMessageSize");h(this,"handler");h(this,"connectionState","new");h(this,"producers");h(this,"consumers");h(this,"connected",!1);h(this,"transportConnectionPromise");h(this,"consumerTrackEvents");h(this,"unknownTracksMap");h(this,"appData");g(this,ua,void 0);m(this,ua,e);const f=e.getValue("logger");f.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const T=XD(l,{});delete T.iceServers,delete T.iceTransportPolicy,delete T.bundlePolicy,delete T.rtcpMuxPolicy,delete T.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new mh(f,!0),this.handler=a(),this.handler.enableHighBitrate=(R=p==null?void 0:p.enableHighBitrate)!=null?R:!1,this.handler.enableStereo=(I=p==null?void 0:p.enableStereo)!=null?I:!1,this.handler.enableDtx=(D=p==null?void 0:p.enableDtx)!=null?D:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const E=3e4;this.transportConnectionPromise=new Promise(A=>{const x=setTimeout(()=>{f.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),A(!1)},E);this.once("connected",()=>{clearTimeout(x),A(!0)}),this.once("disconnect",()=>{clearTimeout(x),A(!1)}),this.once("close",()=>{clearTimeout(x),A(!1)})}),this.handler.on("@connectionstatechange",A=>{A!==this.connectionState&&(this.connectionState=A,A==="connected"&&(this.connected=!0,this.emit("connected")),A==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(A==="failed"||A==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",A))}),this.handler.on("@icecandidate",({candidate:A})=>{this.closed||this.safeEmit("icecandidate",A)})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId!==e&&(this.serverId=e,this.emit("serveridchange",e))}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(Ud).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Ud)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new wt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:a,answer:o}=await e(r);this.setServerId(a),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new wt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new Ao("not a sending Transport");if(r.readyState==="ended")throw new wt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Ar("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:a,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:p={}}=e;this.logger.debug(`produce() [track:${a.id}]`);const{producerId:f,localId:T,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:R,callback:I,sender:D,mid:A}=await this.handler.send({track:a,encodings:o,codecOptions:c,screenShare:p==null?void 0:p.screenShare}),{answer:x,producerId:$}=await r({offer:R,kind:a.kind,paused:l?!a.enabled||Object.hasOwn(a,"fakeTracks"):!1,appData:{...p||{},mid:A},codecOptions:c,producingTransportId:this.serverId}),U=await I(x);return{producerId:$,localId:U,rtpSender:D}},"Transport.produce");return this.createProducerObject({id:f,localId:T,track:a,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:p,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new eO(n(this,ua),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new wt("closed");if(this.direction!=="recv")throw new Ao("not a receiving transport");if(!await this.transportConnectionPromise)throw new Ar("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const a={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,p)=>{a[p]=this.createConsumerObjectAndWaitForTrack({...u,producerId:p})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(a).map(([u,p])=>p.then(f=>l.push(f)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=rs.parse(e.sdp),a={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(a[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),a}static setCodecAndFmtpMappings(e,r,i){const a=rs.parse(e.sdp);return a.media=a.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:rs.write(a)}}static parseHeaderExtensionMappings(e){const r=rs.parse(e.sdp),i={};return r.media.forEach(a=>{i[a.mid]=a.ext}),i}static setHeaderExtensionMappings(e,r){const i=rs.parse(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:rs.write(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),a=_n.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=_n.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=_n.setCodecAndFmtpMappings(c,i,a),c=_n.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=rs.parse(r.sdp);return i.media=i.media.map(a=>{if(a.type==="audio"){const o={...a},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return a}),r.sdp=rs.write(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const a=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(a)});const o=this.consumerTrackEvents.get(a);o?(o(r,i),this.consumerTrackEvents.delete(a)):(this.logger.warn(`track event handler not found ${a}`),this.unknownTracksMap.set(a,e))}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:a,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:p,mimeType:f}=e,T=`${c}:${p}`,E={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(R,I)=>{const D=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${T} producingPeerId: ${a}`),this.consumerTrackEvents.delete(T),E.isTimedout=!0,I(E)},tO),A=($,U)=>{try{if($.readyState==="ended")clearTimeout(D),I(E);else{const z=$;z.enabled=!0,this.handler.midTransceiverMap.set(U.mid,U);const ee=new ZD(n(this,ua),{id:r,localId:U.mid,transceiver:U,track:z,paused:d,producerId:i,producingPeerId:a,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:a},rtpReceiver:U.receiver,mimeType:f});this.consumers.set(r,ee),ee.once("close",()=>{this.consumers.delete(ee.id),this.handler.midTransceiverMap.delete(U.mid)}),this.logger.info(`${l?"screenshare":"participant"} ${p} consumer ${r} created for producer ${i} of remote producing peer ${a} with track ${$.id} on mid ${U.mid}`),this.emit("newconsumer",ee),clearTimeout(D),R(ee)}}catch(z){this.logger.error(`Error while creating ${l?"screenshare":"participant"} ${p} consumer for producerId ${i} of remote peer ${a}`,z),clearTimeout(D),I(E)}},x=this.unknownTracksMap.get(T);x?(this.logger.info(`track event already received for ${l?"screenshare":"participant"} ${p} consumer ${r} of a remote peer ${a} with trackId ${x.track.id} on mid ${x.transceiver.mid} having key ${T}`),this.unknownTracksMap.delete(T),A(x.track,x.transceiver)):(this.logger.info(`Registering onTrack handler for ${l?"screenshare":"participant"} ${p} consumer ${r} of a remote peer ${a} with key ${T}`),this.consumerTrackEvents.set(T,A))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}};let Sh=_n;ua=new WeakMap;var Fe;class sO{constructor(t){g(this,Fe,void 0);h(this,"events");m(this,Fe,t),this.events=us}async joinRoom(t,e,r,i=!1){const a={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await n(this,Fe).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:RR.toBinary(a),timeout:5e3})).payload}async connectTransport(t){const e=(await n(this,Fe).sendMessagePromise(this.events.createWebRTCTransport,eR.toBinary(t))).payload,{transportId:r,description:i,producerIds:a}=Lf.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:a}}async produce(t){var a,o;const e=(await n(this,Fe).sendMessagePromise(this.events.produce,BR.toBinary(t))).payload,r=Pb.fromBinary(e);return{answer:{sdp:(a=r==null?void 0:r.description)==null?void 0:a.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await n(this,Fe).sendMessagePromise(this.events.consume,LR.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=yb.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await n(this,Fe).sendMessagePromise(this.events.closeProducer,KR.toBinary(t))).payload,{description:r}=Ib.fromBinary(e);return r}async closeConsumer(t){return(await n(this,Fe).sendMessagePromise(this.events.closeConsumer,YR.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await n(this,Fe).sendMessagePromise(this.events.updateConsumersSimulcastConfig,UR.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await n(this,Fe).sendMessagePromise(this.events.hostControlPeer,sb.toBinary(r))).payload;if(!i)return!1;const{status:a}=Vb.fromBinary(i);return a==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await n(this,Fe).sendMessagePromise(this.events.hostControlAllPeers,ib.toBinary(e))).payload;if(!r)return!1;const{status:i}=xb.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};n(this,Fe).sendMessagePromise(V.kickAll,Uf.toBinary(t))}async kickPeer(t){n(this,Fe).sendMessagePromise(V.kick,qf.toBinary(t))}async changeDisplayName(t){const e=(await n(this,Fe).sendMessagePromise(this.events.changeDisplayName,eb.toBinary(t))).payload;if(!e)return!1;const{status:r}=Hb.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await n(this,Fe).sendMessagePromise(this.events.selfJoinComplete,kR.toBinary(t))).payload;return Gu.fromBinary(e)}async audioActivity(t){n(this,Fe).sendMessage(this.events.audioActivity,sR.toBinary(t))}}Fe=new WeakMap;var Ft=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Ft||{});class Sp extends hu{constructor(){super(...arguments);h(this,"_sendWebStream",new MediaStream);h(this,"_sendScreenShareStream",new MediaStream);h(this,"_direction");h(this,"pc");h(this,"_transportReady",!1);h(this,"_mapMidTransceiver",new Map);h(this,"enableHighBitrate",!1);h(this,"enableStereo",!1);h(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(this.logger.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){this.logger.error(`${this.name}::pc.close()`,{error:e})}}async restartIce(){this.logger.debug(`${this.name}::restartIce()`);const e=await this.pc.createOffer({iceRestart:!0});return this.logger.debug(`[SDP] ${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`[SDP] ${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:a,proprietaryConstraints:o,onTrackHandler:c}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},o),c&&this.pc.addEventListener("track",d=>{c(d)}),this._addEventListeners()}async connect(){this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly",...this._direction==="send"?{sendEncodings:[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]}:{}});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`[SDP] connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`[SDP] ${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}async getTransportStats(){return this.pc.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}async stopSending(e){this._assertSendDirection(),this.logger.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this.pc.removeTrack(r.sender),r.direction="inactive";const i=await this.pc.createOffer();return this.logger.debug(`[SDP] stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`[SDP] stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(o)}]`),await this.pc.setRemoteDescription(o),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");await i.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters();a.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(a)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters();a.encodings.forEach((o,c)=>{a.encodings[c]={...o,...r}}),await i.sender.setParameters(a)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class Tp extends Sp{static createFactory(t){return()=>new Tp(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:a,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},a),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const a=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const d=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`senders available params: ${JSON.stringify(d)}`);const l=[];r&&r.length&&r.forEach(u=>{var f;const p=d.codecs.find(T=>T.mimeType.includes(u.name));if(u.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(u.parameters)}`);const T=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];T.push(...u.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,u=this.enableHighBitrate?l?128e3:64e3:l?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${d?"usedtx=1;":""}${l?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${u}`),o.sdp+=`a=rtcp-fb:111 nack\r
|
|
9
|
+
`}this.midTransceiverMap.set(a.mid,a);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),a.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:a.sender,mid:a.mid}}}class Hd extends Sp{constructor(e,r){super(e);h(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Hd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:a}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[a?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const p=c.sender.getParameters();p.encodings=r,await c.sender.setParameters(p)}const d=(p,f)=>{var x;const T=rs.parse(p),E=T.media[T.media.length-1],R=E.rtp.filter($=>f.some(U=>U.name===$.codec)),I=E.fmtp.filter($=>R.some(U=>U.payload===$.payload)),D=(x=E.rtcpFb)==null?void 0:x.filter($=>R.some(U=>U.payload===$.payload)),A=R.map($=>$.payload);return T.media[T.media.length-1].rtp=R,T.media[T.media.length-1].fmtp=I,T.media[T.media.length-1].rtcpFb=D,T.media[T.media.length-1].payloads=A.join(" "),rs.write(T)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:p,enableStereo:f}=this,T=this.enableHighBitrate?f?128e3:64e3:f?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${f?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${T}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async p=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(p)}]`),await this.pc.setRemoteDescription(p),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters(),o=a.encodings.length-1-r;a.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(a)}}class vp extends Sp{static createFactory(t){return()=>new vp(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const a=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var f;const p=o.codecs.find(T=>T.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const T=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];T.push(...u.parameters);const E=[...new Set(T).values()];p.sdpFmtpLine=E.join(";")}c.push(p)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),a.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:p}=this,f=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${f}`)}return this.midTransceiverMap.set(a.mid,a),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),a.mid),sender:a.sender,mid:a.mid}}}function rO(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Sm.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}var Xs,Hi;class iO{constructor(t,{handlerName:e,handlerFactory:r}={}){h(this,"handlerFactory");g(this,Xs,void 0);g(this,Hi,void 0);const i=t.getValue("logger");if(i.debug("Device constructor() called."),m(this,Xs,t),m(this,Hi,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)n(this,Hi).debug(`Device::constructor() | handler given: ${e}`);else if(e=rO(n(this,Hi)),e)n(this,Hi).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Tp.createFactory(n(this,Xs));break;case"Safari12":this.handlerFactory=vp.createFactory(n(this,Xs));break;case"Firefox60":this.handlerFactory=Hd.createFactory(n(this,Xs),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Hd.createFactory(n(this,Xs),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=hr.v4();return new Sh(n(this,Xs),{id:e,...t,handlerFactory:this.handlerFactory})}}Xs=new WeakMap,Hi=new WeakMap;const nO=2e3;var ha,je,qe,uc,hc,Bi,pa,pc,ga,Fi,Ps,ws,Rr,gc,Th,ml,kS,mc,vh,fl,IS,Sl,MS,Tl,AS,vl,DS,yl,OS,fc,yh,_s,br;class aO extends ft.EventEmitter{constructor(e,r){super();g(this,ws);g(this,gc);g(this,ml);g(this,mc);g(this,fl);g(this,Sl);g(this,Tl);g(this,vl);g(this,yl);g(this,fc);g(this,_s);h(this,"context");g(this,ha,void 0);g(this,je,void 0);g(this,qe,void 0);g(this,uc,void 0);g(this,hc,void 0);g(this,Bi,void 0);g(this,pa,void 0);g(this,pc,void 0);g(this,ga,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,Fi,void 0);g(this,Ps,"all");this.context=e,m(this,Bi,r),m(this,ha,new iO(e)),m(this,pa,new sO(r)),m(this,pc,us),n(this,ws,Rr).mediaState={send:{state:Ft.NEW},recv:{state:Ft.NEW}},Io(this.context,"forceRelay")&&m(this,Ps,"relay"),this.logger.info(`ICE Transport Policy initially set to ${n(this,Ps)}`),b(this,gc,Th).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return n(this,Bi)}get socketHandler(){return n(this,pa)}get sendTransport(){return n(this,je)}get recvTransport(){return n(this,qe)}get events(){return n(this,pc)}set sendTransportConnectedCallback(e){m(this,uc,e)}set recvTransportConnectedCallback(e){m(this,hc,e)}async setupTransports(e){await b(this,ml,kS).call(this,e);let r,i;e.send&&(r=b(this,mc,vh).call(this,n(this,je)).then(a=>{try{n(this,uc).call(this,a)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=b(this,mc,vh).call(this,n(this,qe)).then(a=>{try{n(this,hc).call(this,a)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,je);this.logger.info("Closing send transport",{transport:{id:a,serverId:o,type:c}}),n(this,je).close(),n(this,je).removeAllListeners(),m(this,je,void 0)}if(e.send&&(n(this,ws,Rr).mediaState.send.state!==Ft.CLOSED||n(this,ws,Rr).mediaState.send.sfuSessionId!==void 0)&&b(this,_s,br).call(this,{direction:"send",state:Ft.CLOSED}),e.recv&&this.recvTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,qe);this.logger.info("Closing recv transport",{transport:{id:a,serverId:o,type:c}}),(r=n(this,qe))==null||r.close(),(i=n(this,qe))==null||i.removeAllListeners(),m(this,qe,void 0)}e.recv&&(n(this,ws,Rr).mediaState.recv.state!==Ft.CLOSED||n(this,ws,Rr).mediaState.recv.sfuSessionId!==void 0)&&b(this,_s,br).call(this,{direction:"recv",state:Ft.CLOSED}),b(this,gc,Th).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}ha=new WeakMap,je=new WeakMap,qe=new WeakMap,uc=new WeakMap,hc=new WeakMap,Bi=new WeakMap,pa=new WeakMap,pc=new WeakMap,ga=new WeakMap,Fi=new WeakMap,Ps=new WeakMap,ws=new WeakSet,Rr=function(){return this.context.getValue("connectionHandler")},gc=new WeakSet,Th=function(){m(this,Fi,{send:void 0,recv:void 0})},ml=new WeakSet,kS=async function(e){var o,c,d,l,u,p,f,T;Io(this.context,"forceRelay")&&m(this,Ps,"relay"),this.logger.info(`ICE Transport Policy set to ${n(this,Ps)}`);const a=await Lt().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&b(this,Sl,MS).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(f=(p=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:p.enableStereo)!=null?f:!1,enableDtx:!1},iceTransportPolicy:n(this,Ps)}),e.recv&&b(this,Tl,AS).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(T=this.context.getValue("modules").e2ee)==null?void 0:T.enabled},iceTransportPolicy:n(this,Ps)})},mc=new WeakSet,vh=async function(e){const{id:r,serverId:i,direction:a}=e;b(this,vl,DS).call(this,e);try{return await xd(async(c,d)=>{c>0&&this.logger.info(`Retrying ${a} transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:a}});try{if(e.closed)throw new Ar("Cannot reconnect closed transport");await b(this,fl,IS).call(this,e)}catch(l){if(l instanceof Ar){this.logger.error(`Failed to connect ${a} transport. It will not be retried.`,{transport:e,error:l}),d(l);return}throw this.logger.error(`Failed to connect ${a} transport, retrying`,{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect ${a} transport after retries: ${e.id}. Transport reconnection will not be retried.`,{error:o,transport:{id:r,serverId:i,type:a}}),e.close(),e.removeAllListeners(),o}},fl=new WeakSet,IS=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!n(this,Bi).isConnected)throw new Ar("Socket is not connected");if(e.connectionState==="closed")throw new Ar("Transport is closed");try{await e.connect(a=>b(this,yl,OS).call(this,i,a)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(a){throw n(this,ga).transportFailureCount[i]+=1,a.message==="ice connection failed"?new Ar(a.message):a}},Sl=new WeakSet,MS=function(e){var r,i;if(n(this,je)&&n(this,je).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=n(this,je))==null?void 0:r.id,serverId:(i=n(this,je))==null?void 0:i.serverId,type:"send"}});return}m(this,je,n(this,ha).createTransport({...e,direction:"send"})),b(this,_s,br).call(this,{state:Ft.NEW,direction:"send",sfuSessionId:n(this,je).serverId}),this.context.getValue("callstats").configureSendTransport(n(this,je))},Tl=new WeakSet,AS=function(e){var r,i;if(n(this,qe)&&n(this,qe).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=n(this,qe))==null?void 0:r.id,serverId:(i=n(this,qe))==null?void 0:i.serverId,type:"recv"}});return}m(this,qe,n(this,ha).createTransport({...e,direction:"recv"})),b(this,_s,br).call(this,{state:Ft.NEW,direction:"recv",sfuSessionId:n(this,qe).serverId}),this.context.getValue("callstats").configureRecvTransport(n(this,qe))},vl=new WeakSet,DS=function(e){const{direction:r,id:i}=e;e.on("serveridchange",a=>{b(this,_s,br).call(this,{state:e.connectionState,direction:r,sfuSessionId:a})}),e.on("connectionstatechange",async a=>{b(this,_s,br).call(this,{state:a,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed to ${a} for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:a}});const o=()=>{const c=n(this,Fi)[r];c!==void 0&&(clearTimeout(c),n(this,Fi)[r]=void 0)};switch(a){case"connected":o(),n(this,ga).lastConnectionTime=performance.now();break;case"disconnected":n(this,Fi)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await b(this,fc,yh).call(this,e.direction)},nO);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await b(this,fc,yh).call(this,e.direction);break}}),e.on("icecandidate",async a=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:a})})},yl=new WeakSet,OS=async function(e,r){const i=e==="recv";try{const{sdp:a,type:o}=r,c={consuming:i,description:{sdp:a,type:o,target:i?gr.SUBSCRIBER:gr.PUBLISHER},producers:[]};return n(this,pa).connectTransport(c)}catch(a){throw this.logger.error(`Error in ${e} transport connection:`,{error:a}),a}},fc=new WeakSet,yh=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),n(this,Bi).isConnected&&n(this,ga).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),m(this,Ps,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:n(this,je)}),this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:n(this,qe)}),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE);break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?n(this,je):n(this,qe);b(this,_s,br).call(this,{state:Ft.CONNECTED,direction:e,sfuSessionId:r.serverId})},_s=new WeakSet,br=function(e){const{state:r,direction:i,sfuSessionId:a}=e;n(this,ws,Rr).mediaState[i]={state:r,sfuSessionId:a},this.context.getValue("peerSessionStore").emit(w.TRANSPORT_STATE_UPDATE,{transport:i,...n(this,ws,Rr).mediaState[i]})};var El,Yt;class oO{constructor(t,e,r,i,a){g(this,El,void 0);g(this,Yt,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=a,m(this,El,t),m(this,Yt,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:p}=d,f={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:p,...f})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),a=new Map;t.forEach(d=>a.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=a.get(d);if(!u)return;if(l.errorCode){n(this,Yt).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let p={};try{p=JSON.parse(l.producerState.appData)}catch(f){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:p})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{n(this,Yt).info("Negotiating socket consumer",{transport:this.recvTransport}),n(this,Yt).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:gr.SUBSCRIBER}};return n(this,Yt).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,nR.toBinary(r)),n(this,Yt).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){n(this,Yt).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return;const e=async(r,i)=>{const a=r.map(l=>l.localId);n(this,Yt).info(`Closing consumers: ${JSON.stringify(a)}`);const o={description:{sdp:i.sdp,type:i.type,target:gr.SUBSCRIBER},consumerIds:a,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=Ab.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"SocketConsumerStrategy.close",{consumersLength:t.length})}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(a=>a&&a.id);i.forEach(({id:a,producingTransportId:o,localId:c})=>{r.requests.push({producerId:a,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),n(this,Yt).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:a})=>a)})}}El=new WeakMap,Yt=new WeakMap;class yp{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return rs.parse(t).media.filter(a=>e==="video"?a.type==="video":a.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:a,producingTransportId:o}){var p,f;const c=yp.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:gr.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(p=i.screenShare)!=null?p:!1,mimeType:`${e}/${(f=a[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function cO(s){try{const t=JSON.parse(s.message);if(typeof t!="object"||t===null)return{};const{errorCode:e,errorDescription:r}=t;return{...typeof e=="string"&&{errorCode:e},...typeof r=="string"&&{errorDescription:r}}}catch(t){return{}}}var ji,Cs,Sc,Rs,Pl,Zs,ma,Tc,Eh,wl,NS,_l,LS,Cl,VS,Rl,$S;class dO extends aO{constructor(e,r){super(e,r);g(this,Tc);g(this,wl);g(this,_l);g(this,Cl);g(this,Rl);g(this,ji,void 0);g(this,Cs,void 0);g(this,Sc,void 0);g(this,Rs,void 0);g(this,Pl,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,Zs,[]);g(this,ma,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{m(this,Sc,new yp(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{m(this,Rs,new oO(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return n(this,ji)}get consumers(){return n(this,Cs)}get logger(){return this.context.getValue("logger")}reset(){m(this,ji,new Map),m(this,Cs,new Map)}async createProducer(e,r){var i,a,o;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const c=await this.sendTransport.produce(e,b(this,wl,NS).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,c),b(this,_l,LS).call(this,c,r),this.logger.info(`Created ${(a=c.appData)!=null&&a.screenShare?"screenshare":"participant"} ${c.kind} producer ${c.id} for local peer on mid ${c.localId}.`),c}catch(c){throw this.logger.error(`Failed to create ${((o=e==null?void 0:e.track)==null?void 0:o.kind)||"unknown"} producer`,{error:c}),n(this,Pl).producerCreationFailureCount+=1,c}}async closeProducer(e,r){var a,o;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),this.logger.info(`Closed ${(a=i.appData)!=null&&a.screenShare?"screenshare":"participant"} ${i.kind} producer ${e} of local peer on mid ${i.localId}. `),(o=this.context.getValue("modules").e2ee)!=null&&o.enabled&&this.context.getValue("peerSessionStore").emit(w.E2EE_INACTIVE_PRODUCER,i)}catch(c){this.logger.error("Failed to close producer on server",{error:c,producer:i})}}closeAllProducers(){return Promise.all(Array.from(n(this,ji).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){n(this,ma)||clearTimeout(n(this,ma)),m(this,Zs,n(this,Zs).concat(e)),await b(this,Tc,Eh).call(this)}removeClosedConsumers(e){return e.filter(r=>{const i=n(this,Cs).get(r);return i!=null&&i.closed?(n(this,Cs).delete(r),!0):!1})}async closeConsumers(e){if(!n(this,Rs))return;const r=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);r.length!==0&&await n(this,Rs).close(r)}closeAllConsumers(){return this.closeConsumers(Array.from(n(this,Cs).keys()))}async switchConsumersToLayer(e,r){n(this,Rs).switchConsumersToLayer(e,r)}}ji=new WeakMap,Cs=new WeakMap,Sc=new WeakMap,Rs=new WeakMap,Pl=new WeakMap,Zs=new WeakMap,ma=new WeakMap,Tc=new WeakSet,Eh=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=n(this,Zs).splice(0,n(this,Zs).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),a=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(a.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(a,b(this,Cl,VS).bind(this),n(this,Rs).negotiate.bind(n(this,Rs)));if(o.forEach(b(this,Rl,$S).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);m(this,Zs,n(this,Zs).concat(d)),m(this,ma,setTimeout(b(this,Tc,Eh).bind(this),e))}}catch(i){const a=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:a});const{errorCode:o,errorDescription:c}=cO(a);if(o==="internal_error"&&c==="Backend error"||o==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:o,message:c}});try{this.stopTransports({recv:!0})}catch(d){}await this.setupTransports({recv:!0})}}},wl=new WeakSet,NS=function(e){return n(this,Sc).create(e)},_l=new WeakSet,LS=function(e,r){e.on("close",async(i,a)=>{const{reason:o}=i,{offer:c}=i;if(this.logger.info("producer::closing",{debuggingHint:o,producer:{...e,status:"closing"}}),o!==Ud){const d={producerId:e.id,description:{sdp:c.sdp,type:c.type,target:gr.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),a({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),n(this,ji).set(e.id,e)},Cl=new WeakSet,VS=async function(e){try{return await this.recvTransport.canConsume(),await n(this,Rs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Rl=new WeakSet,$S=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),n(this,Cs).delete(e.id),this.context.getValue("peerSessionStore").emit(w.CONSUMER_CLOSED,{id:e.id})}),n(this,Cs).set(e.id,e),this.context.getValue("peerSessionStore").emit(w.NEW_CONSUMER_CREATED,{id:e.id,appData:e.appData,peerId:e.peerId})};var vc,yc,Ec,fa,Sa,Ta,Pc,wc,va,yt,cs,ds,qi,Gi,er,_c,bl,xS,kl,US,Il,HS,Ml,BS;const Al=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:a=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,bl);g(this,kl);g(this,vc,void 0);g(this,yc,void 0);g(this,Ec,void 0);g(this,fa,void 0);g(this,Sa,void 0);g(this,Ta,void 0);g(this,Pc,void 0);g(this,wc,void 0);g(this,va,void 0);g(this,yt,void 0);g(this,cs,void 0);g(this,ds,!1);g(this,qi,0);g(this,Gi,0);g(this,er,[]);g(this,_c,void 0);m(this,fa,t),m(this,yt,t),m(this,vc,e),m(this,yc,r),m(this,Ec,i),m(this,Sa,a),m(this,Ta,o),m(this,Pc,c),m(this,wc,d),m(this,va,l),m(this,_c,u),m(this,cs,t/2)}get voiceDetected(){return n(this,ds)}processAudioChunk(t){var o,c;const e=b(o=Al,Il,HS).call(o,t),r=b(c=Al,Ml,BS).call(c,t);return b(this,bl,xS).call(this,e),e/n(this,cs)>n(this,va)&&e>n(this,yt)&&r>n(this,vc)?(m(this,qi,n(this,qi)+1),m(this,Gi,n(this,Ec)),n(this,qi)>=n(this,yc)&&m(this,ds,!0)):(m(this,qi,0),n(this,Gi)>0?m(this,Gi,n(this,Gi)-1):n(this,ds)&&m(this,ds,!1),n(this,ds)||b(this,kl,US).call(this,e)),{energy:e,isVoice:n(this,ds)}}reset(){m(this,ds,!1),m(this,qi,0),m(this,Gi,0),m(this,yt,n(this,fa)),m(this,cs,n(this,fa)/2),m(this,er,[])}getThresholdInfo(){return{currentEnergyThreshold:n(this,yt),backgroundNoiseEnergy:n(this,cs),energyRatioThreshold:n(this,va)}}};let ao=Al;vc=new WeakMap,yc=new WeakMap,Ec=new WeakMap,fa=new WeakMap,Sa=new WeakMap,Ta=new WeakMap,Pc=new WeakMap,wc=new WeakMap,va=new WeakMap,yt=new WeakMap,cs=new WeakMap,ds=new WeakMap,qi=new WeakMap,Gi=new WeakMap,er=new WeakMap,_c=new WeakMap,bl=new WeakSet,xS=function(t){n(this,ds)?m(this,yt,n(this,Ta)*n(this,yt)+(1-n(this,Ta))*t):m(this,yt,n(this,Sa)*n(this,yt)+(1-n(this,Sa))*n(this,cs)),m(this,yt,Math.max(n(this,Pc),Math.min(n(this,wc),n(this,yt))))},kl=new WeakSet,US=function(t){if(t<n(this,yt)*1.2)if(n(this,er).push(t),n(this,er).length>n(this,_c)&&n(this,er).shift(),n(this,er).length>=10){const e=[...n(this,er)].sort((i,a)=>i-a),r=Math.floor(e.length/2);m(this,cs,e[r])}else m(this,cs,.95*n(this,cs)+.05*t)},Il=new WeakSet,HS=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Ml=new WeakSet,BS=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},g(ao,Il),g(ao,Ml);var Cc;class jg{constructor(t){h(this,"RNAudioSampleHandler");g(this,Cc,void 0);m(this,Cc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return n(this,Cc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}Cc=new WeakMap;var Rc;class qg{constructor(t){h(this,"audioContext");h(this,"analyser");g(this,Rc,void 0);m(this,Rc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return n(this,Rc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}Rc=new WeakMap;class FS{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const lO=60,uO=400;var tr,sr,rr,bc,ya,Ea,Jr,Wi,Pa,Ji,ir,bs,kc,Ph,Dl,jS,Ic,wh,Mc,_h,Ol,qS;const Po=class{constructor(t,e){g(this,kc);g(this,Dl);g(this,Mc);g(this,tr,void 0);g(this,sr,void 0);g(this,rr,void 0);g(this,bc,void 0);g(this,ya,void 0);g(this,Ea,void 0);g(this,Jr,void 0);g(this,Wi,void 0);g(this,Pa,void 0);g(this,Ji,void 0);g(this,ir,void 0);g(this,bs,void 0);this.reportRequest=e,m(this,Ji,t),m(this,Ea,new ao);const{isReactNative:r}=navigator;m(this,ir,r?new jg(n(this,Ji)):new qg(n(this,Ji))),m(this,bs,r?FS:po)}get logger(){return n(this,Ji).getValue("logger")}set producerId(t){m(this,rr,t)}set audioTrack(t){m(this,bc,t),n(this,ir)instanceof qg&&(n(this,ir).audioTrack=t)}start(t=!1){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter of audio producer ${n(this,rr)}.`),n(this,tr)&&n(this,bs).clearInterval(n(this,tr)),m(this,tr,n(this,bs).setInterval(b(this,kc,Ph).bind(this),lO)),n(this,sr)&&n(this,bs).clearInterval(n(this,sr)),m(this,sr,n(this,bs).setInterval(b(this,Mc,_h).bind(this),uO)),t&&(b(this,kc,Ph).call(this),b(this,Mc,_h).call(this))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter of audio producer ${n(this,rr)}`),n(this,tr)&&(n(this,bs).clearInterval(n(this,tr)),m(this,tr,void 0)),n(this,sr)&&(n(this,bs).clearInterval(n(this,sr)),m(this,sr,void 0))}catch(t){}n(this,Ea).reset(),n(this,ir)instanceof jg&&n(this,ir).stop()}};let oo=Po;tr=new WeakMap,sr=new WeakMap,rr=new WeakMap,bc=new WeakMap,ya=new WeakMap,Ea=new WeakMap,Jr=new WeakMap,Wi=new WeakMap,Pa=new WeakMap,Ji=new WeakMap,ir=new WeakMap,bs=new WeakMap,kc=new WeakSet,Ph=function(){var i;if(!n(this,bc)||!n(this,rr))return;const{energy:t}=b(this,Dl,jS).call(this),e=b(i=Po,Ic,wh).call(i,t);let r=.9;n(this,Pa)!==e&&n(this,Pa)?r=.9:e?r=.3:r=.5,m(this,ya,(n(this,ya)||0)*(1-r)+t*r)},Dl=new WeakSet,jS=function(){var o;const{samples:t}=n(this,ir),{energy:e,isVoice:r}=n(this,Ea).processAudioChunk(t),i=b(o=Po,Ol,qS).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,Jr)||i<n(this,Jr))&&m(this,Jr,i),(!n(this,Wi)||i>n(this,Wi))&&m(this,Wi,i),{energy:(i-n(this,Jr))/(n(this,Wi)-n(this,Jr))*10||0,isVoice:r})},Ic=new WeakSet,wh=function(t){return t<5},Mc=new WeakSet,_h=function(t=n(this,ya)){var r;if(!n(this,rr)||!t)return;const e={producerId:n(this,rr),energy:Math.round(t),silent:b(r=Po,Ic,wh).call(r,t)};m(this,Pa,e.silent),this.reportRequest(e)},Ol=new WeakSet,qS=function(t){const e=Math.log10(t);return Math.round(e)},g(oo,Ic),g(oo,Ol);var hO=Object.defineProperty,pO=Object.getOwnPropertyDescriptor,ue=(s,t,e,r)=>{for(var i=r>1?void 0:r?pO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&hO(t,e,i),i},Ac,Dc,Ge,B,Nl,ut,nr,Ki,zi,Oc,Dt,ar,ht,Et,or,hi,Nc,Ch,Ll,GS,Vl,WS,$l,JS,Lc,Rh,xl,KS,Ul,zS,Xe,it,Yi,co,Hl,YS,Bl,QS,Fl,XS,jl,ZS;class ne{constructor(t,e){g(this,or);g(this,Nc);g(this,Ll);g(this,Vl);g(this,$l);g(this,Lc);g(this,xl);g(this,Ul);g(this,Xe);g(this,Yi);g(this,Hl);g(this,Bl);g(this,Fl);g(this,jl);h(this,"context");h(this,"authToken");h(this,"e2ee");g(this,Ac,void 0);g(this,Dc,void 0);g(this,Ge,void 0);g(this,B,void 0);g(this,Nl,void 0);g(this,ut,void 0);g(this,nr,void 0);g(this,Ki,void 0);g(this,zi,void 0);g(this,Oc,void 0);g(this,Dt,null);g(this,ar,void 0);g(this,ht,void 0);g(this,Et,void 0);var i,a;this.context=t;const{socket:r}=e;this.mediaJoined=!1,m(this,Ge,r),m(this,nr,!1),m(this,B,new dO(t,r)),m(this,ut,n(this,B).events),m(this,ar,new Set),m(this,ht,new Map),m(this,Ki,!1),m(this,zi,new mh(t.getValue("logger"))),m(this,Et,new oo(this.context,n(this,B).socketHandler.audioActivity.bind(n(this,B).socketHandler))),this.e2ee=(a=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?a:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,Oc,sp(async()=>{if(!n(this,or,hi).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(n(this,Dc),n(this,Ac),!0);o&&(this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return n(this,or,hi).mediaJoined}set mediaJoined(t){n(this,or,hi).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),n(this,B).closeAllProducers(),n(this,B).closeAllConsumers(),n(this,ht).clear(),n(this,ar).clear(),m(this,Dt,null),t&&n(this,zi).stop(),n(this,B).stopAllTransports(),n(this,B).reset(),t&&m(this,zi,new mh)}async joinRoom(t,e,r=!1,i={}){n(this,or,hi).mediaJoinAttempted=!0,m(this,nr,!0);const a=this.peerId;try{const o=await n(this,zi).push(()=>b(this,Ll,GS).call(this,t,e,r,i),"joinRoom");return o.roomJoined||b(this,Nc,Ch).call(this,a),o}catch(o){return this.logger.error("Error in room joining process",{error:o}),b(this,Nc,Ch).call(this,a),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return n(this,Dt)?n(this,Dt):(m(this,Dt,(async()=>{try{await b(this,Lc,Rh).call(this,t,e,r,i)}catch(a){throw m(this,Dt,null),a}})()),n(this,Dt))}getConsumers(){return n(this,B).consumers}getProducers(){return n(this,B).producers}handoverPeerProducers(t,e){const r=new Set(e);return Array.from(n(this,B).consumers.values()).filter(i=>r.has(i.producerId)?(i.reassignPeer(t),!0):!1)}async leaveRoom(){n(this,B).stopAllTransports(),m(this,Ki,!1),n(this,or,hi).mediaJoinAttempted=!1;const t={closeRoom:!1};try{n(this,Ge).sendMessage(n(this,ut).leaveRoom,MR.toBinary(t))||this.logger.warn("MediaNodeClient.leaveRoom: media leave was not sent")}catch(r){this.logger.error("MediaNodeClient.leaveRoom: media leave failed",{error:r})}this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(r=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:r})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():n(this,B).createConsumers(t)}removeClosedConsumers(t){return n(this,B).removeClosedConsumers(t)}async closeConsumersById(t){t.length&&await n(this,B).closeConsumers(t)}async _shareWebcam(t){var u,p,f,T;const e=ye.WEBCAM,r=b(this,Xe,it).call(this,e);if(r){const E=await r;if(n(this,B).producers.has(E)){const R=n(this,B).producers.get(E);if(!R.closed)return await R.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=b(this,jl,ZS).call(this,t),a=Io(this.context,"disableSimulcast"),o=(p=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:p.simulcastConfig;a||o&&o.disable||!((T=(f=this.context)==null?void 0:f.getValue("theme"))!=null&&T.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=eD(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,ht).delete(e)},l=n(this,B).createProducer(i,d);return b(this,Yi,co).call(this,e,l.then(E=>E.id)),l.then(E=>E.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i=await b(this,Xe,it).call(this,ye.SCREENSHARE_VIDEO),a=await b(this,Xe,it).call(this,ye.SCREENSHARE_AUDIO),o=n(this,B).producers.get(i),c=n(this,B).producers.get(a),d=[];if(o&&!o.closed)d.push(o.replaceTrack({track:e}));else{const l={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ve.isElectron()},stopTracks:!1},u=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,ht).delete(ye.SCREENSHARE_VIDEO),n(this,ht).delete(ye.SCREENSHARE_AUDIO)},p=n(this,B).createProducer(l,u);b(this,Yi,co).call(this,ye.SCREENSHARE_VIDEO,p.then(f=>f.id)),d.push(p)}if(r)if(c&&!c.closed)d.push(c.replaceTrack({track:r}));else{const l={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ve.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},u=()=>{},p=n(this,B).createProducer(l,u);b(this,Yi,co).call(this,ye.SCREENSHARE_AUDIO,p.then(f=>f.id)),d.push(p)}await Promise.all(d),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new wt("track undefined");const e=b(this,Xe,it).call(this,ye.MIC);if(e){const o=await e;if(n(this,B).producers.has(o)){const c=n(this,B).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),n(this,Et)&&(n(this,Et).audioTrack=t,n(this,Et).producerId=o,n(this,Et).start(!0));return}await n(this,B).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=b(this,Fl,XS).call(this,t),i=()=>{n(this,ht).delete(ye.MIC)},a=n(this,B).createProducer(r,i);b(this,Yi,co).call(this,ye.MIC,a.then(o=>o.id)),await a.then(o=>{n(this,Et)&&(n(this,Et).audioTrack=o.track,n(this,Et).producerId=o.id,n(this,Et).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await b(this,Xe,it).call(this,ye.MIC),e=n(this,B).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=n(this,Et))==null||i.stop();const r={producerId:e.id,pause:!0};n(this,Ge).sendMessage(n(this,ut).toggleProducer,od.toBinary(r)),this.logger.info(`Paused mic producer ${e.id} of local peer ${this.peerId}. Remote peers will stop hearing this peer.`)}async pauseWebcam(){const t=await b(this,Xe,it).call(this,ye.WEBCAM),e=n(this,B).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};n(this,Ge).sendMessage(n(this,ut).toggleProducer,od.toBinary(r)),this.logger.info(`Paused webcam producer ${e.id} of local peer ${this.peerId}. Remote peers will stop seeing this peer.`)}async resumeMic(){const t=await b(this,Xe,it).call(this,ye.MIC),e=n(this,B).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,Ge).sendMessage(n(this,ut).toggleProducer,od.toBinary(r)),this.logger.info(`Resumed mic producer ${e.id} of local peer ${this.peerId}. Remote peers will start hearing this peer.`)}async resumeWebcam(t=ye.WEBCAM){const e=await b(this,Xe,it).call(this,t),r=n(this,B).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};n(this,Ge).sendMessage(n(this,ut).toggleProducer,od.toBinary(i)),this.logger.info(`Resumed webcam producer ${r.id} of local peer ${this.peerId}. Remote peers will start seeing this peer.`)}async disableWebcam(){const t=ye.WEBCAM,e=await b(this,Xe,it).call(this,t);b(this,Hl,YS).call(this,t),e&&await n(this,B).closeProducer(e)}async disableMic(){var e;const t=await b(this,Xe,it).call(this,ye.MIC);t&&await n(this,B).closeProducer(t),(e=n(this,Et))==null||e.stop(),n(this,ht).delete(ye.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await b(this,Xe,it).call(this,ye.SCREENSHARE_VIDEO),e=await b(this,Xe,it).call(this,ye.SCREENSHARE_AUDIO);t&&await n(this,B).closeProducer(t),e&&await n(this,B).closeProducer(e),n(this,ar).clear(),n(this,ht).delete(ye.SCREENSHARE_VIDEO),n(this,ht).delete(ye.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await b(this,Xe,it).call(this,ye.WEBCAM);await n(this,B).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await b(this,Xe,it).call(this,ye.SCREENSHARE_VIDEO);await n(this,B).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await n(this,B).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};n(this,B).socketHandler.kickPeer(e)}kickAll(){n(this,B).socketHandler.kickAll()}async muteAll(t){if(!await n(this,B).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await n(this,B).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await n(this,B).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await n(this,B).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await n(this,Ge).sendMessagePromise(n(this,ut).globalPinPeer,qR.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&n(this,B).producers.get(t.producerId)&&n(this,ar).add(t.consumerPeerId),n(this,ar).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));n(this,B).switchConsumersToLayer(r,e)}async handleSocketEvents(){n(this,Ge).on(n(this,ut).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{b(this,Bl,QS).call(this,Jb.fromBinary(t))}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),n(this,Ge).on(n(this,ut).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const e=Eg.fromBinary(t),{participantId:r,initiatorParticipantId:i,producerState:{kind:a,pause:o,producerId:c,screenShare:d}}=e;if(d)return;const l=a===Ds.AUDIO?"audio":"video";if(this.logger.info(`Received participant ${l} producer ${o?"paused":"resumed"} broadcast for ${r===this.peerId?"local":"remote"} producer ${c} of peer ${r}. payload: ${Eg.toJsonString(e)}`),r===this.peerId&&i!==this.peerId&&o&&(this.logger.info(`${i?`Remote peer ${i}`:"Kick/Kick-all api"} has paused the ${l==="audio"?"audio":"video"} feed of local peer ${this.peerId}. Reconciling the local state.`),this.context.getValue("peerSessionStore").emit(l==="audio"?w.MUTE_SELF:w.MUTE_SELF_VIDEO)),r===this.peerId)return;this.context.getValue("peerSessionStore").emit(w.PRODUCER_TOGGLE,{peerId:r,producerId:c,paused:o,kind:l}),Array.from(this.getConsumers().values()).filter(p=>p.producerId===c).forEach(p=>{p.kind==="video"&&o||p.paused!==o&&(this.logger.debug(`consumer state mismatched for ${p.id}. updating consumer pause state ${p.paused} to ${o}`),o?(p.pause(),this.context.getValue("peerSessionStore").emit(w.CONSUMER_PAUSED,{id:p.id})):(p.resume(),this.context.getValue("peerSessionStore").emit(w.CONSUMER_RESUMED,{id:p.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),n(this,Ge).on(n(this,ut).peerLeaveBroadcast,async({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Wu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`Received peer left broadcast of remote peer ${e}`),n(this,ar).delete(e),this.context.getValue("peerSessionStore").emit(w.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast of remote peer",{error:e})}}),n(this,Ge).on(n(this,ut).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=Yb.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),n(this,Ge).on(n(this,ut).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,nr)&&!n(this,Ki)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_DISCONNECTED),n(this,Oc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=n(this,B).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(w.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(n(this,B).producers.values()).find(a=>a.id===r);i&&this.context.getValue("peerSessionStore").emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}Ac=new WeakMap,Dc=new WeakMap,Ge=new WeakMap,B=new WeakMap,Nl=new WeakMap,ut=new WeakMap,nr=new WeakMap,Ki=new WeakMap,zi=new WeakMap,Oc=new WeakMap,Dt=new WeakMap,ar=new WeakMap,ht=new WeakMap,Et=new WeakMap,or=new WeakSet,hi=function(){return this.context.getValue("connectionHandler")},Nc=new WeakSet,Ch=function(t){this.mediaJoined=!1,m(this,nr,!1),n(this,Ge).isConnected&&this.peerId===t&&this.context.getValue("peerSessionStore").emit(w.MEDIA_ROOM_JOIN_FAILED)},Ll=new WeakSet,GS=async function(t,e,r,i){var o;m(this,Dc,t);let a=!1;if(r){const{recv:c,send:d}=(o=n(this,or,hi).mediaState)!=null?o:{};(d==null?void 0:d.state)===Ft.CONNECTED&&(c==null?void 0:c.state)===Ft.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — preserving all producers for ownership handover"),m(this,Dt,null),a=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{n(this,Dt)?await n(this,Dt):await b(this,Lc,Rh).call(this,t,e,r,i,a),b(this,$l,JS).call(this,e);const{joined:c,error:d}=await b(this,Vl,WS).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{m(this,Dt,null)}},Vl=new WeakSet,WS=async function(){const t=this.peerId;try{this.mediaJoined=!0;const{roomState:e}=await xd(async(r,i)=>{if(!n(this,Ge).isConnected||this.peerId!==t){const a=new Error("Media room join completion superseded by a newer connection");throw i(a),a}return r>0&&this.logger.warn(`Retrying media room join completion for peer ${t}: attempt=${r+1}`),n(this,B).socketHandler.notifySelfJoinComplete()},{strategy:"exponential",maxRetryCount:3,delayTime:1e3});return m(this,Ac,e.roomUuid),m(this,Ki,!0),m(this,nr,!1),{joined:!0}}catch(e){return this.logger.error("Error completing room join",{error:e}),this.mediaJoined=!1,m(this,nr,!1),{joined:!1,error:e}}},$l=new WeakSet,JS=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...ve.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Lc=new WeakSet,Rh=async function(t,e,r,i,a=!1){try{const o=b(this,xl,KS).call(this);await b(this,Ul,zS).call(this,t,e,r,o),a?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await n(this,B).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},xl=new WeakSet,KS=function(){const t=QD("video/VP8");return m(this,Nl,t),t},Ul=new WeakSet,zS=async function(t,e,r,i){await xd(async(a,o)=>{if(!n(this,Ge).isConnected){o(new Error("Socket is not connected"));return}a>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${a}`});try{await n(this,B).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},Xe=new WeakSet,it=function(t){return n(this,ht).get(t)},Yi=new WeakSet,co=function(t,e){return n(this,ht).set(t,e)},Hl=new WeakSet,YS=function(t){return n(this,ht).delete(t)},Bl=new WeakSet,QS=function({participantId:t,producerState:e}){var i;if(t===this.peerId||!e)return;this.logger.info(`Received remote ${e.screenShare?"screenshare":"participant"} ${e.kind===Ds.AUDIO?"audio":"video"} producer created broadcast for peer ${t} with producer state ${JSON.stringify(e)}.`);const r=(i=e.mimeType)!=null?i:e.kind===Ds.AUDIO?"audio/opus":"video/VP8";this.context.getValue("peerSessionStore").emit(w.NEW_PRODUCER,{peerId:t,producer:{...e,mimeType:r,kind:e.kind===Ds.AUDIO?"audio":"video",producingPeerId:t}})},Fl=new WeakSet,XS=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},jl=new WeakSet,ZS=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};ue([y.trace("MediaNodeClient.reset")],ne.prototype,"reset",1);ue([y.trace("MediaNodeClient.joinRoom")],ne.prototype,"joinRoom",1);ue([y.trace("MediaNodeClient.leaveRoom")],ne.prototype,"leaveRoom",1);ue([y.trace("MediaNodeClient.activatePeers")],ne.prototype,"activatePeers",1);ue([y.trace("MediaNodeClient.createConsumers")],ne.prototype,"createConsumers",1);ue([y.trace("MediaNodeClient.closeConsumersById")],ne.prototype,"closeConsumersById",1);ue([y.trace("MediaNodeClient._shareWebcam")],ne.prototype,"_shareWebcam",1);ue([y.trace("MediaNodeClient.shareWebcam")],ne.prototype,"shareWebcam",1);ue([y.trace("MediaNodeClient.shareScreen")],ne.prototype,"shareScreen",1);ue([y.trace("MediaNodeClient.shareMic")],ne.prototype,"shareMic",1);ue([y.trace("MediaNodeClient.pauseMic")],ne.prototype,"pauseMic",1);ue([y.trace("MediaNodeClient.pauseWebcam")],ne.prototype,"pauseWebcam",1);ue([y.trace("MediaNodeClient.resumeMic")],ne.prototype,"resumeMic",1);ue([y.trace("MediaNodeClient.resumeWebcam")],ne.prototype,"resumeWebcam",1);ue([y.trace("MediaNodeClient.disableWebcam")],ne.prototype,"disableWebcam",1);ue([y.trace("MediaNodeClient.disableMic")],ne.prototype,"disableMic",1);ue([y.trace("MediaNodeClient.disableScreenShare")],ne.prototype,"disableScreenShare",1);ue([y.trace("MediaNodeClient.muteSelf")],ne.prototype,"muteSelf",1);ue([y.trace("MediaNodeClient.resetVideoProducers")],ne.prototype,"resetVideoProducers",1);ue([y.trace("MediaNodeClient.changeDisplayName")],ne.prototype,"changeDisplayName",1);ue([y.trace("MediaNodeClient.kickPeer")],ne.prototype,"kick",1);ue([y.trace("MediaNodeClient.kickAllPeers")],ne.prototype,"kickAll",1);ue([y.trace("MediaNodeClient.muteAll")],ne.prototype,"muteAll",1);ue([y.trace("MediaNodeClient.muteAllVideo")],ne.prototype,"muteAllVideo",1);ue([y.trace("MediaNodeClient.disableAudio")],ne.prototype,"disableAudio",1);ue([y.trace("MediaNodeClient.disableVideo")],ne.prototype,"disableVideo",1);ue([y.trace("MediaNodeClient.pinPeer")],ne.prototype,"pinPeer",1);ue([y.trace("MediaNodeClient.validateScreenShare")],ne.prototype,"validateScreenShare",1);function eT(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new ne(s,t);return s.setValue("roomNodeClient",r),r}function gO(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var mO=Object.defineProperty,fO=Object.getOwnPropertyDescriptor,mn=(s,t,e,r)=>{for(var i=r>1?void 0:r?fO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mO(t,e,i),i},wa,Qt,Y,pt,Rt,gm;const tT=(gm=class{constructor(s,t,e,r){g(this,pt);h(this,"self");h(this,"authToken");g(this,wa,void 0);h(this,"viewType");g(this,Qt,void 0);g(this,Y,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,Y,s),this.viewType=r,this.authToken=a,m(this,wa,i),m(this,Qt,e),this.setupEvents()}get peerId(){return n(this,Y).getValue("peerId")}get telemetry(){return n(this,Y).getValue("telemetry")}get logger(){return n(this,Y).getValue("logger")}get mediaJoined(){return n(this,Y).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=Lt(),o=!!s.getValue("cachedUserDetails"),c=await Ke.__init__(s,e,r,i,i.name,o);s.setValue("self",c);const d=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const u=await c.getAllDevices();d.info("populated_full_device_list",{devices:JSON.stringify(u)}),s.getValue("callstats").devices("AUDIO",u==null?void 0:u.filter(p=>p.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",u==null?void 0:u.filter(p=>p.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",u==null?void 0:u.filter(p=>p.kind==="audiooutput")),d.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:s.getValue("peerId"),engineName:ve.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:d,apiHostnames:PC(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),t.socket.updateCallstatsPeerId(s.getValue("peerId")),d.info("Callstats:: initialized")}catch(p){d.error("Callstats:: initialization failed",{error:p})}},0):d.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new tT(s,c,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===j.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await n(this,pt,Rt).shareMic(s),this.self.audioEnabled||n(this,pt,Rt).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===j.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await n(this,pt,Rt).shareWebcam(t),this.self.videoEnabled||n(this,pt,Rt).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===j.Allowed&&a){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=n(this,pt,Rt))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){var r;const{wasSocketJoinAttempted:t,wasMediaJoinAttempted:e}=s;n(this,Y).getValue("callstats").callEnded(),t||e?(this.logger.info(`Resetting Self post reconnect. Peer has earlier tried joining the ${e?"media room":"socket room only"}. Not closing transports.`),await this.joinRoom({reconnected:!0,joinAttempts:s})):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),(r=n(this,pt,Rt))==null||r.reset({resetTransportQueue:!0}))}setupEvents(){n(this,Y).getValue("peerSessionStore").on(w.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&await this.shareMediaTracks()}),n(this,Y).getValue("peerSessionStore").on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,Y).getValue("peerSessionStore").on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,Y).getValue("peerSessionStore").on(w.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Y).getValue("peerSessionStore").on(w.SOCKET_SERVICE_RECONNECTED,s=>{!s.wasSocketJoinAttempted&&!s.wasMediaJoinAttempted&&(this.self.roomState="init"),this.resetSelf(s).catch(t=>{this.logger.error("Failed to reset self after socket reconnection",{error:t})})}),n(this,Y).getValue("peerSessionStore").on(w.SOCKET_SERVICE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,Y).getValue("peerSessionStore").on(w.SOCKET_SERVICE_FAILED,()=>{this.logger.error("Socket reconnection failed after exhausting all attempts. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Qt).on(V.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,Qt).on(fd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,Y).getValue("peerSessionStore").emit(w.UPDATE_PERMISSIONS,t.patch)})}),n(this,Qt).on(V.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,Qt).on(V.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,Qt).on(V.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,Y).getValue("peerSessionStore").onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,Y).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,Y).getValue("peerSessionStore").on(w.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,Y).getValue("callstats").audioOff())}),n(this,Y).getValue("peerSessionStore").on(w.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,Y).getValue("callstats").videoOff())}),n(this,Y).getValue("peerSessionStore").onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,Y).getValue("peerSessionStore").on(w.PIP_HANGUP,this.leaveRoom.bind(this))}async joinSocketRoomWithRetry(){const s=this.self.id;return xd(async(t,e)=>{if(!n(this,wa).isConnected||this.self.id!==s){const i=new Error("Socket room join superseded by a newer connection");throw e(i),i}t>0&&this.logger.warn(`Retrying socket room join for peer ${s}: attempt=${t+1}`);const r=await n(this,Qt).joinRoom(this.self);if(this.self.id!==s){const i=new Error("Socket room join completed for a superseded peer ID");throw e(i),i}return r},{strategy:"exponential",maxRetryCount:3,delayTime:1e3})}async joinRoom({reconnected:s=!1,joinAttempts:t}={}){var e;try{this.logger.info("Local peer is joining socket room.");const{peer:r}=await this.joinSocketRoomWithRetry();this.logger.info("Local peer has joined socket room."),n(this,Qt).socket.flush();const i=cp(r.stageType);if(n(this,Y).setValue("stageStatus",i,!1),r.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),this.waitlistedHandler();return}}catch(r){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:r}),new C("Check the network and try again.","0002")}if(this.viewType===hs.Livestream&&(t!=null&&t.wasSocketJoinAttempted)&&!t.wasMediaJoinAttempted&&n(this,Y).getValue("stageStatus")!=="ON_STAGE"){this.logger.info("Local livestream peer that only joined the socket room is not ON_STAGE. Closing transports, if any."),(e=n(this,pt,Rt))==null||e.reset({resetTransportQueue:!0}),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s}),n(this,Y).notify("stageStatus");return}try{this.logger.info("Local peer is joining media room."),await this.joinMediaRoom(s),this.logger.info("Local peer has joined media room."),n(this,Y).notify("stageStatus")}catch(r){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:r}),r instanceof Ar&&r.message==="ice connection failed"?new C("A firewall or network restriction may be blocking the connection.","0014"):new C("Check the network and try again.","0014")}}async leaveRoom(s="left"){var e;if(this.logger.info(`Leaving room with state: ${s}`),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}if(this.self.setIsPinned(!1),n(this,Y).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,Y).setValue("roomNodeClient",void 0),n(this,Y).notify("stageStatus"),n(this,Y).getValue("connectionHandler").socketJoined)try{n(this,Qt).leaveRoom(this.self)||this.logger.warn("SelfController.leaveRoom: socket leave was not sent")}catch(r){this.logger.error("SelfController.leaveRoom: socket leave failed",{error:r})}(e=n(this,Y).getValue("roomSocketHandler"))==null||e.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,Y).getAllValues();try{if(e===hs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}eT(n(this,Y),{socket:n(this,wa),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:p}=(o=await((a=n(this,pt,Rt))==null?void 0:a.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw p!=null?p:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=n(this,Y).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===hs.Webinar)&&n(this,pt,Rt)&&(n(this,pt,Rt).mediaJoined&&s!=="disconnected"&&await n(this,pt,Rt).leaveRoom(),!(s==="stageLeft"&&t===hs.Livestream)&&(n(this,pt,Rt).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()}},wa=new WeakMap,Qt=new WeakMap,Y=new WeakMap,pt=new WeakSet,Rt=function(){return n(this,Y).getValue("roomNodeClient")},gm);let di=tT;mn([y.trace("SelfController.resetSelf")],di.prototype,"resetSelf",1);mn([y.trace("SelfController.setupEvents")],di.prototype,"setupEvents",1);mn([y.trace("SelfController.joinRoom")],di.prototype,"joinRoom",1);mn([y.trace("SelfController.leaveRoom")],di.prototype,"leaveRoom",1);mn([y.trace("SelfController.joinMediaRoom")],di.prototype,"joinMediaRoom",1);mn([y.trace("SelfController.leaveMediaRoom")],di.prototype,"leaveMediaRoom",1);mn([y.trace("SelfController.init")],di,"init",1);var Vc;class SO{constructor(t){g(this,Vc,void 0);m(this,Vc,t)}on(t,e){let r;t===V.roomPeerCount?r=_g.fromBinary.bind(_g):r=Dg.fromBinary.bind(Dg),n(this,Vc).on(t,({payload:i})=>{if(t===V.roomPeerCount&&!i)return;const a=r(i);e(a)})}}Vc=new WeakMap;var $c,xc;class TO{constructor(t,e){g(this,$c,void 0);g(this,xc,void 0);m(this,$c,e),m(this,xc,t)}get logger(){return n(this,xc).getValue("logger")}on(t,e){let r,i;switch(t){case V.transcript:{r=Cu.fromBinary.bind(Cu),i=Cu.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,$c).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)})}}$c=new WeakMap,xc=new WeakMap;var vO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,Ep=(s,t,e,r)=>{for(var i=r>1?void 0:r?yO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vO(t,e,i),i},cr,_a;class pu{constructor(t,e){g(this,cr,void 0);g(this,_a,void 0);m(this,cr,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,cr).sendMessagePromise(Bs.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,cr).sendMessage(Bs.createPoll,bA.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,cr).sendMessage(Bs.votePoll,IA.toBinary(r))}on(t,e){let r,i;switch(t){case Bs.updatePoll:case Bs.createPoll:case Bs.votePoll:{r=Au.fromBinary.bind(Au),i=Au.create();break}}n(this,cr).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,cr).removeListeners(t)}}cr=new WeakMap,_a=new WeakMap;Ep([y.trace("PollSocketHandler.getPolls")],pu.prototype,"getPolls",1);Ep([y.trace("PollSocketHandler.createPoll")],pu.prototype,"createPoll",1);Ep([y.trace("PollSocketHandler.votePoll")],pu.prototype,"votePoll",1);var EO=Object.defineProperty,PO=Object.getOwnPropertyDescriptor,wO=(s,t,e,r)=>{for(var i=r>1?void 0:r?PO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EO(t,e,i),i},Ot;class sT{constructor(t,e){h(this,"socket");g(this,Ot,void 0);m(this,Ot,t),this.socket=e,this.handleSocketEvents(),n(this,Ot).setValue("roomSocketHandler",this)}get telemetry(){return n(this,Ot).getValue("telemetry")}get logger(){return n(this,Ot).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(V.joinRoom,bk.toBinary(e));try{const{peer:a}=Sn.fromBinary((await r).payload);n(this,Ot).getValue("connectionHandler").socketJoined=!0,n(this,Ot).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return n(this,Ot).getValue("peerSessionStore").emit(w.ROOM_STATE,d),n(this,Ot).getValue("peerSessionStore").emit(w.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),a}}async getAllAddedParticipants(){try{return uI.fromBinary((await this.socket.sendMessagePromise(V.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(V.getRoomPeersInfo,Sk.toBinary(a));i=Ru.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(V.getRoomPeersInfo);t=Ru.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(V.getRoomPeersInfo);t=Ru.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(V.getPeerInfo,Ff.toBinary({peerId:t}));e=Sn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Cg.create();try{const e=await this.socket.sendMessagePromise(V.getRoomInfo);t=Cg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=Ig.create();try{const e=await this.socket.sendMessagePromise(V.getRoomStageState);t=Ig.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(V.broadcastMessage,Qa.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(V.broadcastToEntity,Qa.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(V.broadcastToEntity,Qa.toBinary(i))}leaveRoom(t){this.socket.joinAttempted=!1;const e={peer:{peerId:t.peerId,userId:t.userId,displayName:t.name,waitlisted:t.waitlistStatus==="waiting"}};return this.socket.sendMessage(V.leaveRoom,Ik.toBinary(e))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(V.kick,qf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(V.kickAll,Uf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(V.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(V.acceptWaitingRoomRequests,SI.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(V.denyWaitingRoomRequests,vI.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(fd.updateUserPreset,KI.toBinary(r))}handleSocketEvents(){this.socket.on(V.broadcastMessage,({payload:t})=>{try{const e=Qa.fromBinary(t);n(this,Ot).getValue("peerSessionStore").emit(w.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(V.broadcastToEntity,({payload:t})=>{try{const e=Qa.fromBinary(t);n(this,Ot).getValue("peerSessionStore").emit(w.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case V.joinRoom:case V.leaveRoom:case V.kick:case V.kickAll:{r=Sn.fromBinary.bind(Sn),i=Sn.create();break}case V.getWaitingRoomRequests:{r=(a,o)=>a?kg.fromBinary(a,o):{requests:[]},i=kg.create();break}case V.recordingPaused:case V.recordingStarted:case V.recordingStopped:{r=Lg.fromBinary.bind(Lg);break}case fd.updateUserPreset:{r=Mg.fromBinary.bind(Mg);break}case us.peerJoinedBroadcast:case Mr.peerJoinedBroadcast:{r=vg.fromBinary.bind(vg);break}case us.selfJoinComplete:case Mr.selfJoinComplete:{r=Gu.fromBinary.bind(Gu);break}case us.globalPeerPinBroadcast:case Mr.globalPeerPinBroadcast:{r=Pg.fromBinary.bind(Pg);break}case us.selectedPeer:case Mr.selectedPeer:{r=qu.fromBinary.bind(qu);break}case us.selectedPeerDiff:case Mr.selectedPeerDiff:{r=Tg.fromBinary.bind(Tg);break}case us.leaveRoom:case Mr.leaveRoom:{r=Wu.fromBinary.bind(Wu);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(fd.getUserPresets,BI.toBinary(e)),i=GI.fromBinary(r.payload).peerPresets[0],a=new TextDecoder().decode(i.preset),o=JSON.parse(a).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Ot=new WeakMap;wO([y.trace("RoomSocketHandler.joinRoom")],sT.prototype,"joinRoom",1);var Pt;class _O{constructor(t){g(this,Pt,void 0);m(this,Pt,t)}async getStageRequests(){const{payload:t}=await n(this,Pt).sendMessagePromise(V.getStageRequests);return t?Mu.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,Pt).sendMessage(V.requestStageAccess)}cancelRequestAccess(){n(this,Pt).sendMessage(V.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,Pt).sendMessage(V.grantStageAccess,SA.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,Pt).sendMessage(V.denyStageAccess,vA.toBinary(e))}joinStage(){return n(this,Pt).sendMessagePromise(V.joinStage,void 0,void 0,V.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,Pt).sendMessagePromise(V.leaveStage,Ng.toBinary(e),void 0,V.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,Pt).sendMessagePromise(V.leaveStage,Ng.toBinary(e))}on(t,e){let r;switch(t){case V.grantStageAccess:case V.denyStageAccess:{r=void 0;break}case V.getStagePeers:{r=Og.fromBinary.bind(Og);break}case V.getStageRequests:case V.requestStageAccess:case V.cancelStageRequest:{r=Mu.fromBinary.bind(Mu);break}case V.peerStageStatusUpdate:{r=wg.fromBinary.bind(wg);break}}n(this,Pt).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,Pt).sendMessagePromise(V.getPeerInfo,Ff.toBinary({peerId:t}));return Sn.fromBinary(e.payload)}}Pt=new WeakMap;var Kr,Ca;class CO{constructor(t,e){g(this,Kr,void 0);g(this,Ca,void 0);m(this,Kr,e),m(this,Ca,t)}get logger(){return n(this,Ca).getValue("logger")}get peerId(){return n(this,Ca).getValue("peerId")}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,Kr).sendMessage(Hs.storeInsertKeys,QM.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,Kr).sendMessage(Hs.storeGetKeys,ZM.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,Kr).sendMessage(Hs.storeDeleteKeys,tA.toBinary(a),i)}on(t,e){const r=Ag.fromBinary.bind(Ag);n(this,Kr).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}Kr=new WeakMap,Ca=new WeakMap;var RO=Object.defineProperty,bO=(s,t,e)=>t in s?RO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,kO=(s,t,e)=>(bO(s,typeof t!="symbol"?t+"":t,e),e),Pp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(Pp(s,t,"read from private field"),e?e.call(s):t.get(s)),oe=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},te=(s,t,e,r)=>(Pp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),re=(s,t,e)=>(Pp(s,t,"access private method"),e),Bd={},IO={get exports(){return Bd},set exports(s){Bd=s}},bn=typeof Reflect=="object"?Reflect:null,Gg=bn&&typeof bn.apply=="function"?bn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Pd;bn&&typeof bn.ownKeys=="function"?Pd=bn.ownKeys:Object.getOwnPropertySymbols?Pd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Pd=function(s){return Object.getOwnPropertyNames(s)};function MO(s){console&&console.warn&&console.warn(s)}var rT=Number.isNaN||function(s){return s!==s};function le(){le.init.call(this)}IO.exports=le;Bd.once=NO;le.EventEmitter=le;le.prototype._events=void 0;le.prototype._eventsCount=0;le.prototype._maxListeners=void 0;var Wg=10;function gu(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(le,"defaultMaxListeners",{enumerable:!0,get:function(){return Wg},set:function(s){if(typeof s!="number"||s<0||rT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Wg=s}});le.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};le.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||rT(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 iT(s){return s._maxListeners===void 0?le.defaultMaxListeners:s._maxListeners}le.prototype.getMaxListeners=function(){return iT(this)};le.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")Gg(c,this,t);else for(var d=c.length,l=dT(c,d),e=0;e<d;++e)Gg(l[e],this,t);return!0};function nT(s,t,e,r){var i,a,o;if(gu(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=iT(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,MO(c)}return s}le.prototype.addListener=function(s,t){return nT(this,s,t,!1)};le.prototype.on=le.prototype.addListener;le.prototype.prependListener=function(s,t){return nT(this,s,t,!0)};function AO(){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 aT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=AO.bind(r);return i.listener=e,r.wrapFn=i,i}le.prototype.once=function(s,t){return gu(t),this.on(s,aT(this,s,t)),this};le.prototype.prependOnceListener=function(s,t){return gu(t),this.prependListener(s,aT(this,s,t)),this};le.prototype.removeListener=function(s,t){var e,r,i,a,o;if(gu(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():DO(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};le.prototype.off=le.prototype.removeListener;le.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),a;for(r=0;r<i.length;++r)a=i[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function oT(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?OO(i):dT(i,i.length)}le.prototype.listeners=function(s){return oT(this,s,!0)};le.prototype.rawListeners=function(s){return oT(this,s,!1)};le.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):cT.call(s,t)};le.prototype.listenerCount=cT;function cT(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}le.prototype.eventNames=function(){return this._eventsCount>0?Pd(this._events):[]};function dT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function DO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function OO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function NO(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}lT(s,t,a,{once:!0}),t!=="error"&&LO(s,i,{once:!0})})}function LO(s,t,e){typeof s.on=="function"&&lT(s,"error",t,e)}function lT(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class VO extends v.MessageType{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const Jg=new VO;class uT{static encode(t){return Jg.toBinary(t)}static decode(t){return Jg.fromBinary(new Uint8Array(t))}}function $O(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var kr;class xO{constructor(t={}){kO(this,"opts"),oe(this,kr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},te(this,kr,0)}async wait(){te(this,kr,M(this,kr)+1);const t=$O(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,kr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,kr)}reset(){te(this,kr,0)}}kr=new WeakMap;const Pr={debug:0,info:1,warn:2,error:3};var pi,gi;class UO{constructor(t){oe(this,pi,void 0),oe(this,gi,void 0),te(this,pi,console),te(this,gi,t)}debug(...t){Pr[M(this,gi)]>Pr.debug||M(this,pi).debug("[Sockrates]:",...t)}info(...t){Pr[M(this,gi)]>Pr.info||M(this,pi).info("[Sockrates]:",...t)}warn(...t){Pr[M(this,gi)]>Pr.warn||M(this,pi).warn("[Sockrates]:",...t)}error(...t){Pr[M(this,gi)]>Pr.error||M(this,pi).error("[Sockrates]:",...t)}}pi=new WeakMap,gi=new WeakMap;var hT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(hT||{});const Kg="2",zg="3";var be,yn,ce,Pe,Ir,Je,lr,si,ls,En,Pn,Us,bh,pT,lo,wd,kh,gT,_d,Nu,Fd,Ih,Mh,mT,So,Cd,kn,To,jd,Ah,In,vo,Dh,fT,yo,Rd,Eo,qd;class HO{constructor(t,e){var E,R,I,D,A,x,$,U,z,ee,H,X;oe(this,bh),oe(this,lo),oe(this,kh),oe(this,_d),oe(this,Fd),oe(this,Mh),oe(this,So),oe(this,kn),oe(this,jd),oe(this,In),oe(this,Dh),oe(this,yo),oe(this,Eo),oe(this,be,void 0),oe(this,yn,void 0),oe(this,ce,void 0),oe(this,Pe,void 0),oe(this,Ir,void 0),oe(this,Je,void 0),oe(this,lr,void 0),oe(this,si,void 0),oe(this,ls,void 0),oe(this,En,void 0),oe(this,Pn,void 0),oe(this,Us,void 0);var r,i,a,o,c,d,l,u,p,f,T;te(this,yn,t),te(this,Ir,[]),te(this,Je,new Bd),te(this,lr,!0),te(this,ls,!1),te(this,ce,e!=null?e:{}),(E=(r=M(this,ce)).autoReconnect)!=null||(r.autoReconnect=!0),(R=(i=M(this,ce)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(I=(a=M(this,ce)).pingTimeout)!=null||(a.pingTimeout=3e4),(D=(o=M(this,ce)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(A=(c=M(this,ce)).debug)!=null||(c.debug=!0),(x=(d=M(this,ce)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),($=(l=M(this,ce)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(U=(u=M(this,ce)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(z=(p=M(this,ce)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),(ee=(f=M(this,ce)).clientInitiatedPings)!=null||(f.clientInitiatedPings=!1),(H=(T=M(this,ce)).clientInitiatedPingInterval)!=null||(T.clientInitiatedPingInterval=3e4),te(this,si,{code:void 0,reason:void 0}),te(this,Pe,(X=M(this,ce).logger)!=null?X:new UO(M(this,ce).debug?"debug":"info")),te(this,Us,new xO)}get readyState(){var t;return(t=M(this,be))==null?void 0:t.readyState}get url(){return M(this,yn)}updateURL(t){te(this,yn,t),re(this,Mh,mT).call(this)}get config(){return M(this,ce)}get sendQueue(){return M(this,Ir)}flush(){if(!M(this,ce).queueOnDisconnect)return!1;const t=[];return M(this,Ir).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),te(this,Ir,t),M(this,Ir)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,Pe).debug("Websocket was already connecting or connected.");return}if(M(this,lr)!==!1)return new Promise((e,r)=>{re(this,In,vo).call(this),re(this,Eo,qd).call(this);try{te(this,be,new WebSocket(re(this,bh,pT).call(this,M(this,yn)))),M(this,be).binaryType="arraybuffer",M(this,Pe).debug("Connecting");const i=setTimeout(()=>{M(this,Pe).debug("Connection timeout. Closing socket"),te(this,lr,!0),re(this,Eo,qd).call(this),M(this,be).close(3001,"Connection Timeout"),M(this,ce).autoReconnect&&!M(this,ls)&&(M(this,Je).emit("reconnecting"),re(this,So,Cd).call(this)),r(new Error("Connection timed out!"))},M(this,ce).connectionTimeout);M(this,be).onopen=()=>{M(this,Pe).debug(`Ready State: ${hT[M(this,be).readyState]}`),i&&clearTimeout(i),re(this,jd,Ah).call(this),re(this,Dh,fT).call(this),te(this,si,{code:void 0,reason:void 0}),M(this,Je).emit("connected"),M(this,ce).flushOnReconnect&&this.flush(),e()},M(this,be).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),M(this,Pe).debug("Socket closed. Close event:",{event:a}),M(this,Pe).debug(`Connection closed code: ${o}`),M(this,Pe).debug(`Connection closed reason: ${c}`),M(this,ls)||re(this,Fd,Ih).call(this,o,c)}catch(o){re(this,lo,wd).call(this,o)}},M(this,be).onerror=a=>{re(this,lo,wd).call(this,a)},M(this,be).onmessage=a=>re(this,kh,gT).call(this,a)}catch(i){re(this,lo,wd).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(M(this,ce).queueOnDisconnect&&(!M(this,be)||M(this,be).readyState!==1))return M(this,Pe).debug("Queuing message since socket is not connected!",a),M(this,Ir).push(a),!1;const o=uT.encode(a);return re(this,kn,To).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return re(this,kn,To).call(this,t)}receive(t,e){return M(this,Je).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,Je).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Je).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Je).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Je).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){te(this,lr,!1),re(this,In,vo).call(this),re(this,yo,Rd).call(this),this.removeAllListeners(),te(this,si,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,be).close(1e3,"Sockrates disconnect method called.")}}be=new WeakMap,yn=new WeakMap,ce=new WeakMap,Pe=new WeakMap,Ir=new WeakMap,Je=new WeakMap,lr=new WeakMap,si=new WeakMap,ls=new WeakMap,En=new WeakMap,Pn=new WeakMap,Us=new WeakMap,bh=new WeakSet,pT=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)://.")},lo=new WeakSet,wd=function(s,t){M(this,Pe).error("Error:",{error:s}),M(this,Je).emit("errored",{error:s}),t==null||t(s)},kh=new WeakSet,gT=function(s){if(re(this,jd,Ah).call(this),s.data===Kg){M(this,Pe).debug("Received ping from server"),re(this,kn,To).call(this,zg);return}if(s.data===zg){M(this,Pe).debug("Received pong from server");return}const t=uT.decode(s.data),{id:e,payload:r}=t;M(this,Pe).debug("Received message",{event:t.event,messageID:e}),M(this,Je).emit(t.event.toString(),{id:e,payload:r})},_d=new WeakSet,Nu=function(){return M(this,be).readyState===1},Fd=new WeakSet,Ih=function(s,t){te(this,si,{reason:t,code:s}),M(this,Je).emit("disconnected",{code:s,reason:t})},Mh=new WeakSet,mT=function(){const{reason:s,code:t}=M(this,si);t&&t!==1e3&&M(this,lr)&&M(this,ce).autoReconnect&&!M(this,ls)&&(M(this,Pe).debug(`Triggering reconnection due to ${s}.`),M(this,Je).emit("reconnecting"),re(this,So,Cd).call(this))},So=new WeakSet,Cd=async function(s=!0){if(s&&M(this,ls)){M(this,Pe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,ls)||M(this,Us).reset(),M(this,ce).maxReconnectionAttempts!==null&&M(this,Us).getAttempts()>=M(this,ce).maxReconnectionAttempts){M(this,Je).emit("failed"),te(this,ls,!1);return}te(this,ls,!0),re(this,Eo,qd).call(this),re(this,In,vo).call(this);try{if(await M(this,Us).wait(),M(this,lr)===!1)return;if(M(this,Pe).debug(`Reconnection attempt ${M(this,Us).getAttempts()}`),M(this,Je).emit("reconnectAttempt",{attempt:M(this,Us).getAttempts()}),await this.connect(),!re(this,_d,Nu).call(this))throw Error("Reconnect Failed");te(this,ls,!1),te(this,si,{code:void 0,reason:void 0}),M(this,Je).emit("reconnected")}catch(t){M(this,Pe).debug("Failed to reconnect."),M(this,Je).emit("reconnectFailure",{attempt:M(this,Us).getAttempts()}),re(this,So,Cd).call(this,!1)}},kn=new WeakSet,To=function(s){try{return M(this,be).send(s),!0}catch(t){return M(this,Pe).error(t.message),!1}},jd=new WeakSet,Ah=function(){this.config.disconnectOnPingTimeout&&(M(this,Pe).debug("Resetting ping timeout"),re(this,In,vo).call(this),te(this,En,setTimeout(()=>{var s;M(this,Pe).debug("Disconnecting the socket due to ping timeout"),te(this,lr,!0);const t=3002,e="Ping timeout";(s=M(this,be))==null||s.close(t,e),re(this,Fd,Ih).call(this,t,e)},M(this,ce).pingTimeout)))},In=new WeakSet,vo=function(){M(this,En)&&(clearTimeout(M(this,En)),te(this,En,void 0))},Dh=new WeakSet,fT=function(){re(this,yo,Rd).call(this),M(this,ce).clientInitiatedPings&&te(this,Pn,setInterval(()=>{re(this,_d,Nu).call(this)&&(M(this,Pe).debug("Sending client-initiated ping"),re(this,kn,To).call(this,Kg))},M(this,ce).clientInitiatedPingInterval))},yo=new WeakSet,Rd=function(){M(this,Pn)&&(clearInterval(M(this,Pn)),te(this,Pn,void 0))},Eo=new WeakSet,qd=function(){re(this,yo,Rd).call(this),M(this,be)&&(M(this,be).onopen=void 0,M(this,be).onerror=void 0,M(this,be).onmessage=void 0,M(this,be).onclose=void 0)};function ST(s){return`${s.slice(0,10)}...${s.slice(-10)}`}function BO(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://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=fi.baseURI.prod;t&&(a=t);const o=`https://${Od({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}var FO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,mu=(s,t,e,r)=>{for(var i=r>1?void 0:r?jO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&FO(t,e,i),i};const Yg=65535,qO=3,GO=15e3,WO=8e3,JO=50,KO=1e3,zO=1e4;var ks,Ra,Ee,Ze,nt,zr,Yr,Qi,Xi,Qr,Is,Ms,Xr,Zi,gt,Zr,mt,Ve,Uc,Oh,ql,vT,Gl,yT,Wl,ET,Hc,Nh,Bc,Lh,en,uo,Jl,Lu,PT,Kl,wT,Fc,Vh,jc,$h,qc,xh,zl,_T,Gc,Uh,Wc,Hh;const TT=(Lu=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Ze);g(this,Uc);g(this,ql);g(this,Gl);g(this,Wl);g(this,Hc);g(this,Bc);g(this,en);g(this,Kl);g(this,Fc);g(this,jc);g(this,qc);g(this,zl);g(this,Gc);g(this,Wc);g(this,ks,void 0);g(this,Ra,void 0);g(this,Ee,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");g(this,zr,[]);g(this,Yr,void 0);g(this,Qi,!1);g(this,Xi,void 0);g(this,Qr,void 0);g(this,Is,void 0);g(this,Ms,void 0);g(this,Xr,void 0);g(this,Zi,void 0);g(this,gt,0);g(this,Zr,void 0);g(this,mt,!0);g(this,Ve,void 0);if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");m(this,Ve,s),m(this,Ms,navigator.isReactNative?FS:po),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,ks,b(this,Uc,Oh).call(this,t)),m(this,Ra,t);const a=i.includes("PING");m(this,Ee,new HO(n(this,ks),{autoReconnect:!1,disconnectOnPingTimeout:a,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!a,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,Ze,nt).socketJoinAttempted}set joinAttempted(s){n(this,Ze,nt).socketJoinAttempted=s}get telemetry(){return n(this,Ve).getValue("telemetry")}get logger(){return n(this,Ve).getValue("logger")}get peerId(){return n(this,Ve).getValue("peerId")}get supersededLocalPeerIds(){return n(this,zr).filter(s=>s!==this.peerId)}updateCallstatsPeerId(s){const t=n(this,Ve).getValue("callstats");t.peerId=s,t.backend&&(t.backend.peerId=s,t.backend.eventHandler&&Object.assign(t.backend.eventHandler,{peerId:s}))}updateURL(s){var t;m(this,ks,b(this,Uc,Oh).call(this,s)),m(this,Ra,s),n(this,Ve).getValue("telemetry").resetPeerId(s),(t=n(this,Ve).getValue("apiClient"))==null||t.setHeader("tracing-id",s),this.updateCallstatsPeerId(s),ii.remapContext(s,n(this,Ve)),this.logger.info(`Attempting websocket connection with URL: ${n(this,en,uo)}`),n(this,Ee).updateURL(n(this,ks))}get url(){return n(this,ks)}async connect(){var t;const s=n(this,gt)+1;m(this,gt,s),b(this,Fc,Vh).call(this),m(this,mt,!0),b(this,Wl,ET).call(this);try{if(await n(this,Ee).connect(),!n(this,mt)||s!==n(this,gt))throw new Error("Socket connection was canceled");b(this,Bc,Lh).call(this,this.peerId),(t=n(this,Is))!=null||m(this,Is,this.peerId),n(this,Ze,nt).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}catch(e){throw this.logger.error(`Websocket connection failed with URL: ${n(this,en,uo)}`,{error:e}),n(this,mt)&&s===n(this,gt)&&b(this,qc,xh).call(this,s),e}}disconnect(){m(this,gt,n(this,gt)+1),m(this,mt,!1),b(this,Fc,Vh).call(this),b(this,Hc,Nh).call(this),m(this,Is,void 0),n(this,Ee).disconnect(),n(this,Ze,nt).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,Ee).readyState===1}catch(s){return!1}}sendMessage(s,t,e){if(!n(this,Gc,Uh))return!1;const r={};return n(this,Ve).getValue("telemetry").injectContext(r),n(this,Ee).send(s,e!=null?e:b(this,Wc,Hh).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){if(!n(this,Gc,Uh))return Promise.reject(new Error("Socket is not connected for the current peer ID"));const a=i!=null?i:s;return new Promise((o,c)=>{let d;const l=(I,D)=>{d&&clearTimeout(d),n(this,Ee).removeListener(a,I),n(this,Ee).removeListener(Yg,D),n(this,Ee).removeListener(Mr.errorResponse,D),n(this,Ee).removeListener(us.errorResponse,D)},u=r!=null?r:b(this,Wc,Hh).call(this),p={};n(this,Ve).getValue("telemetry").injectContext(p);const T=({id:I,payload:D})=>{if(u===I){let A;try{const x=cb.fromBinary(D);A=new Error(x.errorMessage)}catch(x){A=new Error("failed to parse error message",{cause:x});try{const $=lk.fromBinary(D);A=new Error($.message)}catch($){A=new Error("failed to parse error message",{cause:$})}}c(A),l(E,T)}},E=({id:I,payload:D})=>{u===I&&(o({id:I,payload:D}),l(E,T))};n(this,Ee).on(a,E),n(this,Ee).on(Yg,T),n(this,Ee).on(Mr.errorResponse,T),n(this,Ee).on(us.errorResponse,T),d=setTimeout(()=>{l(E,T),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,Ee).send(s,u,e,new TextEncoder().encode(JSON.stringify(p)))||(l(E,T),c(new Error("Socket message could not be sent for the current peer ID")))})}on(s,t){n(this,Ee).on(s,t)}onStateEvent(s,t){n(this,Ee).on(s,t)}removeListener(s,t){n(this,Ee).removeListener(s,t)}removeListeners(s){n(this,Ee).removeListeners(s)}flush(){return n(this,Ee).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{var s;this.logger.info(`Websocket connected with URL: ${n(this,en,uo)}`),(s=n(this,Is))!=null||m(this,Is,this.peerId),n(this,Ze,nt).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{!n(this,mt)||n(this,Zr)===n(this,gt)||(this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}}),n(this,Ze,nt).updateSocketConnectionState("disconnected"),n(this,Ve).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Ze,nt).joinAttempted}),b(this,qc,xh).call(this,n(this,gt)))})}},ks=new WeakMap,Ra=new WeakMap,Ee=new WeakMap,Ze=new WeakSet,nt=function(){return n(this,Ve).getValue("connectionHandler")},zr=new WeakMap,Yr=new WeakMap,Qi=new WeakMap,Xi=new WeakMap,Qr=new WeakMap,Is=new WeakMap,Ms=new WeakMap,Xr=new WeakMap,Zi=new WeakMap,gt=new WeakMap,Zr=new WeakMap,mt=new WeakMap,Ve=new WeakMap,Uc=new WeakSet,Oh=function(s){let t=rp({servicePrefix:"ws",baseURI:n(this,Ve).getValue("baseURI")});const e=Io(n(this,Ve),"socket_server_base");if(typeof e=="string"){const a=/^(http|ws):\/\//i.test(e),o=e.replace(/^(https?|wss?):\/\//i,"").replace(/\/+$/,"");t=`${a?"ws":"wss"}://${o}/ws`}const r=new URL(t),i={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n(this,zr).length>0&&{oldPeerIds:n(this,zr).join(",")},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Nd[a]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0,apiVersion:"23-09-2026"};return Object.entries(i).forEach(([a,o])=>{r.searchParams.append(a,o.toString())}),r.href},ql=new WeakSet,vT=function(){if(!n(this,Is))return;const s=new URL(n(this,ks));return s.protocol=s.protocol==="ws:"?"http:":"https:",s.pathname=`${s.pathname.replace(/\/+$/,"")}/ping`,s.search="",s.searchParams.set("peerId",n(this,Is)),s.href},Gl=new WeakSet,yT=async function(){const s=b(this,ql,vT).call(this);if(!s||n(this,Qi))return;const t={},e=typeof AbortController=="function"?new AbortController:void 0;let r;m(this,Qi,!0),m(this,Qr,t),m(this,Xi,e);try{e&&(r=n(this,Ms).setTimeout(()=>e.abort(),WO));const i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${this.authToken}`},...e&&{signal:e.signal}});i.ok||this.logger.warn("SocketService::API ping request failed",{networkCall:{status:i.status,url:s}})}catch(i){n(this,Qr)===t&&this.logger.warn("SocketService::API ping request failed",{error:i,networkCall:{url:s}})}finally{r!==void 0&&n(this,Ms).clearTimeout(r),n(this,Qr)===t&&(m(this,Qi,!1),m(this,Qr,void 0),m(this,Xi,void 0))}},Wl=new WeakSet,ET=function(){n(this,Yr)===void 0&&m(this,Yr,n(this,Ms).setInterval(()=>b(this,Gl,yT).call(this),GO))},Hc=new WeakSet,Nh=function(){var s;n(this,Yr)!==void 0&&n(this,Ms).clearInterval(n(this,Yr)),(s=n(this,Xi))==null||s.abort(),m(this,Yr,void 0),m(this,Qi,!1),m(this,Qr,void 0),m(this,Xi,void 0)},Bc=new WeakSet,Lh=function(s){m(this,zr,[s,...n(this,zr).filter(t=>t!==s)].slice(0,qO))},en=new WeakSet,uo=function(){const s=new URL(n(this,ks)),t=s.searchParams.get("authToken");return t&&s.searchParams.set("authToken",ST(t)),s.href},Jl=new WeakSet,PT=function(s){const t=Math.min(zO,KO*2**(s-1));return Math.floor(Math.random()*(t+1))},Kl=new WeakSet,wT=function(s){return new Promise(t=>{var e;m(this,Zi,t),m(this,Xr,n(this,Ms).setTimeout(()=>{m(this,Xr,void 0),m(this,Zi,void 0),t()},b(e=TT,Jl,PT).call(e,s)))})},Fc=new WeakSet,Vh=function(){var s;n(this,Xr)!==void 0&&(n(this,Ms).clearTimeout(n(this,Xr)),m(this,Xr,void 0)),(s=n(this,Zi))==null||s.call(this),m(this,Zi,void 0)},jc=new WeakSet,$h=function(s,t){!n(this,mt)||s!==n(this,gt)||(t&&this.logger.error("SocketService::Reconnect loop failed",{error:t}),m(this,mt,!1),b(this,Hc,Nh).call(this),m(this,Is,void 0),n(this,Ze,nt).updateSocketConnectionState("failed"),n(this,Ve).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_FAILED))},qc=new WeakSet,xh=function(s){!n(this,mt)||n(this,Zr)===s||(m(this,Zr,s),n(this,Ze,nt).updateSocketConnectionState("reconnecting"),b(this,zl,_T).call(this,s).catch(t=>b(this,jc,$h).call(this,s,t)))},zl=new WeakSet,_T=async function(s){try{for(let t=1;t<=JO;t+=1){if(!n(this,mt)||s!==n(this,gt)||(await b(this,Kl,wT).call(this,t),!n(this,mt)||s!==n(this,gt)))return;this.updateURL(hr.v4()),this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:t}}),n(this,Ze,nt).updateSocketConnectionState("reconnectAttempt",t);try{if(await n(this,Ee).connect(!0),!n(this,mt)||s!==n(this,gt))return;if(!this.isConnected)throw new Error("Reconnect failed");b(this,Bc,Lh).call(this,this.peerId),m(this,Is,this.peerId),n(this,Ze,nt).updateSocketConnectionState("reconnected"),n(this,Ve).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_RECONNECTED,{wasSocketJoinAttempted:n(this,Ze,nt).socketJoinAttempted,wasMediaJoinAttempted:n(this,Ze,nt).mediaJoinAttempted});return}catch(e){if(!n(this,mt)||s!==n(this,gt))return;this.logger.error(`Websocket connection retry attempt ${t} failed with URL: ${n(this,en,uo)}`,{error:e,socket:{retryAttempt:t}}),n(this,Ze,nt).updateSocketConnectionState("reconnectFailure",t)}}b(this,jc,$h).call(this,s)}finally{n(this,Zr)===s&&m(this,Zr,void 0)}},Gc=new WeakSet,Uh=function(){return this.isConnected&&n(this,Ra)===this.peerId},Wc=new WeakSet,Hh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},g(Lu,Jl),Lu);let rd=TT;mu([y.trace("SocketService.connect")],rd.prototype,"connect",1);mu([y.trace("SocketService.disconnect")],rd.prototype,"disconnect",1);mu([y.trace("SocketService.sendMessagePromise")],rd.prototype,"sendMessagePromise",1);mu([y.trace("SocketService.sendMessagePromiseWithTimeout")],rd.prototype,"sendMessagePromiseWithTimeout",1);class YO{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=$k.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=dI.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=jf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return bg.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return Zk.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(V.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(V.createConnectedRooms,Bk.toBinary({payloads:t}));return bg.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(V.deleteConnectedRooms,Qk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(V.movePeers,nI.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}}}var QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,ZO=(s,t,e,r)=>{for(var i=r>1?void 0:r?XO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QO(t,e,i),i},Nt;class CT extends xt{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);g(this,Nt,void 0);m(this,Nt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=n(this,Nt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=n(this,Nt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const a=n(this,Nt).getValue("userId");if(!(r.length===1&&r[0]===a))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await n(this,Nt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await n(this,Nt).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await n(this,Nt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await n(this,Nt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,Nt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,Nt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),a}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>a.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Nt=new WeakMap;ZO([Ut({maxInvocations:60,period:60})],CT.prototype,"getConnectedMeetings",1);var e1=Object.defineProperty,t1=Object.getOwnPropertyDescriptor,wp=(s,t,e,r)=>{for(var i=r>1?void 0:r?t1(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&e1(t,e,i),i},me,mm;const RT=(mm=class{constructor(s){h(this,"connectedMeetings");g(this,me,void 0);m(this,me,s),this.connectedMeetings=new CT(s)}get telemetry(){return n(this,me).getValue("telemetry")}get logger(){return n(this,me).getValue("logger")}static init(s){const t=new RT(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,me).getValue("connectedMeetingsSocketHandler").socketService.on(V.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,me).getValue("connectedMeetingsSocketHandler").socketService.on(V.transferPeer,this.handleTransferPeer.bind(this)),n(this,me).getValue("connectedMeetingsSocketHandler").socketService.on(V.movedPeer,this.handleMovedPeer.bind(this)),n(this,me).getValue("connectedMeetingsSocketHandler").socketService.on(V.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,me).getValue("connectedMeetingsSocketHandler").socketService.on(V.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,me).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,a,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:n(this,me).getValue("self").videoEnabled,audio:n(this,me).getValue("self").audioEnabled};try{n(this,me).getValue("self").cleanupEvents(),await n(this,me).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,me).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 kT.init({...n(this,me).getValue("options"),cachedUserDetails:null,defaults:{...n(this,me).getValue("options").defaults,...e,mediaHandler:n(this,me).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,me).getValue("self");r.self.setName(n(this,me).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,me).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,me).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,me).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,me).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})}},me=new WeakMap,mm);let fu=RT;wp([y.trace("ConnectedMeetingsController.getConnectedMeetings")],fu.prototype,"getConnectedMeetings",1);wp([y.trace("ConnectedMeetingsController.setupEvents")],fu.prototype,"setupEvents",1);wp([y.trace("ConnectedMeetingsController.switchMeeting")],fu.prototype,"switchMeeting",1);var s1=Object.defineProperty,r1=Object.getOwnPropertyDescriptor,_p=(s,t,e,r)=>{for(var i=r>1?void 0:r?r1(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&s1(t,e,i),i};const ho=class{constructor(s,t,e){h(this,"apiBase");h(this,"selfController");h(this,"pollController");h(this,"chatController");h(this,"metaController");h(this,"storesManager");h(this,"stageController");h(this,"pluginController");h(this,"internalsController");h(this,"recordingController");h(this,"livestreamController");h(this,"participantController");h(this,"connectedMeetingsController");h(this,"telemetry");h(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var x,$;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(gO(s),ve.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=i0(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 H0(s);s.setValue("connectionHandler",l);let u="",p=null;c.info("CF SFU is being used.");const f=ho.createSocketService(s),T=f.connect();T.catch(()=>{});const E=d.getUserDetails();try{p=await E,u=((x=p.meeting)==null?void 0:x.title)||"",s.setValue("presetName",p.preset.name)}catch(U){throw c.error("Failed to get user details",{error:U}),f.disconnect(),U instanceof Ld?U.status===401?new C("Unauthorized. The auth token may be invalid or expired. (401)","0004"):U.status===403?new C("Access denied. Insufficient permissions to join the meeting. (403)","0004"):U.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new C("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004")):U.status>=500?new C(`The server encountered an error. Try again. (${U.status})`,"0001"):U.isHttpError?new C(`Request rejected by the server. (${U.status})`,"0001"):U.isTimeout?new C("Connection timed out. Check the network and try again.","0001"):new C("Unable to connect to the server. Check the internet connection.","0001"):new C((U==null?void 0:U.message)||"Failed to initialize.","0001")}try{await T}catch(U){c.error("[Controller]: Failed to connect to socket server:",{error:U})}const R=ch.init(p.preset,!s.getValue("modules").theme);s.setValue("theme",R);const I=ph.init(s,R.viewType,p.preset.permissions),D=ho.setupControllers(f,s,p,u,R,I);k0(R)&&(($=ho.createRoomNodeClient(s,f).initializeConnection(p.participant.name,i,!1,I))==null||$.catch(z=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:z})}));const{controllers:A}=await D;return jC(),new ho(e,A,s)}static async setupControllers(s,t,e,r,i,a){var ae,N,_;const o=t.getValue("modules"),{participant:c}=e,d=t.getValue("defaults"),l=t.getValue("logger"),{viewType:u,mediaConstraints:{audio:p}}=i;t.setValue("viewType",u),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(ae=p.enableHighBitrate)!=null?ae:!1,enableStereo:(N=p.enableStereo)!=null?N:!1}},...d}),t.setValue("maxPreferredStreams",ve.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let f,T,E,R,I,D,A,x,$;const U=new TO(t,s),z=new YO(s);t.setValue("connectedMeetingsSocketHandler",z);const ee=new pu(t,s),H=new Tr(t,s),X=new _O(s),pe=new sT(t,s),et=new CO(t,s),k=new SO(s),S=await di.init(t,pe,c,a,i);t.setValue("selfController",S);const P=await rS.init(t,S.self,pe,U,r);o.participant&&(x=new Er(t,S.self,pe)),(_=o.e2ee)!=null&&_.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(T=await fo.init(t,H,S.self,x.participants)),o.internals&&(I=await up.init(t)),o.livestream&&i.viewType===hs.Livestream&&(A=new gS(t,S.self,k)),o.poll&&(f=await eS.init(t,S.self,ee)),o.recording&&(D=new dS(t,S.self,pe)),o.stage&&(E=new iS(t,X,pe,S.self,x.participants));const L=new DD(t,et);if(o.plugin){if(!x)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const ke=d.plugins||[];R=await cS.init(t,ke,S.self,L)}if(o.connectedMeetings&&($=await fu.init(t)),o.pip){const ke=await ju._init(t,S.self);t.setValue("pip",ke)}return{theme:i,permissions:a,controllers:{storesManager:L,pollController:f,selfController:S,metaController:P,chatController:T,stageController:E,pluginController:R,recordingController:D,internalsController:I,livestreamController:A,participantController:x,connectedMeetingsController:$}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return eT(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=[];return new rd(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Su=ho;_p([y.trace("Controller.init")],Su,"init",1);_p([y.trace("Controller.createRoomNodeClient")],Su,"createRoomNodeClient",1);_p([y.trace("Controller.createSocketService")],Su,"createSocketService",1);class i1{constructor(){h(this,"battery");h(this,"logger");h(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)}});h(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});h(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});h(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 Qg=new i1;var ei,tn,sn,Jc,Yl,bT;class n1{constructor(){g(this,Yl);g(this,ei,new Audio);g(this,tn,new MediaStream);g(this,sn,new Map);g(this,Jc,void 0);n(this,ei).srcObject=n(this,tn),n(this,ei).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,sn).has(e.id)||(n(this,tn).addTrack(e),n(this,sn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,ei).setSinkId(t)}removeTrack(t){const e=n(this,sn).get(t);e&&(n(this,tn).removeTrack(e),n(this,sn).delete(t))}async play(){return n(this,ei).srcObject=n(this,tn),n(this,ei).play().catch(t=>{b(this,Yl,bT).call(this,t)})}onError(t){m(this,Jc,t)}}ei=new WeakMap,tn=new WeakMap,sn=new WeakMap,Jc=new WeakMap,Yl=new WeakSet,bT=function(t){var e;(e=n(this,Jc))==null||e.call(this,t)};var As;class a1 extends n1{constructor(){super();g(this,As,void 0);m(this,As,new Map)}addParticipantTrack(e,r){n(this,As).set(e,r.id),this.playTracks([r])}reassignParticipantTrack(e,r){const i=n(this,As).get(e);i&&(n(this,As).delete(e),n(this,As).set(r,i))}removeParticipantTrack(e){const r=n(this,As).get(e);r&&this.removeTrack(r),n(this,As).delete(e)}}As=new WeakMap;var o1=Object.defineProperty,c1=Object.getOwnPropertyDescriptor,Tu=(s,t,e,r)=>{for(var i=r>1?void 0:r?c1(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&&o1(t,e,i),i},De,rn,fm;let ni=(fm=class{constructor(t,e){g(this,De,void 0);g(this,rn,void 0);m(this,rn,t),m(this,De,e)}get peerId(){return n(this,rn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:hr.v4(),a=ii.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new CS(a,o);return await c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,T,E,R,I,D,A;ve.init();const e=(T=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?T:hr.v4(),{authToken:r,baseURI:i}=t,{meetingId:a,...o}=BO(r,i);if((E=o.baseURI)!=null&&E.includes("dyte.io"))throw new C("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=ni.setupContext(e,t,a,o),d=c.getValue("telemetry"),l=c.getValue("logger");LT(l),Qg.init(l),d.init(c,{roomName:a,userId:o.participantId,organizationId:o.orgId,peerId:e},(I=(R=t.modules)==null?void 0:R.tracing)!=null?I:!0,(A=(D=t==null?void 0:t.modules)==null?void 0:D.devTools)==null?void 0:A.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:ST(t.authToken)}});const u=await Su.init(c),p=new ni(c,u);return c.setValue("meeting",p),p}static setupContext(t,e,r,i){var d,l;const a=ii.createContext(t,e),o={...yC,...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",EC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",Os(e.cachedUserDetails)),a.setValue("sdkVersion","2.0.3"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new a1),a}async join(){const{selfController:t}=n(this,De);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;Qg.cleanup(),n(this,rn).getValue("peerSessionStore").reset(),(r=n(this,De).pluginController)==null||r.cleanup();const{selfController:e}=n(this,De);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,De).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,De).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,De).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,De).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,De).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,De).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,De).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,De).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,De).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,De).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,De).stageController)==null?void 0:t.stage}get stores(){return n(this,De).storesManager}get audio(){return n(this,rn).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,De).internalsController)==null?void 0:t.internals}},De=new WeakMap,rn=new WeakMap,fm);Tu([rt("0002"),yr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],ni.prototype,"join",1);Tu([rt("0003")],ni.prototype,"leave",1);Tu([rt("0001"),yr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],ni,"init",1);ni=Tu([rt("0000")],ni);const kT=ni;module.exports=kT;
|