@100mslive/hms-video-store 0.15.1 → 0.15.2-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var oo=Object.create;var bt=Object.defineProperty,co=Object.defineProperties,lo=Object.getOwnPropertyDescriptor,uo=Object.getOwnPropertyDescriptors,po=Object.getOwnPropertyNames,Si=Object.getOwnPropertySymbols,ta=Object.getPrototypeOf,Gr=Object.prototype.hasOwnProperty,ia=Object.prototype.propertyIsEnumerable,ho=Reflect.get;var ea=(a,e,t)=>e in a?bt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,m=(a,e)=>{for(var t in e||(e={}))Gr.call(e,t)&&ea(a,t,e[t]);if(Si)for(var t of Si(e))ia.call(e,t)&&ea(a,t,e[t]);return a},M=(a,e)=>co(a,uo(e));var $r=(a,e)=>{var t={};for(var i in a)Gr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&Si)for(var i of Si(a))e.indexOf(i)<0&&ia.call(a,i)&&(t[i]=a[i]);return t};var mo=(a,e)=>()=>{try{return e||a((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},So=(a,e)=>{for(var t in e)bt(a,t,{get:e[t],enumerable:!0})},ra=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of po(e))!Gr.call(a,r)&&r!==t&&bt(a,r,{get:()=>e[r],enumerable:!(i=lo(e,r))||i.enumerable});return a};var We=(a,e,t)=>(t=a!=null?oo(ta(a)):{},ra(e||!a||!a.__esModule?bt(t,"default",{value:a,enumerable:!0}):t,a)),go=a=>ra(bt({},"__esModule",{value:!0}),a);var me=(a,e,t)=>ho(ta(a),t,e);var c=(a,e,t)=>new Promise((i,r)=>{var s=l=>{try{o(t.next(l))}catch(u){r(u)}},n=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(s,n);o((t=t.apply(a,e)).next())});var Zr=mo((uu,Eo)=>{Eo.exports={version:"0.15.1",license:"MIT",repository:{type:"git",url:"https://github.com/100mslive/web-sdks.git",directory:"packages/hms-video-store"},main:"dist/index.cjs.js",module:"dist/index.js",typings:"dist/index.d.ts",files:["dist"],engines:{node:">=12"},exports:{".":{require:"./dist/index.cjs.js",import:"./dist/index.js",default:"./dist/index.js"}},sideEffects:!1,scripts:{prestart:"rm -rf dist && yarn types:build",start:'concurrently "yarn dev" "yarn types"',dev:"node ../../scripts/dev","build:only":"node ../../scripts/build",build:"yarn build:only && yarn types:build",types:"tsc -w","types:build":"tsc -p tsconfig.json",format:"prettier --write src/**/*.ts",test:"jest --maxWorkers=1","test:watch":"jest --watch","test:coverage":"jest --coverage",lint:"eslint -c ../../.eslintrc .","lint:fix":"yarn lint --fix",prepare:"yarn build",size:"size-limit",analyze:"size-limit --why",docs:"rm -rf ./docs && typedoc && rm -f ./docs/README.md && mkdir ./docs/home &&mv ./docs/modules.md ./docs/home/content.md && node ../../scripts/docs-store && npx prettier --write './docs/**/*'"},name:"@100mslive/hms-video-store",author:"100ms",dependencies:{eventemitter2:"^6.4.9",immer:"^9.0.6","lodash.isequal":"^4.5.0",reselect:"4.0.0","sdp-transform":"^2.14.1","ua-parser-js":"^2.0.6",uuid:"^11.1.1","webrtc-adapter":"^8.0.0",zustand:"3.5.7"},devDependencies:{"@types/dom-screen-wake-lock":"^1.0.1","@types/lodash.isequal":"^4.5.8","@types/sdp-transform":"^2.4.4","@types/ua-parser-js":"^0.7.39","@types/uuid":"^8.3.0","jest-canvas-mock":"^2.3.1","jsdom-worker":"^0.3.0",tslib:"^2.2.0"},description:"@100mslive Core SDK which abstracts the complexities of webRTC while providing a reactive store for data management with a unidirectional data flow",keywords:["video","webrtc","conferencing","100ms"],gitHead:"8ab2e2f747591a298371e00222d32152ff629a89"}});var Pl={};So(Pl,{ConnectivityState:()=>Nn,DeviceType:()=>ls,Diagnostics:()=>gt,DomainCategory:()=>Jr,EventBus:()=>Tt,HLSPlaylistType:()=>ns,HLSStreamType:()=>os,HMSAudioDeviceCategory:()=>Hi,HMSAudioMode:()=>Ri,HMSAudioPluginType:()=>ki,HMSLogLevel:()=>Kr,HMSMessageType:()=>sa,HMSNotificationSeverity:()=>Wr,HMSNotificationTypes:()=>Ti,HMSPeerType:()=>Ai,HMSPlaylistType:()=>qr,HMSPluginUnsupportedTypes:()=>Ei,HMSReactiveStore:()=>et,HMSRecordingState:()=>as,HMSRoomState:()=>gi,HMSStats:()=>kt,HMSTrackExceptionTrackType:()=>zr,HMSTranscriptionMode:()=>ds,HMSTranscriptionState:()=>cs,HMSVideoPluginCanvasContextType:()=>Oi,HMSVideoPluginType:()=>Ni,createDefaultStatsStore:()=>At,createDefaultStoreState:()=>It,getAudioDeviceCategory:()=>Ci,parsedUserAgent:()=>J,selectAppData:()=>Gc,selectAppDataByPath:()=>Wc,selectAudioPlaylist:()=>Ls,selectAudioPlaylistTrackByPeerID:()=>ad,selectAudioTrackByID:()=>jc,selectAudioTrackByPeerID:()=>vn,selectAudioTrackVolume:()=>Bs,selectAudioVolumeByPeerID:()=>ud,selectAuxiliaryAudioByPeerID:()=>id,selectAuxiliaryTracksByPeerID:()=>Yc,selectAvailableRoleNames:()=>Tc,selectBroadcastMessages:()=>En,selectBroadcastMessagesUnreadCount:()=>gd,selectCameraStreamByPeerID:()=>zc,selectConnectionQualities:()=>Qo,selectConnectionQualityByPeerID:()=>td,selectDegradedTracks:()=>uc,selectDevices:()=>jo,selectDidIJoinWithin:()=>Vd,selectDominantSpeaker:()=>ic,selectEffectsKey:()=>Hc,selectErrors:()=>sn,selectFullAppData:()=>qi,selectHLSState:()=>yc,selectHMSBroadcastMessages:()=>on,selectHMSMessages:()=>mt,selectHMSMessagesCount:()=>pc,selectHMSStats:()=>no,selectHandRaisedPeers:()=>Dc,selectHasPeerHandRaised:()=>Pd,selectIsAllowedToPreviewMedia:()=>wd,selectIsAllowedToPublish:()=>Ld,selectIsAllowedToSubscribe:()=>fc,selectIsAudioLocallyMuted:()=>Us,selectIsConnectedToRoom:()=>Ce,selectIsEffectsEnabled:()=>Ac,selectIsInPreview:()=>bs,selectIsLargeRoom:()=>Ic,selectIsLocalAudioEnabled:()=>rc,selectIsLocalAudioInterrupted:()=>sc,selectIsLocalAudioPluginPresent:()=>xd,selectIsLocalScreenShared:()=>ji,selectIsLocalVideoDisplayEnabled:()=>Ps,selectIsLocalVideoEnabled:()=>Ki,selectIsLocalVideoInterrupted:()=>ac,selectIsLocalVideoPluginPresent:()=>Od,selectIsLocallyMutedByPeerID:()=>dd,selectIsPeerAudioEnabled:()=>od,selectIsPeerVideoEnabled:()=>cd,selectIsRoleAllowedToPublish:()=>Dd,selectIsScreenShareLocallyMutedByPeerID:()=>ld,selectIsSomeoneScreenSharing:()=>nc,selectIsTranscriptionAllowedByMode:()=>Ad,selectIsTranscriptionEnabled:()=>gc,selectIsVBEnabled:()=>Rc,selectLocalAudioTrackID:()=>ue,selectLocalMediaSettings:()=>ks,selectLocalPeer:()=>X,selectLocalPeerID:()=>Ie,selectLocalPeerName:()=>Xo,selectLocalPeerRole:()=>ze,selectLocalPeerRoleName:()=>Zo,selectLocalTrackIDs:()=>Es,selectLocalVideoTrackID:()=>ie,selectMessageByMessageID:()=>Id,selectMessageIDsInOrder:()=>ys,selectMessagesByPeerID:()=>Td,selectMessagesByRole:()=>fd,selectMessagesMap:()=>$t,selectMessagesUnreadCountByPeerID:()=>Md,selectMessagesUnreadCountByRole:()=>vd,selectPeerAudioByID:()=>ed,selectPeerByCondition:()=>Ud,selectPeerByID:()=>se,selectPeerCount:()=>Jo,selectPeerMetadata:()=>Ed,selectPeerName:()=>bd,selectPeerNameByID:()=>qc,selectPeerScreenSharing:()=>nn,selectPeerSharingAudio:()=>oc,selectPeerSharingAudioPlaylist:()=>lc,selectPeerSharingVideoPlaylist:()=>dc,selectPeerTypeByID:()=>Kc,selectPeers:()=>Me,selectPeersByCondition:()=>Bd,selectPeersByRole:()=>yd,selectPeersByRoles:()=>kd,selectPeersMap:()=>Y,selectPeersScreenSharing:()=>cc,selectPeersWithAudioStatus:()=>Rd,selectPermissions:()=>As,selectPollByID:()=>Vs,selectPolls:()=>wc,selectPollsMap:()=>Rs,selectPreviewRole:()=>Is,selectPreviewRoleName:()=>cn,selectRTMPState:()=>Mc,selectRecentError:()=>qo,selectRecordingState:()=>vc,selectRemotePeers:()=>tc,selectRoleByRoleName:()=>Pn,selectRoleChangeRequest:()=>Cd,selectRolesMap:()=>ye,selectRoom:()=>V,selectRoomID:()=>Ko,selectRoomStartTime:()=>bc,selectRoomStarted:()=>Sc,selectRoomState:()=>oe,selectScreenAudioTrackByID:()=>Qc,selectScreenShareAudioByPeerID:()=>xs,selectScreenShareByPeerID:()=>nd,selectScreenSharesByPeerId:()=>Os,selectScreenVideoTrackByID:()=>Jc,selectScreenshareAudioVolumeByPeerID:()=>pd,selectSessionId:()=>Pc,selectSessionMetadata:()=>Lc,selectSessionStore:()=>$c,selectSimulcastLayerByTrack:()=>hd,selectSpeakers:()=>an,selectTemplateAppData:()=>Cc,selectTrackAudioByID:()=>Xc,selectTrackByID:()=>Kt,selectTracksMap:()=>_,selectTranscriptionsState:()=>kc,selectTranslationState:()=>Ec,selectUnreadHMSBroadcastMessagesCount:()=>mc,selectUnreadHMSMessagesCount:()=>hc,selectVideoPlaylist:()=>ws,selectVideoPlaylistAudioTrackByPeerID:()=>sd,selectVideoPlaylistVideoTrackByPeerID:()=>rd,selectVideoTrackByID:()=>Ns,selectVideoTrackByPeerID:()=>fn,selectWhiteboard:()=>_c,selectWhiteboards:()=>dn,simulcastMapping:()=>Ue});module.exports=go(Pl);var gi=(o=>(o.Disconnected="Disconnected",o.Preview="Preview",o.Connecting="Connecting",o.Connected="Connected",o.Reconnecting="Reconnecting",o.Disconnecting="Disconnecting",o.Failed="Failed",o))(gi||{});var It=()=>({room:{id:"",isConnected:!1,name:"",peers:[],localPeer:"",roomState:"Disconnected",recording:{browser:{running:!1},server:{running:!1},hls:{running:!1}},rtmp:{running:!1},hls:{running:!1,variants:[]},sessionId:""},peers:{},tracks:{},playlist:{audio:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1},video:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1}},messages:{byID:{},allIDs:[]},speakers:{},connectionQualities:{},settings:{audioInputDeviceId:"",audioOutputDeviceId:"",videoInputDeviceId:""},devices:{audioInput:[],audioOutput:[],videoInput:[]},roles:{},roleChangeRequests:[],errors:[],sessionStore:{},templateAppData:{},polls:{},whiteboards:{},hideLocalPeer:!1}),At=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var sa=(e=>(e.CHAT="chat",e))(sa||{});var Wr=(t=>(t.INFO="info",t.ERROR="error",t))(Wr||{}),Ti=(D=>(D.PEER_JOINED="PEER_JOINED",D.PEER_LEFT="PEER_LEFT",D.PEER_LIST="PEER_LIST",D.NEW_MESSAGE="NEW_MESSAGE",D.ERROR="ERROR",D.RECONNECTING="RECONNECTING",D.RECONNECTED="RECONNECTED",D.TRACK_ADDED="TRACK_ADDED",D.TRACK_REMOVED="TRACK_REMOVED",D.TRACK_MUTED="TRACK_MUTED",D.TRACK_UNMUTED="TRACK_UNMUTED",D.TRACK_DEGRADED="TRACK_DEGRADED",D.TRACK_RESTORED="TRACK_RESTORED",D.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",D.ROLE_UPDATED="ROLE_UPDATED",D.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",D.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",D.ROOM_ENDED="ROOM_ENDED",D.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",D.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",D.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",D.NAME_UPDATED="NAME_UPDATED",D.METADATA_UPDATED="METADATA_UPDATED",D.POLL_CREATED="POLL_CREATED",D.POLL_STARTED="POLL_STARTED",D.POLL_STOPPED="POLL_STOPPED",D.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",D.POLLS_LIST="POLLS_LIST",D.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",D.TRANSCRIPTION_STATE_UPDATED="TRANSCRIPTION_STATE_UPDATED",D.TRACK_INTERRUPTION_START="TRACK_INTERRUPTION_START",D.TRACK_INTERRUPTION_END="TRACK_INTERRUPTION_END",D))(Ti||{});var qr=(t=>(t.audio="audio",t.video="video",t))(qr||{});var I=require("reselect");function qe(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];To(s)&&(i=Rt(s)?s:i,t=Ht(s)?s:t)}return{video:t,audio:i}}function Rt(a){return a&&a.type==="audio"}function Ht(a){return a&&a.type==="video"}function To(a){return a&&a.source==="screen"}function fi(a){return a&&a.source==="audioplaylist"}function Ct(a){return a&&a.source==="videoplaylist"}function aa(a){return a?!!(a!=null&&a.degraded):!1}function tt(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function na(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function Lt(a){var r;let e=!1,t=!1,i=!1;return(r=a==null?void 0:a.publishParams)!=null&&r.allowed&&(e=a.publishParams.allowed.includes("video"),t=a.publishParams.allowed.includes("audio"),i=a.publishParams.allowed.includes("screen")),{video:e,audio:t,screen:i}}var Kr=(l=>(l[l.VERBOSE=0]="VERBOSE",l[l.DEBUG=1]="DEBUG",l[l.INFO=2]="INFO",l[l.WARN=3]="WARN",l[l.TIME=4]="TIME",l[l.TIMEEND=5]="TIMEEND",l[l.ERROR=6]="ERROR",l[l.NONE=7]="NONE",l))(Kr||{}),fo=typeof window!="undefined"&&typeof window.expect!="undefined",d=class{static v(e,...t){this.log(0,e,...t)}static d(e,...t){this.log(1,e,...t)}static i(e,...t){this.log(2,e,...t)}static w(e,...t){this.log(3,e,...t)}static e(e,...t){this.log(6,e,...t)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,t,...i){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(t,...i);break}case 1:{console.debug(t,...i);break}case 2:{console.info(t,...i);break}case 3:{console.warn(t,...i);break}case 6:{console.error(t,...i);break}case 4:{performance.mark(i[0]);break}case 5:{let r=i[0];try{let s=performance.measure(r,r);this.log(1,t,r,s==null?void 0:s.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(s){this.log(1,t,r,s)}break}}}};d.level=fo?7:0;var it=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var ma=require("ua-parser-js");var jr=new ma.UAParser,wt=null,Qr=null,F=typeof window!="undefined";if(F)try{let a=jr.getResult(),e=a.withClientHints();e&&typeof e.then=="function"?(Qr=e,Qr.then(t=>{wt=t}).catch(()=>{wt=a})):(d.d("UAParser","Client Hints not supported, using standard UA parsing"),wt=e)}catch(a){wt=jr.getResult()}var _e=()=>wt||jr.getResult(),J={getBrowser:()=>_e().browser,getOS:()=>_e().os,getDevice:()=>_e().device,getCPU:()=>_e().cpu,getEngine:()=>_e().engine,getUA:()=>_e().ua,getResult:_e,withClientHints:()=>Qr||Promise.resolve(_e())},oa,Ke=typeof window=="undefined"&&!((oa=J.getBrowser().name)!=null&&oa.toLowerCase().includes("electron"));var vo=()=>!Ke,Nl=vo(),Sa=()=>J.getDevice().type==="mobile",Mo=()=>{var a;return typeof navigator!="undefined"&&navigator.maxTouchPoints>1&&!!((a=J.getOS().name)!=null&&a.toLowerCase().includes("mac"))},vi=()=>{let a=J.getDevice().type;return a==="mobile"||a==="tablet"||Mo()},ga=()=>typeof document!="undefined"&&document.hidden,Ta=()=>{var a;return((a=J.getOS().name)==null?void 0:a.toLowerCase())==="ios"},ca,da,fa=(da=(ca=J.getBrowser())==null?void 0:ca.name)==null?void 0:da.toLowerCase().includes("safari"),la,ua,va=((ua=(la=J.getBrowser())==null?void 0:la.name)==null?void 0:ua.toLowerCase())==="firefox",pa,ha,Ma=((ha=(pa=J.getEngine())==null?void 0:pa.name)==null?void 0:ha.toLowerCase())==="blink";var Aa=require("uuid");var Jr=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Jr||{});function yo(){if(F&&window){let a=window.location.hostname;return a==="localhost"||a==="127.0.0.1"?"LOCAL":a.includes("app.100ms.live")?"HMS":"CUSTOM"}return"CUSTOM"}var rt=yo();var ka=require("uuid");var E={WebSocketConnectionErrors:{FAILED_TO_CONNECT:1e3,WEBSOCKET_CONNECTION_LOST:1003,ABNORMAL_CLOSE:1006},APIErrors:{SERVER_ERRORS:2e3,INIT_CONFIG_NOT_AVAILABLE:2002,ENDPOINT_UNREACHABLE:2003,INVALID_TOKEN_FORMAT:2004},TracksErrors:{GENERIC_TRACK:3e3,CANT_ACCESS_CAPTURE_DEVICE:3001,DEVICE_NOT_AVAILABLE:3002,DEVICE_IN_USE:3003,DEVICE_LOST_MIDWAY:3004,NOTHING_TO_RETURN:3005,INVALID_VIDEO_SETTINGS:3006,CODEC_CHANGE_NOT_PERMITTED:3007,AUTOPLAY_ERROR:3008,OVER_CONSTRAINED:3009,NO_AUDIO_DETECTED:3010,SYSTEM_DENIED_PERMISSION:3011,CURRENT_TAB_NOT_SHARED:3012,AUDIO_PLAYBACK_ERROR:3013,SELECTED_DEVICE_MISSING:3014,NO_DATA:3015},WebrtcErrors:{CREATE_OFFER_FAILED:4001,CREATE_ANSWER_FAILED:4002,SET_LOCAL_DESCRIPTION_FAILED:4003,SET_REMOTE_DESCRIPTION_FAILED:4004,ICE_FAILURE:4005,ICE_DISCONNECTED:4006,STATS_FAILED:4007},WebsocketMethodErrors:{SERVER_ERRORS:5e3,ALREADY_JOINED:5001,CANNOT_JOIN_PREVIEW_IN_PROGRESS:5002},GenericErrors:{NOT_CONNECTED:6e3,SIGNALLING:6001,UNKNOWN:6002,NOT_READY:6003,JSON_PARSING_FAILED:6004,TRACK_METADATA_MISSING:6005,RTC_TRACK_MISSING:6006,PEER_METADATA_MISSING:6007,INVALID_ROLE:6008,PREVIEW_IN_PROGRESS:6009,MISSING_MEDIADEVICES:6010,MISSING_RTCPEERCONNECTION:6011,LOCAL_STORAGE_ACCESS_DENIED:6012,VALIDATION_FAILED:6013},PlaylistErrors:{NO_ENTRY_TO_PLAY:8001,NO_ENTRY_IS_PLAYING:8002}};var k=class a extends Error{constructor(t,i,r,s,n,o=!1){super(s);this.code=t;this.name=i;this.message=s;this.description=n;this.isTerminal=o;Object.setPrototypeOf(this,a.prototype),this.action=r.toString()}toAnalyticsProperties(){return{error_name:this.name,error_code:this.code,error_message:this.message,error_description:this.description,action:this.action,is_terminal:this.isTerminal}}addNativeError(t){this.nativeError=t}toString(){var t;return`{
1
+ "use strict";var oo=Object.create;var bt=Object.defineProperty,co=Object.defineProperties,lo=Object.getOwnPropertyDescriptor,uo=Object.getOwnPropertyDescriptors,po=Object.getOwnPropertyNames,Si=Object.getOwnPropertySymbols,ta=Object.getPrototypeOf,Gr=Object.prototype.hasOwnProperty,ia=Object.prototype.propertyIsEnumerable,ho=Reflect.get;var ea=(a,e,t)=>e in a?bt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,m=(a,e)=>{for(var t in e||(e={}))Gr.call(e,t)&&ea(a,t,e[t]);if(Si)for(var t of Si(e))ia.call(e,t)&&ea(a,t,e[t]);return a},M=(a,e)=>co(a,uo(e));var $r=(a,e)=>{var t={};for(var i in a)Gr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&Si)for(var i of Si(a))e.indexOf(i)<0&&ia.call(a,i)&&(t[i]=a[i]);return t};var mo=(a,e)=>()=>{try{return e||a((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},So=(a,e)=>{for(var t in e)bt(a,t,{get:e[t],enumerable:!0})},ra=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of po(e))!Gr.call(a,r)&&r!==t&&bt(a,r,{get:()=>e[r],enumerable:!(i=lo(e,r))||i.enumerable});return a};var We=(a,e,t)=>(t=a!=null?oo(ta(a)):{},ra(e||!a||!a.__esModule?bt(t,"default",{value:a,enumerable:!0}):t,a)),go=a=>ra(bt({},"__esModule",{value:!0}),a);var me=(a,e,t)=>ho(ta(a),t,e);var c=(a,e,t)=>new Promise((i,r)=>{var s=l=>{try{o(t.next(l))}catch(u){r(u)}},n=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(s,n);o((t=t.apply(a,e)).next())});var Zr=mo((uu,Eo)=>{Eo.exports={version:"0.15.2-alpha.0",license:"MIT",repository:{type:"git",url:"https://github.com/100mslive/web-sdks.git",directory:"packages/hms-video-store"},main:"dist/index.cjs.js",module:"dist/index.js",typings:"dist/index.d.ts",files:["dist"],engines:{node:">=12"},exports:{".":{require:"./dist/index.cjs.js",import:"./dist/index.js",default:"./dist/index.js"}},sideEffects:!1,scripts:{prestart:"rm -rf dist && yarn types:build",start:'concurrently "yarn dev" "yarn types"',dev:"node ../../scripts/dev","build:only":"node ../../scripts/build",build:"yarn build:only && yarn types:build",types:"tsc -w","types:build":"tsc -p tsconfig.json",format:"prettier --write src/**/*.ts",test:"jest --maxWorkers=1","test:watch":"jest --watch","test:coverage":"jest --coverage",lint:"eslint -c ../../.eslintrc .","lint:fix":"yarn lint --fix",prepare:"yarn build",size:"size-limit",analyze:"size-limit --why",docs:"rm -rf ./docs && typedoc && rm -f ./docs/README.md && mkdir ./docs/home &&mv ./docs/modules.md ./docs/home/content.md && node ../../scripts/docs-store && npx prettier --write './docs/**/*'"},name:"@100mslive/hms-video-store",author:"100ms",dependencies:{eventemitter2:"^6.4.9",immer:"^9.0.6","lodash.isequal":"^4.5.0",reselect:"4.0.0","sdp-transform":"^2.14.1","ua-parser-js":"^2.0.6",uuid:"^11.1.1","webrtc-adapter":"^8.0.0",zustand:"3.5.7"},devDependencies:{"@types/dom-screen-wake-lock":"^1.0.1","@types/lodash.isequal":"^4.5.8","@types/sdp-transform":"^2.4.4","@types/ua-parser-js":"^0.7.39","@types/uuid":"^8.3.0","jest-canvas-mock":"^2.3.1","jsdom-worker":"^0.3.0",tslib:"^2.2.0"},description:"@100mslive Core SDK which abstracts the complexities of webRTC while providing a reactive store for data management with a unidirectional data flow",keywords:["video","webrtc","conferencing","100ms"],gitHead:"d0c8c72bbabc260df939f332183a33df018d665b"}});var Pl={};So(Pl,{ConnectivityState:()=>Nn,DeviceType:()=>ls,Diagnostics:()=>gt,DomainCategory:()=>Jr,EventBus:()=>Tt,HLSPlaylistType:()=>ns,HLSStreamType:()=>os,HMSAudioDeviceCategory:()=>Hi,HMSAudioMode:()=>Ri,HMSAudioPluginType:()=>ki,HMSLogLevel:()=>Kr,HMSMessageType:()=>sa,HMSNotificationSeverity:()=>Wr,HMSNotificationTypes:()=>Ti,HMSPeerType:()=>Ai,HMSPlaylistType:()=>qr,HMSPluginUnsupportedTypes:()=>Ei,HMSReactiveStore:()=>et,HMSRecordingState:()=>as,HMSRoomState:()=>gi,HMSStats:()=>kt,HMSTrackExceptionTrackType:()=>zr,HMSTranscriptionMode:()=>ds,HMSTranscriptionState:()=>cs,HMSVideoPluginCanvasContextType:()=>Oi,HMSVideoPluginType:()=>Ni,createDefaultStatsStore:()=>At,createDefaultStoreState:()=>It,getAudioDeviceCategory:()=>Ci,parsedUserAgent:()=>J,selectAppData:()=>Gc,selectAppDataByPath:()=>Wc,selectAudioPlaylist:()=>Ls,selectAudioPlaylistTrackByPeerID:()=>ad,selectAudioTrackByID:()=>jc,selectAudioTrackByPeerID:()=>vn,selectAudioTrackVolume:()=>Bs,selectAudioVolumeByPeerID:()=>ud,selectAuxiliaryAudioByPeerID:()=>id,selectAuxiliaryTracksByPeerID:()=>Yc,selectAvailableRoleNames:()=>Tc,selectBroadcastMessages:()=>En,selectBroadcastMessagesUnreadCount:()=>gd,selectCameraStreamByPeerID:()=>zc,selectConnectionQualities:()=>Qo,selectConnectionQualityByPeerID:()=>td,selectDegradedTracks:()=>uc,selectDevices:()=>jo,selectDidIJoinWithin:()=>Vd,selectDominantSpeaker:()=>ic,selectEffectsKey:()=>Hc,selectErrors:()=>sn,selectFullAppData:()=>qi,selectHLSState:()=>yc,selectHMSBroadcastMessages:()=>on,selectHMSMessages:()=>mt,selectHMSMessagesCount:()=>pc,selectHMSStats:()=>no,selectHandRaisedPeers:()=>Dc,selectHasPeerHandRaised:()=>Pd,selectIsAllowedToPreviewMedia:()=>wd,selectIsAllowedToPublish:()=>Ld,selectIsAllowedToSubscribe:()=>fc,selectIsAudioLocallyMuted:()=>Us,selectIsConnectedToRoom:()=>Ce,selectIsEffectsEnabled:()=>Ac,selectIsInPreview:()=>bs,selectIsLargeRoom:()=>Ic,selectIsLocalAudioEnabled:()=>rc,selectIsLocalAudioInterrupted:()=>sc,selectIsLocalAudioPluginPresent:()=>xd,selectIsLocalScreenShared:()=>ji,selectIsLocalVideoDisplayEnabled:()=>Ps,selectIsLocalVideoEnabled:()=>Ki,selectIsLocalVideoInterrupted:()=>ac,selectIsLocalVideoPluginPresent:()=>Od,selectIsLocallyMutedByPeerID:()=>dd,selectIsPeerAudioEnabled:()=>od,selectIsPeerVideoEnabled:()=>cd,selectIsRoleAllowedToPublish:()=>Dd,selectIsScreenShareLocallyMutedByPeerID:()=>ld,selectIsSomeoneScreenSharing:()=>nc,selectIsTranscriptionAllowedByMode:()=>Ad,selectIsTranscriptionEnabled:()=>gc,selectIsVBEnabled:()=>Rc,selectLocalAudioTrackID:()=>ue,selectLocalMediaSettings:()=>ks,selectLocalPeer:()=>X,selectLocalPeerID:()=>Ie,selectLocalPeerName:()=>Xo,selectLocalPeerRole:()=>ze,selectLocalPeerRoleName:()=>Zo,selectLocalTrackIDs:()=>Es,selectLocalVideoTrackID:()=>ie,selectMessageByMessageID:()=>Id,selectMessageIDsInOrder:()=>ys,selectMessagesByPeerID:()=>Td,selectMessagesByRole:()=>fd,selectMessagesMap:()=>$t,selectMessagesUnreadCountByPeerID:()=>Md,selectMessagesUnreadCountByRole:()=>vd,selectPeerAudioByID:()=>ed,selectPeerByCondition:()=>Ud,selectPeerByID:()=>se,selectPeerCount:()=>Jo,selectPeerMetadata:()=>Ed,selectPeerName:()=>bd,selectPeerNameByID:()=>qc,selectPeerScreenSharing:()=>nn,selectPeerSharingAudio:()=>oc,selectPeerSharingAudioPlaylist:()=>lc,selectPeerSharingVideoPlaylist:()=>dc,selectPeerTypeByID:()=>Kc,selectPeers:()=>Me,selectPeersByCondition:()=>Bd,selectPeersByRole:()=>yd,selectPeersByRoles:()=>kd,selectPeersMap:()=>Y,selectPeersScreenSharing:()=>cc,selectPeersWithAudioStatus:()=>Rd,selectPermissions:()=>As,selectPollByID:()=>Vs,selectPolls:()=>wc,selectPollsMap:()=>Rs,selectPreviewRole:()=>Is,selectPreviewRoleName:()=>cn,selectRTMPState:()=>Mc,selectRecentError:()=>qo,selectRecordingState:()=>vc,selectRemotePeers:()=>tc,selectRoleByRoleName:()=>Pn,selectRoleChangeRequest:()=>Cd,selectRolesMap:()=>ye,selectRoom:()=>V,selectRoomID:()=>Ko,selectRoomStartTime:()=>bc,selectRoomStarted:()=>Sc,selectRoomState:()=>oe,selectScreenAudioTrackByID:()=>Qc,selectScreenShareAudioByPeerID:()=>xs,selectScreenShareByPeerID:()=>nd,selectScreenSharesByPeerId:()=>Os,selectScreenVideoTrackByID:()=>Jc,selectScreenshareAudioVolumeByPeerID:()=>pd,selectSessionId:()=>Pc,selectSessionMetadata:()=>Lc,selectSessionStore:()=>$c,selectSimulcastLayerByTrack:()=>hd,selectSpeakers:()=>an,selectTemplateAppData:()=>Cc,selectTrackAudioByID:()=>Xc,selectTrackByID:()=>Kt,selectTracksMap:()=>_,selectTranscriptionsState:()=>kc,selectTranslationState:()=>Ec,selectUnreadHMSBroadcastMessagesCount:()=>mc,selectUnreadHMSMessagesCount:()=>hc,selectVideoPlaylist:()=>ws,selectVideoPlaylistAudioTrackByPeerID:()=>sd,selectVideoPlaylistVideoTrackByPeerID:()=>rd,selectVideoTrackByID:()=>Ns,selectVideoTrackByPeerID:()=>fn,selectWhiteboard:()=>_c,selectWhiteboards:()=>dn,simulcastMapping:()=>Ue});module.exports=go(Pl);var gi=(o=>(o.Disconnected="Disconnected",o.Preview="Preview",o.Connecting="Connecting",o.Connected="Connected",o.Reconnecting="Reconnecting",o.Disconnecting="Disconnecting",o.Failed="Failed",o))(gi||{});var It=()=>({room:{id:"",isConnected:!1,name:"",peers:[],localPeer:"",roomState:"Disconnected",recording:{browser:{running:!1},server:{running:!1},hls:{running:!1}},rtmp:{running:!1},hls:{running:!1,variants:[]},sessionId:""},peers:{},tracks:{},playlist:{audio:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1},video:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1}},messages:{byID:{},allIDs:[]},speakers:{},connectionQualities:{},settings:{audioInputDeviceId:"",audioOutputDeviceId:"",videoInputDeviceId:""},devices:{audioInput:[],audioOutput:[],videoInput:[]},roles:{},roleChangeRequests:[],errors:[],sessionStore:{},templateAppData:{},polls:{},whiteboards:{},hideLocalPeer:!1}),At=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var sa=(e=>(e.CHAT="chat",e))(sa||{});var Wr=(t=>(t.INFO="info",t.ERROR="error",t))(Wr||{}),Ti=(D=>(D.PEER_JOINED="PEER_JOINED",D.PEER_LEFT="PEER_LEFT",D.PEER_LIST="PEER_LIST",D.NEW_MESSAGE="NEW_MESSAGE",D.ERROR="ERROR",D.RECONNECTING="RECONNECTING",D.RECONNECTED="RECONNECTED",D.TRACK_ADDED="TRACK_ADDED",D.TRACK_REMOVED="TRACK_REMOVED",D.TRACK_MUTED="TRACK_MUTED",D.TRACK_UNMUTED="TRACK_UNMUTED",D.TRACK_DEGRADED="TRACK_DEGRADED",D.TRACK_RESTORED="TRACK_RESTORED",D.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",D.ROLE_UPDATED="ROLE_UPDATED",D.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",D.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",D.ROOM_ENDED="ROOM_ENDED",D.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",D.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",D.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",D.NAME_UPDATED="NAME_UPDATED",D.METADATA_UPDATED="METADATA_UPDATED",D.POLL_CREATED="POLL_CREATED",D.POLL_STARTED="POLL_STARTED",D.POLL_STOPPED="POLL_STOPPED",D.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",D.POLLS_LIST="POLLS_LIST",D.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",D.TRANSCRIPTION_STATE_UPDATED="TRANSCRIPTION_STATE_UPDATED",D.TRACK_INTERRUPTION_START="TRACK_INTERRUPTION_START",D.TRACK_INTERRUPTION_END="TRACK_INTERRUPTION_END",D))(Ti||{});var qr=(t=>(t.audio="audio",t.video="video",t))(qr||{});var I=require("reselect");function qe(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];To(s)&&(i=Rt(s)?s:i,t=Ht(s)?s:t)}return{video:t,audio:i}}function Rt(a){return a&&a.type==="audio"}function Ht(a){return a&&a.type==="video"}function To(a){return a&&a.source==="screen"}function fi(a){return a&&a.source==="audioplaylist"}function Ct(a){return a&&a.source==="videoplaylist"}function aa(a){return a?!!(a!=null&&a.degraded):!1}function tt(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function na(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function Lt(a){var r;let e=!1,t=!1,i=!1;return(r=a==null?void 0:a.publishParams)!=null&&r.allowed&&(e=a.publishParams.allowed.includes("video"),t=a.publishParams.allowed.includes("audio"),i=a.publishParams.allowed.includes("screen")),{video:e,audio:t,screen:i}}var Kr=(l=>(l[l.VERBOSE=0]="VERBOSE",l[l.DEBUG=1]="DEBUG",l[l.INFO=2]="INFO",l[l.WARN=3]="WARN",l[l.TIME=4]="TIME",l[l.TIMEEND=5]="TIMEEND",l[l.ERROR=6]="ERROR",l[l.NONE=7]="NONE",l))(Kr||{}),fo=typeof window!="undefined"&&typeof window.expect!="undefined",d=class{static v(e,...t){this.log(0,e,...t)}static d(e,...t){this.log(1,e,...t)}static i(e,...t){this.log(2,e,...t)}static w(e,...t){this.log(3,e,...t)}static e(e,...t){this.log(6,e,...t)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,t,...i){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(t,...i);break}case 1:{console.debug(t,...i);break}case 2:{console.info(t,...i);break}case 3:{console.warn(t,...i);break}case 6:{console.error(t,...i);break}case 4:{performance.mark(i[0]);break}case 5:{let r=i[0];try{let s=performance.measure(r,r);this.log(1,t,r,s==null?void 0:s.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(s){this.log(1,t,r,s)}break}}}};d.level=fo?7:0;var it=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var ma=require("ua-parser-js");var jr=new ma.UAParser,wt=null,Qr=null,F=typeof window!="undefined";if(F)try{let a=jr.getResult(),e=a.withClientHints();e&&typeof e.then=="function"?(Qr=e,Qr.then(t=>{wt=t}).catch(()=>{wt=a})):(d.d("UAParser","Client Hints not supported, using standard UA parsing"),wt=e)}catch(a){wt=jr.getResult()}var _e=()=>wt||jr.getResult(),J={getBrowser:()=>_e().browser,getOS:()=>_e().os,getDevice:()=>_e().device,getCPU:()=>_e().cpu,getEngine:()=>_e().engine,getUA:()=>_e().ua,getResult:_e,withClientHints:()=>Qr||Promise.resolve(_e())},oa,Ke=typeof window=="undefined"&&!((oa=J.getBrowser().name)!=null&&oa.toLowerCase().includes("electron"));var vo=()=>!Ke,Nl=vo(),Sa=()=>J.getDevice().type==="mobile",Mo=()=>{var a;return typeof navigator!="undefined"&&navigator.maxTouchPoints>1&&!!((a=J.getOS().name)!=null&&a.toLowerCase().includes("mac"))},vi=()=>{let a=J.getDevice().type;return a==="mobile"||a==="tablet"||Mo()},ga=()=>typeof document!="undefined"&&document.hidden,Ta=()=>{var a;return((a=J.getOS().name)==null?void 0:a.toLowerCase())==="ios"},ca,da,fa=(da=(ca=J.getBrowser())==null?void 0:ca.name)==null?void 0:da.toLowerCase().includes("safari"),la,ua,va=((ua=(la=J.getBrowser())==null?void 0:la.name)==null?void 0:ua.toLowerCase())==="firefox",pa,ha,Ma=((ha=(pa=J.getEngine())==null?void 0:pa.name)==null?void 0:ha.toLowerCase())==="blink";var Aa=require("uuid");var Jr=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Jr||{});function yo(){if(F&&window){let a=window.location.hostname;return a==="localhost"||a==="127.0.0.1"?"LOCAL":a.includes("app.100ms.live")?"HMS":"CUSTOM"}return"CUSTOM"}var rt=yo();var ka=require("uuid");var E={WebSocketConnectionErrors:{FAILED_TO_CONNECT:1e3,WEBSOCKET_CONNECTION_LOST:1003,ABNORMAL_CLOSE:1006},APIErrors:{SERVER_ERRORS:2e3,INIT_CONFIG_NOT_AVAILABLE:2002,ENDPOINT_UNREACHABLE:2003,INVALID_TOKEN_FORMAT:2004},TracksErrors:{GENERIC_TRACK:3e3,CANT_ACCESS_CAPTURE_DEVICE:3001,DEVICE_NOT_AVAILABLE:3002,DEVICE_IN_USE:3003,DEVICE_LOST_MIDWAY:3004,NOTHING_TO_RETURN:3005,INVALID_VIDEO_SETTINGS:3006,CODEC_CHANGE_NOT_PERMITTED:3007,AUTOPLAY_ERROR:3008,OVER_CONSTRAINED:3009,NO_AUDIO_DETECTED:3010,SYSTEM_DENIED_PERMISSION:3011,CURRENT_TAB_NOT_SHARED:3012,AUDIO_PLAYBACK_ERROR:3013,SELECTED_DEVICE_MISSING:3014,NO_DATA:3015},WebrtcErrors:{CREATE_OFFER_FAILED:4001,CREATE_ANSWER_FAILED:4002,SET_LOCAL_DESCRIPTION_FAILED:4003,SET_REMOTE_DESCRIPTION_FAILED:4004,ICE_FAILURE:4005,ICE_DISCONNECTED:4006,STATS_FAILED:4007},WebsocketMethodErrors:{SERVER_ERRORS:5e3,ALREADY_JOINED:5001,CANNOT_JOIN_PREVIEW_IN_PROGRESS:5002},GenericErrors:{NOT_CONNECTED:6e3,SIGNALLING:6001,UNKNOWN:6002,NOT_READY:6003,JSON_PARSING_FAILED:6004,TRACK_METADATA_MISSING:6005,RTC_TRACK_MISSING:6006,PEER_METADATA_MISSING:6007,INVALID_ROLE:6008,PREVIEW_IN_PROGRESS:6009,MISSING_MEDIADEVICES:6010,MISSING_RTCPEERCONNECTION:6011,LOCAL_STORAGE_ACCESS_DENIED:6012,VALIDATION_FAILED:6013},PlaylistErrors:{NO_ENTRY_TO_PLAY:8001,NO_ENTRY_IS_PLAYING:8002}};var k=class a extends Error{constructor(t,i,r,s,n,o=!1){super(s);this.code=t;this.name=i;this.message=s;this.description=n;this.isTerminal=o;Object.setPrototypeOf(this,a.prototype),this.action=r.toString()}toAnalyticsProperties(){return{error_name:this.name,error_code:this.code,error_message:this.message,error_description:this.description,action:this.action,is_terminal:this.isTerminal}}addNativeError(t){this.nativeError=t}toString(){var t;return`{
2
2
  code: ${this.code};
3
3
  name: ${this.name};
4
4
  action: ${this.action};
@@ -77,7 +77,7 @@
77
77
  Setting layer field to=${t}`)}setVideoLayer(t,i,r,s){return c(this,null,function*(){var o;d.d(`[Remote stream] ${r}
78
78
  streamId=${this.id}
79
79
  trackId=${i}
80
- source: ${s} request ${t} layer`),this.setVideoLayerLocally(t,r,s);let n=++this.seq;this.videoRequest={layer:t,seq:n};try{let l=yield this.connection.sendOverApiDataChannelWithResponse({params:{max_spatial_layer:this.video,track_id:i},method:"prefer-video-track-state"});return this.isApplied(l,this.video===t)&&(this.confirmedVideo=t),l}finally{((o=this.videoRequest)==null?void 0:o.seq)===n&&(this.videoRequest=void 0)}})}isVideoLayerSettled(t){return this.videoRequest?this.videoRequest.layer===t:this.confirmedVideo===t}getSimulcastLayer(){return this.video}getVideoLayer(){return this.video}isAudioSubscribed(){return this.audio}};var ja=a=>{let e=a.kind||a.mediaType;return!e||e==="video"},Qa=(a,e)=>!e||!a.trackIdentifier?!0:a.trackIdentifier===e,Ja=a=>{var e,t;return{frames:a.frames,framesPerSecond:a.framesPerSecond,framesDropped:a.framesDropped,width:(e=a.width)!=null?e:a.frameWidth,height:(t=a.height)!=null?t:a.frameHeight,timestamp:a.timestamp}},_o=(a,e)=>{if(!(!W(a.frames)||!W(e==null?void 0:e.sourceFrames)||!W(a.timestamp)||!W(e==null?void 0:e.sourceTimestamp)))return Ui(a.frames,e==null?void 0:e.sourceFrames,a.timestamp,e==null?void 0:e.sourceTimestamp)*1e3},No=(a,e)=>W(a.framesPerSecond)?a.framesPerSecond:_o(a,e),za=a=>{if(a)return{none:a.none||0,cpu:a.cpu||0,bandwidth:a.bandwidth||0,other:a.other||0}},Oo=(a,e)=>{var i,r,s;if(!a)return;let t=(s=(r=(i=e.transceiver)==null?void 0:i.sender)==null?void 0:r.track)==null?void 0:s.id;for(let n of a.values()){if(n.type!=="track")continue;let o=n;if(ja(o)&&Qa(o,t))return Ja(o)}},xo=(a,e)=>Bo(a,e)||Oo(a,e),Ya=(a,e,t,i)=>c(null,null,function*(){var n;let r,s={};if((n=e.transceiver)!=null&&n.sender.track){try{r=yield e.transceiver.sender.getStats();let o={},l={},u={},p=e.type==="video"?xo(r,e):void 0;r==null||r.forEach(h=>{switch(h.type){case"outbound-rtp":l[h.id]=h;break;case"remote-inbound-rtp":u[h.ssrc]=h;break;case"codec":o[h.id]=h.mimeType;break;default:break}}),Object.keys(m({},l)).forEach(h=>{var De,Et,Pt,O,Q,Xs,Zs;let T=(De=l[h])==null?void 0:De.codecId,g=T?o[T]:void 0,f;g&&(f=g.substring(g.indexOf("/")+1));let P=M(m({},l[h]),{rid:(Et=l[h])==null?void 0:Et.rid}),v=za(P.qualityLimitationDurations),A=M(m({},P),{qualityLimitationDurations:v}),$=A,ce=(Zs=(Xs=A.trackIdentifier)!=null?Xs:(Q=(O=(Pt=e.transceiver)==null?void 0:Pt.sender)==null?void 0:O.track)==null?void 0:Q.id)!=null?Zs:e.trackId,B=u[P.ssrc],de=e.type==="video"?Fo(p,A.framesEncoded,i==null?void 0:i[h]):{};s[h]=M(m(m({},A),de),{trackIdentifier:ce,bitrate:lt("bytesSent",$,i==null?void 0:i[h]),packetsLost:B==null?void 0:B.packetsLost,jitter:B==null?void 0:B.jitter,roundTripTime:B==null?void 0:B.roundTripTime,totalRoundTripTime:B==null?void 0:B.totalRoundTripTime,peerName:t,peerID:e.peerId,enabled:e.enabled,codec:f})})}catch(o){a.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("TRACK",`Error getting local track stats ${e.trackId} - ${o.message}`))),d.w("[HMSWebrtcStats]","Error in getting local track stats",e,o,o.name)}return s}}),Xa=(a,e,t,i)=>c(null,null,function*(){var u,p,h,T,g,f;let r;try{r=yield(u=e.transceiver)==null?void 0:u.receiver.getStats()}catch(P){a.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("TRACK",`Error getting remote track stats ${e.trackId} - ${P.message}`))),d.w("[HMSWebrtcStats]","Error in getting remote track stats",e,P)}let s=Uo(r),n=s,o=lt("bytesReceived",n,i),l=fs("packetsLost",n,i);return s!=null&&s.remote&&Object.assign(s.remote,{packetsLostRate:fs("packetsLost",s.remote,i==null?void 0:i.remote)}),s&&M(m({},s),{trackIdentifier:(f=(g=s.trackIdentifier)!=null?g:(T=(h=(p=e.transceiver)==null?void 0:p.receiver)==null?void 0:h.track)==null?void 0:T.id)!=null?f:e.trackId,bitrate:o,packetsLostRate:l,peerID:e.peerId,enabled:e.enabled,peerName:t,codec:s.codec})}),Uo=a=>{let e,t,i={};a==null||a.forEach(o=>{switch(o.type){case"inbound-rtp":e=o;break;case"outbound-rtp":e=o;break;case"remote-inbound-rtp":t=o;break;case"codec":i[o.id]=o.mimeType;break;default:break}});let r=e!=null&&e.codecId?i[e.codecId]:void 0,s;if(r&&(s=r.substring(r.indexOf("/")+1)),!e)return;let n=za(e.qualityLimitationDurations);return Object.assign({},e,m({remote:t&&m({},t),codec:s},n?{qualityLimitationDurations:n}:{}))},Bo=(a,e)=>{var i,r,s;if(!a)return;let t=(s=(r=(i=e.transceiver)==null?void 0:i.sender)==null?void 0:r.track)==null?void 0:s.id;for(let n of a.values()){if(n.type!=="media-source")continue;let o=n;if(ja(o)&&Qa(o,t))return Ja(o)}},Vo=(a,e,t,i)=>{if(!W(a)||!W(e)||!W(t)||!W(i))return;let r=a-t,s=e-i;return Math.max(0,r-s)},Fo=(a,e,t)=>{let i=Vo(a==null?void 0:a.frames,e,t==null?void 0:t.sourceFrames,t==null?void 0:t.framesEncoded);return{sourceFrameWidth:a==null?void 0:a.width,sourceFrameHeight:a==null?void 0:a.height,sourceFrames:a==null?void 0:a.frames,sourceFramesDropped:i,sourceFramesPerSecond:a?No(a,t):void 0,sourceTimestamp:a==null?void 0:a.timestamp,sourceStatsAvailable:!!a}},Go=a=>{let e=0;return a==null||a.forEach(t=>{t.type==="outbound-rtp"&&(e+=t.bytesSent||0)}),e},$o=(a,e)=>Object.assign({},a,{localCandidate:e==null?void 0:e.get(a.localCandidateId),remoteCandidate:e==null?void 0:e.get(a.remoteCandidateId)}),vs=a=>{let e=a==null?void 0:a.localCandidate;if(e)return e.relayProtocol?`relay(${e.relayProtocol})`:e.candidateType},Ms=(a,e,t)=>{var n,o;let i=Wo(e);if(!i)return;let r=$o(i,e);if(a==="publish"){let l=Go(e),u=(n=t==null?void 0:t.publish)==null?void 0:n.outboundRtpBytesSent,p=u!==void 0?lt("bytesSent",{bytesSent:l,timestamp:r.timestamp},{bytesSent:u,timestamp:(o=t==null?void 0:t.publish)==null?void 0:o.timestamp}):0;return Object.assign(r,{bitrate:p,outboundRtpBytesSent:l})}let s=lt("bytesReceived",r,t&&t[a]);return Object.assign(r,{bitrate:s})},Wo=a=>{let e;return a==null||a.forEach(t=>{t.type==="transport"&&(e=a==null?void 0:a.get(t.selectedCandidatePairId))}),e||a==null||a.forEach(t=>{t.type==="candidate-pair"&&t.selected&&(e=t)}),e},Za=a=>{let e={packetsLost:0,jitter:0};return a==null||a.forEach(t=>{t.packetsLost&&(e.packetsLost+=t.packetsLost),t.jitter>e.jitter&&(e.jitter=t.jitter)}),e},en=(a,e)=>Array.from(new Set(a.concat(e))),lt=(a,e,t)=>fs(a,e,t)*8,fs=(a,e,t)=>{let i=e&&e[a],r=t?t[a]:null;return[e,t,W(i),W(r)].every(n=>!!n)?Ui(i,r,e==null?void 0:e.timestamp,t==null?void 0:t.timestamp)*1e3:0},Ui=(a,e,t,i)=>W(a)&&W(e)&&t&&i?(a-e)/(t-i):0;var Bi=class{constructor(e,t,i,r){this.store=e;this.eventBus=t;this.publishConnection=i;this.subscribeConnection=r;this.TAG="[HMSWebrtcStats]";this.peerStats={};this.remoteTrackStats={};this.localTrackStats={};this.getLocalPeerStats=()=>this.peerStats[this.localPeerID];this.getRemoteTrackStats=e=>this.remoteTrackStats[e];this.getAllRemoteTracksStats=()=>this.remoteTrackStats;this.getLocalTrackStats=()=>this.localTrackStats;this.updateStats=()=>c(this,null,function*(){yield this.updateLocalPeerStats(),yield this.updateLocalTrackStats(),yield this.updateRemoteTrackStats()});this.updateLocalPeerStats=()=>c(this,null,function*(){var p,h,T,g;let e=this.getLocalPeerStats(),t;try{t=yield(p=this.publishConnection)==null?void 0:p.getStats()}catch(f){this.eventBus.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("PUBLISH",f.message))),d.w(this.TAG,"Error in getting publish stats",f)}let i=t&&Ms("publish",t,e),r;try{r=yield(h=this.subscribeConnection)==null?void 0:h.getStats()}catch(f){this.eventBus.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("SUBSCRIBE",f.message))),d.w(this.TAG,"Error in getting subscribe stats",f)}let s=r&&Ms("subscribe",r,e),{packetsLost:n,jitter:o}=Za(r),l=Ui(n,(T=e==null?void 0:e.subscribe)==null?void 0:T.packetsLost,s==null?void 0:s.timestamp,(g=e==null?void 0:e.subscribe)==null?void 0:g.timestamp),u=s&&Object.assign(s,{packetsLostRate:l,jitter:o,packetsLost:n});this.peerStats[this.localPeerID]={publish:i,subscribe:u}});this.updateRemoteTrackStats=()=>c(this,null,function*(){var i;let e=Array.from(this.store.getTracksMap().values()).filter(r=>r instanceof x||r instanceof le),t=e.map(r=>r.trackId);Object.keys(this.remoteTrackStats).forEach(r=>{t.includes(r)||delete this.remoteTrackStats[r]});for(let r of e){let s=r.peerId&&((i=this.store.getPeerById(r.peerId))==null?void 0:i.name),n=this.getRemoteTrackStats(r.trackId),o=yield Xa(this.eventBus,r,s,n);o&&(this.remoteTrackStats[r.trackId]=o)}});this.updateLocalTrackStats=()=>c(this,null,function*(){var i;let e=this.store.getLocalPeerTracks().reduce((r,s)=>(r[s.getTrackIDBeingSent()]=s,r),{}),t=en(Object.keys(this.localTrackStats),Object.keys(e));for(let r of t){let s=e[r];if(s){let n=(i=this.store.getLocalPeer())==null?void 0:i.name,o=yield Ya(this.eventBus,s,n,this.localTrackStats[r]);o&&(this.localTrackStats[r]=o)}else delete this.localTrackStats[r]}});var s;this.localPeerID=(s=this.store.getLocalPeer())==null?void 0:s.peerId}setPeerConnections({publish:e,subscribe:t}){this.publishConnection=e,this.subscribeConnection=t}getPublishPeerConnection(){return this.publishConnection}getSubscribePeerConnection(){return this.subscribeConnection}};var Vi=class{constructor(e,t){this.store=e;this.eventBus=t;this.TAG="[HMSWebrtcInternals]";this.interval=1e3;this.isMonitored=!1;this.handleStatsUpdate=()=>c(this,null,function*(){var e;yield(e=this.hmsStats)==null?void 0:e.updateStats(),this.hmsStats&&this.eventBus.statsUpdate.publish(this.hmsStats)})}getCurrentStats(){return this.hmsStats}getPublishPeerConnection(){var e;return(e=this.hmsStats)==null?void 0:e.getPublishPeerConnection()}getSubscribePeerConnection(){var e;return(e=this.hmsStats)==null?void 0:e.getSubscribePeerConnection()}onStatsChange(e){return this.eventBus.statsUpdate.subscribe(e),()=>{this.eventBus.statsUpdate.unsubscribe(e)}}setPeerConnections({publish:e,subscribe:t}){this.hmsStats?this.hmsStats.setPeerConnections({publish:e,subscribe:t}):this.hmsStats=new Bi(this.store,this.eventBus,e,t)}start(){return c(this,null,function*(){if(this.isMonitored){d.d(this.TAG,"Already started");return}this.stop(),this.isMonitored=!0,d.d(this.TAG,"Starting Webrtc Stats Monitor"),this.startLoop().then(()=>d.d(this.TAG,"Stopping Webrtc Stats Monitor")).catch(e=>{this.eventBus.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("PUBLISH",e.message))),d.e(this.TAG,e.message)})})}stop(){this.isMonitored=!1}startLoop(){return c(this,null,function*(){for(;this.isMonitored;)yield this.handleStatsUpdate(),yield te(this.interval)})}cleanup(){this.stop(),this.eventBus.statsUpdate.removeAllListeners()}};var ut=class{constructor({peerId:e,name:t,isLocal:i,customerUserId:r,metadata:s,role:n,joinedAt:o,groups:l,realtime:u,type:p}){this.customerUserId="";this.metadata="";this.auxiliaryTracks=[];this.name=t,this.peerId=e,this.isLocal=i,this.customerUserId=r,this.metadata=s,this.joinedAt=o,this.groups=l,this.realtime=u,this.type=p,n&&(this.role=n)}get isHandRaised(){var e;return!!((e=this.groups)!=null&&e.includes(He))}updateRole(e){this.role=e}updateName(e){this.name=e}updateNetworkQuality(e){this.networkQuality=e}updateMetadata(e){this.metadata=e}updateGroups(e){this.groups=e}toString(){var e,t,i,r;return`{
80
+ source: ${s} request ${t} layer`),this.setVideoLayerLocally(t,r,s);let n=++this.seq;this.videoRequest={layer:t,seq:n};try{let l=yield this.connection.sendOverApiDataChannelWithResponse({params:{max_spatial_layer:this.video,track_id:i},method:"prefer-video-track-state"});return this.isApplied(l,this.video===t)&&(this.confirmedVideo=t),l}finally{((o=this.videoRequest)==null?void 0:o.seq)===n&&(this.videoRequest=void 0)}})}isVideoLayerSettled(t){return this.videoRequest?this.videoRequest.layer===t:this.confirmedVideo===t}getSimulcastLayer(){return this.video}getVideoLayer(){return this.video}isAudioSubscribed(){return this.audio}};var ja=a=>{let e=a.kind||a.mediaType;return!e||e==="video"},Qa=(a,e)=>!e||!a.trackIdentifier?!0:a.trackIdentifier===e,Ja=a=>{var e,t;return{frames:a.frames,framesPerSecond:a.framesPerSecond,framesDropped:a.framesDropped,width:(e=a.width)!=null?e:a.frameWidth,height:(t=a.height)!=null?t:a.frameHeight,timestamp:a.timestamp}},_o=(a,e)=>{if(!(!W(a.frames)||!W(e==null?void 0:e.sourceFrames)||!W(a.timestamp)||!W(e==null?void 0:e.sourceTimestamp)))return Ui(a.frames,e==null?void 0:e.sourceFrames,a.timestamp,e==null?void 0:e.sourceTimestamp)*1e3},No=(a,e)=>W(a.framesPerSecond)?a.framesPerSecond:_o(a,e),za=a=>{if(a)return{none:a.none||0,cpu:a.cpu||0,bandwidth:a.bandwidth||0,other:a.other||0}},Oo=(a,e)=>{var i,r,s;if(!a)return;let t=(s=(r=(i=e.transceiver)==null?void 0:i.sender)==null?void 0:r.track)==null?void 0:s.id;for(let n of a.values()){if(n.type!=="track")continue;let o=n;if(ja(o)&&Qa(o,t))return Ja(o)}},xo=(a,e)=>Bo(a,e)||Oo(a,e),Ya=(a,e,t,i)=>c(null,null,function*(){var n;let r,s={};if((n=e.transceiver)!=null&&n.sender.track){try{r=yield e.transceiver.sender.getStats();let o={},l={},u={},p=e.type==="video"?xo(r,e):void 0;r==null||r.forEach(h=>{switch(h.type){case"outbound-rtp":l[h.id]=h;break;case"remote-inbound-rtp":u[h.ssrc]=h;break;case"codec":o[h.id]=h.mimeType;break;default:break}}),Object.keys(m({},l)).forEach(h=>{var De,Et,Pt,O,Q,Xs,Zs;let T=(De=l[h])==null?void 0:De.codecId,g=T?o[T]:void 0,f;g&&(f=g.substring(g.indexOf("/")+1));let P=M(m({},l[h]),{rid:(Et=l[h])==null?void 0:Et.rid}),v=za(P.qualityLimitationDurations),R=M(m({},P),{qualityLimitationDurations:v}),$=R,ce=(Zs=(Xs=R.trackIdentifier)!=null?Xs:(Q=(O=(Pt=e.transceiver)==null?void 0:Pt.sender)==null?void 0:O.track)==null?void 0:Q.id)!=null?Zs:e.trackId,B=u[P.ssrc],de=e.type==="video"?Fo(p,R.framesEncoded,i==null?void 0:i[h]):{};s[h]=M(m(m({},R),de),{trackIdentifier:ce,bitrate:lt("bytesSent",$,i==null?void 0:i[h]),packetsLost:B==null?void 0:B.packetsLost,jitter:B==null?void 0:B.jitter,roundTripTime:B==null?void 0:B.roundTripTime,totalRoundTripTime:B==null?void 0:B.totalRoundTripTime,peerName:t,peerID:e.peerId,enabled:e.enabled,codec:f})})}catch(o){a.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("TRACK",`Error getting local track stats ${e.trackId} - ${o.message}`))),d.w("[HMSWebrtcStats]","Error in getting local track stats",e,o,o.name)}return s}}),Xa=(a,e,t,i)=>c(null,null,function*(){var u,p,h,T,g,f;let r;try{r=yield(u=e.transceiver)==null?void 0:u.receiver.getStats()}catch(P){a.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("TRACK",`Error getting remote track stats ${e.trackId} - ${P.message}`))),d.w("[HMSWebrtcStats]","Error in getting remote track stats",e,P)}let s=Uo(r),n=s,o=lt("bytesReceived",n,i),l=fs("packetsLost",n,i);return s!=null&&s.remote&&Object.assign(s.remote,{packetsLostRate:fs("packetsLost",s.remote,i==null?void 0:i.remote)}),s&&M(m({},s),{trackIdentifier:(f=(g=s.trackIdentifier)!=null?g:(T=(h=(p=e.transceiver)==null?void 0:p.receiver)==null?void 0:h.track)==null?void 0:T.id)!=null?f:e.trackId,bitrate:o,packetsLostRate:l,peerID:e.peerId,enabled:e.enabled,peerName:t,codec:s.codec})}),Uo=a=>{let e,t,i={};a==null||a.forEach(o=>{switch(o.type){case"inbound-rtp":e=o;break;case"outbound-rtp":e=o;break;case"remote-inbound-rtp":t=o;break;case"codec":i[o.id]=o.mimeType;break;default:break}});let r=e!=null&&e.codecId?i[e.codecId]:void 0,s;if(r&&(s=r.substring(r.indexOf("/")+1)),!e)return;let n=za(e.qualityLimitationDurations);return Object.assign({},e,m({remote:t&&m({},t),codec:s},n?{qualityLimitationDurations:n}:{}))},Bo=(a,e)=>{var i,r,s;if(!a)return;let t=(s=(r=(i=e.transceiver)==null?void 0:i.sender)==null?void 0:r.track)==null?void 0:s.id;for(let n of a.values()){if(n.type!=="media-source")continue;let o=n;if(ja(o)&&Qa(o,t))return Ja(o)}},Vo=(a,e,t,i)=>{if(!W(a)||!W(e)||!W(t)||!W(i))return;let r=a-t,s=e-i;return Math.max(0,r-s)},Fo=(a,e,t)=>{let i=Vo(a==null?void 0:a.frames,e,t==null?void 0:t.sourceFrames,t==null?void 0:t.framesEncoded);return{sourceFrameWidth:a==null?void 0:a.width,sourceFrameHeight:a==null?void 0:a.height,sourceFrames:a==null?void 0:a.frames,sourceFramesDropped:i,sourceFramesPerSecond:a?No(a,t):void 0,sourceTimestamp:a==null?void 0:a.timestamp,sourceStatsAvailable:!!a}},Go=a=>{let e=0;return a==null||a.forEach(t=>{t.type==="outbound-rtp"&&(e+=t.bytesSent||0)}),e},$o=(a,e)=>Object.assign({},a,{localCandidate:e==null?void 0:e.get(a.localCandidateId),remoteCandidate:e==null?void 0:e.get(a.remoteCandidateId)}),vs=a=>{let e=a==null?void 0:a.localCandidate;if(e)return e.relayProtocol?`relay(${e.relayProtocol})`:e.candidateType},Ms=(a,e,t)=>{var n,o;let i=Wo(e);if(!i)return;let r=$o(i,e);if(a==="publish"){let l=Go(e),u=(n=t==null?void 0:t.publish)==null?void 0:n.outboundRtpBytesSent,p=u!==void 0?lt("bytesSent",{bytesSent:l,timestamp:r.timestamp},{bytesSent:u,timestamp:(o=t==null?void 0:t.publish)==null?void 0:o.timestamp}):0;return Object.assign(r,{bitrate:p,outboundRtpBytesSent:l})}let s=lt("bytesReceived",r,t&&t[a]);return Object.assign(r,{bitrate:s})},Wo=a=>{let e;return a==null||a.forEach(t=>{t.type==="transport"&&(e=a==null?void 0:a.get(t.selectedCandidatePairId))}),e||a==null||a.forEach(t=>{t.type==="candidate-pair"&&t.selected&&(e=t)}),e},Za=a=>{let e={packetsLost:0,jitter:0};return a==null||a.forEach(t=>{t.packetsLost&&(e.packetsLost+=t.packetsLost),t.jitter>e.jitter&&(e.jitter=t.jitter)}),e},en=(a,e)=>Array.from(new Set(a.concat(e))),lt=(a,e,t)=>fs(a,e,t)*8,fs=(a,e,t)=>{let i=e&&e[a],r=t?t[a]:null;return[e,t,W(i),W(r)].every(n=>!!n)?Ui(i,r,e==null?void 0:e.timestamp,t==null?void 0:t.timestamp)*1e3:0},Ui=(a,e,t,i)=>W(a)&&W(e)&&t&&i?(a-e)/(t-i):0;var Bi=class{constructor(e,t,i,r){this.store=e;this.eventBus=t;this.publishConnection=i;this.subscribeConnection=r;this.TAG="[HMSWebrtcStats]";this.peerStats={};this.remoteTrackStats={};this.localTrackStats={};this.getLocalPeerStats=()=>this.peerStats[this.localPeerID];this.getRemoteTrackStats=e=>this.remoteTrackStats[e];this.getAllRemoteTracksStats=()=>this.remoteTrackStats;this.getLocalTrackStats=()=>this.localTrackStats;this.updateStats=()=>c(this,null,function*(){yield this.updateLocalPeerStats(),yield this.updateLocalTrackStats(),yield this.updateRemoteTrackStats()});this.updateLocalPeerStats=()=>c(this,null,function*(){var p,h,T,g;let e=this.getLocalPeerStats(),t;try{t=yield(p=this.publishConnection)==null?void 0:p.getStats()}catch(f){this.eventBus.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("PUBLISH",f.message))),d.w(this.TAG,"Error in getting publish stats",f)}let i=t&&Ms("publish",t,e),r;try{r=yield(h=this.subscribeConnection)==null?void 0:h.getStats()}catch(f){this.eventBus.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("SUBSCRIBE",f.message))),d.w(this.TAG,"Error in getting subscribe stats",f)}let s=r&&Ms("subscribe",r,e),{packetsLost:n,jitter:o}=Za(r),l=Ui(n,(T=e==null?void 0:e.subscribe)==null?void 0:T.packetsLost,s==null?void 0:s.timestamp,(g=e==null?void 0:e.subscribe)==null?void 0:g.timestamp),u=s&&Object.assign(s,{packetsLostRate:l,jitter:o,packetsLost:n});this.peerStats[this.localPeerID]={publish:i,subscribe:u}});this.updateRemoteTrackStats=()=>c(this,null,function*(){var i;let e=Array.from(this.store.getTracksMap().values()).filter(r=>r instanceof x||r instanceof le),t=e.map(r=>r.trackId);Object.keys(this.remoteTrackStats).forEach(r=>{t.includes(r)||delete this.remoteTrackStats[r]});for(let r of e){let s=r.peerId&&((i=this.store.getPeerById(r.peerId))==null?void 0:i.name),n=this.getRemoteTrackStats(r.trackId),o=yield Xa(this.eventBus,r,s,n);o&&(this.remoteTrackStats[r.trackId]=o)}});this.updateLocalTrackStats=()=>c(this,null,function*(){var i;let e=this.store.getLocalPeerTracks().reduce((r,s)=>(r[s.getTrackIDBeingSent()]=s,r),{}),t=en(Object.keys(this.localTrackStats),Object.keys(e));for(let r of t){let s=e[r];if(s){let n=(i=this.store.getLocalPeer())==null?void 0:i.name,o=yield Ya(this.eventBus,s,n,this.localTrackStats[r]);o&&(this.localTrackStats[r]=o)}else delete this.localTrackStats[r]}});var s;this.localPeerID=(s=this.store.getLocalPeer())==null?void 0:s.peerId}setPeerConnections({publish:e,subscribe:t}){this.publishConnection=e,this.subscribeConnection=t}getPublishPeerConnection(){return this.publishConnection}getSubscribePeerConnection(){return this.subscribeConnection}};var Vi=class{constructor(e,t){this.store=e;this.eventBus=t;this.TAG="[HMSWebrtcInternals]";this.interval=1e3;this.isMonitored=!1;this.handleStatsUpdate=()=>c(this,null,function*(){var e;yield(e=this.hmsStats)==null?void 0:e.updateStats(),this.hmsStats&&this.eventBus.statsUpdate.publish(this.hmsStats)})}getCurrentStats(){return this.hmsStats}getPublishPeerConnection(){var e;return(e=this.hmsStats)==null?void 0:e.getPublishPeerConnection()}getSubscribePeerConnection(){var e;return(e=this.hmsStats)==null?void 0:e.getSubscribePeerConnection()}onStatsChange(e){return this.eventBus.statsUpdate.subscribe(e),()=>{this.eventBus.statsUpdate.unsubscribe(e)}}setPeerConnections({publish:e,subscribe:t}){this.hmsStats?this.hmsStats.setPeerConnections({publish:e,subscribe:t}):this.hmsStats=new Bi(this.store,this.eventBus,e,t)}start(){return c(this,null,function*(){if(this.isMonitored){d.d(this.TAG,"Already started");return}this.stop(),this.isMonitored=!0,d.d(this.TAG,"Starting Webrtc Stats Monitor"),this.startLoop().then(()=>d.d(this.TAG,"Stopping Webrtc Stats Monitor")).catch(e=>{this.eventBus.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("PUBLISH",e.message))),d.e(this.TAG,e.message)})})}stop(){this.isMonitored=!1}startLoop(){return c(this,null,function*(){for(;this.isMonitored;)yield this.handleStatsUpdate(),yield te(this.interval)})}cleanup(){this.stop(),this.eventBus.statsUpdate.removeAllListeners()}};var ut=class{constructor({peerId:e,name:t,isLocal:i,customerUserId:r,metadata:s,role:n,joinedAt:o,groups:l,realtime:u,type:p}){this.customerUserId="";this.metadata="";this.auxiliaryTracks=[];this.name=t,this.peerId=e,this.isLocal=i,this.customerUserId=r,this.metadata=s,this.joinedAt=o,this.groups=l,this.realtime=u,this.type=p,n&&(this.role=n)}get isHandRaised(){var e;return!!((e=this.groups)!=null&&e.includes(He))}updateRole(e){this.role=e}updateName(e){this.name=e}updateNetworkQuality(e){this.networkQuality=e}updateMetadata(e){this.metadata=e}updateGroups(e){this.groups=e}toString(){var e,t,i,r;return`{
81
81
  name: ${this.name};
82
82
  role: ${(e=this.role)==null?void 0:e.name};
83
83
  peerId: ${this.peerId};
@@ -93,14 +93,14 @@
93
93
  ${this.asRole?`asRole: ${this.asRole.name};`:""}
94
94
  ${this.audioTrack?`audioTrack: ${(i=this.audioTrack)==null?void 0:i.trackId};`:""}
95
95
  ${this.videoTrack?`videoTrack: ${(r=this.videoTrack)==null?void 0:r.trackId};`:""}
96
- }`}};var Ft=class extends ut{constructor(t){super(M(m({},t),{isLocal:!1}));this.isLocal=!1;this.auxiliaryTracks=[];this.fromRoomState=!1;this.fromRoomState=!!t.fromRoomState}};var be=(a,e)=>new Ft({peerId:a.peer_id,name:a.info.name,role:e.getPolicyForRole(a.role),customerUserId:a.info.user_id,metadata:a.info.data,groups:a.groups,type:a.info.type});var Fi=class{constructor(e,t,i){this.transport=e;this.store=t;this.options=i;this.isEnd=!1;this.iterator=null;this.total=0;this.defaultPaginationLimit=10}validateConnection(){if(!this.transport||!this.store)throw Error("Use usePaginatedParticipants or hmsActions.getPeerListIterator after preview or join has happened")}hasNext(){return!this.isEnd}getTotal(){return this.total}findPeers(){return c(this,null,function*(){var t;this.validateConnection();let e=yield this.transport.signal.findPeers(M(m({},this.options||{}),{limit:((t=this.options)==null?void 0:t.limit)||this.defaultPaginationLimit}));return this.updateState(e),this.processPeers(e.peers)})}next(){return c(this,null,function*(){var t;this.validateConnection();let e;return!this.iterator&&!this.isEnd?yield this.findPeers():this.iterator?(e=yield this.transport.signal.peerIterNext({iterator:this.iterator,limit:((t=this.options)==null?void 0:t.limit)||this.defaultPaginationLimit}),this.updateState(e),this.processPeers(e.peers)):[]})}processPeers(e){let t=[];return e.forEach(i=>{let r=be(i,this.store);t.push(r)}),t}updateState(e){this.isEnd=e.eof,this.total=e.total,e.iterator&&(this.iterator=e.iterator)}};var ht=class{constructor(e){this.TAG="[AudioContextManager]";this.audioContext=new AudioContext,this.source=this.audioContext.createMediaElementSource(e),this.source.connect(this.audioContext.destination)}resumeContext(){return c(this,null,function*(){let e=this.audioContext.state;e==="running"||e==="closed"||(yield this.audioContext.resume(),d.d(this.TAG,"AudioContext is resumed",`from ${e}`))})}getAudioTrack(){return this.destinationNode&&this.source.disconnect(this.destinationNode),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.source.connect(this.destinationNode),this.destinationNode.stream.getAudioTracks()[0]}cleanup(){this.audioContext.state!=="closed"&&this.audioContext.close().catch(e=>{d.d(this.TAG,"AudioContext close error",e.message)})}};var rn=require("eventemitter2"),Ge=class extends rn.EventEmitter2{on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,t){return super.emit(e,t)}listeners(e){return super.listeners(e)}};var Gi=class extends Ge{constructor(){super(...arguments);this.audioElement=null;this.TAG="[PlaylistAudioManager]";this.seeked=!1}play(t){return c(this,null,function*(){return this.audioElement=this.getAudioElement(),new Promise((i,r)=>{this.audioElement=this.getAudioElement(),this.audioElement.src=t,this.seeked=!1,this.audioElement.onerror=()=>{let s=`Error loading ${t}`;d.e(this.TAG,s),this.stop(),r(s)},this.audioElement.oncanplaythrough=()=>c(this,null,function*(){try{if(!this.audioElement)return;if(this.audioContextManager.resumeContext(),this.track)this.seeked?this.seeked=!1:(yield this.audioElement.play(),i([this.track]));else{yield this.audioElement.play();let s=this.audioContextManager.getAudioTrack();this.track=s,i([s])}}catch(s){d.e(this.TAG,"Error playing audio",t,s.message),r(s)}}),this.audioElement.onseeked=()=>{this.seeked=!0}})})}getTracks(){return this.track?[this.track.id]:[]}getElement(){return this.audioElement||(this.audioElement=this.getAudioElement()),this.audioElement}stop(){var t,i,r;(t=this.audioElement)==null||t.pause(),(i=this.audioElement)==null||i.removeAttribute("src"),this.audioElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.track=void 0}getAudioElement(){if(this.audioElement)return this.audioElement;let t=document.createElement("audio");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new ht(t),t}};var $i=class extends Ge{constructor(){super(...arguments);this.TAG="[PlaylistVideoManager]";this.videoElement=null;this.canvasContext=null;this.tracks=[];this.DEFAUL_FPS=24;this.seeked=!1;this.drawImage=()=>{var t,i,r;this.videoElement&&!this.videoElement.paused&&!this.videoElement.ended&&((r=this.canvasContext)==null||r.drawImage(this.videoElement,0,0,(t=this.canvas)==null?void 0:t.width,(i=this.canvas)==null?void 0:i.height),this.timer=setTimeout(()=>{this.drawImage()},1e3/this.DEFAUL_FPS))}}play(t){return this.videoElement=this.getVideoElement(),this.createCanvas(),new Promise((i,r)=>{this.videoElement=this.getVideoElement(),this.videoElement.src=t,this.seeked=!1,this.videoElement.onerror=()=>{let s=`Error loading ${t}`;d.e(this.TAG,s),this.stop(),r(s)},this.videoElement.oncanplaythrough=()=>c(this,null,function*(){var s,n,o;try{if(!this.videoElement)return;if(this.canvas.width=this.videoElement.videoWidth,this.canvas.height=this.videoElement.videoHeight,this.tracks.length===0){this.clearCanvasAndTracks();let l=this.canvas.captureStream();if(!l){d.e(this.TAG,"Browser does not support captureStream");return}this.videoElement.onplay=this.drawImage,yield this.audioContextManager.resumeContext(),yield this.videoElement.play();let u=this.audioContextManager.getAudioTrack();l.addTrack(u),l.getTracks().forEach(p=>{this.tracks.push(p)}),i(this.tracks)}else this.seeked?(this.seeked=!1,(o=this.canvasContext)==null||o.drawImage(this.videoElement,0,0,(s=this.canvas)==null?void 0:s.width,(n=this.canvas)==null?void 0:n.height)):(yield this.videoElement.play(),i(this.tracks))}catch(l){d.e(this.TAG,"Error playing video",t,l.message),r(l)}}),this.videoElement.onseeked=()=>{this.seeked=!0}})}getTracks(){return this.tracks.map(t=>t.id)}getElement(){return this.videoElement||(this.videoElement=this.getVideoElement()),this.videoElement}stop(){var t,i,r;(t=this.videoElement)==null||t.pause(),(i=this.videoElement)==null||i.removeAttribute("src"),this.videoElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.clearCanvasAndTracks()}clearCanvasAndTracks(){var t;this.tracks=[],(t=this.canvasContext)==null||t.clearRect(0,0,this.canvas.width,this.canvas.height),clearTimeout(this.timer)}getVideoElement(){if(this.videoElement)return this.videoElement;let t=document.createElement("video");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new ht(t),t}createCanvas(){this.canvas||(this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"))}};var Wi={audio:{list:[],currentIndex:-1,isAutoplayOn:!0},video:{list:[],currentIndex:-1,isAutoplayOn:!0}},Gt=class extends Ge{constructor(t,i){super();this.sdk=t;this.eventBus=i;this.state={audio:m({},Wi.audio),video:m({},Wi.video)};this.TAG="[PlaylistManager]";this.handlePausePlaylist=r=>c(this,[r],function*({enabled:t,track:i}){var n;if(t)return;let s;i.source==="audioplaylist"&&(s="audio"),i.source==="videoplaylist"&&(s="video"),s&&((n=this.getElement(s))==null||n.pause())});this.addTrack=(t,i)=>c(this,null,function*(){yield this.sdk.addTrack(t,i),d.d(this.TAG,"Playlist track added",yi(t))});this.removeTrack=t=>c(this,null,function*(){yield this.sdk.removeTrack(t,!0),d.d(this.TAG,"Playlist track removed",t)});this.audioManager=new Gi,this.videoManager=new $i,this.addListeners()}getList(t="audio"){return this.state[t].list}setList(t){if(!t||t.length===0){d.w(this.TAG,"Please pass in a list of HMSPlaylistItem's");return}t.forEach(i=>{this.state[i.type].list.find(r=>r.id===i.id)||this.state[i.type].list.push(i)})}clearList(t){return c(this,null,function*(){this.isPlaying(t)&&(yield this.stop(t)),this.state[t].list=[]})}removeItem(t,i){return c(this,null,function*(){let{list:r,currentIndex:s}=this.state[i],n=r.findIndex(o=>t===o.id);return n>-1?(s===n&&this.isPlaying(i)&&(yield this.stop(i)),r.splice(n,1),!0):!1})}seek(t,i="audio"){let{currentIndex:r}=this.state[i];if(r===-1)throw S.PlaylistErrors.NoEntryToPlay("PLAYLIST","No item is currently playing");let s=this.getElement(i);if(s){let n=Math.max(s.currentTime+t,0);s.currentTime=Math.min(n,s.duration)}}seekTo(t,i="audio"){let{currentIndex:r}=this.state[i];if(r===-1)throw S.PlaylistErrors.NoEntryToPlay("PLAYLIST","No item is currently playing");if(t<0)throw Error("value cannot be negative");let s=this.getElement(i);s&&(s.currentTime=Math.min(t,s.duration))}setVolume(t,i="audio"){if(t<0||t>100)throw Error("Please pass a valid number between 0-100");let r=this.getElement(i);r&&(r.volume=t*.01)}getVolume(t="audio"){let i=this.getElement(t);return i?Math.floor(i.volume*100):0}getCurrentTime(t="audio"){let i=this.getElement(t);return(i==null?void 0:i.currentTime)||0}getCurrentIndex(t="audio"){return this.state[t].currentIndex}getCurrentProgress(t="audio"){var o;let{list:i,currentIndex:r}=this.state[t],s=(o=i[r])==null?void 0:o.url,n=this.getElement(t);return!s||!n?0:Math.floor(100*(n.currentTime/n.duration))}getCurrentSelection(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r!==-1)return i[r]}isPlaying(t="audio"){let i=this.getElement(t);return!!i&&!i.paused}setIsAutoplayOn(t="audio",i){this.state[t].isAutoplayOn=i}getPlaybackRate(t="audio"){let i=this.getElement(t);return i?i.playbackRate:1}setPlaybackRate(t="audio",i){if(i<.25||i>2)throw Error("Please pass a value between 0.25 and 2.0");let r=this.getElement(t);r&&(r.playbackRate=i)}setEnabled(s,n){return c(this,arguments,function*(t,{id:i,type:r="audio"}){let l=this.state[r].list.findIndex(p=>p.id===i);if(!i||l===-1){d.w(this.TAG,"Pass a valid id");return}let u=this.state[r].list[l].url;t?yield this.play(u,r):yield this.pause(u,r),this.state[r].currentIndex=l,this.setDuration(r)})}playNext(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r>=i.length-1)throw S.PlaylistErrors.NoEntryToPlay("PLAYLIST","Reached end of playlist");yield this.play(i[r+1].url,t),this.state[t].currentIndex=r+1,this.setDuration(t)})}playPrevious(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r<=0)throw S.PlaylistErrors.NoEntryToPlay("PLAYLIST","Reached start of playlist");yield this.play(i[r-1].url,t),this.state[t].currentIndex=r-1,this.setDuration(t)})}stop(){return c(this,arguments,function*(t="audio"){var r;let i=t==="audio"?this.audioManager:this.videoManager;(r=i.getElement())==null||r.pause(),yield this.removeTracks(t),i.stop(),this.state[t].currentIndex=-1})}cleanup(){this.state={audio:m({},Wi.audio),video:m({},Wi.video)},this.eventBus.localAudioEnabled.unsubscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.unsubscribe(this.handlePausePlaylist),this.audioManager.stop(),this.videoManager.stop()}onProgress(t){this.videoManager.on("progress",()=>{try{t({type:"video",progress:this.getCurrentProgress("video")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}}),this.audioManager.on("progress",()=>{try{t({type:"audio",progress:this.getCurrentProgress("audio")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}})}onNewTrackStart(t){this.on("newTrackStart",t)}onPlaylistEnded(t){this.on("playlistEnded",t)}onCurrentTrackEnded(t){this.on("currentTrackEnded",t)}getElement(t="audio"){return t==="audio"?this.audioManager.getElement():this.videoManager.getElement()}removeTracks(){return c(this,arguments,function*(t="audio"){let r=(t==="audio"?this.audioManager:this.videoManager).getTracks();for(let s of r)yield this.removeTrack(s)})}play(r){return c(this,arguments,function*(t,i="audio"){let s=i==="audio"?this.audioManager:this.videoManager,n=s.getElement();if(this.isItemCurrentlyPlaying(t,i)){d.w(this.TAG,`The ${i} is currently playing`);return}if(n!=null&&n.src.includes(t))yield n.play();else{n==null||n.pause();let o=yield s.play(t);for(let l of o)yield this.addTrack(l,i==="audio"?"audioplaylist":"videoplaylist")}})}isItemCurrentlyPlaying(t,i){let r=this.getElement(i);return!!(r&&!r.paused&&r.src.includes(t))}setDuration(t="audio"){let i=this.getElement(t),{list:r,currentIndex:s}=this.state[t];r[s]&&(r[s].duration=(i==null?void 0:i.duration)||0),this.emit("newTrackStart",r[s])}pause(r){return c(this,arguments,function*(t,i="audio"){let s=this.getElement(i);s&&!s.paused&&s.src.includes(t)?(s.pause(),d.d(this.TAG,"paused url",t)):d.w(this.TAG,"The passed in url is not currently playing")})}addListeners(){this.audioManager.on("ended",()=>this.handleEnded("audio")),this.videoManager.on("ended",()=>this.handleEnded("video")),this.eventBus.localAudioEnabled.subscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.subscribe(this.handlePausePlaylist)}handleEnded(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r,isAutoplayOn:s}=this.state[t];r===i.length-1?(yield this.stop(t),this.emit("playlistEnded",t)):s?this.playNext(t):yield this.pause(i[r].url,t),this.emit("currentTrackEnded",i[r])})}};var V=a=>a.room,sn=a=>a.errors,qo=(0,I.createSelector)(sn,a=>a.length===0?null:a.at(-1)),Ko=(0,I.createSelector)(V,a=>a.id),Y=a=>a.peers,$t=a=>a.messages.byID,ys=a=>a.messages.allIDs,_=a=>a.tracks,ks=a=>a.settings,qi=a=>a.appData,jo=a=>a.devices,an=a=>a.speakers,Qo=a=>a.connectionQualities,Ce=(0,I.createSelector)([V],a=>a&&a.isConnected),Jo=(0,I.createSelector)([Ce,V],(a,e)=>a?e.peerCount!==void 0?e.peerCount||1:e.peers.length:Math.max(e.peerCount!==void 0?e.peerCount:e.peers.length-1,0)),zo=a=>a.hideLocalPeer,Me=(0,I.createSelector)([V,Y,zo],(a,e,t)=>t?a.peers.filter(i=>a.localPeer!==i).map(i=>e[i]):a.peers.map(i=>e[i])),Yo=(0,I.createSelector)(_,a=>Object.values(a)),X=(0,I.createSelector)(V,Y,(a,e)=>e[a.localPeer]),Ie=(0,I.createSelector)(V,a=>a.localPeer),Xo=(0,I.createSelector)(X,a=>a==null?void 0:a.name),Zo=(0,I.createSelector)(X,a=>a==null?void 0:a.roleName),ue=(0,I.createSelector)(X,a=>a==null?void 0:a.audioTrack),ie=(0,I.createSelector)(X,a=>a==null?void 0:a.videoTrack),ec=(0,I.createSelector)(X,a=>a==null?void 0:a.auxiliaryTracks),Es=(0,I.createSelector)([ue,ie,ec],(a,e,t)=>{let i=t?[...t]:[];return a&&i.unshift(a),e&&i.unshift(e),i}),tc=(0,I.createSelector)(Me,a=>a.filter(e=>!e.isLocal)),ic=(0,I.createSelector)(Y,an,(a,e)=>{let t=Object.entries(e).sort((i,r)=>{var o,l;let s=((o=i[1])==null?void 0:o.audioLevel)||0;return(((l=r[1])==null?void 0:l.audioLevel)||0)>s?1:-1});if(t.length>0&&t[0][1].audioLevel&&t[0][1].audioLevel>0){let i=t[0][1].peerID;if(i in a)return a[i]}return null}),rc=a=>{let e=X(a);return tt(a,e==null?void 0:e.audioTrack)},Ki=a=>{let e=X(a);return tt(a,e==null?void 0:e.videoTrack)},sc=a=>{var t,i;let e=(t=X(a))==null?void 0:t.audioTrack;return!!(e&&((i=a.tracks[e])!=null&&i.interrupted))},ac=a=>{var t,i;let e=(t=X(a))==null?void 0:t.videoTrack;return!!(e&&((i=a.tracks[e])!=null&&i.interrupted))},Ps=a=>{let e=X(a);return na(a,e==null?void 0:e.videoTrack)},ji=(0,I.createSelector)(X,_,(a,e)=>{let{video:t,audio:i}=qe(e,a);return!!(t||i)}),nn=(0,I.createSelector)(Y,_,(a,e)=>{let t;for(let i in a){let r=a[i],{video:s,audio:n}=qe(e,r);if(s)return r;n&&!t&&(t=r)}return t}),nc=(0,I.createSelector)(nn,a=>!!a),oc=(0,I.createSelector)(Y,_,(a,e)=>{for(let t in a){let i=a[t],{audio:r,video:s}=qe(e,i);if(!s&&r)return i}}),cc=(0,I.createSelector)(Y,_,(a,e)=>{let t=[],i=[];for(let r in a){let s=a[r],{video:n,audio:o}=qe(e,s);n?t.push(s):o&&i.push(s)}return t.concat(i)}),dc=(0,I.createSelector)(Y,_,(a,e)=>{for(let t in e){let i=e[t];if(Ct(i)&&Ht(i)&&i.peerId)return a[i.peerId]}}),lc=(0,I.createSelector)(Y,_,(a,e)=>{for(let t in e){let i=e[t];if(fi(i)&&i.peerId)return a[i.peerId]}}),uc=(0,I.createSelector)(Yo,a=>a.filter(aa)),pc=(0,I.createSelector)(ys,a=>a.length),hc=(0,I.createSelector)($t,a=>Object.values(a).filter(e=>!e.read).length),mt=(0,I.createSelector)(ys,$t,(a,e)=>{let t=[];return a.forEach(i=>{t.push(e[i])}),t}),on=(0,I.createSelector)(mt,a=>a.filter(e=>{var t;return!e.recipientPeer&&!(e.recipientRoles&&((t=e.recipientRoles)==null?void 0:t.length)>0)})),mc=(0,I.createSelector)(on,a=>a.filter(e=>!e.read).length),oe=(0,I.createSelector)([V],a=>a&&a.roomState),bs=(0,I.createSelector)(oe,a=>a==="Preview"),Sc=(0,I.createSelector)(V,a=>a.roomState!=="Disconnected"),gc=(0,I.createSelector)(V,a=>!a.transcriptions||a.transcriptions.length<=0?!1:a.transcriptions.some(e=>e.mode==="caption"&&e.state==="started")),ye=a=>a.roles,Tc=(0,I.createSelector)([ye],a=>Object.keys(a)),ze=(0,I.createSelector)([X,ye],(a,e)=>a!=null&&a.roleName?e[a.roleName]:null),cn=a=>{var e;return(e=a.preview)==null?void 0:e.asRole},Is=(0,I.createSelector)([cn,ye],(a,e)=>a?e[a]:null),fc=(0,I.createSelector)([ze],a=>{var e;return(e=a==null?void 0:a.subscribeParams)!=null&&e.subscribeToRoles?a.subscribeParams.subscribeToRoles.length>0:!1}),As=(0,I.createSelector)(ze,a=>a==null?void 0:a.permissions),vc=(0,I.createSelector)(V,a=>a.recording),Mc=(0,I.createSelector)(V,a=>a.rtmp),yc=(0,I.createSelector)(V,a=>a.hls),kc=(0,I.createSelector)(V,a=>a.transcriptions),Ec=(0,I.createSelector)(V,a=>{var i,r;let e=(i=a.transcriptions)==null?void 0:i.find(s=>s.mode==="caption");if(e!=null&&e.translation)return{available:!0,enabled:e.translation.enabled,roleLanguages:e.translation.roleLanguages};let t=(r=a.translationConfig)==null?void 0:r.caption;return t?{available:!0,enabled:!1,roleLanguages:t.roleLanguages}:{available:!1,enabled:!1,roleLanguages:void 0}}),Pc=(0,I.createSelector)(V,a=>a.sessionId),bc=(0,I.createSelector)(V,a=>a.startedAt),Ic=(0,I.createSelector)(V,a=>!!a.isLargeRoom),Ac=(0,I.createSelector)(V,a=>!!a.isEffectsEnabled),Rc=(0,I.createSelector)(V,a=>!!a.isVBEnabled),Hc=(0,I.createSelector)(V,a=>a.effectsKey),Cc=a=>a.templateAppData,Lc=a=>a.sessionMetadata,Rs=a=>a.polls,wc=a=>Object.values(a.polls),Dc=(0,I.createSelector)(Me,a=>a.filter(e=>e.isHandRaised)),dn=a=>a.whiteboards,_c=(0,I.createSelector)(dn,a=>Object.values(a)[0]);var Hs=require("reselect");var ln=(a="audio")=>e=>e.playlist[a].list,Cs=(a="audio")=>e=>e.playlist[a].selection,un=(a="audio")=>e=>e.playlist[a].progress,pn=(a="audio")=>e=>e.playlist[a].currentTime,hn=(a="audio")=>e=>e.playlist[a].playbackRate,mn=(a="audio")=>e=>e.playlist[a].volume,Sn=(a="audio")=>(0,Hs.createSelector)(ln(a),e=>Object.values(e)),gn=(a="audio")=>(0,Hs.createSelector)(ln(a),Cs(a),(e,t)=>{if(t.id)return e[t.id]}),Ls={selection:Cs("audio"),progress:un("audio"),currentTime:pn("audio"),playbackRate:hn("audio"),volume:mn("audio"),list:Sn("audio"),selectedItem:gn("audio")},ws={selection:Cs("video"),progress:un("video"),currentTime:pn("video"),playbackRate:hn("video"),volume:mn("video"),list:Sn("video"),selectedItem:gn("video")};var w=require("reselect");function H(a){return e=>t=>a(t,e)}var Wt="HMS-Store:",b=class{static v(e,...t){this.log(0,e,...t)}static d(...e){this.log(1,...e)}static i(...e){this.log(2,...e)}static w(...e){this.log(3,...e)}static e(...e){this.log(6,...e)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,...t){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(Wt,...t);break}case 1:{console.debug(Wt,...t);break}case 2:{console.info(Wt,...t);break}case 3:{console.warn(Wt,...t);break}case 6:{console.error(Wt,...t);break}case 4:{performance.mark(t[1]);break}case 5:{let i=t[0],r=t[1];try{let s=performance.measure(r,r);this.log(1,i,r,s==null?void 0:s.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(s){this.log(1,i,r,s)}break}}}};b.level=0;var Ds=(a,e)=>e,qt=(a,e)=>e,Tn=(a,e)=>e,Nc=(a,e)=>e,Oc=(a,e)=>e,re=(0,w.createSelector)([Y,Ds],(a,e)=>e?a[e]:null),_s=(0,w.createSelector)([_,qt],(a,e)=>e?a[e]:null),xc=(0,w.createSelector)([_,qt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="video"?t:null}),Uc=(0,w.createSelector)([_,qt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="audio"?t:null}),Bc=(0,w.createSelector)([_,qt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="audio"&&(t==null?void 0:t.source)==="screen"?t:null}),Vc=(0,w.createSelector)([_,qt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="video"&&(t==null?void 0:t.source)==="screen"?t:null}),Fc=(0,w.createSelector)([Rs,Oc],(a,e)=>e?a[e]:null),se=H(re),Gc=H((0,w.createSelector)([qi,Nc],(a,e)=>{if(a)return e?a[e]:a}));function $c(a){return e=>{if(e.sessionStore)return a?e.sessionStore[a]:e.sessionStore}}var Wc=(...a)=>(0,w.createSelector)([qi],e=>{if(e){if(a&&a.length>0){let t=e;for(let i of a){if(!i)return t;t=t==null?void 0:t[i]}return t}return e}}),qc=H((0,w.createSelector)(re,a=>a==null?void 0:a.name)),Kc=H((0,w.createSelector)(re,a=>a==null?void 0:a.type)),Kt=H(_s),Ns=H(xc),jc=H(Uc),Qc=H(Bc),Jc=H(Vc),fn=H((a,e)=>{let t=re(a,e);if(t&&t.videoTrack&&t.videoTrack!=="")return a.tracks[t.videoTrack]}),vn=H((a,e)=>{let t=re(a,e);if(t&&t.audioTrack&&t.audioTrack!=="")return a.tracks[t.audioTrack]}),zc=fn,Yc=H((a,e)=>{let t=re(a,e);return(t==null?void 0:t.auxiliaryTracks.map(i=>a.tracks[i]))||[]}),Mn=(a,e)=>e?a.speakers[e]:null,Xc=H((0,w.createSelector)(Mn,a=>(a==null?void 0:a.audioLevel)||0)),Zc=(a,e)=>{let t=vn(e)(a);return Mn(a,t==null?void 0:t.id)},ed=H((0,w.createSelector)(Zc,a=>(a==null?void 0:a.audioLevel)||0)),td=H((a,e)=>{if(e)return a.connectionQualities[e]}),id=H((a,e)=>{let t=re(a,e);if(t){let i=t==null?void 0:t.auxiliaryTracks.find(r=>Rt(a.tracks[r]));return i?a.tracks[i]:void 0}}),rd=H((0,w.createSelector)(_,re,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return Ct(r)&&Ht(r)});return t?a[t]:void 0})),sd=H((0,w.createSelector)(_,re,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return Ct(r)&&Rt(r)});return t?a[t]:void 0})),ad=H((0,w.createSelector)(_,re,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return fi(r)&&Rt(r)});return t?a[t]:void 0})),Os=H((0,w.createSelector)(_,re,(a,e)=>qe(a,e))),nd=a=>(0,w.createSelector)(Os(a),e=>e.video),xs=a=>(0,w.createSelector)(Os(a),e=>e.audio),od=H((a,e)=>{let t=re(a,e);return tt(a,t==null?void 0:t.audioTrack)}),cd=H((a,e)=>{let t=re(a,e);return tt(a,t==null?void 0:t.videoTrack)}),Us=H((a,e)=>{if(e&&a.tracks[e])return a.tracks[e].volume===0}),dd=H((a,e)=>{let t=re(a,e);return Us(t==null?void 0:t.audioTrack)(a)}),ld=H((a,e)=>{let t=xs(e)(a);return Us(t==null?void 0:t.id)(a)}),Bs=H((a,e)=>{let t=_s(a,e);if(t){if(t.type!=="audio"){b.w("Please pass audio track here");return}return t.volume}}),ud=H((a,e)=>{let t=re(a,e);return Bs(t==null?void 0:t.audioTrack)(a)}),pd=H((a,e)=>{let t=xs(e)(a);return Bs(t==null?void 0:t.id)(a)}),hd=H((a,e)=>{let t=_s(a,e);if(t){if(t.type!=="video"){b.w("Please pass video track here");return}return t.layer}}),yn=(0,w.createSelector)([mt,Ie,Ds],(a,e,t)=>{if(t)return a.filter(i=>{var r;return!i.recipientPeer&&!((r=i.recipientRoles)!=null&&r.length)||i.sender&&![e,t].includes(i.sender)?!1:[e,t].includes(i.recipientPeer)})}),kn=(0,w.createSelector)([mt,Tn],(a,e)=>{if(e)return a.filter(t=>{var i,r;return(i=t.recipientRoles)!=null&&i.length?(r=t.recipientRoles)==null?void 0:r.includes(e):!1})}),En=(0,w.createSelector)(mt,a=>a.filter(e=>{var t;return!e.recipientPeer&&!((t=e.recipientRoles)!=null&&t.length)})),md=(0,w.createSelector)([kn,Tn],a=>a?a.filter(e=>!e.read).length:0),Sd=(0,w.createSelector)([yn,Ds],a=>a?a.filter(e=>!e.read).length:0),gd=(0,w.createSelector)(En,a=>a.filter(e=>!e.read).length),Td=H(yn),fd=H(kn),vd=H(md),Md=H(Sd),yd=a=>(0,w.createSelector)([Me],e=>e.filter(t=>t.roleName===a)),kd=a=>(0,w.createSelector)([Me],e=>e.filter(t=>t.roleName?a.includes(t.roleName):!1)),Ed=a=>(0,w.createSelector)(se(a),e=>{try{return e!=null&&e.metadata&&e.metadata!==""?JSON.parse(e.metadata):{}}catch(t){return console.error("cannot parse peer metadata",t),{}}}),Pd=a=>(0,w.createSelector)(se(a),e=>!!(e!=null&&e.isHandRaised)),bd=a=>(0,w.createSelector)(se(a),e=>e==null?void 0:e.name),Vs=H(Fc),Id=a=>(0,w.createSelector)($t,e=>e[a]),Ad=a=>(0,w.createSelector)(ze,e=>e!=null&&e.permissions.transcriptions?e.permissions.transcriptions[a].length>0:!1);var jt=require("reselect");var Rd=(0,jt.createSelector)([Y,_],(a,e)=>Object.values(a).map(i=>{var r;return{peer:i,isAudioEnabled:i.audioTrack?(r=e[i.audioTrack])==null?void 0:r.enabled:!1}})),Hd=a=>a.roleChangeRequests[0]||null,Cd=(0,jt.createSelector)([Hd,Y,ye],(a,e,t)=>a?{requestedBy:a.requestedBy?e[a.requestedBy]:void 0,role:t[a.roleName],token:a.token}:null),Ld=(0,jt.createSelector)([ze],a=>Lt(a)),wd=(0,jt.createSelector)([Is],a=>Lt(a));var Ae=require("reselect");var Pn=a=>(0,Ae.createSelector)([ye],e=>e[a]),Dd=a=>(0,Ae.createSelector)(Pn(a),e=>Lt(e)),_d=(0,Ae.createSelector)([ie,_],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),Nd=(0,Ae.createSelector)([ue,_],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),Od=a=>(0,Ae.createSelector)([_d],e=>e.includes(a)),xd=a=>(0,Ae.createSelector)([Nd],e=>e.includes(a)),Ud=a=>(0,Ae.createSelector)(Me,e=>e.find(a)),Bd=a=>(0,Ae.createSelector)(Me,e=>e.filter(a)),Vd=a=>(0,Ae.createSelector)(V,e=>e.joinedAt&&Date.now()-e.joinedAt.getTime()<=a);var Zn=require("immer"),eo=We(require("zustand/shallow")),to=We(require("zustand/vanilla"));var In=require("eventemitter2");var Qi={0:"PEER_JOINED",1:"PEER_LEFT",8:"ROLE_UPDATED",10:"NAME_UPDATED",11:"METADATA_UPDATED",12:"HAND_RAISE_CHANGED"},Qt={0:"TRACK_ADDED",1:"TRACK_REMOVED",2:"TRACK_MUTED",3:"TRACK_UNMUTED",5:"TRACK_DEGRADED",6:"TRACK_RESTORED",4:"TRACK_DESCRIPTION_CHANGED"},Ji={0:"POLL_CREATED",1:"POLL_STARTED",2:"POLL_STOPPED",4:"POLL_VOTES_UPDATED",3:"POLLS_LIST"},bn={TRANSCRIPTION_STATE_UPDATED:"TRANSCRIPTION_STATE_UPDATED"};var Fs="hmsNotification",zi=class{constructor(e){this.id=0;this.onNotification=(e,t)=>{let i=r=>{if(t){let s;if(Array.isArray(t)?s=t.includes(r.type):s=t===r.type,!s)return}e(r)};return this.eventEmitter.addListener(Fs,i),()=>{this.eventEmitter.removeListener(Fs,i)}};this.store=e,this.eventEmitter=new In.EventEmitter2({maxListeners:Object.keys(Ti).length})}sendPlaylistTrackEnded(e){let t=this.createNotification("PLAYLIST_TRACK_ENDED",e,"info");this.emitEvent(t)}sendDeviceChange(e){var i;let t=this.createNotification("DEVICE_CHANGE_UPDATE",e,e.error?"error":"info",`Selected ${e.type} device - ${(i=e.selection)==null?void 0:i.label}`);this.emitEvent(t)}sendLeaveRoom(e){var r;let t=(r=e.requestedBy)==null?void 0:r.name,i=this.createNotification(e.roomEnded||!t?"ROOM_ENDED":"REMOVED_FROM_ROOM",e,"info",`${e.roomEnded?"Room ended":"Removed from room"} ${t?`by ${t}`:""}`);this.emitEvent(i)}sendPeerList(e){if(e.length===0)return;let t=this.createNotification("PEER_LIST",e,"info");this.emitEvent(t)}sendPeerUpdate(e,t){let i=this.store.getState(se(t==null?void 0:t.id))||t,r=Qi[e];if(r&&i){let s=this.createNotification(r,i,"info");this.emitEvent(s)}}sendTrackUpdate(e,t){let i=this.store.getState(Kt(t)),r=Qt[e];if(r){let s=this.createNotification(r,i,"info");this.emitEvent(s)}}sendMessageReceived(e){let t=this.createNotification("NEW_MESSAGE",e,"info");this.emitEvent(t)}sendError(e){let t=this.createNotification("ERROR",e,"error");this.emitEvent(t)}sendReconnecting(e){let t=this.createNotification("RECONNECTING",e,"error");this.emitEvent(t)}sendReconnected(){let e=this.createNotification("RECONNECTED",null,"info");this.emitEvent(e)}sendChangeTrackStateRequest(e){let t=this.createNotification("CHANGE_TRACK_STATE_REQUEST",e,"info");this.emitEvent(t)}sendChangeMultiTrackStateRequest(e){let t=this.createNotification("CHANGE_MULTI_TRACK_STATE_REQUEST",e,"info");this.emitEvent(t)}sendPollUpdate(e,t){let i=Ji[e],r=this.store.getState(Vs(t));if(i){let s=this.createNotification(i,r,"info");this.emitEvent(s)}}sendTrackInterruption(e){let t=e.type==="audio"?"microphone":"camera",i=this.createNotification(e.started?"TRACK_INTERRUPTION_START":"TRACK_INTERRUPTION_END",e,e.started?"error":"info",e.started?`Your ${t} was interrupted, another app may be using it`:`Your ${t} is available again`);this.emitEvent(i)}sendTranscriptionUpdate(e){let t=this.createNotification(bn.TRANSCRIPTION_STATE_UPDATED,e,"info");this.emitEvent(t)}emitEvent(e){this.eventEmitter.emit(Fs,e)}createNotification(e,t,i,r=""){return this.id++,{id:this.id,type:e,message:r,data:t,severity:i}}};var Yi=class{constructor(e){this.queuedUpdates={};this.timers={};this.DEFAULT_INTERVAL_MS=50;this.store=e}setState(e,t,i=this.DEFAULT_INTERVAL_MS){this.queuedUpdates[t]=this.queuedUpdates[t]||[],this.queuedUpdates[t].push(e),!this.timers[t]&&(window?this.timers[t]=window.setTimeout(()=>this.setStateBatched(t),i):this.setStateBatched(t))}setStateBatched(e){var t;if(((t=this.queuedUpdates[e])==null?void 0:t.length)>0){let i=r=>{this.queuedUpdates[e].forEach(s=>{try{s(r)}catch(n){b.w("failed to update store",n)}})};console.time(`timed-${e}`),this.store.namedSetState(i,e),console.timeEnd(`timed-${e}`)}delete this.queuedUpdates[e],window&&this.timers[e]&&(window.clearTimeout(this.timers[e]),delete this.timers[e])}};function An(a){return a instanceof le||a instanceof x}var Rn=(a,e)=>{let t=Jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Ye(r,s)?(pe(r.auxiliaryTracks,s.auxiliaryTracks)&&(s.auxiliaryTracks=r.auxiliaryTracks),r.groups&&pe(r.groups,s.groups)&&(s.groups=r.groups),Object.assign(r,s)):Ws(r,s)?delete a[i]:Xi(r,s)&&(a[i]=s)}},Hn=(a,e)=>{let t=Jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Ye(r,s)?($s(r,s),Object.assign(r,s)):Ws(r,s)?delete a[i]:Xi(r,s)&&(a[i]=s)}},Cn=(a,e)=>{let t=Jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Ye(r,s)?(r.questions&&pe(r.questions,s.questions)&&(s.questions=r.questions),Object.assign(r,s)):Xi(r,s)&&(a[i]=s)}},Gs=(a,e)=>{let t=Jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Ye(r,s)?Object.assign(r,s):Ws(r,s)?delete a[i]:Xi(r,s)&&(a[i]=s)}},Ln=(a,e,t)=>{let i=t.reduce((s,n)=>(s[n.firstTrackId]=Object.values(e[n.getTrackIDBeingSent()]||{}).sort((o,l)=>!o.rid||!l.rid?0:o.rid<l.rid?-1:1),s),{}),r=Jt(Object.keys(a),Object.keys(i));for(let s of r){if(!i[s]){delete a[s];continue}a[s]=i[s]}},$s=(a,e)=>{a.plugins&&pe(a.plugins,e.plugins)&&(e.plugins=a.plugins),a.type==="video"&&a.layerDefinitions&&pe(a.layerDefinitions,e.layerDefinitions)&&(e.layerDefinitions=a.layerDefinitions)},Ye=(a,e)=>a&&e,Ws=(a,e)=>a&&!e,Xi=(a,e)=>!a&&e,pe=(a,e)=>{if(a===e||a.length===0&&(e==null?void 0:e.length)===0)return!0;if(!a||!e||a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(a[t]!==e[t])return!1;return!0},Jt=(a,e)=>{let t=new Set;for(let i of a)t.add(i);for(let i of e)t.add(i);return Array.from(t)};var N=class a{static convertPeer(e){var t,i,r;return{id:e.peerId,name:e.name,roleName:(t=e.role)==null?void 0:t.name,isLocal:e.isLocal,videoTrack:(i=e.videoTrack)==null?void 0:i.trackId,audioTrack:(r=e.audioTrack)==null?void 0:r.trackId,auxiliaryTracks:e.auxiliaryTracks.map(s=>s.trackId),customerUserId:e.customerUserId,metadata:e.metadata,joinedAt:e.joinedAt,groups:e.groups,isHandRaised:e.isHandRaised,type:e.type}}static convertTrack(e,t){let i={id:e.trackId,source:e.source,type:e.type,enabled:e.enabled,displayEnabled:e.enabled,peerId:e.peerId||t};return this.enrichTrack(i,e),i}static enrichTrack(e,t){let i=t.getMediaTrackSettings();t instanceof le&&(e.volume=t.getVolume()||0),a.updateDeviceID(e,t),a.enrichLocalTrack(e,t),e.type==="video"&&(e.source==="screen"?(e.displaySurface=i.displaySurface,a.enrichScreenTrack(e,t)):e.source==="regular"&&(e.facingMode=i.facingMode),e.height=i.height,e.width=i.width,a.enrichVideoTrack(e,t)),a.enrichPluginsDetails(e,t)}static enrichLocalTrack(e,t){(t instanceof q||t instanceof Se)&&(e.isPublished=t.isPublished)}static updateDeviceID(e,t){var i;t instanceof q||t instanceof Se?e.deviceID=t.settings.deviceId:e.deviceID=(i=t.getMediaTrackSettings())==null?void 0:i.deviceId}static enrichVideoTrack(e,t){t instanceof x&&(e.layer=t.getLayer(),e.preferredLayer=t.getPreferredLayer(),e.degraded=t.degraded),(t instanceof x||t instanceof q)&&(pe(t.getSimulcastDefinitions(),e.layerDefinitions)||(e.layerDefinitions=t.getSimulcastDefinitions()))}static enrichScreenTrack(e,t){var i,r;if(t instanceof q){let s=(i=t.getCaptureHandle)==null?void 0:i.call(t);(s==null?void 0:s.handle)!==((r=e.captureHandle)==null?void 0:r.handle)&&(e.captureHandle=s),t.isCurrentTab&&(e.displaySurface="selfBrowser")}}static enrichPluginsDetails(e,t){(t instanceof q||t instanceof Se)&&(pe(t.getPlugins(),e.plugins)||(e.plugins=t.getPlugins()))}static convertRoom(e,t){let{recording:i,rtmp:r,hls:s,transcriptions:n}=a.convertRecordingStreamingState(e.recording,e.rtmp,e.hls,e.transcriptions);return{id:e.id,name:e.name,localPeer:t,recording:i,rtmp:r,hls:s,transcriptions:n,sessionId:e.sessionId,startedAt:e.startedAt,joinedAt:e.joinedAt,peerCount:e.peerCount,isLargeRoom:e.large_room_optimization,isEffectsEnabled:e.isEffectsEnabled,disableNoneLayerRequest:e.disableNoneLayerRequest,isVBEnabled:e.isVBEnabled,effectsKey:e.effectsKey,isHipaaEnabled:e.isHipaaEnabled,isNoiseCancellationEnabled:e.isNoiseCancellationEnabled}}static convertMessage(e,t){var i,r,s,n;return{sender:(i=e.peer)==null?void 0:i.peer_id,senderName:(r=e.peer)==null?void 0:r.info.name,senderRole:(s=e.peer)==null?void 0:s.role,senderUserId:(n=e.peer)==null?void 0:n.info.user_id,recipientPeer:e.private?t:void 0,recipientRoles:e.roles,time:new Date(e.timestamp),type:e.info.type,message:e.info.message,id:e.message_id}}static convertRoles(e){let t={};return e&&e.forEach(i=>{t[i.name]=i}),t}static convertRoleChangeRequest(e){var t;return{requestedBy:(t=e.requestedBy)==null?void 0:t.peerId,roleName:e.role.name,token:e.token}}static convertException(e){let t="trackType"in e,i={code:e.code,action:e.action,name:e.name,message:e.message,description:e.description,isTerminal:e.isTerminal,nativeError:e.nativeError,timestamp:new Date};return t&&(i.trackType=e==null?void 0:e.trackType),i}static convertDeviceChangeUpdate(e){let t={devices:e.devices,selection:e.selection,type:e.type};return e.error&&(t.error=this.convertException(e.error)),t}static convertPlaylist(e){let t=this.getConvertedPlaylistType(e,"audio"),i=this.getConvertedPlaylistType(e,"video");return{audio:t,video:i}}static convertPlaylistItem(e,t){let i=t.type,r=e.getCurrentSelection(i),s=e.isPlaying(i),n=t.url===(r==null?void 0:r.url);return M(m({},t),{type:t.type,selected:n,playing:n&&s})}static getConvertedPlaylistType(e,t){let i={},r=e.getCurrentSelection(t),s=e.getCurrentProgress(t),n=e.getVolume(t),o=e.getList(t),l=e.getCurrentIndex(t);return e.getList(t).forEach(u=>{i[u.id]=a.convertPlaylistItem(e,u)}),{list:i,selection:{id:r==null?void 0:r.id,hasPrevious:l>0,hasNext:l<o.length-1},progress:s,volume:n,currentTime:e.getCurrentTime(t),playbackRate:e.getPlaybackRate(t)}}static convertRecordingStreamingState(e,t,i,r){var s;return{recording:{browser:m({running:!1},e==null?void 0:e.browser),server:m({running:!1},e==null?void 0:e.server),hls:m({running:!1},e==null?void 0:e.hls)},rtmp:m({running:!1},t),hls:{variants:((s=i==null?void 0:i.variants)==null?void 0:s.map(n=>n))||[],running:!!(i!=null&&i.running),error:i==null?void 0:i.error},transcriptions:r||[]}}};var zt=class{constructor(e,t,i,r){this.playlistManager=e;this.syncPlaylistState=i;this.store=r;this.type=t}play(e){return c(this,null,function*(){if(!e){b.w("Please pass id to play");return}yield this.playlistManager.setEnabled(!0,{id:e,type:this.type})})}pause(){return c(this,null,function*(){let e=this.type==="audio"?Ls:ws,t=this.store.getState(e.selection);if(!t.id){b.w("No item is currently playing to pause");return}yield this.playlistManager.setEnabled(!1,{id:t.id,type:this.type})})}playNext(){return c(this,null,function*(){yield this.playlistManager.playNext(this.type)})}playPrevious(){return c(this,null,function*(){yield this.playlistManager.playPrevious(this.type)})}seek(e){this.playlistManager.seek(e,this.type),this.syncPlaylistState(`seekOn${this.type}Playlist`)}seekTo(e){this.playlistManager.seekTo(e,this.type),this.syncPlaylistState(`seekToOn${this.type}Playlist`)}setVolume(e){this.playlistManager.setVolume(e,this.type),this.syncPlaylistState(`setVolumeOn${this.type}Playlist`)}setList(e){this.playlistManager.setList(e),this.syncPlaylistState(`setListOn${this.type}Playlist`)}stop(){return c(this,null,function*(){yield this.playlistManager.stop(this.type),this.syncPlaylistState(`stop${this.type}Playlist`)})}setIsAutoplayOn(e){this.playlistManager.setIsAutoplayOn(this.type,e)}setPlaybackRate(e){this.playlistManager.setPlaybackRate(this.type,e),this.syncPlaylistState(`set${this.type}PlaybackRate`)}removeItem(e){return c(this,null,function*(){let t=yield this.playlistManager.removeItem(e,this.type);return t&&this.syncPlaylistState(`remove${this.type}PlaylistItem`),t})}clearList(){return c(this,null,function*(){yield this.playlistManager.clearList(this.type),this.syncPlaylistState(`clear${this.type}Playlist`)})}};var Zi=class{constructor(e,t){this.sdk=e;this.setLocally=t}get sdkSessionStore(){return this.sdk.getSessionStore()}set(e,t){return c(this,null,function*(){let{value:i}=yield this.sdkSessionStore.set(String(e),t);this.setLocally({key:e,value:i})})}observe(e){return c(this,null,function*(){let t=Array.isArray(e)?e.map(i=>String(i)):[String(e)];yield this.sdkSessionStore.observe(t)})}unobserve(e){return c(this,null,function*(){let t=Array.isArray(e)?e.map(i=>String(i)):[String(e)];yield this.sdkSessionStore.unobserve(t)})}};var er=class{constructor(e,t){this.TAG="[BeamSpeakerLabelsLogger]";this.intervalMs=100,this.shouldMonitor=!1,this.hasStarted=!1,this.unsubs=[],this.analysers={},this.store=e,this.actions=t}start(){return c(this,null,function*(){if(this.hasStarted)return;this.hasStarted=!0,b.d("starting audio level monitor for remote peers",this.store);let e=this.store.getState(Ce);b.d("starting audio levels is connected to room",e),e&&(yield this.monitorAudioLevels());let t=this.store.subscribe(this.monitorAudioLevels.bind(this),Ce);this.unsubs.push(t)})}stop(){return c(this,null,function*(){this.hasStarted&&(this.hasStarted=!1,this.shouldMonitor=!1,this.unsubs.forEach(e=>e()),b.d("stopped audio level monitor for remote peers"))})}monitorAudioLevels(){return c(this,null,function*(){if(!this.store.getState(Ce)){this.shouldMonitor&&(b.i("room no longer connected, stopping audio level monitoring for remote"),this.shouldMonitor=!1);return}if(this.shouldMonitor)return;b.i("monitoring audio levels"),this.shouldMonitor=!0;let t=()=>{this.shouldMonitor?(this.logAllPeersAudioLevels(),setTimeout(t,this.intervalMs)):b.i("stopped monitoring audio levels")};setTimeout(t,1e3)})}logAllPeersAudioLevels(){return c(this,null,function*(){var r;if(!window.__triggerBeamEvent__)return;let e=this.store.getState(Me),t=e.filter(s=>!!s.audioTrack);b.d(this.TAG,"Peers Without audio track",e.filter(s=>!s.audioTrack).map(s=>s.id).join(","));let i=[];for(let s of t){let n=this.actions.getTrackById(s.audioTrack||""),o=(r=n==null?void 0:n.stream)==null?void 0:r.nativeStream;if(s.joinedAt&&o){let l=yield this.getAudioLevel(s,o);b.d(this.TAG,s.id,l),l.level>0&&i.push(l)}}if(i.length>0){let s={event:"app-audio-level",data:i};b.d("logging audio levels",JSON.stringify(i)),window.__triggerBeamEvent__(JSON.stringify(s))}})}getAudioLevel(e,t){return c(this,null,function*(){this.analysers[t.id]||(this.analysers[t.id]=this.createAnalyserNode(t));let i=this.analysers[t.id],r=this.calculateAudioLevel(i);return{peerId:e.id,peerName:e.name,userId:e.customerUserId,level:r}})}createAnalyserNode(e){this.audioContext||(this.audioContext=new AudioContext);let t=this.audioContext.createAnalyser();return this.audioContext.createMediaStreamSource(e).connect(t),t}calculateAudioLevel(e){let t=new Uint8Array(e.fftSize);e.getByteTimeDomainData(t);let i=.009,r=i;for(let o of t)r=Math.max(r,(o-128)/128);let s=(Math.log(i)-Math.log(r))/Math.log(i);return Math.ceil(Math.min(Math.max(s*100,0),100))}};var wn=2e4,Dn=1e4,St={name:"diagnostics-role",priority:1,publishParams:{allowed:["audio","video"],audio:{bitRate:32,codec:"opus"},video:{bitRate:100,codec:"vp8",frameRate:30,height:720,width:1280},screen:{bitRate:100,codec:"vp8",frameRate:10,height:1080,width:1920}},subscribeParams:{subscribeToRoles:[],maxSubsBitRate:3200},permissions:{browserRecording:!1,changeRole:!1,endRoom:!1,hlsStreaming:!1,mute:!1,pollRead:!1,pollWrite:!1,removeOthers:!1,rtmpStreaming:!1,unmute:!1}},_n="https://100ms.live/test-audio.wav";var tr=class{constructor(){this.networkScores=[];this.lastPushedAt=0}pushScore(e){!e||e<0||(this.networkScores.length===0?(this.networkScores.push(e),this.lastPushedAt=Date.now()):this.addPendingCQSTillNow())}addPendingCQSTillNow(){if(this.networkScores.length>0){let e=(Date.now()-this.lastPushedAt)/1e3;for(;e>0;)this.networkScores.push(this.networkScores[this.networkScores.length-1]),e-=1;this.lastPushedAt=Date.now()}}getCQS(){return this.networkScores.reduce((e,t)=>e+t,0)/this.networkScores.length}};var Fd=a=>!!a&&!isNaN(a),he=a=>a[a.length-1],$e=(a,e)=>{let t=a.filter(i=>Fd(e(i)));return t.reduce((i,r)=>i+(e(r)||0),0)/t.length},ir=class{constructor(e){this.sdk=e;this.peerStatsList=[];this.localAudioTrackStatsList=[];this.localVideoTrackStatsList=[];this.remoteAudioTrackStatsList=[];this.remoteVideoTrackStatsList=[]}handleStatsUpdate(e){return c(this,null,function*(){var o,l,u,p,h,T,g,f;let t=e.getLocalPeerStats();t&&this.peerStatsList.push(t);let i=(u=(l=(o=this.sdk.getLocalPeer())==null?void 0:o.audioTrack)==null?void 0:l.nativeTrack)==null?void 0:u.id,r=(T=(h=(p=this.sdk.getLocalPeer())==null?void 0:p.videoTrack)==null?void 0:h.nativeTrack)==null?void 0:T.id,s=e.getLocalTrackStats();s&&(i&&this.localAudioTrackStatsList.push(s[i]),r&&this.localVideoTrackStatsList.push(s[r]));let n=yield(f=(g=this.sdk.getWebrtcInternals())==null?void 0:g.getSubscribePeerConnection())==null?void 0:f.getStats();n==null||n.forEach(P=>{if(P.type==="inbound-rtp"){let v=P.kind==="audio"?this.remoteAudioTrackStatsList:this.remoteVideoTrackStatsList,A=lt("bytesReceived",P,he(v));v.push(M(m({},P),{bitrate:A}))}})})}buildReport(){var P,v,A,$,ce,B,de,De,Et,Pt;let e=(P=he(this.peerStatsList))==null?void 0:P.publish,t=(v=he(this.peerStatsList))==null?void 0:v.subscribe,i=e!=null&&e.responsesReceived?((e==null?void 0:e.totalRoundTripTime)||0)/e.responsesReceived:0,r=t!=null&&t.responsesReceived?((t==null?void 0:t.totalRoundTripTime)||0)/t.responsesReceived:0,s=Number(((i+r)/2*1e3).toFixed(2)),n=((A=he(this.remoteAudioTrackStatsList))==null?void 0:A.packetsReceived)||0,o=(($=he(this.remoteVideoTrackStatsList))==null?void 0:$.packetsReceived)||0,l=this.localAudioTrackStatsList.map(O=>O?$e(Object.values(O),Q=>Q.bitrate):0),u=this.localVideoTrackStatsList.map(O=>O?$e(Object.values(O),Q=>Q.bitrate):0),p=((ce=he(this.remoteAudioTrackStatsList))==null?void 0:ce.jitter)||0,h=((B=he(this.remoteVideoTrackStatsList))==null?void 0:B.jitter)||0,T=Math.max(p,h),g=he(this.localAudioTrackStatsList),f=he(this.localVideoTrackStatsList);return{combined:{roundTripTime:s,packetsReceived:n+o,packetsLost:(t==null?void 0:t.packetsLost)||0,bytesSent:(e==null?void 0:e.bytesSent)||0,bytesReceived:(t==null?void 0:t.bytesReceived)||0,bitrateSent:$e(this.peerStatsList,O=>{var Q;return(Q=O.publish)==null?void 0:Q.bitrate}),bitrateReceived:$e(this.peerStatsList,O=>{var Q;return(Q=O.subscribe)==null?void 0:Q.bitrate}),jitter:T},audio:{roundTripTime:s,packetsReceived:n,packetsLost:((de=he(this.remoteAudioTrackStatsList))==null?void 0:de.packetsLost)||0,bytesReceived:((De=he(this.remoteAudioTrackStatsList))==null?void 0:De.bytesReceived)||0,bitrateSent:$e(l,O=>O),bitrateReceived:$e(this.remoteAudioTrackStatsList,O=>O.bitrate),bytesSent:g?Object.values(g).reduce((O,Q)=>O+(Q.bytesSent||0),0):0,jitter:p},video:{roundTripTime:s,packetsLost:((Et=he(this.remoteVideoTrackStatsList))==null?void 0:Et.packetsLost)||0,bytesReceived:((Pt=he(this.remoteVideoTrackStatsList))==null?void 0:Pt.bytesReceived)||0,packetsReceived:o,bitrateSent:$e(u,O=>O),bitrateReceived:$e(this.remoteVideoTrackStatsList,O=>O.bitrate),bytesSent:f?Object.values(f).reduce((O,Q)=>O+(Q.bytesSent||0),0):0,jitter:h}}}};var Nn=(o=>(o[o.STARTING=0]="STARTING",o[o.INIT_FETCHED=1]="INIT_FETCHED",o[o.SIGNAL_CONNECTED=2]="SIGNAL_CONNECTED",o[o.ICE_ESTABLISHED=3]="ICE_ESTABLISHED",o[o.MEDIA_CAPTURED=4]="MEDIA_CAPTURED",o[o.MEDIA_PUBLISHED=5]="MEDIA_PUBLISHED",o[o.COMPLETED=6]="COMPLETED",o))(Nn||{});var On,xn,rr=class{constructor(e,t,i,r,s=wn){this.sdk=e;this.sdkListener=t;this.progressCallback=i;this.completionCallback=r;this.connectivityDuration=s;this.wsConnected=!1;this.initConnected=!1;this.isPublishICEConnected=!1;this.isSubscribeICEConnected=!1;this.gatheredPublishICECandidates=[];this.gatheredSubscribeICECandidates=[];this.errors=[];this.isAudioTrackCaptured=!1;this.isVideoTrackCaptured=!1;this.isAudioTrackPublished=!1;this.isVideoTrackPublished=!1;this.cqsCalculator=new tr;this.timestamp=Date.now();this.onRoomUpdate=this.sdkListener.onRoomUpdate.bind(this.sdkListener);this.onPeerUpdate=this.sdkListener.onPeerUpdate.bind(this.sdkListener);this.onMessageReceived=this.sdkListener.onMessageReceived.bind(this.sdkListener);this.onReconnected=this.sdkListener.onReconnected.bind(this.sdkListener);this.onRoleChangeRequest=this.sdkListener.onRoleChangeRequest.bind(this.sdkListener);this.onRoleUpdate=this.sdkListener.onRoleUpdate.bind(this.sdkListener);this.onChangeTrackStateRequest=this.sdkListener.onChangeTrackStateRequest.bind(this.sdkListener);this.onChangeMultiTrackStateRequest=this.sdkListener.onChangeMultiTrackStateRequest.bind(this.sdkListener);this.onRemovedFromRoom=this.sdkListener.onRemovedFromRoom.bind(this.sdkListener);this.onNetworkQuality=(On=this.sdkListener.onNetworkQuality)==null?void 0:On.bind(this.sdkListener);this.onPreview=this.sdkListener.onPreview.bind(this.sdkListener);this.onDeviceChange=(xn=this.sdkListener.onDeviceChange)==null?void 0:xn.bind(this.sdkListener);this.onSessionStoreUpdate=this.sdkListener.onSessionStoreUpdate.bind(this.sdkListener);this.onPollsUpdate=this.sdkListener.onPollsUpdate.bind(this.sdkListener);this.onWhiteboardUpdate=this.sdkListener.onWhiteboardUpdate.bind(this.sdkListener);this.handleConnectionQualityUpdate=e=>{let t=e.find(i=>{var r,s;return i.peerID===((s=(r=this.sdk)==null?void 0:r.store.getLocalPeer())==null?void 0:s.peerId)});this.cqsCalculator.pushScore(t==null?void 0:t.downlinkQuality)};this.statsCollector=new ir(e),this.state=0}get state(){return this._state}set state(e){var t;e===void 0||this._state!==void 0&&e<this._state||(this._state=e,(t=this.progressCallback)==null||t.call(this,e))}onICESuccess(e){e?this.isPublishICEConnected=!0:this.isSubscribeICEConnected=!0,this.isPublishICEConnected&&this.isSubscribeICEConnected&&(this.state=3)}onSelectedICECandidatePairChange(e,t){t?this.selectedPublishICECandidate=e:this.selectedSubscribeICECandidate=e}onICECandidate(e,t){t?this.gatheredPublishICECandidates.push(e):this.gatheredSubscribeICECandidates.push(e)}onMediaPublished(e){switch(e.type){case"audio":this.isAudioTrackPublished=!0;break;case"video":this.isVideoTrackPublished=!0;break;default:break}this.isVideoTrackPublished&&this.isAudioTrackPublished&&(this.state=5)}onInitSuccess(e){this.websocketURL=e,this.initConnected=!0,this.state=1}onSignallingSuccess(){this.wsConnected=!0,this.state=2}onJoin(e){var t,i;this.sdkListener.onJoin(e),(t=this.sdk.getWebrtcInternals())==null||t.onStatsChange(r=>this.statsCollector.handleStatsUpdate(r)),(i=this.sdk.getWebrtcInternals())==null||i.start(),this.cleanupTimer=window.setTimeout(()=>{this.cleanupAndReport()},this.connectivityDuration)}onError(e){this.sdkListener.onError(e),this.errors.push(e),e!=null&&e.isTerminal&&this.cleanupAndReport()}onTrackUpdate(e,t,i){if(this.sdkListener.onTrackUpdate(e,t,i),i.isLocal&&e===0){switch(t.type){case"audio":this.isAudioTrackCaptured=!0;break;case"video":this.isVideoTrackCaptured=!0;break;default:break}this.isVideoTrackCaptured&&this.isAudioTrackCaptured&&(this.state=4)}}onReconnecting(e){this.sdkListener.onReconnecting(e),this.cqsCalculator.addPendingCQSTillNow()}cleanupAndReport(){var e;clearTimeout(this.cleanupTimer),this.cleanupTimer=void 0,this.state===5&&(this.state=6),(e=this.completionCallback)==null||e.call(this,this.buildReport()),this.sdk.leave()}buildReport(){this.cqsCalculator.addPendingCQSTillNow();let e=this.cqsCalculator.getCQS(),t=this.statsCollector.buildReport();return{testTimestamp:this.timestamp,connectivityState:this.state,errors:this.errors,signallingReport:{isConnected:this.wsConnected,isInitConnected:this.initConnected,websocketUrl:this.websocketURL},mediaServerReport:{stats:t,connectionQualityScore:e,isPublishICEConnected:this.isPublishICEConnected,isSubscribeICEConnected:this.isSubscribeICEConnected,publishICECandidatePairSelected:this.selectedPublishICECandidate,subscribeICECandidatePairSelected:this.selectedSubscribeICECandidate,publishIceCandidatesGathered:this.gatheredPublishICECandidates,subscribeIceCandidatesGathered:this.gatheredSubscribeICECandidates}}}};var Xe=class{constructor(e){this.recording={server:{running:!1},browser:{running:!1},hls:{running:!1}};this.rtmp={running:!1};this.hls={running:!1,variants:[]};this.transcriptions=[];this.isNoiseCancellationEnabledFromInit=!1;this.isNoiseCancellationEnabledFromPolicy=!1;this.id=e}get isNoiseCancellationEnabled(){return this.isNoiseCancellationEnabledFromInit&&this.isNoiseCancellationEnabledFromPolicy}};var sr=(a,e,t)=>c(null,null,function*(){let r=Error("something went wrong during fetch");for(let s=0;s<4;s++)try{let n=yield fetch(a,e),o=yield n.clone().json();if(t&&t.length&&!n.ok&&t.includes(o.code))throw S.APIErrors.ServerErrors(o.code,"GET_TOKEN",o.message,!1);return n}catch(n){r=n}throw["Failed to fetch","NetworkError"].some(s=>r.message.includes(s))?S.APIErrors.EndpointUnreachable("GET_TOKEN",r.message):r});var gt=class{constructor(e,t){this.sdk=e;this.sdkListener=t;this.recordedAudio=_n;this.sdk.setIsDiagnostics(!0),this.initSdkWithLocalPeer()}get localPeer(){var e;return(e=this.sdk)==null?void 0:e.store.getLocalPeer()}checkBrowserSupport(){_t(),Dt()}requestPermission(e){return c(this,null,function*(){try{let t=yield navigator.mediaDevices.getUserMedia(e);return t.getTracks().forEach(i=>i.stop()),yield this.sdk.deviceManager.init(!0),{audio:t.getAudioTracks().length>0,video:t.getVideoTracks().length>0}}catch(t){throw xe(t,this.sdk.localTrackManager.getErrorType(!!e.video,!!e.audio))}})}startCameraCheck(e){return c(this,null,function*(){var s,n,o,l;if(this.initSdkWithLocalPeer(),!this.localPeer)throw new Error("Local peer not found");this.sdk.store.setSimulcastEnabled(!1),this.localPeer.role=M(m({},St),{publishParams:M(m({},St.publishParams),{allowed:["video"]})});let t=new Be().video(new z().deviceId(e||"default").build()).build(),i=yield(s=this.sdk)==null?void 0:s.localTrackManager.getLocalTracks({audio:!1,video:!0},t),r=i==null?void 0:i.find(u=>u.type==="video");if(!r)throw new Error("No video track found");(n=this.sdk)==null||n.deviceManager.init(!0),this.localPeer.videoTrack=r,(l=(o=this.sdk)==null?void 0:o.listener)==null||l.onPeerUpdate(9,[this.localPeer])})}stopCameraCheck(){var e,t;(t=(e=this.localPeer)==null?void 0:e.videoTrack)==null||t.cleanup(),this.localPeer&&(this.localPeer.videoTrack=void 0)}startMicCheck(s){return c(this,arguments,function*({inputDevice:e,onError:t,onStop:i,time:r=Dn}){var u,p,h,T;this.initSdkWithLocalPeer(g=>{this.stopMicCheck(),t==null||t(g)});let n=yield this.getLocalAudioTrack(e);if((u=this.sdk)==null||u.deviceManager.init(!0),!this.localPeer)throw new Error("Local peer not found");if(!n)throw new Error("No audio track found");this.localPeer.audioTrack=n,(p=this.sdk)==null||p.initPreviewTrackAudioLevelMonitor(),(T=(h=this.sdk)==null?void 0:h.listener)==null||T.onPeerUpdate(9,[this.localPeer]),this.mediaRecorder=new MediaRecorder(n.stream.nativeStream);let o=[];this.mediaRecorder.ondataavailable=function(g){o.push(g.data)},this.mediaRecorder.onstop=()=>{var f,P;let g=new Blob(o,{type:(f=this.mediaRecorder)==null?void 0:f.mimeType});this.recordedAudio=URL.createObjectURL(g),(P=this.onStopMicCheck)==null||P.call(this)},this.mediaRecorder.start();let l=setTimeout(()=>{this.stopMicCheck()},r);this.onStopMicCheck=()=>{clearTimeout(l),i==null||i()}})}stopMicCheck(){var e,t,i;(e=this.mediaRecorder)==null||e.stop(),(i=(t=this.localPeer)==null?void 0:t.audioTrack)==null||i.cleanup(),this.localPeer&&(this.localPeer.audioTrack=void 0)}getRecordedAudio(){return this.recordedAudio}startConnectivityCheck(e,t,i,r){return c(this,null,function*(){if(!this.sdk)throw new Error("SDK not found");this.connectivityCheck=new rr(this.sdk,this.sdkListener,e,t,r);let s=yield this.getAuthToken(i);yield this.sdk.leave(),yield this.sdk.join({authToken:s,userName:"diagnostics-test"},this.connectivityCheck),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:n=>{var o;(o=this.connectivityCheck)==null||o.handleConnectionQualityUpdate(n)}})})}stopConnectivityCheck(){return c(this,null,function*(){var e;return(e=this.connectivityCheck)==null?void 0:e.cleanupAndReport()})}initSdkWithLocalPeer(e){var r,s,n;this.sdkListener&&((r=this.sdk)==null||r.initStoreAndManagers(M(m({},this.sdkListener),{onError:o=>{e==null||e(o),this.sdkListener.onError(o)}})));let t=new Je({name:"diagnostics-peer",role:St,type:"regular"});(s=this.sdk)==null||s.store.addPeer(t);let i=new Xe("diagnostics-room");this.sdk.store.setRoom(i),this.sdkListener.onRoomUpdate("ROOM_PEER_COUNT_UPDATED",i),(n=this.sdk)==null||n.deviceManager.init(!0)}getAuthToken(e){return c(this,null,function*(){let t=new URL("https://api.100ms.live/v2/diagnostics/token");e&&t.searchParams.append("region",e);let i=yield sr(t.toString(),{method:"GET"},[429,500,501,502,503,504,505,506,507,508,509,510,511]),r=yield i.json();if(!i.ok)throw S.APIErrors.ServerErrors(r.code,"GET_TOKEN",r.message,!1);let{token:s}=r;if(!s)throw Error(r.message);return s})}getLocalAudioTrack(e){return c(this,null,function*(){var r;if(!this.localPeer)return;this.localPeer.role=M(m({},St),{publishParams:M(m({},St.publishParams),{allowed:["audio"]})});let t=new Be().audio(new ee().deviceId(e||"default").build()).build(),i=yield(r=this.sdk)==null?void 0:r.localTrackManager.getLocalTracks({audio:!0,video:!1},t);return i==null?void 0:i.find(s=>s.type==="audio")})}};var ar=class{constructor(e,t,i){this.isRoomJoinCalled=!1;this.ignoredMessageTypes=[];this.setProgress=({type:e,progress:t})=>{this.setState(i=>{i.playlist[e].progress=t,i.playlist[e].currentTime=this.sdk.getPlaylistManager().getCurrentTime(e)},"playlistProgress")};this.syncPlaylistState=e=>{this.setState(t=>{Object.assign(t.playlist,N.convertPlaylist(this.sdk.getPlaylistManager()))},e)};this.sendPeerUpdateNotification=(e,t)=>{let i=this.store.getState(se(t.peerId)),r=Qi[e]||"peerUpdate";if(e===8)this.syncRoomState(r),this.updateMidCallPreviewRoomState(e,t);else if([0,1].includes(e))this.syncRoomState(r),i||(i=this.store.getState(se(t.peerId)));else if([12,13,14].includes(e))this.syncRoomState(r),i||(i=this.store.getState(se(t.peerId)));else{let s=N.convertPeer(t);this.setState(n=>{let o=n.peers[s.id];Ye(o,s)&&(pe(o.auxiliaryTracks,s.auxiliaryTracks)&&(o.auxiliaryTracks=s.auxiliaryTracks),Object.assign(o,s)),i=s},r)}this.hmsNotifications.sendPeerUpdate(e,i)};this.getSDKHMSPeer=e=>this.sdk.getPeerMap()[e];this.setState=(e,t)=>this.store.namedSetState(e,t);this.store=e,this.sdk=t,this.hmsNotifications=i,this.sessionStore=new Zi(this.sdk,this.setSessionStoreValueLocally.bind(this)),this.actionBatcher=new Yi(e)}submitSessionFeedback(e,t){return this.sdk.submitSessionFeedback(e,t)}getLocalTrack(e){return this.sdk.store.getLocalPeerTracks().find(t=>t.trackId===e)}get interactivityCenter(){return this.sdk.getInteractivityCenter()}setPlaylistSettings(e){this.sdk.updatePlaylistSettings(e)}refreshDevices(){return c(this,null,function*(){yield this.sdk.refreshDevices()})}unblockAudio(){return c(this,null,function*(){yield this.sdk.getAudioOutput().unblockAutoplay()})}setVolume(e,t){return c(this,null,function*(){t?yield this.setTrackVolume(e,t):(yield this.sdk.getAudioOutput().setVolume(e),this.syncRoomState("setOutputVolume"))})}setAudioOutputDevice(e){return c(this,null,function*(){(yield this.sdk.getAudioOutput().setDevice(e))&&this.setState(i=>{i.settings.audioOutputDeviceId=e},"setAudioOutputDevice")})}setPreferredLayer(e,t){return c(this,null,function*(){var r;let i=this.getTrackById(e);if(i)if(i instanceof x){if(t==="none"){b.d("layer none will be ignored");return}if(((r=this.store.getState(Ns(e)))==null?void 0:r.preferredLayer)===t){b.d(`preferred layer is already ${t}`);return}this.setState(n=>{let o=n.tracks[e];o&&(o.preferredLayer=t)},"setPreferredLayer"),yield i.setPreferredLayer(t)}else b.d(`track ${e} is not a remote video track`);else this.logPossibleInconsistency(`track ${e} not present, unable to set preffer layer`)})}getNativeTrackById(e){var t;return(t=this.sdk.store.getTrackById(e))==null?void 0:t.nativeTrack}getTrackById(e){return this.sdk.store.getTrackById(e)}getAuthTokenByRoomCode(e,t){return this.sdk.getAuthTokenByRoomCode(e,t)}preview(e){return c(this,null,function*(){let t=this.store.getState(oe);if(t==="Preview"||t==="Connecting"){this.logPossibleInconsistency("attempting to call preview while room is in preview/connecting");return}try{t!=="Connected"&&this.setState(i=>{i.room.roomState="Connecting"},"connecting"),yield this.sdkPreviewWithListeners(e)}catch(i){throw b.e("Cannot show preview. Failed to connect to room - ",i),i}})}cancelMidCallPreview(){return c(this,null,function*(){return this.sdk.cancelMidCallPreview()})}join(e){return c(this,null,function*(){if(this.isRoomJoinCalled){this.logPossibleInconsistency("room join is called again");return}try{this.isRoomJoinCalled=!0,this.setState(t=>{t.room.roomState="Connecting"},"join"),yield this.sdkJoinWithListeners(e)}catch(t){throw this.isRoomJoinCalled=!1,b.e("Failed to connect to room - ",t),t}})}leave(){return c(this,null,function*(){let e=this.store.getState(Ce),t=!0;e||(t=!1,this.logPossibleInconsistency("room leave is called when no room is connected"));let i=this.store.getState(oe);return this.setState(r=>{r.room.roomState="Disconnecting"},"leaving"),this.sdk.leave(t).then(()=>{this.resetState("leave"),this.beamSpeakerLabelsLogger&&this.beamSpeakerLabelsLogger.stop().catch(b.e),b.i("left room")}).catch(r=>{b.e("error in leaving room - ",r),this.setState(s=>{s.room.roomState=i},"revertLeave")})})}setScreenShareEnabled(e,t){return c(this,null,function*(){typeof t=="boolean"&&(t={audioOnly:t});try{e?yield this.startScreenShare(t):yield this.stopScreenShare()}catch(i){throw this.hmsNotifications.sendError(N.convertException(i)),i}})}addTrack(e,t="regular"){return c(this,null,function*(){yield this.sdk.addTrack(e,t),this.syncRoomState("addTrack")})}removeTrack(e){return c(this,null,function*(){yield this.sdk.removeTrack(e),this.syncRoomState("removeTrack")})}setLocalAudioEnabled(e){return c(this,null,function*(){let t=this.store.getState(ue);t&&(yield this.setEnabledTrack(t,e))})}setLocalVideoEnabled(e){return c(this,null,function*(){let t=this.store.getState(ie);t&&(yield this.setEnabledTrack(t,e))})}setEnabledTrack(e,t){return c(this,null,function*(){var s;if(((s=this.store.getState().tracks[e])==null?void 0:s.enabled)===t){this.logPossibleInconsistency(`local track[${e}] enabled state - ${t}`);return}this.setState(n=>{n.tracks[e]?n.tracks[e].displayEnabled=t:this.logPossibleInconsistency("track id not found for setEnabled")},"displayEnabled");try{yield this.setEnabledSDKTrack(e,t),this.syncRoomState("setEnabled")}catch(n){throw this.setState(o=>{o.tracks[e].displayEnabled=!t},"rollbackDisplayEnabled"),this.hmsNotifications.sendError(N.convertException(n)),n}let r=t?3:2;this.hmsNotifications.sendTrackUpdate(r,e)})}autoSelectAudioOutput(e){return c(this,null,function*(){yield this.sdk.autoSelectAudioOutput(e)})}setAudioSettings(e){return c(this,null,function*(){let t=this.store.getState(ue);t&&(yield this.setSDKLocalAudioTrackSettings(t,e),this.syncRoomState("setAudioSettings"))})}setVideoSettings(e){return c(this,null,function*(){let t=this.store.getState(ie);t&&(yield this.setSDKLocalVideoTrackSettings(t,e),this.syncRoomState("setVideoSettings"))})}switchCamera(){return c(this,null,function*(){let e=this.store.getState(ie);if(e){let t=this.sdk.store.getLocalPeerTracks().find(i=>i.trackId===e);t&&(yield t.switchCamera(),this.syncRoomState("switchCamera"))}})}sendMessage(e){this.sendBroadcastMessage(e)}sendBroadcastMessage(e,t){return c(this,null,function*(){let{message_id:i,timestamp:r}=yield this.sdk.sendBroadcastMessage(e,t);this.updateMessageInStore({message:e,type:t,id:i,time:r})})}sendGroupMessage(e,t,i){return c(this,null,function*(){let r=this.store.getState(ye),s=t.map(l=>r[l]),{message_id:n,timestamp:o}=yield this.sdk.sendGroupMessage(e,s,i);this.updateMessageInStore({message:e,recipientRoles:t,type:i,id:n,time:o})})}sendDirectMessage(e,t,i){return c(this,null,function*(){let{message_id:r,timestamp:s}=yield this.sdk.sendDirectMessage(e,t,i);this.updateMessageInStore({message:e,recipientPeer:t,type:i,id:r,time:s})})}updateMessageInStore(e){var s;if(!e.message)throw b.w("sendMessage","Failed to send message",e),Error(`sendMessage Failed - ${JSON.stringify(e)}`);if(!!e.type&&this.ignoredMessageTypes.includes(e.type))return;let i=this.sdk.getLocalPeer(),r={read:!0,id:e.id,time:new Date(e.time),message:e.message,type:e.type||"chat",recipientPeer:e.recipientPeer,recipientRoles:e.recipientRoles,senderName:i==null?void 0:i.name,sender:i==null?void 0:i.peerId,senderRole:(s=i==null?void 0:i.role)==null?void 0:s.name,ignored:!1};this.setState(n=>{n.messages.byID[r.id]=r,n.messages.allIDs.push(r.id)},"newMessage")}setMessageRead(e,t){this.setState(i=>{t?i.messages.byID[t]?i.messages.byID[t].read=e:this.logPossibleInconsistency("no message with id is found"):i.messages.allIDs.forEach(r=>{i.messages.byID[r].read=e})},"setMessageRead")}attachVideo(e,t){return c(this,null,function*(){if(this.localAndVideoUnmuting(e))return new Promise(i=>{let r=this.store.subscribe(s=>c(this,null,function*(){s&&(yield this.attachVideoInternal(e,t),r(),i())}),Ki)});yield this.attachVideoInternal(e,t)})}detachVideo(e,t){return c(this,null,function*(){let i=this.getTrackById(e);(i==null?void 0:i.type)==="video"?yield this.sdk.detachVideo(i,t):(t&&(t.srcObject=null),b.d("possible inconsistency detected - no video track found to remove sink"))})}addPluginToVideoTrack(e,t){return c(this,null,function*(){return this.addRemoveVideoPlugin(e,"add",t)})}addPluginsToVideoStream(e){return c(this,null,function*(){return this.addRemoveMediaStreamVideoPlugins(e,"add")})}removePluginsFromVideoStream(e){return c(this,null,function*(){return this.addRemoveMediaStreamVideoPlugins(e,"remove")})}addPluginToAudioTrack(e){return c(this,null,function*(){return this.addRemoveAudioPlugin(e,"add")})}validateVideoPluginSupport(e){let t={};if(t.isSupported=!1,!e)return b.w("no plugin passed in for checking support"),t.errMsg="no plugin passed in for checking support",t;let i=this.store.getState(ie);if(!i)return b.w("video Track not added to local peer yet"),t.errMsg="call this function only after local peer has video track",t;let r=this.getTrackById(i);return r?t=r.validatePlugin(e):(b.w(`track ${i} not present, unable to validate plugin`),t.errMsg=`track ${i} not present, unable to validate plugin`),t}validateAudioPluginSupport(e){let t={};if(t.isSupported=!1,!e)return b.w('no plugin passed in for checking support"'),t.errMsg='no plugin passed in for checking support"',t;let i=this.store.getState(ue);if(!i)return b.w("audio track not added to local peer yet"),t.errMsg="call this function only after local peer has audio track",t;let r=this.getTrackById(i);return r?t=r.validatePlugin(e):(b.w(`track ${i} not present, unable to validate plugin`),t.errMsg=`track ${i} not present, unable to validate plugin`),t}removePluginFromVideoTrack(e){return c(this,null,function*(){return this.addRemoveVideoPlugin(e,"remove")})}removePluginFromAudioTrack(e){return c(this,null,function*(){return this.addRemoveAudioPlugin(e,"remove")})}changeRole(e,t,i=!1){return c(this,null,function*(){yield this.sdk.changeRoleOfPeer(e,t,i)})}changeRoleOfPeer(e,t,i=!1){return c(this,null,function*(){yield this.sdk.changeRoleOfPeer(e,t,i)})}changeRoleOfPeersWithRoles(e,t){return c(this,null,function*(){let i=this.sdk.getRoles().filter(r=>e.includes(r.name));yield this.sdk.changeRoleOfPeersWithRoles(i,t)})}acceptChangeRole(e){return c(this,null,function*(){let t=e.requestedBy?this.getSDKHMSPeer(e.requestedBy.id):void 0;t||b.w(`peer for which role change is requested no longer available - ${e.requestedBy}`);let i={requestedBy:t,role:e.role,token:e.token};yield this.sdk.acceptChangeRole(i),this.removeRoleChangeRequest(e)})}raiseLocalPeerHand(){return c(this,null,function*(){yield this.sdk.raiseLocalPeerHand()})}lowerLocalPeerHand(){return c(this,null,function*(){yield this.sdk.lowerLocalPeerHand()})}raiseRemotePeerHand(e){return c(this,null,function*(){yield this.sdk.raiseRemotePeerHand(e)})}lowerRemotePeerHand(e){return c(this,null,function*(){yield this.sdk.lowerRemotePeerHand(e)})}getPeer(e){return c(this,null,function*(){let t=yield this.sdk.getPeer(e);if(t)return N.convertPeer(t)})}findPeerByName(e){return c(this,null,function*(){let{offset:t,peers:i,eof:r}=yield this.sdk.findPeerByName(e);return{offset:t,eof:r,peers:i.map(s=>N.convertPeer(s))}})}getPeerListIterator(e){let t=this.sdk.getPeerListIterator(e);return{hasNext:()=>t.hasNext(),next:()=>c(this,null,function*(){return(yield t.next()).map(r=>N.convertPeer(r))}),findPeers:()=>c(this,null,function*(){return(yield t.findPeers()).map(r=>N.convertPeer(r))}),getTotal:()=>t.getTotal()}}initAppData(e){this.setState(t=>{t.appData=e},"initAppData")}setAppData(e,t,i){let r=(t==null?void 0:t.constructor.name)==="Object";this.setState(s=>{if(s.appData)i&&r?Object.assign(s.appData[e],t):s.appData[e]=t;else{let n={[e]:t};s.appData=n}},`setAppData-${e}`)}rejectChangeRole(e){this.removeRoleChangeRequest(e)}endRoom(e,t){return c(this,null,function*(){let i=this.store.getState(As);if(!(i!=null&&i.endRoom)){b.w("You are not allowed to perform this action - endRoom");return}let r=this.store.getState(oe);this.setState(s=>{s.room.roomState="Disconnecting"},"endingRoom");try{yield this.sdk.endRoom(e,t),this.resetState("endRoom")}catch(s){b.e("error in ending room - ",s),this.setState(n=>{n.room.roomState=r},"revertEndRoom")}})}removePeer(e,t){return c(this,null,function*(){var r;let i=(r=this.sdk.getLocalPeer())==null?void 0:r.peerId;e!==i&&(yield this.sdk.removePeer(e,t))})}startRTMPOrRecording(e){return c(this,null,function*(){yield this.sdk.startRTMPOrRecording(e)})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.sdk.stopRTMPAndRecording()})}startHLSStreaming(e){return c(this,null,function*(){yield this.sdk.startHLSStreaming(e)})}stopHLSStreaming(e){return c(this,null,function*(){yield this.sdk.stopHLSStreaming(e)})}startTranscription(e){return c(this,null,function*(){yield this.sdk.startTranscription(e)})}stopTranscription(e){return c(this,null,function*(){yield this.sdk.stopTranscription(e)})}updateTranscriptionConfig(e){return c(this,null,function*(){yield this.sdk.updateTranscriptionConfig(e)})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.sdk.sendHLSTimedMetadata(e)})}changeName(e){return c(this,null,function*(){yield this.sdk.changeName(e)})}changeMetadata(e){return c(this,null,function*(){typeof e!="string"&&(e=JSON.stringify(e)),yield this.sdk.changeMetadata(e)})}setSessionMetadata(e){return c(this,null,function*(){yield this.sdk.setSessionMetadata(e),this.setState(t=>{t.sessionMetadata=e},"setSessionMetadata"),this.setSessionStoreValueLocally({key:"default",value:e},"setSessionMetadata")})}populateSessionMetadata(){return c(this,null,function*(){let e=yield this.sdk.getSessionMetadata();this.setState(t=>{t.sessionMetadata=e},"populateSessionMetadata"),this.setSessionStoreValueLocally({key:"default",value:e},"populateSessionmetadata")})}setRemoteTrackEnabled(e,t){return c(this,null,function*(){if(typeof e=="string"){let i=this.getTrackById(e);i&&An(i)?yield this.sdk.changeTrackState(i,t):this.logPossibleInconsistency(`No remote track with ID ${e} found for change track state`)}else Array.isArray(e)&&e.forEach(i=>this.setRemoteTrackEnabled(i,t))})}setRemoteTracksEnabled(e){return c(this,null,function*(){let t={enabled:e.enabled,type:e.type,source:e.source};if(e.roles){let i=this.store.getState(ye);t.roles=e.roles.map(r=>i[r])}yield this.sdk.changeMultiTrackState(t)})}setLogLevel(e){b.level=e,this.sdk.setLogLevel(e)}setFrameworkInfo(e){this.sdk.setFrameworkInfo(e)}ignoreMessageTypes(e,t=!1){if(t)this.ignoredMessageTypes=e;else for(let i of e)this.ignoredMessageTypes.includes(i)||this.ignoredMessageTypes.push(i)}enableBeamSpeakerLabelsLogging(){return c(this,null,function*(){this.beamSpeakerLabelsLogger||(b.i("enabling beam speaker labels logging"),this.beamSpeakerLabelsLogger=new er(this.store,this),yield this.beamSpeakerLabelsLogger.start())})}initDiagnostics(){let e=new gt(this.sdk,{onJoin:this.onJoin.bind(this),onPreview:this.onPreview.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this),onTrackUpdate:this.onTrackUpdate.bind(this),onMessageReceived:this.onMessageReceived.bind(this),onError:this.onError.bind(this),onReconnected:this.onReconnected.bind(this),onReconnecting:this.onReconnecting.bind(this),onRoleChangeRequest:this.onRoleChangeRequest.bind(this),onRoleUpdate:this.onRoleUpdate.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onTrackInterruption:this.onTrackInterruption.bind(this),onChangeTrackStateRequest:this.onChangeTrackStateRequest.bind(this),onChangeMultiTrackStateRequest:this.onChangeMultiTrackStateRequest.bind(this),onRemovedFromRoom:this.onRemovedFromRoom.bind(this),onNetworkQuality:this.onNetworkQuality.bind(this),onSessionStoreUpdate:this.onSessionStoreUpdate.bind(this),onPollsUpdate:this.onPollsUpdate.bind(this),onWhiteboardUpdate:this.onWhiteboardUpdate.bind(this)});return this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)}),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:this.onConnectionQualityUpdate.bind(this)}),e}resetState(e="resetState"){this.isRoomJoinCalled=!1,b.cleanup(),this.setState(t=>{Object.assign(t,It())},e)}getDebugInfo(){return this.sdk.getDebugInfo()}sdkJoinWithListeners(e){return c(this,null,function*(){yield this.sdk.join(e,{onJoin:this.onJoin.bind(this),onPreview:this.onPreview.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this),onTrackUpdate:this.onTrackUpdate.bind(this),onMessageReceived:this.onMessageReceived.bind(this),onError:this.onError.bind(this),onReconnected:this.onReconnected.bind(this),onReconnecting:this.onReconnecting.bind(this),onRoleChangeRequest:this.onRoleChangeRequest.bind(this),onRoleUpdate:this.onRoleUpdate.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onTrackInterruption:this.onTrackInterruption.bind(this),onChangeTrackStateRequest:this.onChangeTrackStateRequest.bind(this),onChangeMultiTrackStateRequest:this.onChangeMultiTrackStateRequest.bind(this),onRemovedFromRoom:this.onRemovedFromRoom.bind(this),onNetworkQuality:this.onNetworkQuality.bind(this),onSessionStoreUpdate:this.onSessionStoreUpdate.bind(this),onPollsUpdate:this.onPollsUpdate.bind(this),onWhiteboardUpdate:this.onWhiteboardUpdate.bind(this),onSFUMigration:this.onSFUMigration.bind(this)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)}),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:this.onConnectionQualityUpdate.bind(this)})})}onSFUMigration(){this.syncRoomState("SFUMigration")}onRemovedFromRoom(e){var r;let t=this.store.getState(se((r=e.requestedBy)==null?void 0:r.peerId));this.hmsNotifications.sendLeaveRoom(M(m({},e),{requestedBy:t||void 0}));let i=e.roomEnded||!t?"roomEnded":"removedFromRoom";b.i(`resetting state after peer removed ${i}`,e),this.resetState(i)}onTrackInterruption(e){this.setState(t=>{let i=t.tracks[e.trackId];i&&(i.interrupted=e.started)},"trackInterruption"),this.hmsNotifications.sendTrackInterruption(e)}onDeviceChange(e){let t=e.devices;if(!t)return;let i=this.store.getState(X);if(this.setState(r=>{pe(r.devices.audioInput,t.audioInput)||(r.devices.audioInput=t.audioInput),pe(r.devices.videoInput,t.videoInput)||(r.devices.videoInput=t.videoInput),pe(r.devices.audioOutput,t.audioOutput)||(r.devices.audioOutput=t.audioOutput);let s=this.sdk.getLocalPeer();i!=null&&i.id&&s&&Object.assign(r.settings,this.getMediaSettings(s))},"deviceChange"),e.selection&&!e.internal){let r=N.convertDeviceChangeUpdate(e);this.hmsNotifications.sendDeviceChange(r)}}sdkPreviewWithListeners(e){return c(this,null,function*(){yield this.sdk.preview(e,{onPreview:this.onPreview.bind(this),onError:this.onError.bind(this),onReconnected:this.onReconnected.bind(this),onReconnecting:this.onReconnecting.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onTrackInterruption:this.onTrackInterruption.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this),onNetworkQuality:this.onNetworkQuality.bind(this),onTrackUpdate:this.onTrackUpdate.bind(this)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)})})}onNetworkQuality(e){this.setState(t=>{var r;let i=t.room.localPeer||((r=this.sdk.getLocalPeer())==null?void 0:r.peerId);i&&(t.connectionQualities[i]={peerID:i,downlinkQuality:e})},"ConnectionQuality")}onSessionStoreUpdate(e){this.setSessionStoreValueLocally(e,"sessionStoreUpdate")}onPollsUpdate(e,t){let i=Ji[e];this.setState(r=>{let s=t.reduce((n,o)=>{var l;return n[o.id]=M(m({},o),{questions:(l=o.questions)==null?void 0:l.map(u=>{var p,h;return M(m({},u),{answer:u.answer?m({},u.answer):void 0,options:(p=u.options)==null?void 0:p.map(T=>m({},T)),responses:(h=u.responses)==null?void 0:h.map(T=>m({},T))})})}),n},{});Cn(r.polls,s)},i),t.forEach(r=>this.hmsNotifications.sendPollUpdate(e,r.id))}onWhiteboardUpdate(e){this.setState(t=>{t.whiteboards[e.id]=e},"whiteboardUpdate")}startScreenShare(e){return c(this,null,function*(){this.store.getState(ji)?this.logPossibleInconsistency("start screenshare is called while it's on"):(yield this.sdk.startScreenShare(()=>this.syncRoomState("screenshareStopped"),e),this.syncRoomState("startScreenShare"))})}stopScreenShare(){return c(this,null,function*(){this.store.getState(ji)?(yield this.sdk.stopScreenShare(),this.syncRoomState("stopScreenShare")):this.logPossibleInconsistency("stop screenshare is called while it's not on")})}attachVideoInternal(e,t){return c(this,null,function*(){let i=this.getTrackById(e);i||(i=this.getLocalTrack(e)),i&&i.type==="video"?yield this.sdk.attachVideo(i,t):this.logPossibleInconsistency("no video track found to add sink")})}syncRoomState(e){e=`${e}_fullSync`,b.time(`store-sync-${e}`);let t={},i=[],r={},s={},n={},o,l=this.sdk.getPeers();for(let g of l){let f=N.convertPeer(g);t[f.id]=f,i.push(f.id),n[f.id]={peerID:f.id,downlinkQuality:g.networkQuality||-1};let P=[g.audioTrack,g.videoTrack,...g.auxiliaryTracks];for(let v of P){if(!v)continue;let A=N.convertTrack(v);r[A.id]=A}if(g.isLocal){let v=g;o=this.getPreviewFields(v),Object.assign(s,this.getMediaSettings(v))}}let u=this.sdk.getRecordingState(),p=this.sdk.getRTMPState(),h=this.sdk.getHLSState(),T=this.sdk.getTranscriptionState();this.setState(g=>{var v;g.room.peers=i;let f=g.peers,P=g.tracks;Rn(f,t),Hn(P,r),Object.assign(g.settings,s),g.room.isConnected&&Object.assign(g.connectionQualities,n),(v=g.preview)!=null&&v.localPeer&&(o!=null&&o.localPeer)?Object.assign(g.preview,o):g.preview=o,Object.assign(g.roles,N.convertRoles(this.sdk.getRoles())),Object.assign(g.playlist,N.convertPlaylist(this.sdk.getPlaylistManager())),Object.assign(g.room,N.convertRecordingStreamingState(u,p,h,T)),Object.assign(g.templateAppData,this.sdk.getTemplateAppData())},e),b.timeEnd(`store-sync-${e}`)}onPreview(e){this.setState(t=>{var i;Object.assign(t.room,N.convertRoom(e,(i=this.sdk.getLocalPeer())==null?void 0:i.peerId)),t.room.roomState="Preview"},"previewStart"),this.syncRoomState("previewSync")}onJoin(e){let t=this.sdk.getPlaylistManager();this.audioPlaylist=new zt(t,"audio",this.syncPlaylistState.bind(this),this.store),this.videoPlaylist=new zt(t,"video",this.syncRoomState.bind(this),this.store),this.syncRoomState("joinSync"),this.setState(i=>{var r;Object.assign(i.room,N.convertRoom(e,(r=this.sdk.getLocalPeer())==null?void 0:r.peerId)),i.room.isConnected=!0,i.room.roomState="Connected"},"joined"),t.onProgress(this.setProgress),t.onNewTrackStart(i=>{this.syncPlaylistState(`${i.type}PlaylistUpdate`)}),t.onPlaylistEnded(i=>{this.syncPlaylistState(`${i}PlaylistEnded`)}),t.onCurrentTrackEnded(i=>{this.hmsNotifications.sendPlaylistTrackEnded(N.convertPlaylistItem(t,i)),this.syncPlaylistState(`${i.type}PlaylistItemEnded`)})}onRoomUpdate(e,t){this.setState(i=>{var r;Object.assign(i.room,N.convertRoom(t,(r=this.sdk.getLocalPeer())==null?void 0:r.peerId))},e),e==="TRANSCRIPTION_STATE_UPDATED"&&this.hmsNotifications.sendTranscriptionUpdate(t.transcriptions)}onPeerUpdate(e,t){if(![4,5].includes(e)){if(Array.isArray(t)){let i=this.store.getState(Y),r=t.filter(n=>!i[n.peerId]);if(this.syncRoomState("peersJoined"),this.store.getState(Ce)){let n=[];for(let o of t){let l=this.store.getState(se(o.peerId));l&&n.push(l)}this.hmsNotifications.sendPeerList(n)}else r.forEach(n=>{let o=this.store.getState(se(n.peerId));o&&this.hmsNotifications.sendPeerUpdate(0,o)});return}this.sendPeerUpdateNotification(e,t)}}onTrackUpdate(e,t,i){if(e===1)this.hmsNotifications.sendTrackUpdate(e,t.trackId),this.handleTrackRemove(t,i);else if([0,1].includes(e)){let r=Qt[e];this.syncRoomState(r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}else{let r=Qt[e]||"trackUpdate",s=N.convertTrack(t);this.setState(n=>{let o=n.tracks[s.id];Ye(o,s)&&($s(o,s),Object.assign(o,s))},r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}}onMessageReceived(e){let t=N.convertMessage(e,this.store.getState(Ie));t.read=!1,t.ignored=this.ignoredMessageTypes.includes(t.type),t.type==="hms_transcript"&&(t.ignored=!0),this.putMessageInStore(t),this.hmsNotifications.sendMessageReceived(t)}putMessageInStore(e){e.ignored||this.actionBatcher.setState(t=>{t.messages.byID[e.id]=e,t.messages.allIDs.push(e.id)},"newMessage",150)}onAudioLevelUpdate(e){this.setState(t=>{let i={};e.forEach(s=>{if(!s.track||!s.peer)return;let n=s.track.trackId;i[n]=s.audioLevel,t.speakers[n]||(t.speakers[n]={audioLevel:s.audioLevel,peerID:s.peer.peerId,trackID:n})});let r=Object.entries(t.speakers);for(let[s,n]of r)n.audioLevel=i[s]||0,n.audioLevel===0&&delete t.speakers[s]},"audioLevel")}onConnectionQualityUpdate(e){this.setState(t=>{e.forEach(i=>{let r=i.peerID;r&&(t.connectionQualities[r]?Object.assign(t.connectionQualities[r],i):t.connectionQualities[r]=i)})},"connectionQuality")}onChangeTrackStateRequest(e){var s;let t=this.store.getState(se((s=e.requestedBy)==null?void 0:s.peerId)),i=this.getStoreLocalTrackIDfromSDKTrack(e.track),r=this.store.getState(Kt(i));if(!r)return this.logPossibleInconsistency(`Not found track for which track state change was requested, ${e.track}`);e.enabled||this.syncRoomState("changeTrackStateRequest"),this.hmsNotifications.sendChangeTrackStateRequest({requestedBy:t||void 0,track:r,enabled:e.enabled})}onChangeMultiTrackStateRequest(e){var s;let t=this.store.getState(se((s=e.requestedBy)==null?void 0:s.peerId));e.enabled||this.syncRoomState("changeMultiTrackStateRequest");let i=[],r=this.store.getState(_);for(let n of e.tracks){let o=this.getStoreLocalTrackIDfromSDKTrack(n);o&&r[o]&&i.push(r[o])}this.hmsNotifications.sendChangeMultiTrackStateRequest({requestedBy:t||void 0,tracks:i,enabled:e.enabled,type:e.type,source:e.source})}onReconnected(){this.syncRoomState("reconnectedSync"),this.hmsNotifications.sendReconnected(),this.setState(e=>{e.room.roomState=e.room.isConnected?"Connected":"Preview"},"reconnected")}onReconnecting(e){let t=N.convertException(e);b.e("Reconnection: received error from sdk",t),this.hmsNotifications.sendReconnecting(t),this.setState(i=>{i.room.roomState="Reconnecting",i.errors.push(t)},"reconnecting")}onError(e){let t=N.convertException(e);t.isTerminal?(this.leave().then(()=>b.e("error from SDK, left room.")),this.setState(i=>{i.room.roomState="Failed",i.errors.push(t)},"errorTerminal")):this.store.getState().errors.length<50&&this.setState(r=>{r.errors.push(t)},"error"),this.syncRoomState("errorSync"),this.hmsNotifications.sendError(t),b.e("received error from sdk",t instanceof k?`${t}`:t)}handleTrackRemove(e,t){this.setState(i=>{let r=i.peers[t.peerId],s=i.tracks,n=e.trackId;if(r)if(n===r.audioTrack)delete r.audioTrack;else if(n===r.videoTrack)delete r.videoTrack;else{let o=r.auxiliaryTracks.indexOf(n);o>-1&&r.auxiliaryTracks.splice(o,1)}delete s[n]},"trackRemoved")}setEnabledSDKTrack(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setEnabled(t):this.logPossibleInconsistency(`track ${e} not present, unable to enabled/disable`)})}setSDKLocalVideoTrackSettings(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setSettings(t):this.logPossibleInconsistency(`local track ${e} not present, unable to set settings`)})}setSDKLocalAudioTrackSettings(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setSettings(t):this.logPossibleInconsistency(`local track ${e} not present, unable to set settings`)})}getMediaSettings(e){var s;let t=this.store.getState(ks),i=e.audioTrack,r=e.videoTrack;return{audioInputDeviceId:(i==null?void 0:i.settings.deviceId)||t.audioInputDeviceId,videoInputDeviceId:(r==null?void 0:r.settings.deviceId)||t.videoInputDeviceId,audioOutputDeviceId:(s=this.sdk.getAudioOutput().getDevice())==null?void 0:s.deviceId,audioMode:(i==null?void 0:i.settings.audioMode)||"voice"}}getPreviewFields(e){var i,r;if(!e.isInPreview())return;let t=N.convertPeer(e);return{localPeer:t.id,audioTrack:t.audioTrack,videoTrack:t.videoTrack,asRole:((i=e.asRole)==null?void 0:i.name)||((r=e.role)==null?void 0:r.name)}}setTrackVolume(e,t){return c(this,null,function*(){let i=this.getTrackById(t);i?i instanceof Oe?(yield i.setVolume(e),this.setState(r=>{let s=r.tracks[t];s&&s.type==="audio"&&(s.volume=e)},"trackVolume")):b.w(`track ${t} is not an audio track`):this.logPossibleInconsistency(`track ${t} not present, unable to set volume`)})}localAndVideoUnmuting(e){let t=this.store.getState(X);if((t==null?void 0:t.videoTrack)!==e)return!1;let i=this.store.getState(Ps),r=this.store.getState(Ki);return i&&!r}logPossibleInconsistency(e){b.w("possible inconsistency detected - ",e)}addRemoveVideoPlugin(e,t,i){return c(this,null,function*(){if(!e){b.w("Invalid plugin received in store");return}let r=this.store.getState(ie);if(r){let s=this.getLocalTrack(r);s?(t==="add"?yield s.addPlugin(e,i):t==="remove"&&(yield s.removePlugin(e)),this.syncRoomState(`${t}VideoPlugin`)):this.logPossibleInconsistency(`track ${r} not present, unable to ${t} plugin`)}})}addRemoveMediaStreamVideoPlugins(e,t){return c(this,null,function*(){if(e.length===0){b.w("Invalid plugin received in store");return}let i=this.store.getState(ie);if(i){let r=this.getLocalTrack(i);r?(t==="add"?yield r.addStreamPlugins(e):t==="remove"&&(yield r.removeStreamPlugins(e)),this.syncRoomState(`${t}MediaStreamPlugin`)):this.logPossibleInconsistency(`track ${i} not present, unable to ${t} plugin`)}})}addRemoveAudioPlugin(e,t){return c(this,null,function*(){try{if(!e){b.w("Invalid plugin received in store");return}let i=this.store.getState(ue);if(i){let r=this.getLocalTrack(i);r?(t==="add"?yield r.addPlugin(e):t==="remove"&&(yield r.removePlugin(e)),this.syncRoomState(`${t}AudioPlugin`)):this.logPossibleInconsistency(`track ${i} not present, unable to ${t} plugin`)}}catch(i){console.error(i)}})}onRoleChangeRequest(e){this.setState(t=>{t.roleChangeRequests.length===0&&t.roleChangeRequests.push(N.convertRoleChangeRequest(e))},"roleChangeRequest")}removeRoleChangeRequest(e){this.setState(t=>{let i=t.roleChangeRequests.findIndex(r=>r.token===e.token);i!==-1&&t.roleChangeRequests.splice(i,1)},"removeRoleChangeRequest")}onRoleUpdate(){this.syncRoomState("roleUpdate")}getStoreLocalTrackIDfromSDKTrack(e){return this.store.getState(Es).find(i=>{var r;return((r=this.getTrackById(i))==null?void 0:r.trackId)===e.trackId})}updateMidCallPreviewRoomState(e,t){t.isLocal&&e===8&&this.store.getState(bs)&&this.setState(i=>{i.room.roomState="Connected"},"midCallPreviewCompleted")}setSessionStoreValueLocally(e,t="setSessionStore"){let i=Array.isArray(e)?e:[e];this.setState(r=>{i.forEach(s=>{r.sessionStore[s.key]=s.value})},t)}hasActiveElements(e){let t=Object.keys(this.store.getState().whiteboards).length>0,i=Object.keys(this.store.getState().polls).length>0,r=Object.keys(this.store.getState().peers).length>0,s=e.getState().remoteTrackStats;return r&&(t||i||Object.values(s).some(n=>n&&typeof n.bitrate=="number"&&n.bitrate>0))}};var nr=a=>F?`${a} ${document.title}`:a;var or=class{constructor(e,t){this.eventBus=e;this.listener=t;this.TAG="[NetworkTestManager]";this.controller=new AbortController;this.start=e=>c(this,null,function*(){var u;if(!e)return;let{url:t,timeout:i,scoreMap:r}=e,s=this.controller.signal,n=Date.now(),o=0,l=te(i).then(()=>{this.controller.abort()});try{let h=(u=(yield fetch(`${t}?${Date.now()}`,{signal:s})).body)==null?void 0:u.getReader();if(!h)throw Error("unable to process request");let T=()=>c(this,null,function*(){if(h)try{let g=!1;for(;!g;){let{value:f,done:P}=yield h.read();g=P,f&&(o+=f.byteLength,this.sendScore({scoreMap:r,downloadedSize:o,startTime:n}))}}catch(g){g.name!=="AbortError"&&d.d(this.TAG,g)}});return Promise.race([T(),l]).then(()=>{this.sendScore({scoreMap:r,downloadedSize:o,startTime:n,finished:!0})}).catch(g=>{d.d(this.TAG,g),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:g.message}))})}catch(p){p.name!=="AbortError"?(d.d(this.TAG,p),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:p.message}))):d.d(this.TAG,p)}});this.stop=()=>{this.controller.signal.aborted||this.controller.abort()};this.sendScore=({scoreMap:e,downloadedSize:t,startTime:i,finished:r=!1})=>{let s=(Date.now()-i)/1e3,o=t/1024/s*8,l=-1;for(let u in e){let p=e[u];o>=p.low&&(!p.high||o<=p.high)&&(l=Number(u))}this.updateScoreToListener(l),r&&this.eventBus.analytics.publish(y.previewNetworkQuality({score:l,downLink:o.toFixed(2)}))}}updateScoreToListener(e){var t,i;e!==this.score&&(this.score=e,(i=(t=this.listener)==null?void 0:t.onNetworkQuality)==null||i.call(t,e))}};var Yt=class{constructor(e,t,i,r,s,n){this.store=e;this.transport=t;this.deviceManager=i;this.publish=r;this.removeAuxiliaryTrack=s;this.listener=n;this.handleLocalPeerRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){var s;let r=this.store.getLocalPeer();r&&(yield this.diffRolesAndPublishTracks({oldRole:e,newRole:t}),(s=this.listener)==null||s.onPeerUpdate(8,r))});this.diffRolesAndPublishTracks=i=>c(this,[i],function*({oldRole:e,newRole:t}){var g,f,P,v,A,$;let r=new Set(e.publishParams.allowed),s=new Set(t.publishParams.allowed),n=this.removeTrack(r,s,"video"),o=this.removeTrack(r,s,"audio"),l=this.removeTrack(r,s,"screen"),u=this.hasSimulcastDifference((g=e.publishParams.simulcast)==null?void 0:g.video,(f=t.publishParams.simulcast)==null?void 0:f.video),p=this.hasSimulcastDifference((P=e.publishParams.simulcast)==null?void 0:P.screen,(v=t.publishParams.simulcast)==null?void 0:v.screen),h=($=(A=this.store.getLocalPeer())==null?void 0:A.videoTrack)==null?void 0:$.enabled;yield this.removeAudioTrack(o),yield this.removeVideoTracks(n||u),yield this.removeScreenTracks(l||p);let T=this.getSettings();u&&(T.isVideoMuted=!h),yield this.publish(T),yield this.syncDevices(T,t)})}syncDevices(e,t){return c(this,null,function*(){(!e.isAudioMuted||!e.isVideoMuted)&&t.publishParams.allowed.length>0&&(yield this.deviceManager.init(!0))})}removeVideoTracks(e){return c(this,null,function*(){var i;if(!e)return;let t=this.store.getLocalPeer();t!=null&&t.videoTrack&&(t.videoTrack.isPublished?yield this.transport.unpublish([t.videoTrack]):yield t.videoTrack.cleanup(),(i=this.listener)==null||i.onTrackUpdate(1,t.videoTrack,t),t.videoTrack=void 0),yield this.removeAuxTracks(r=>r.source!=="screen"&&r.type==="video")})}removeAudioTrack(e){return c(this,null,function*(){var i;if(!e)return;let t=this.store.getLocalPeer();t!=null&&t.audioTrack&&(t.audioTrack.isPublished?yield this.transport.unpublish([t.audioTrack]):yield t.audioTrack.cleanup(),(i=this.listener)==null||i.onTrackUpdate(1,t.audioTrack,t),t.audioTrack=void 0),yield this.removeAuxTracks(r=>r.source!=="screen"&&r.type==="audio")})}removeScreenTracks(e){return c(this,null,function*(){e&&(yield this.removeAuxTracks(t=>t.source==="screen"))})}removeAuxTracks(e){return c(this,null,function*(){let t=this.store.getLocalPeer();if(t!=null&&t.auxiliaryTracks){let i=[...t.auxiliaryTracks];for(let r of i)e(r)&&(yield this.removeAuxiliaryTrack(r.trackId))}})}removeTrack(e,t,i){return e.has(i)&&!t.has(i)}hasSimulcastDifference(e,t){var i,r,s;return!e&&!t?!1:((i=e==null?void 0:e.layers)==null?void 0:i.length)!==((r=t==null?void 0:t.layers)==null?void 0:r.length)?!0:!!((s=e==null?void 0:e.layers)!=null&&s.some(n=>{var l;let o=(l=t==null?void 0:t.layers)==null?void 0:l.find(u=>u.rid===n.rid);return(o==null?void 0:o.maxBitrate)!==n.maxBitrate||(o==null?void 0:o.maxFramerate)!==n.maxFramerate}))}getSettings(){let{isAudioMuted:e,isVideoMuted:t}=this.getMutedStatus(),{audioInputDeviceId:i,audioOutputDeviceId:r}=this.getAudioDeviceSettings(),s=this.getVideoInputDeviceId();return{isAudioMuted:e,isVideoMuted:t,audioInputDeviceId:i,audioOutputDeviceId:r,videoDeviceId:s}}getMutedStatus(){var t,i,r;let e=(t=this.store.getConfig())==null?void 0:t.settings;return{isAudioMuted:(i=e==null?void 0:e.isAudioMuted)!=null?i:!0,isVideoMuted:(r=e==null?void 0:e.isVideoMuted)!=null?r:!0}}getAudioDeviceSettings(){var r,s,n;let e=(r=this.store.getConfig())==null?void 0:r.settings,t=((s=this.deviceManager.currentSelection.audioInput)==null?void 0:s.deviceId)||(e==null?void 0:e.audioInputDeviceId)||"default",i=((n=this.deviceManager.currentSelection.audioOutput)==null?void 0:n.deviceId)||(e==null?void 0:e.audioOutputDeviceId)||"default";return{audioInputDeviceId:t,audioOutputDeviceId:i}}getVideoInputDeviceId(){var t,i;let e=(t=this.store.getConfig())==null?void 0:t.settings;return((i=this.deviceManager.currentSelection.videoInput)==null?void 0:i.deviceId)||(e==null?void 0:e.videoDeviceId)||"default"}};var qs=class{constructor(){this.TAG="[HTTPAnalyticsTransport]";this.failedEvents=new Ee("client-events");this.isConnected=!0;this.env=null;this.websocketURL=""}setEnv(e){this.env=e,this.flushFailedEvents()}setWebsocketEndpoint(e){this.websocketURL=e}sendEvent(e){if(!this.env){this.addEventToStorage(e);return}let t={event:e.name,payload:e.properties,event_id:String(e.timestamp),peer:e.metadata.peer,timestamp:e.timestamp,device_id:e.device_id,cluster:{websocket_url:this.websocketURL}},i=this.env==="prod"?Ra:Ha;fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.metadata.token}`,user_agent_v2:e.metadata.userAgent},body:JSON.stringify(t)}).then(r=>{if(r.status===401){this.removeFromStorage(e);return}if(r.status!==200)throw Error(r.statusText);this.removeFromStorage(e)}).catch(r=>{d.v(this.TAG,"Failed to send event",r,e),this.addEventToStorage(e)})}flushFailedEvents(){let e=this.failedEvents.get();e==null||e.forEach(t=>this.sendEvent(t))}addEventToStorage(e){let t=this.failedEvents.get()||[];t.find(i=>i.timestamp===e.timestamp)||(t.length===100&&t.shift(),t.push(e),this.failedEvents.set(t))}removeFromStorage(e){let t=this.failedEvents.get()||[],i=t.findIndex(r=>r.timestamp===e.timestamp);i>-1&&(t.splice(i,1),this.failedEvents.set(t))}},Le=new qs;var Xt=class{constructor(e){this.type=e.type,this.source=e.source||"regular",this.description="",e instanceof Ne?(this.mute=!e.enabled,this.track_id=e.publishedTrackId,this.stream_id=e.stream.id):(this.mute=e.mute,this.track_id=e.track_id,this.stream_id=e.stream_id)}};var Zt=class{constructor(){this.TAG="[Store]:";this.knownRoles={};this.peers={};this.tracks=new Map;this.peerTrackStates={};this.speakers=[];this.roleDetailsArrived=!1;this.env="prod";this.simulcastEnabled=!1;this.userAgent=Nt(this.env);this.polls=new Map;this.whiteboards=new Map;this.addPermissionToRole=(e,t,i,r)=>{var n;if(!this.knownRoles[e]){d.d(this.TAG,`role ${e} is not present in given roles`,this.knownRoles);return}let s=this.knownRoles[e].permissions;t==="transcriptions"&&r?s[t]=M(m({},s[t]),{[r]:[i]}):t==="whiteboard"&&(s[t]||(s[t]=[]),(n=s[t])==null||n.push(i))};this.addWhiteboardPluginToRole=e=>{var i,r,s;let t=e==null?void 0:e.permissions;(i=t==null?void 0:t.admin)==null||i.forEach(n=>this.addPermissionToRole(n,"whiteboard","admin")),(r=t==null?void 0:t.reader)==null||r.forEach(n=>this.addPermissionToRole(n,"whiteboard","read")),(s=t==null?void 0:t.writer)==null||s.forEach(n=>this.addPermissionToRole(n,"whiteboard","write"))};this.addTranscriptionsPluginToRole=(e=[])=>{var t,i;for(let r of e)(i=(t=r.permissions)==null?void 0:t.admin)==null||i.forEach(s=>this.addPermissionToRole(s,"transcriptions","admin",r.mode)),r.translation&&this.room&&(this.room.translationConfig||(this.room.translationConfig={}),this.room.translationConfig[r.mode]=r.translation)};this.handleNoiseCancellationPlugin=e=>{this.room&&(this.room.isNoiseCancellationEnabledFromPolicy=!!(e!=null&&e.enabled))}}getConfig(){return this.config}setSimulcastEnabled(e){this.simulcastEnabled=e}removeRemoteTracks(){this.tracks.forEach(e=>{(e instanceof le||e instanceof x)&&(this.removeTrack(e),delete this.peerTrackStates[e.trackId])})}getEnv(){return this.env}getPublishParams(){let e=this.getLocalPeer(),t=(e==null?void 0:e.asRole)||(e==null?void 0:e.role);return t==null?void 0:t.publishParams}getRoom(){return this.room}getPolicyForRole(e){return this.knownRoles[e]}getKnownRoles(){return this.knownRoles}getTemplateAppData(){return this.templateAppData}getLocalPeer(){if(this.localPeerId&&this.peers[this.localPeerId])return this.peers[this.localPeerId]}getRemotePeers(){return Object.values(this.peers).filter(e=>!e.isLocal)}getPeers(){return Object.values(this.peers)}getPeerMap(){return this.peers}getPeerById(e){if(this.peers[e])return this.peers[e]}getTracksMap(){return this.tracks}getTracks(){return Array.from(this.tracks.values())}getVideoTracks(){return this.getTracks().filter(e=>e.type==="video")}getRemoteVideoTracks(){return this.getTracks().filter(e=>e instanceof x)}getAudioTracks(){return this.getTracks().filter(e=>e.type==="audio")}getPeerTracks(e){let t=e?this.peers[e]:void 0,i=[];return t!=null&&t.videoTrack&&i.push(t.videoTrack),t!=null&&t.audioTrack&&i.push(t.audioTrack),i.concat((t==null?void 0:t.auxiliaryTracks)||[])}getLocalPeerTracks(){return this.getPeerTracks(this.localPeerId)}hasTrack(e){return this.tracks.has(e)}getTrackById(e){var r,s;let t=Array.from(this.tracks.values()).find(n=>n.trackId===e);if(t)return t;let i=this.getLocalPeer();if(i){if((r=i.audioTrack)!=null&&r.isPublishedTrackId(e))return i.audioTrack;if((s=i.videoTrack)!=null&&s.isPublishedTrackId(e))return i.videoTrack}}getPeerByTrackId(e){let t=Array.from(this.tracks.values()).find(i=>i.trackId===e);return t!=null&&t.peerId?this.peers[t.peerId]:void 0}getSpeakers(){return this.speakers}getSpeakerPeers(){return this.speakers.map(e=>e.peer)}getUserAgent(){return this.userAgent}createAndSetUserAgent(e){this.userAgent=Nt(this.env,e)}setRoom(e){this.room=e}setKnownRoles(e){var i,r,s;if(this.knownRoles=e.known_roles,this.addPluginsToRoles(e.plugins),this.handleNoiseCancellationPlugin((i=e.plugins)==null?void 0:i.noiseCancellation),this.roleDetailsArrived=!0,this.templateAppData=e.app_data,!this.simulcastEnabled)return;let t=(r=this.knownRoles[e.name])==null?void 0:r.publishParams;this.videoLayers=this.convertSimulcastLayers((s=t.simulcast)==null?void 0:s.video),this.updatePeersPolicy()}hasRoleDetailsArrived(){return this.roleDetailsArrived}setConfig(e){var t,i,r;if(ae.rememberDevices(!!e.rememberDeviceSelection),e.rememberDeviceSelection){let s=ae.getSelection();s&&(e.settings||(e.settings={}),(t=s.audioInput)!=null&&t.deviceId&&(e.settings.audioInputDeviceId=e.settings.audioInputDeviceId||s.audioInput.deviceId),(i=s.audioOutput)!=null&&i.deviceId&&(e.settings.audioOutputDeviceId=e.settings.audioOutputDeviceId||s.audioOutput.deviceId),(r=s.videoInput)!=null&&r.deviceId&&(e.settings.videoDeviceId=e.settings.videoDeviceId||s.videoInput.deviceId))}e.autoManageVideo=e.autoManageVideo!==!1,e.autoManageWakeLock=e.autoManageWakeLock!==!1,this.config=e,this.setEnv()}addPeer(e){this.peers[e.peerId]=e,e.isLocal&&(this.localPeerId=e.peerId)}addTrack(e){this.tracks.set(e,e)}getTrackState(e){return this.peerTrackStates[e]}setTrackState(e){this.peerTrackStates[e.trackInfo.track_id]=e}removeTrackState(e){delete this.peerTrackStates[e]}removePeer(e){this.localPeerId===e&&(this.localPeerId=void 0),delete this.peers[e]}removeTrack(e){this.tracks.delete(e)}updateSpeakers(e){this.speakers=e}updateAudioOutputVolume(e){return c(this,null,function*(){yield Promise.all(this.getAudioTracks().map(t=>t.setVolume(e)))})}updateAudioOutputDevice(e){return c(this,null,function*(){let t=[];this.getAudioTracks().forEach(s=>{s instanceof le&&t.push(s.setOutputDevice(e))});let r=(yield Promise.allSettled(t)).filter(s=>s.status==="rejected");if(r.length>0)throw new Error(`updateAudioOutputDevice: ${r.length}/${t.length} track(s) failed to switch sink: ${r[0].reason}`)})}getSimulcastLayers(e){var t;return!this.simulcastEnabled||!["screen","regular"].includes(e)?[]:e==="screen"?[]:((t=this.videoLayers)==null?void 0:t.layers)||[]}convertSimulcastLayers(e){if(e)return M(m({},e),{layers:(e.layers||[]).map(t=>M(m({},t),{maxBitrate:t.maxBitrate*1e3}))})}getSimulcastDefinitionsForPeer(e,t){var o,l,u;if([!e||!e.role,t==="screen",!this.simulcastEnabled].some(p=>!!p))return[];let i=this.getPolicyForRole(e.role.name).publishParams,r,s,n;return t==="regular"?(r=(o=i.simulcast)==null?void 0:o.video,s=i.video.width,n=i.video.height):t==="screen"&&(r=(l=i.simulcast)==null?void 0:l.screen,s=i.screen.width,n=i.screen.height),((u=r==null?void 0:r.layers)==null?void 0:u.map(p=>{let h=Ue[p.rid],T={width:Math.floor(s/p.scaleResolutionDownBy),height:Math.floor(n/p.scaleResolutionDownBy)};return{layer:h,resolution:T}}))||[]}setPoll(e){this.polls.set(e.id,e)}getPoll(e){return this.polls.get(e)}setWhiteboard(e){this.whiteboards.set(e.id,e)}getWhiteboards(){return this.whiteboards}getWhiteboard(e){return e?this.whiteboards.get(e):this.whiteboards.values().next().value}getErrorListener(){return this.errorListener}cleanup(){let e=this.getTracks();for(let t of e)t.cleanup();this.room=void 0,this.config=void 0,this.localPeerId=void 0,this.roleDetailsArrived=!1}setErrorListener(e){this.errorListener=e}updatePeersPolicy(){this.getPeers().forEach(e=>{var t;if(!e.role){(t=this.errorListener)==null||t.onError(S.GenericErrors.InvalidRole("VALIDATION",""));return}e.role=this.getPolicyForRole(e.role.name)})}addPluginsToRoles(e){e&&Object.keys(e).forEach(t=>{let i=t;switch(i){case"whiteboard":{this.addWhiteboardPluginToRole(e[i]);break}case"transcriptions":{this.addTranscriptionsPluginToRole(e[i]);break}default:break}})}setEnv(){var r;let t=((r=this.config)==null?void 0:r.initEndpoint).split("https://")[1],i="prod";t.startsWith("prod")?i="prod":t.startsWith("qa")?i="qa":t.startsWith("dev")&&(i="dev"),this.env=i,Le.setEnv(i)}};var cr=class{constructor(){this.TAG="[WakeLockManager]";this.wakeLock=null;this.acquireLock=()=>c(this,null,function*(){yield this.requestWakeLock(),document==null||document.addEventListener("visibilitychange",this.visibilityHandler)});this.cleanup=()=>c(this,null,function*(){if(this.wakeLock&&!this.wakeLock.released)try{yield this.wakeLock.release(),d.d(this.TAG,"Wake lock released")}catch(e){let t=e;d.w(this.TAG,"Error while releasing wake lock",`name=${t.name}, message=${t.message}`)}document==null||document.removeEventListener("visibilitychange",this.visibilityHandler),this.wakeLock=null});this.visibilityHandler=()=>c(this,null,function*(){(document==null?void 0:document.visibilityState)==="visible"&&(!this.wakeLock||this.wakeLock.released)&&(d.d(this.TAG,"Re-acquiring wake lock due to visibility change"),yield this.requestWakeLock())});this.requestWakeLock=()=>c(this,null,function*(){try{if(!("wakeLock"in navigator)){d.d(this.TAG,"Wake lock feature not supported");return}this.wakeLock=yield navigator.wakeLock.request("screen"),d.d(this.TAG,"Wake lock acquired")}catch(e){let t=e;d.w(this.TAG,"Error acquiring wake lock",`name=${t.name}, message=${t.message}`)}})}};var dr=class{constructor(e){this.store=e;this.bufferSize=100;this.TAG="[AnalyticsEventsService]";this.transport=null;this.pendingEvents=[];this.level=1}setTransport(e){this.transport=e}reset(){this.transport=null,this.pendingEvents=[]}queue(e){if(e.level>=this.level&&(this.pendingEvents.push(e),this.pendingEvents.length>this.bufferSize)){let t=this.pendingEvents.shift();d.d(this.TAG,"Max buffer size reached","Removed event to accommodate new events",t)}return this}flushFailedClientEvents(){Le.flushFailedEvents()}flush(){var e;try{for(;this.pendingEvents.length>0;){let t=this.pendingEvents.shift();t&&(t.metadata.peer.peer_id=(e=this.store.getLocalPeer())==null?void 0:e.peerId,t.metadata.userAgent=this.store.getUserAgent(),this.transport&&this.transport.transportProvider.isConnected?this.transport.sendEvent(t):this.sendClientEventOnHTTP(t))}}catch(t){d.w(this.TAG,"Flush Failed",t)}}sendClientEventOnHTTP(e){var r,s,n,o;let t=this.store.getRoom(),i=this.store.getLocalPeer();e.metadata.token=(r=this.store.getConfig())==null?void 0:r.authToken,e.metadata.peer={session_id:t==null?void 0:t.sessionId,room_id:t==null?void 0:t.id,room_name:t==null?void 0:t.name,template_id:t==null?void 0:t.templateId,joined_at:(s=t==null?void 0:t.joinedAt)==null?void 0:s.getTime(),session_started_at:(n=t==null?void 0:t.startedAt)==null?void 0:n.getTime(),role:(o=i==null?void 0:i.role)==null?void 0:o.name,user_name:i==null?void 0:i.name,user_data:i==null?void 0:i.metadata,peer_id:i==null?void 0:i.peerId},Le.sendEvent(e)}};var Bn=require("uuid");var Un={autoplayFailed:void 0,initialized:!1,autoplayCheckPromise:void 0},ei=class{constructor(e,t,i){this.store=e;this.deviceManager=t;this.eventBus=i;this.autoPausedTracks=new Set;this.TAG="[AudioSinkManager]:";this.volume=100;this.state=m({},Un);this.handleAudioPaused=e=>c(this,null,function*(){d.d(this.TAG,"Audio Paused",e.target.id);let t=this.store.getTrackById(e.target.id);t&&this.autoPausedTracks.add(t)});this.handleTrackUpdate=({track:e})=>{d.d(this.TAG,"Track updated",`${e}`)};this.handleTrackAdd=r=>c(this,[r],function*({track:e,peer:t,callListener:i=!0}){var o,l,u,p;let s=document.createElement("audio");s.style.display="none",s.id=e.trackId;let n=(o=e.getRequestedVolume())!=null?o:this.volume;s.volume=n/100,s.addEventListener("pause",this.handleAudioPaused),s.onerror=()=>c(this,null,function*(){var T,g;d.e(this.TAG,"error on audio element",s.error);let h=S.TracksErrors.AudioPlaybackError(`Audio playback error for track - ${e.trackId} code - ${(T=s==null?void 0:s.error)==null?void 0:T.code}`);this.eventBus.analytics.publish(y.audioPlaybackError(h)),((g=s==null?void 0:s.error)==null?void 0:g.code)===MediaError.MEDIA_ERR_DECODE&&(this.removeAudioElement(s,e),yield te(500),yield this.handleTrackAdd({track:e,peer:t,callListener:!1}),this.state.autoplayFailed||this.eventBus.analytics.publish(y.audioRecovered("Audio recovered after media decode error")))}),e.setAudioElement(s),d.d(this.TAG,"Audio track added",`${e}`),this.init(),(l=this.audioSink)==null||l.append(s),this.outputDevice&&(yield e.setOutputDevice(this.outputDevice)),s.srcObject=new MediaStream([e.nativeTrack]),i&&((u=this.listener)==null||u.onTrackUpdate(0,e,t)),yield this.handleAutoplayError(e),e.setVolume((p=e.getRequestedVolume())!=null?p:this.volume).catch(h=>d.e(this.TAG,"Could not apply audio subscription state",`${e}`,h))});this.handleAutoplayError=e=>c(this,null,function*(){if(this.state.autoplayFailed===void 0&&(this.state.autoplayCheckPromise||(this.state.autoplayCheckPromise=new Promise(t=>{this.playAudioFor(e).then(t)})),yield this.state.autoplayCheckPromise),this.state.autoplayFailed){this.autoPausedTracks.add(e);return}yield this.playAudioFor(e)});this.handleAudioDeviceChange=e=>c(this,null,function*(){e.isUserSelection||e.error||!e.selection||e.type==="video"||(yield this.unpauseAudioTracks())});this.handleTrackRemove=e=>{this.autoPausedTracks.delete(e);let t=document.getElementById(e.trackId);t&&this.removeAudioElement(t,e),this.audioSink&&this.audioSink.childElementCount===0&&(this.state.autoplayCheckPromise=void 0,this.state.autoplayFailed=void 0),d.d(this.TAG,"Audio track removed",`${e}`)};this.unpauseAudioTracks=()=>c(this,null,function*(){let e=[];this.autoPausedTracks.forEach(t=>{e.push(this.playAudioFor(t))}),yield Promise.all(e)});this.removeAudioElement=(e,t)=>{e&&(d.d(this.TAG,"removing audio element",`${t}`),e.removeEventListener("pause",this.handleAudioPaused),e.srcObject=null,e.remove(),t.setAudioElement(null))};this.eventBus.audioTrackAdded.subscribe(this.handleTrackAdd),this.eventBus.audioTrackRemoved.subscribe(this.handleTrackRemove),this.eventBus.audioTrackUpdate.subscribe(this.handleTrackUpdate),this.eventBus.deviceChange.subscribe(this.handleAudioDeviceChange),this.eventBus.localVideoUnmutedNatively.subscribe(this.unpauseAudioTracks),this.eventBus.localAudioUnmutedNatively.subscribe(this.unpauseAudioTracks)}setListener(e){this.listener=e}get outputDevice(){return this.deviceManager.outputDevice}getVolume(){return this.volume}setVolume(e){return c(this,null,function*(){if(!(e>=0&&e<=100))throw Error("Please pass a valid number between 0-100");this.volume=e,yield this.store.updateAudioOutputVolume(e)})}unblockAutoplay(){return c(this,null,function*(){this.autoPausedTracks.size>0&&(yield this.unpauseAudioTracks()),yield ne.resumeContext()})}init(e){if(this.state.initialized||this.audioSink)return;this.state.initialized=!0;let t=document.createElement("div");t.id=`HMS-SDK-audio-sink-${(0,Bn.v4)()}`,(e&&document.getElementById(e)||document.body).append(t),this.audioSink=t,d.d(this.TAG,"audio sink created",this.audioSink)}cleanup(){var e;(e=this.audioSink)==null||e.remove(),this.audioSink=void 0,this.eventBus.audioTrackAdded.unsubscribe(this.handleTrackAdd),this.eventBus.audioTrackRemoved.unsubscribe(this.handleTrackRemove),this.eventBus.audioTrackUpdate.unsubscribe(this.handleTrackUpdate),this.eventBus.deviceChange.unsubscribe(this.handleAudioDeviceChange),this.eventBus.localVideoUnmutedNatively.unsubscribe(this.unpauseAudioTracks),this.eventBus.localAudioUnmutedNatively.unsubscribe(this.unpauseAudioTracks),this.autoPausedTracks=new Set,this.state=m({},Un)}playAudioFor(e){return c(this,null,function*(){let t=e.getAudioElement();if(!t){d.w(this.TAG,"No audio element found on track",e.trackId);return}try{yield t.play(),this.state.autoplayFailed=!1,this.autoPausedTracks.delete(e),d.d(this.TAG,"Played track",`${e}`)}catch(i){this.autoPausedTracks.add(e),d.w(this.TAG,"Failed to play track",`${e}`,i);let r=i;if(!this.state.autoplayFailed&&r.name==="NotAllowedError"){this.state.autoplayFailed=!0;let s=S.TracksErrors.AutoplayBlocked("AUTOPLAY","");s.addNativeError(r),this.eventBus.analytics.publish(y.autoplayError()),this.eventBus.autoplayError.publish(s)}}})}};var lr=class{constructor(e){this.eventBus=e;this.pluginUsage=new Map;this.pluginLastAddedAt=new Map;this.getPluginUsage=e=>{if(this.pluginUsage.has(e)||this.pluginUsage.set(e,0),this.pluginLastAddedAt.has(e)){let i=this.pluginLastAddedAt.get(e)||0,r=i?Date.now()-i:0;this.pluginUsage.set(e,(this.pluginUsage.get(e)||0)+r),this.pluginLastAddedAt.delete(e)}return this.pluginUsage.get(e)};this.updatePluginUsageData=e=>{var i;let t=((i=e.properties)==null?void 0:i.plugin_name)||"";switch(e.name){case"mediaPlugin.toggled.on":case"mediaPlugin.added":{let r=e.properties.added_at||Date.now();this.pluginLastAddedAt.set(t,r);break}case"mediaPlugin.toggled.off":case"mediaPlugin.failed":case"mediaPlugin.stats":{if(this.pluginLastAddedAt.has(t)){let r=e.properties.duration||(Date.now()-(this.pluginLastAddedAt.get(t)||0))/1e3;this.pluginUsage.set(t,(this.pluginUsage.get(t)||0)+Math.max(r,0)*1e3),this.pluginLastAddedAt.delete(t)}break}default:}};this.cleanup=()=>{this.pluginLastAddedAt.clear(),this.pluginUsage.clear()};this.eventBus.analytics.subscribe(t=>this.updatePluginUsageData(t))}};var ti=class{constructor(e,t){this.store=e;this.eventBus=t;this.audioInput=[];this.audioOutput=[];this.videoInput=[];this.hasWebcamPermission=!1;this.hasMicrophonePermission=!1;this.currentSelection={audioInput:void 0,videoInput:void 0,audioOutput:void 0};this.TAG="[Device Manager]:";this.initialized=!1;this.videoInputChanged=!1;this.audioInputChanged=!1;this.earpieceSelected=!1;this.timer=null;this.updateOutputDevice=(e,t)=>c(this,null,function*(){let i=this.audioOutput.find(r=>r.deviceId===e);if(!i){d.d(this.TAG,"updateOutputDevice - requested device not in the enumerated audioOutput list",`{
96
+ }`}};var Ft=class extends ut{constructor(t){super(M(m({},t),{isLocal:!1}));this.isLocal=!1;this.auxiliaryTracks=[];this.fromRoomState=!1;this.fromRoomState=!!t.fromRoomState}};var be=(a,e)=>new Ft({peerId:a.peer_id,name:a.info.name,role:e.getPolicyForRole(a.role),customerUserId:a.info.user_id,metadata:a.info.data,groups:a.groups,type:a.info.type});var Fi=class{constructor(e,t,i){this.transport=e;this.store=t;this.options=i;this.isEnd=!1;this.iterator=null;this.total=0;this.defaultPaginationLimit=10}validateConnection(){if(!this.transport||!this.store)throw Error("Use usePaginatedParticipants or hmsActions.getPeerListIterator after preview or join has happened")}hasNext(){return!this.isEnd}getTotal(){return this.total}findPeers(){return c(this,null,function*(){var t;this.validateConnection();let e=yield this.transport.signal.findPeers(M(m({},this.options||{}),{limit:((t=this.options)==null?void 0:t.limit)||this.defaultPaginationLimit}));return this.updateState(e),this.processPeers(e.peers)})}next(){return c(this,null,function*(){var t;this.validateConnection();let e;return!this.iterator&&!this.isEnd?yield this.findPeers():this.iterator?(e=yield this.transport.signal.peerIterNext({iterator:this.iterator,limit:((t=this.options)==null?void 0:t.limit)||this.defaultPaginationLimit}),this.updateState(e),this.processPeers(e.peers)):[]})}processPeers(e){let t=[];return e.forEach(i=>{let r=be(i,this.store);t.push(r)}),t}updateState(e){this.isEnd=e.eof,this.total=e.total,e.iterator&&(this.iterator=e.iterator)}};var ht=class{constructor(e){this.TAG="[AudioContextManager]";this.audioContext=new AudioContext,this.source=this.audioContext.createMediaElementSource(e),this.source.connect(this.audioContext.destination)}resumeContext(){return c(this,null,function*(){let e=this.audioContext.state;e==="running"||e==="closed"||(yield this.audioContext.resume(),d.d(this.TAG,"AudioContext is resumed",`from ${e}`))})}getAudioTrack(){return this.destinationNode&&this.source.disconnect(this.destinationNode),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.source.connect(this.destinationNode),this.destinationNode.stream.getAudioTracks()[0]}cleanup(){this.audioContext.state!=="closed"&&this.audioContext.close().catch(e=>{d.d(this.TAG,"AudioContext close error",e.message)})}};var rn=require("eventemitter2"),Ge=class extends rn.EventEmitter2{on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,t){return super.emit(e,t)}listeners(e){return super.listeners(e)}};var Gi=class extends Ge{constructor(){super(...arguments);this.audioElement=null;this.TAG="[PlaylistAudioManager]";this.seeked=!1}play(t){return c(this,null,function*(){return this.audioElement=this.getAudioElement(),new Promise((i,r)=>{this.audioElement=this.getAudioElement(),this.audioElement.src=t,this.seeked=!1,this.audioElement.onerror=()=>{let s=`Error loading ${t}`;d.e(this.TAG,s),this.stop(),r(s)},this.audioElement.oncanplaythrough=()=>c(this,null,function*(){try{if(!this.audioElement)return;if(this.audioContextManager.resumeContext(),this.track)this.seeked?this.seeked=!1:(yield this.audioElement.play(),i([this.track]));else{yield this.audioElement.play();let s=this.audioContextManager.getAudioTrack();this.track=s,i([s])}}catch(s){d.e(this.TAG,"Error playing audio",t,s.message),r(s)}}),this.audioElement.onseeked=()=>{this.seeked=!0}})})}getTracks(){return this.track?[this.track.id]:[]}getElement(){return this.audioElement||(this.audioElement=this.getAudioElement()),this.audioElement}stop(){var t,i,r;(t=this.audioElement)==null||t.pause(),(i=this.audioElement)==null||i.removeAttribute("src"),this.audioElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.track=void 0}getAudioElement(){if(this.audioElement)return this.audioElement;let t=document.createElement("audio");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new ht(t),t}};var $i=class extends Ge{constructor(){super(...arguments);this.TAG="[PlaylistVideoManager]";this.videoElement=null;this.canvasContext=null;this.tracks=[];this.DEFAUL_FPS=24;this.seeked=!1;this.drawImage=()=>{var t,i,r;this.videoElement&&!this.videoElement.paused&&!this.videoElement.ended&&((r=this.canvasContext)==null||r.drawImage(this.videoElement,0,0,(t=this.canvas)==null?void 0:t.width,(i=this.canvas)==null?void 0:i.height),this.timer=setTimeout(()=>{this.drawImage()},1e3/this.DEFAUL_FPS))}}play(t){return this.videoElement=this.getVideoElement(),this.createCanvas(),new Promise((i,r)=>{this.videoElement=this.getVideoElement(),this.videoElement.src=t,this.seeked=!1,this.videoElement.onerror=()=>{let s=`Error loading ${t}`;d.e(this.TAG,s),this.stop(),r(s)},this.videoElement.oncanplaythrough=()=>c(this,null,function*(){var s,n,o;try{if(!this.videoElement)return;if(this.canvas.width=this.videoElement.videoWidth,this.canvas.height=this.videoElement.videoHeight,this.tracks.length===0){this.clearCanvasAndTracks();let l=this.canvas.captureStream();if(!l){d.e(this.TAG,"Browser does not support captureStream");return}this.videoElement.onplay=this.drawImage,yield this.audioContextManager.resumeContext(),yield this.videoElement.play();let u=this.audioContextManager.getAudioTrack();l.addTrack(u),l.getTracks().forEach(p=>{this.tracks.push(p)}),i(this.tracks)}else this.seeked?(this.seeked=!1,(o=this.canvasContext)==null||o.drawImage(this.videoElement,0,0,(s=this.canvas)==null?void 0:s.width,(n=this.canvas)==null?void 0:n.height)):(yield this.videoElement.play(),i(this.tracks))}catch(l){d.e(this.TAG,"Error playing video",t,l.message),r(l)}}),this.videoElement.onseeked=()=>{this.seeked=!0}})}getTracks(){return this.tracks.map(t=>t.id)}getElement(){return this.videoElement||(this.videoElement=this.getVideoElement()),this.videoElement}stop(){var t,i,r;(t=this.videoElement)==null||t.pause(),(i=this.videoElement)==null||i.removeAttribute("src"),this.videoElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.clearCanvasAndTracks()}clearCanvasAndTracks(){var t;this.tracks=[],(t=this.canvasContext)==null||t.clearRect(0,0,this.canvas.width,this.canvas.height),clearTimeout(this.timer)}getVideoElement(){if(this.videoElement)return this.videoElement;let t=document.createElement("video");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new ht(t),t}createCanvas(){this.canvas||(this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"))}};var Wi={audio:{list:[],currentIndex:-1,isAutoplayOn:!0},video:{list:[],currentIndex:-1,isAutoplayOn:!0}},Gt=class extends Ge{constructor(t,i){super();this.sdk=t;this.eventBus=i;this.state={audio:m({},Wi.audio),video:m({},Wi.video)};this.TAG="[PlaylistManager]";this.handlePausePlaylist=r=>c(this,[r],function*({enabled:t,track:i}){var n;if(t)return;let s;i.source==="audioplaylist"&&(s="audio"),i.source==="videoplaylist"&&(s="video"),s&&((n=this.getElement(s))==null||n.pause())});this.addTrack=(t,i)=>c(this,null,function*(){yield this.sdk.addTrack(t,i),d.d(this.TAG,"Playlist track added",yi(t))});this.removeTrack=t=>c(this,null,function*(){yield this.sdk.removeTrack(t,!0),d.d(this.TAG,"Playlist track removed",t)});this.audioManager=new Gi,this.videoManager=new $i,this.addListeners()}getList(t="audio"){return this.state[t].list}setList(t){if(!t||t.length===0){d.w(this.TAG,"Please pass in a list of HMSPlaylistItem's");return}t.forEach(i=>{this.state[i.type].list.find(r=>r.id===i.id)||this.state[i.type].list.push(i)})}clearList(t){return c(this,null,function*(){this.isPlaying(t)&&(yield this.stop(t)),this.state[t].list=[]})}removeItem(t,i){return c(this,null,function*(){let{list:r,currentIndex:s}=this.state[i],n=r.findIndex(o=>t===o.id);return n>-1?(s===n&&this.isPlaying(i)&&(yield this.stop(i)),r.splice(n,1),!0):!1})}seek(t,i="audio"){let{currentIndex:r}=this.state[i];if(r===-1)throw S.PlaylistErrors.NoEntryToPlay("PLAYLIST","No item is currently playing");let s=this.getElement(i);if(s){let n=Math.max(s.currentTime+t,0);s.currentTime=Math.min(n,s.duration)}}seekTo(t,i="audio"){let{currentIndex:r}=this.state[i];if(r===-1)throw S.PlaylistErrors.NoEntryToPlay("PLAYLIST","No item is currently playing");if(t<0)throw Error("value cannot be negative");let s=this.getElement(i);s&&(s.currentTime=Math.min(t,s.duration))}setVolume(t,i="audio"){if(t<0||t>100)throw Error("Please pass a valid number between 0-100");let r=this.getElement(i);r&&(r.volume=t*.01)}getVolume(t="audio"){let i=this.getElement(t);return i?Math.floor(i.volume*100):0}getCurrentTime(t="audio"){let i=this.getElement(t);return(i==null?void 0:i.currentTime)||0}getCurrentIndex(t="audio"){return this.state[t].currentIndex}getCurrentProgress(t="audio"){var o;let{list:i,currentIndex:r}=this.state[t],s=(o=i[r])==null?void 0:o.url,n=this.getElement(t);return!s||!n?0:Math.floor(100*(n.currentTime/n.duration))}getCurrentSelection(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r!==-1)return i[r]}isPlaying(t="audio"){let i=this.getElement(t);return!!i&&!i.paused}setIsAutoplayOn(t="audio",i){this.state[t].isAutoplayOn=i}getPlaybackRate(t="audio"){let i=this.getElement(t);return i?i.playbackRate:1}setPlaybackRate(t="audio",i){if(i<.25||i>2)throw Error("Please pass a value between 0.25 and 2.0");let r=this.getElement(t);r&&(r.playbackRate=i)}setEnabled(s,n){return c(this,arguments,function*(t,{id:i,type:r="audio"}){let l=this.state[r].list.findIndex(p=>p.id===i);if(!i||l===-1){d.w(this.TAG,"Pass a valid id");return}let u=this.state[r].list[l].url;t?yield this.play(u,r):yield this.pause(u,r),this.state[r].currentIndex=l,this.setDuration(r)})}playNext(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r>=i.length-1)throw S.PlaylistErrors.NoEntryToPlay("PLAYLIST","Reached end of playlist");yield this.play(i[r+1].url,t),this.state[t].currentIndex=r+1,this.setDuration(t)})}playPrevious(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r<=0)throw S.PlaylistErrors.NoEntryToPlay("PLAYLIST","Reached start of playlist");yield this.play(i[r-1].url,t),this.state[t].currentIndex=r-1,this.setDuration(t)})}stop(){return c(this,arguments,function*(t="audio"){var r;let i=t==="audio"?this.audioManager:this.videoManager;(r=i.getElement())==null||r.pause(),yield this.removeTracks(t),i.stop(),this.state[t].currentIndex=-1})}cleanup(){this.state={audio:m({},Wi.audio),video:m({},Wi.video)},this.eventBus.localAudioEnabled.unsubscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.unsubscribe(this.handlePausePlaylist),this.audioManager.stop(),this.videoManager.stop()}onProgress(t){this.videoManager.on("progress",()=>{try{t({type:"video",progress:this.getCurrentProgress("video")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}}),this.audioManager.on("progress",()=>{try{t({type:"audio",progress:this.getCurrentProgress("audio")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}})}onNewTrackStart(t){this.on("newTrackStart",t)}onPlaylistEnded(t){this.on("playlistEnded",t)}onCurrentTrackEnded(t){this.on("currentTrackEnded",t)}getElement(t="audio"){return t==="audio"?this.audioManager.getElement():this.videoManager.getElement()}removeTracks(){return c(this,arguments,function*(t="audio"){let r=(t==="audio"?this.audioManager:this.videoManager).getTracks();for(let s of r)yield this.removeTrack(s)})}play(r){return c(this,arguments,function*(t,i="audio"){let s=i==="audio"?this.audioManager:this.videoManager,n=s.getElement();if(this.isItemCurrentlyPlaying(t,i)){d.w(this.TAG,`The ${i} is currently playing`);return}if(n!=null&&n.src.includes(t))yield n.play();else{n==null||n.pause();let o=yield s.play(t);for(let l of o)yield this.addTrack(l,i==="audio"?"audioplaylist":"videoplaylist")}})}isItemCurrentlyPlaying(t,i){let r=this.getElement(i);return!!(r&&!r.paused&&r.src.includes(t))}setDuration(t="audio"){let i=this.getElement(t),{list:r,currentIndex:s}=this.state[t];r[s]&&(r[s].duration=(i==null?void 0:i.duration)||0),this.emit("newTrackStart",r[s])}pause(r){return c(this,arguments,function*(t,i="audio"){let s=this.getElement(i);s&&!s.paused&&s.src.includes(t)?(s.pause(),d.d(this.TAG,"paused url",t)):d.w(this.TAG,"The passed in url is not currently playing")})}addListeners(){this.audioManager.on("ended",()=>this.handleEnded("audio")),this.videoManager.on("ended",()=>this.handleEnded("video")),this.eventBus.localAudioEnabled.subscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.subscribe(this.handlePausePlaylist)}handleEnded(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r,isAutoplayOn:s}=this.state[t];r===i.length-1?(yield this.stop(t),this.emit("playlistEnded",t)):s?this.playNext(t):yield this.pause(i[r].url,t),this.emit("currentTrackEnded",i[r])})}};var V=a=>a.room,sn=a=>a.errors,qo=(0,I.createSelector)(sn,a=>a.length===0?null:a.at(-1)),Ko=(0,I.createSelector)(V,a=>a.id),Y=a=>a.peers,$t=a=>a.messages.byID,ys=a=>a.messages.allIDs,_=a=>a.tracks,ks=a=>a.settings,qi=a=>a.appData,jo=a=>a.devices,an=a=>a.speakers,Qo=a=>a.connectionQualities,Ce=(0,I.createSelector)([V],a=>a&&a.isConnected),Jo=(0,I.createSelector)([Ce,V],(a,e)=>a?e.peerCount!==void 0?e.peerCount||1:e.peers.length:Math.max(e.peerCount!==void 0?e.peerCount:e.peers.length-1,0)),zo=a=>a.hideLocalPeer,Me=(0,I.createSelector)([V,Y,zo],(a,e,t)=>t?a.peers.filter(i=>a.localPeer!==i).map(i=>e[i]):a.peers.map(i=>e[i])),Yo=(0,I.createSelector)(_,a=>Object.values(a)),X=(0,I.createSelector)(V,Y,(a,e)=>e[a.localPeer]),Ie=(0,I.createSelector)(V,a=>a.localPeer),Xo=(0,I.createSelector)(X,a=>a==null?void 0:a.name),Zo=(0,I.createSelector)(X,a=>a==null?void 0:a.roleName),ue=(0,I.createSelector)(X,a=>a==null?void 0:a.audioTrack),ie=(0,I.createSelector)(X,a=>a==null?void 0:a.videoTrack),ec=(0,I.createSelector)(X,a=>a==null?void 0:a.auxiliaryTracks),Es=(0,I.createSelector)([ue,ie,ec],(a,e,t)=>{let i=t?[...t]:[];return a&&i.unshift(a),e&&i.unshift(e),i}),tc=(0,I.createSelector)(Me,a=>a.filter(e=>!e.isLocal)),ic=(0,I.createSelector)(Y,an,(a,e)=>{let t=Object.entries(e).sort((i,r)=>{var o,l;let s=((o=i[1])==null?void 0:o.audioLevel)||0;return(((l=r[1])==null?void 0:l.audioLevel)||0)>s?1:-1});if(t.length>0&&t[0][1].audioLevel&&t[0][1].audioLevel>0){let i=t[0][1].peerID;if(i in a)return a[i]}return null}),rc=a=>{let e=X(a);return tt(a,e==null?void 0:e.audioTrack)},Ki=a=>{let e=X(a);return tt(a,e==null?void 0:e.videoTrack)},sc=a=>{var t,i;let e=(t=X(a))==null?void 0:t.audioTrack;return!!(e&&((i=a.tracks[e])!=null&&i.interrupted))},ac=a=>{var t,i;let e=(t=X(a))==null?void 0:t.videoTrack;return!!(e&&((i=a.tracks[e])!=null&&i.interrupted))},Ps=a=>{let e=X(a);return na(a,e==null?void 0:e.videoTrack)},ji=(0,I.createSelector)(X,_,(a,e)=>{let{video:t,audio:i}=qe(e,a);return!!(t||i)}),nn=(0,I.createSelector)(Y,_,(a,e)=>{let t;for(let i in a){let r=a[i],{video:s,audio:n}=qe(e,r);if(s)return r;n&&!t&&(t=r)}return t}),nc=(0,I.createSelector)(nn,a=>!!a),oc=(0,I.createSelector)(Y,_,(a,e)=>{for(let t in a){let i=a[t],{audio:r,video:s}=qe(e,i);if(!s&&r)return i}}),cc=(0,I.createSelector)(Y,_,(a,e)=>{let t=[],i=[];for(let r in a){let s=a[r],{video:n,audio:o}=qe(e,s);n?t.push(s):o&&i.push(s)}return t.concat(i)}),dc=(0,I.createSelector)(Y,_,(a,e)=>{for(let t in e){let i=e[t];if(Ct(i)&&Ht(i)&&i.peerId)return a[i.peerId]}}),lc=(0,I.createSelector)(Y,_,(a,e)=>{for(let t in e){let i=e[t];if(fi(i)&&i.peerId)return a[i.peerId]}}),uc=(0,I.createSelector)(Yo,a=>a.filter(aa)),pc=(0,I.createSelector)(ys,a=>a.length),hc=(0,I.createSelector)($t,a=>Object.values(a).filter(e=>!e.read).length),mt=(0,I.createSelector)(ys,$t,(a,e)=>{let t=[];return a.forEach(i=>{t.push(e[i])}),t}),on=(0,I.createSelector)(mt,a=>a.filter(e=>{var t;return!e.recipientPeer&&!(e.recipientRoles&&((t=e.recipientRoles)==null?void 0:t.length)>0)})),mc=(0,I.createSelector)(on,a=>a.filter(e=>!e.read).length),oe=(0,I.createSelector)([V],a=>a&&a.roomState),bs=(0,I.createSelector)(oe,a=>a==="Preview"),Sc=(0,I.createSelector)(V,a=>a.roomState!=="Disconnected"),gc=(0,I.createSelector)(V,a=>!a.transcriptions||a.transcriptions.length<=0?!1:a.transcriptions.some(e=>e.mode==="caption"&&e.state==="started")),ye=a=>a.roles,Tc=(0,I.createSelector)([ye],a=>Object.keys(a)),ze=(0,I.createSelector)([X,ye],(a,e)=>a!=null&&a.roleName?e[a.roleName]:null),cn=a=>{var e;return(e=a.preview)==null?void 0:e.asRole},Is=(0,I.createSelector)([cn,ye],(a,e)=>a?e[a]:null),fc=(0,I.createSelector)([ze],a=>{var e;return(e=a==null?void 0:a.subscribeParams)!=null&&e.subscribeToRoles?a.subscribeParams.subscribeToRoles.length>0:!1}),As=(0,I.createSelector)(ze,a=>a==null?void 0:a.permissions),vc=(0,I.createSelector)(V,a=>a.recording),Mc=(0,I.createSelector)(V,a=>a.rtmp),yc=(0,I.createSelector)(V,a=>a.hls),kc=(0,I.createSelector)(V,a=>a.transcriptions),Ec=(0,I.createSelector)(V,a=>{var i,r;let e=(i=a.transcriptions)==null?void 0:i.find(s=>s.mode==="caption");if(e!=null&&e.translation)return{available:!0,enabled:e.translation.enabled,roleLanguages:e.translation.roleLanguages};let t=(r=a.translationConfig)==null?void 0:r.caption;return t?{available:!0,enabled:!1,roleLanguages:t.roleLanguages}:{available:!1,enabled:!1,roleLanguages:void 0}}),Pc=(0,I.createSelector)(V,a=>a.sessionId),bc=(0,I.createSelector)(V,a=>a.startedAt),Ic=(0,I.createSelector)(V,a=>!!a.isLargeRoom),Ac=(0,I.createSelector)(V,a=>!!a.isEffectsEnabled),Rc=(0,I.createSelector)(V,a=>!!a.isVBEnabled),Hc=(0,I.createSelector)(V,a=>a.effectsKey),Cc=a=>a.templateAppData,Lc=a=>a.sessionMetadata,Rs=a=>a.polls,wc=a=>Object.values(a.polls),Dc=(0,I.createSelector)(Me,a=>a.filter(e=>e.isHandRaised)),dn=a=>a.whiteboards,_c=(0,I.createSelector)(dn,a=>Object.values(a)[0]);var Hs=require("reselect");var ln=(a="audio")=>e=>e.playlist[a].list,Cs=(a="audio")=>e=>e.playlist[a].selection,un=(a="audio")=>e=>e.playlist[a].progress,pn=(a="audio")=>e=>e.playlist[a].currentTime,hn=(a="audio")=>e=>e.playlist[a].playbackRate,mn=(a="audio")=>e=>e.playlist[a].volume,Sn=(a="audio")=>(0,Hs.createSelector)(ln(a),e=>Object.values(e)),gn=(a="audio")=>(0,Hs.createSelector)(ln(a),Cs(a),(e,t)=>{if(t.id)return e[t.id]}),Ls={selection:Cs("audio"),progress:un("audio"),currentTime:pn("audio"),playbackRate:hn("audio"),volume:mn("audio"),list:Sn("audio"),selectedItem:gn("audio")},ws={selection:Cs("video"),progress:un("video"),currentTime:pn("video"),playbackRate:hn("video"),volume:mn("video"),list:Sn("video"),selectedItem:gn("video")};var w=require("reselect");function H(a){return e=>t=>a(t,e)}var Wt="HMS-Store:",b=class{static v(e,...t){this.log(0,e,...t)}static d(...e){this.log(1,...e)}static i(...e){this.log(2,...e)}static w(...e){this.log(3,...e)}static e(...e){this.log(6,...e)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,...t){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(Wt,...t);break}case 1:{console.debug(Wt,...t);break}case 2:{console.info(Wt,...t);break}case 3:{console.warn(Wt,...t);break}case 6:{console.error(Wt,...t);break}case 4:{performance.mark(t[1]);break}case 5:{let i=t[0],r=t[1];try{let s=performance.measure(r,r);this.log(1,i,r,s==null?void 0:s.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(s){this.log(1,i,r,s)}break}}}};b.level=0;var Ds=(a,e)=>e,qt=(a,e)=>e,Tn=(a,e)=>e,Nc=(a,e)=>e,Oc=(a,e)=>e,re=(0,w.createSelector)([Y,Ds],(a,e)=>e?a[e]:null),_s=(0,w.createSelector)([_,qt],(a,e)=>e?a[e]:null),xc=(0,w.createSelector)([_,qt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="video"?t:null}),Uc=(0,w.createSelector)([_,qt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="audio"?t:null}),Bc=(0,w.createSelector)([_,qt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="audio"&&(t==null?void 0:t.source)==="screen"?t:null}),Vc=(0,w.createSelector)([_,qt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="video"&&(t==null?void 0:t.source)==="screen"?t:null}),Fc=(0,w.createSelector)([Rs,Oc],(a,e)=>e?a[e]:null),se=H(re),Gc=H((0,w.createSelector)([qi,Nc],(a,e)=>{if(a)return e?a[e]:a}));function $c(a){return e=>{if(e.sessionStore)return a?e.sessionStore[a]:e.sessionStore}}var Wc=(...a)=>(0,w.createSelector)([qi],e=>{if(e){if(a&&a.length>0){let t=e;for(let i of a){if(!i)return t;t=t==null?void 0:t[i]}return t}return e}}),qc=H((0,w.createSelector)(re,a=>a==null?void 0:a.name)),Kc=H((0,w.createSelector)(re,a=>a==null?void 0:a.type)),Kt=H(_s),Ns=H(xc),jc=H(Uc),Qc=H(Bc),Jc=H(Vc),fn=H((a,e)=>{let t=re(a,e);if(t&&t.videoTrack&&t.videoTrack!=="")return a.tracks[t.videoTrack]}),vn=H((a,e)=>{let t=re(a,e);if(t&&t.audioTrack&&t.audioTrack!=="")return a.tracks[t.audioTrack]}),zc=fn,Yc=H((a,e)=>{let t=re(a,e);return(t==null?void 0:t.auxiliaryTracks.map(i=>a.tracks[i]))||[]}),Mn=(a,e)=>e?a.speakers[e]:null,Xc=H((0,w.createSelector)(Mn,a=>(a==null?void 0:a.audioLevel)||0)),Zc=(a,e)=>{let t=vn(e)(a);return Mn(a,t==null?void 0:t.id)},ed=H((0,w.createSelector)(Zc,a=>(a==null?void 0:a.audioLevel)||0)),td=H((a,e)=>{if(e)return a.connectionQualities[e]}),id=H((a,e)=>{let t=re(a,e);if(t){let i=t==null?void 0:t.auxiliaryTracks.find(r=>Rt(a.tracks[r]));return i?a.tracks[i]:void 0}}),rd=H((0,w.createSelector)(_,re,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return Ct(r)&&Ht(r)});return t?a[t]:void 0})),sd=H((0,w.createSelector)(_,re,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return Ct(r)&&Rt(r)});return t?a[t]:void 0})),ad=H((0,w.createSelector)(_,re,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return fi(r)&&Rt(r)});return t?a[t]:void 0})),Os=H((0,w.createSelector)(_,re,(a,e)=>qe(a,e))),nd=a=>(0,w.createSelector)(Os(a),e=>e.video),xs=a=>(0,w.createSelector)(Os(a),e=>e.audio),od=H((a,e)=>{let t=re(a,e);return tt(a,t==null?void 0:t.audioTrack)}),cd=H((a,e)=>{let t=re(a,e);return tt(a,t==null?void 0:t.videoTrack)}),Us=H((a,e)=>{if(e&&a.tracks[e])return a.tracks[e].volume===0}),dd=H((a,e)=>{let t=re(a,e);return Us(t==null?void 0:t.audioTrack)(a)}),ld=H((a,e)=>{let t=xs(e)(a);return Us(t==null?void 0:t.id)(a)}),Bs=H((a,e)=>{let t=_s(a,e);if(t){if(t.type!=="audio"){b.w("Please pass audio track here");return}return t.volume}}),ud=H((a,e)=>{let t=re(a,e);return Bs(t==null?void 0:t.audioTrack)(a)}),pd=H((a,e)=>{let t=xs(e)(a);return Bs(t==null?void 0:t.id)(a)}),hd=H((a,e)=>{let t=_s(a,e);if(t){if(t.type!=="video"){b.w("Please pass video track here");return}return t.layer}}),yn=(0,w.createSelector)([mt,Ie,Ds],(a,e,t)=>{if(t)return a.filter(i=>{var r;return!i.recipientPeer&&!((r=i.recipientRoles)!=null&&r.length)||i.sender&&![e,t].includes(i.sender)?!1:[e,t].includes(i.recipientPeer)})}),kn=(0,w.createSelector)([mt,Tn],(a,e)=>{if(e)return a.filter(t=>{var i,r;return(i=t.recipientRoles)!=null&&i.length?(r=t.recipientRoles)==null?void 0:r.includes(e):!1})}),En=(0,w.createSelector)(mt,a=>a.filter(e=>{var t;return!e.recipientPeer&&!((t=e.recipientRoles)!=null&&t.length)})),md=(0,w.createSelector)([kn,Tn],a=>a?a.filter(e=>!e.read).length:0),Sd=(0,w.createSelector)([yn,Ds],a=>a?a.filter(e=>!e.read).length:0),gd=(0,w.createSelector)(En,a=>a.filter(e=>!e.read).length),Td=H(yn),fd=H(kn),vd=H(md),Md=H(Sd),yd=a=>(0,w.createSelector)([Me],e=>e.filter(t=>t.roleName===a)),kd=a=>(0,w.createSelector)([Me],e=>e.filter(t=>t.roleName?a.includes(t.roleName):!1)),Ed=a=>(0,w.createSelector)(se(a),e=>{try{return e!=null&&e.metadata&&e.metadata!==""?JSON.parse(e.metadata):{}}catch(t){return console.error("cannot parse peer metadata",t),{}}}),Pd=a=>(0,w.createSelector)(se(a),e=>!!(e!=null&&e.isHandRaised)),bd=a=>(0,w.createSelector)(se(a),e=>e==null?void 0:e.name),Vs=H(Fc),Id=a=>(0,w.createSelector)($t,e=>e[a]),Ad=a=>(0,w.createSelector)(ze,e=>e!=null&&e.permissions.transcriptions?e.permissions.transcriptions[a].length>0:!1);var jt=require("reselect");var Rd=(0,jt.createSelector)([Y,_],(a,e)=>Object.values(a).map(i=>{var r;return{peer:i,isAudioEnabled:i.audioTrack?(r=e[i.audioTrack])==null?void 0:r.enabled:!1}})),Hd=a=>a.roleChangeRequests[0]||null,Cd=(0,jt.createSelector)([Hd,Y,ye],(a,e,t)=>a?{requestedBy:a.requestedBy?e[a.requestedBy]:void 0,role:t[a.roleName],token:a.token}:null),Ld=(0,jt.createSelector)([ze],a=>Lt(a)),wd=(0,jt.createSelector)([Is],a=>Lt(a));var Ae=require("reselect");var Pn=a=>(0,Ae.createSelector)([ye],e=>e[a]),Dd=a=>(0,Ae.createSelector)(Pn(a),e=>Lt(e)),_d=(0,Ae.createSelector)([ie,_],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),Nd=(0,Ae.createSelector)([ue,_],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),Od=a=>(0,Ae.createSelector)([_d],e=>e.includes(a)),xd=a=>(0,Ae.createSelector)([Nd],e=>e.includes(a)),Ud=a=>(0,Ae.createSelector)(Me,e=>e.find(a)),Bd=a=>(0,Ae.createSelector)(Me,e=>e.filter(a)),Vd=a=>(0,Ae.createSelector)(V,e=>e.joinedAt&&Date.now()-e.joinedAt.getTime()<=a);var Zn=require("immer"),eo=We(require("zustand/shallow")),to=We(require("zustand/vanilla"));var In=require("eventemitter2");var Qi={0:"PEER_JOINED",1:"PEER_LEFT",8:"ROLE_UPDATED",10:"NAME_UPDATED",11:"METADATA_UPDATED",12:"HAND_RAISE_CHANGED"},Qt={0:"TRACK_ADDED",1:"TRACK_REMOVED",2:"TRACK_MUTED",3:"TRACK_UNMUTED",5:"TRACK_DEGRADED",6:"TRACK_RESTORED",4:"TRACK_DESCRIPTION_CHANGED"},Ji={0:"POLL_CREATED",1:"POLL_STARTED",2:"POLL_STOPPED",4:"POLL_VOTES_UPDATED",3:"POLLS_LIST"},bn={TRANSCRIPTION_STATE_UPDATED:"TRANSCRIPTION_STATE_UPDATED"};var Fs="hmsNotification",zi=class{constructor(e){this.id=0;this.onNotification=(e,t)=>{let i=r=>{if(t){let s;if(Array.isArray(t)?s=t.includes(r.type):s=t===r.type,!s)return}e(r)};return this.eventEmitter.addListener(Fs,i),()=>{this.eventEmitter.removeListener(Fs,i)}};this.store=e,this.eventEmitter=new In.EventEmitter2({maxListeners:Object.keys(Ti).length})}sendPlaylistTrackEnded(e){let t=this.createNotification("PLAYLIST_TRACK_ENDED",e,"info");this.emitEvent(t)}sendDeviceChange(e){var i;let t=this.createNotification("DEVICE_CHANGE_UPDATE",e,e.error?"error":"info",`Selected ${e.type} device - ${(i=e.selection)==null?void 0:i.label}`);this.emitEvent(t)}sendLeaveRoom(e){var r;let t=(r=e.requestedBy)==null?void 0:r.name,i=this.createNotification(e.roomEnded||!t?"ROOM_ENDED":"REMOVED_FROM_ROOM",e,"info",`${e.roomEnded?"Room ended":"Removed from room"} ${t?`by ${t}`:""}`);this.emitEvent(i)}sendPeerList(e){if(e.length===0)return;let t=this.createNotification("PEER_LIST",e,"info");this.emitEvent(t)}sendPeerUpdate(e,t){let i=this.store.getState(se(t==null?void 0:t.id))||t,r=Qi[e];if(r&&i){let s=this.createNotification(r,i,"info");this.emitEvent(s)}}sendTrackUpdate(e,t){let i=this.store.getState(Kt(t)),r=Qt[e];if(r){let s=this.createNotification(r,i,"info");this.emitEvent(s)}}sendMessageReceived(e){let t=this.createNotification("NEW_MESSAGE",e,"info");this.emitEvent(t)}sendError(e){let t=this.createNotification("ERROR",e,"error");this.emitEvent(t)}sendReconnecting(e){let t=this.createNotification("RECONNECTING",e,"error");this.emitEvent(t)}sendReconnected(){let e=this.createNotification("RECONNECTED",null,"info");this.emitEvent(e)}sendChangeTrackStateRequest(e){let t=this.createNotification("CHANGE_TRACK_STATE_REQUEST",e,"info");this.emitEvent(t)}sendChangeMultiTrackStateRequest(e){let t=this.createNotification("CHANGE_MULTI_TRACK_STATE_REQUEST",e,"info");this.emitEvent(t)}sendPollUpdate(e,t){let i=Ji[e],r=this.store.getState(Vs(t));if(i){let s=this.createNotification(i,r,"info");this.emitEvent(s)}}sendTrackInterruption(e){let t=e.type==="audio"?"microphone":"camera",i=this.createNotification(e.started?"TRACK_INTERRUPTION_START":"TRACK_INTERRUPTION_END",e,e.started?"error":"info",e.started?`Your ${t} was interrupted, another app may be using it`:`Your ${t} is available again`);this.emitEvent(i)}sendTranscriptionUpdate(e){let t=this.createNotification(bn.TRANSCRIPTION_STATE_UPDATED,e,"info");this.emitEvent(t)}emitEvent(e){this.eventEmitter.emit(Fs,e)}createNotification(e,t,i,r=""){return this.id++,{id:this.id,type:e,message:r,data:t,severity:i}}};var Yi=class{constructor(e){this.queuedUpdates={};this.timers={};this.DEFAULT_INTERVAL_MS=50;this.store=e}setState(e,t,i=this.DEFAULT_INTERVAL_MS){this.queuedUpdates[t]=this.queuedUpdates[t]||[],this.queuedUpdates[t].push(e),!this.timers[t]&&(window?this.timers[t]=window.setTimeout(()=>this.setStateBatched(t),i):this.setStateBatched(t))}setStateBatched(e){var t;if(((t=this.queuedUpdates[e])==null?void 0:t.length)>0){let i=r=>{this.queuedUpdates[e].forEach(s=>{try{s(r)}catch(n){b.w("failed to update store",n)}})};console.time(`timed-${e}`),this.store.namedSetState(i,e),console.timeEnd(`timed-${e}`)}delete this.queuedUpdates[e],window&&this.timers[e]&&(window.clearTimeout(this.timers[e]),delete this.timers[e])}};function An(a){return a instanceof le||a instanceof x}var Rn=(a,e)=>{let t=Jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Ye(r,s)?(pe(r.auxiliaryTracks,s.auxiliaryTracks)&&(s.auxiliaryTracks=r.auxiliaryTracks),r.groups&&pe(r.groups,s.groups)&&(s.groups=r.groups),Object.assign(r,s)):Ws(r,s)?delete a[i]:Xi(r,s)&&(a[i]=s)}},Hn=(a,e)=>{let t=Jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Ye(r,s)?($s(r,s),Object.assign(r,s)):Ws(r,s)?delete a[i]:Xi(r,s)&&(a[i]=s)}},Cn=(a,e)=>{let t=Jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Ye(r,s)?(r.questions&&pe(r.questions,s.questions)&&(s.questions=r.questions),Object.assign(r,s)):Xi(r,s)&&(a[i]=s)}},Gs=(a,e)=>{let t=Jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Ye(r,s)?Object.assign(r,s):Ws(r,s)?delete a[i]:Xi(r,s)&&(a[i]=s)}},Ln=(a,e,t)=>{let i=t.reduce((s,n)=>(s[n.firstTrackId]=Object.values(e[n.getTrackIDBeingSent()]||{}).sort((o,l)=>!o.rid||!l.rid?0:o.rid<l.rid?-1:1),s),{}),r=Jt(Object.keys(a),Object.keys(i));for(let s of r){if(!i[s]){delete a[s];continue}a[s]=i[s]}},$s=(a,e)=>{a.plugins&&pe(a.plugins,e.plugins)&&(e.plugins=a.plugins),a.type==="video"&&a.layerDefinitions&&pe(a.layerDefinitions,e.layerDefinitions)&&(e.layerDefinitions=a.layerDefinitions)},Ye=(a,e)=>a&&e,Ws=(a,e)=>a&&!e,Xi=(a,e)=>!a&&e,pe=(a,e)=>{if(a===e||a.length===0&&(e==null?void 0:e.length)===0)return!0;if(!a||!e||a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(a[t]!==e[t])return!1;return!0},Jt=(a,e)=>{let t=new Set;for(let i of a)t.add(i);for(let i of e)t.add(i);return Array.from(t)};var N=class a{static convertPeer(e){var t,i,r;return{id:e.peerId,name:e.name,roleName:(t=e.role)==null?void 0:t.name,isLocal:e.isLocal,videoTrack:(i=e.videoTrack)==null?void 0:i.trackId,audioTrack:(r=e.audioTrack)==null?void 0:r.trackId,auxiliaryTracks:e.auxiliaryTracks.map(s=>s.trackId),customerUserId:e.customerUserId,metadata:e.metadata,joinedAt:e.joinedAt,groups:e.groups,isHandRaised:e.isHandRaised,type:e.type}}static convertTrack(e,t){let i={id:e.trackId,source:e.source,type:e.type,enabled:e.enabled,displayEnabled:e.enabled,peerId:e.peerId||t};return this.enrichTrack(i,e),i}static enrichTrack(e,t){let i=t.getMediaTrackSettings();t instanceof le&&(e.volume=t.getVolume()||0),a.updateDeviceID(e,t),a.enrichLocalTrack(e,t),e.type==="video"&&(e.source==="screen"?(e.displaySurface=i.displaySurface,a.enrichScreenTrack(e,t)):e.source==="regular"&&(e.facingMode=i.facingMode),e.height=i.height,e.width=i.width,a.enrichVideoTrack(e,t)),a.enrichPluginsDetails(e,t)}static enrichLocalTrack(e,t){(t instanceof q||t instanceof Se)&&(e.isPublished=t.isPublished)}static updateDeviceID(e,t){var i;t instanceof q||t instanceof Se?e.deviceID=t.settings.deviceId:e.deviceID=(i=t.getMediaTrackSettings())==null?void 0:i.deviceId}static enrichVideoTrack(e,t){t instanceof x&&(e.layer=t.getLayer(),e.preferredLayer=t.getPreferredLayer(),e.degraded=t.degraded),(t instanceof x||t instanceof q)&&(pe(t.getSimulcastDefinitions(),e.layerDefinitions)||(e.layerDefinitions=t.getSimulcastDefinitions()))}static enrichScreenTrack(e,t){var i,r;if(t instanceof q){let s=(i=t.getCaptureHandle)==null?void 0:i.call(t);(s==null?void 0:s.handle)!==((r=e.captureHandle)==null?void 0:r.handle)&&(e.captureHandle=s),t.isCurrentTab&&(e.displaySurface="selfBrowser")}}static enrichPluginsDetails(e,t){(t instanceof q||t instanceof Se)&&(pe(t.getPlugins(),e.plugins)||(e.plugins=t.getPlugins()))}static convertRoom(e,t){let{recording:i,rtmp:r,hls:s,transcriptions:n}=a.convertRecordingStreamingState(e.recording,e.rtmp,e.hls,e.transcriptions);return{id:e.id,name:e.name,localPeer:t,recording:i,rtmp:r,hls:s,transcriptions:n,sessionId:e.sessionId,startedAt:e.startedAt,joinedAt:e.joinedAt,peerCount:e.peerCount,isLargeRoom:e.large_room_optimization,isEffectsEnabled:e.isEffectsEnabled,disableNoneLayerRequest:e.disableNoneLayerRequest,isVBEnabled:e.isVBEnabled,effectsKey:e.effectsKey,isHipaaEnabled:e.isHipaaEnabled,isNoiseCancellationEnabled:e.isNoiseCancellationEnabled}}static convertMessage(e,t){var i,r,s,n;return{sender:(i=e.peer)==null?void 0:i.peer_id,senderName:(r=e.peer)==null?void 0:r.info.name,senderRole:(s=e.peer)==null?void 0:s.role,senderUserId:(n=e.peer)==null?void 0:n.info.user_id,recipientPeer:e.private?t:void 0,recipientRoles:e.roles,time:new Date(e.timestamp),type:e.info.type,message:e.info.message,id:e.message_id}}static convertRoles(e){let t={};return e&&e.forEach(i=>{t[i.name]=i}),t}static convertRoleChangeRequest(e){var t;return{requestedBy:(t=e.requestedBy)==null?void 0:t.peerId,roleName:e.role.name,token:e.token}}static convertException(e){let t="trackType"in e,i={code:e.code,action:e.action,name:e.name,message:e.message,description:e.description,isTerminal:e.isTerminal,nativeError:e.nativeError,timestamp:new Date};return t&&(i.trackType=e==null?void 0:e.trackType),i}static convertDeviceChangeUpdate(e){let t={devices:e.devices,selection:e.selection,type:e.type};return e.error&&(t.error=this.convertException(e.error)),t}static convertPlaylist(e){let t=this.getConvertedPlaylistType(e,"audio"),i=this.getConvertedPlaylistType(e,"video");return{audio:t,video:i}}static convertPlaylistItem(e,t){let i=t.type,r=e.getCurrentSelection(i),s=e.isPlaying(i),n=t.url===(r==null?void 0:r.url);return M(m({},t),{type:t.type,selected:n,playing:n&&s})}static getConvertedPlaylistType(e,t){let i={},r=e.getCurrentSelection(t),s=e.getCurrentProgress(t),n=e.getVolume(t),o=e.getList(t),l=e.getCurrentIndex(t);return e.getList(t).forEach(u=>{i[u.id]=a.convertPlaylistItem(e,u)}),{list:i,selection:{id:r==null?void 0:r.id,hasPrevious:l>0,hasNext:l<o.length-1},progress:s,volume:n,currentTime:e.getCurrentTime(t),playbackRate:e.getPlaybackRate(t)}}static convertRecordingStreamingState(e,t,i,r){var s;return{recording:{browser:m({running:!1},e==null?void 0:e.browser),server:m({running:!1},e==null?void 0:e.server),hls:m({running:!1},e==null?void 0:e.hls)},rtmp:m({running:!1},t),hls:{variants:((s=i==null?void 0:i.variants)==null?void 0:s.map(n=>n))||[],running:!!(i!=null&&i.running),error:i==null?void 0:i.error},transcriptions:r||[]}}};var zt=class{constructor(e,t,i,r){this.playlistManager=e;this.syncPlaylistState=i;this.store=r;this.type=t}play(e){return c(this,null,function*(){if(!e){b.w("Please pass id to play");return}yield this.playlistManager.setEnabled(!0,{id:e,type:this.type})})}pause(){return c(this,null,function*(){let e=this.type==="audio"?Ls:ws,t=this.store.getState(e.selection);if(!t.id){b.w("No item is currently playing to pause");return}yield this.playlistManager.setEnabled(!1,{id:t.id,type:this.type})})}playNext(){return c(this,null,function*(){yield this.playlistManager.playNext(this.type)})}playPrevious(){return c(this,null,function*(){yield this.playlistManager.playPrevious(this.type)})}seek(e){this.playlistManager.seek(e,this.type),this.syncPlaylistState(`seekOn${this.type}Playlist`)}seekTo(e){this.playlistManager.seekTo(e,this.type),this.syncPlaylistState(`seekToOn${this.type}Playlist`)}setVolume(e){this.playlistManager.setVolume(e,this.type),this.syncPlaylistState(`setVolumeOn${this.type}Playlist`)}setList(e){this.playlistManager.setList(e),this.syncPlaylistState(`setListOn${this.type}Playlist`)}stop(){return c(this,null,function*(){yield this.playlistManager.stop(this.type),this.syncPlaylistState(`stop${this.type}Playlist`)})}setIsAutoplayOn(e){this.playlistManager.setIsAutoplayOn(this.type,e)}setPlaybackRate(e){this.playlistManager.setPlaybackRate(this.type,e),this.syncPlaylistState(`set${this.type}PlaybackRate`)}removeItem(e){return c(this,null,function*(){let t=yield this.playlistManager.removeItem(e,this.type);return t&&this.syncPlaylistState(`remove${this.type}PlaylistItem`),t})}clearList(){return c(this,null,function*(){yield this.playlistManager.clearList(this.type),this.syncPlaylistState(`clear${this.type}Playlist`)})}};var Zi=class{constructor(e,t){this.sdk=e;this.setLocally=t}get sdkSessionStore(){return this.sdk.getSessionStore()}set(e,t){return c(this,null,function*(){let{value:i}=yield this.sdkSessionStore.set(String(e),t);this.setLocally({key:e,value:i})})}observe(e){return c(this,null,function*(){let t=Array.isArray(e)?e.map(i=>String(i)):[String(e)];yield this.sdkSessionStore.observe(t)})}unobserve(e){return c(this,null,function*(){let t=Array.isArray(e)?e.map(i=>String(i)):[String(e)];yield this.sdkSessionStore.unobserve(t)})}};var er=class{constructor(e,t){this.TAG="[BeamSpeakerLabelsLogger]";this.intervalMs=100,this.shouldMonitor=!1,this.hasStarted=!1,this.unsubs=[],this.analysers={},this.store=e,this.actions=t}start(){return c(this,null,function*(){if(this.hasStarted)return;this.hasStarted=!0,b.d("starting audio level monitor for remote peers",this.store);let e=this.store.getState(Ce);b.d("starting audio levels is connected to room",e),e&&(yield this.monitorAudioLevels());let t=this.store.subscribe(this.monitorAudioLevels.bind(this),Ce);this.unsubs.push(t)})}stop(){return c(this,null,function*(){this.hasStarted&&(this.hasStarted=!1,this.shouldMonitor=!1,this.unsubs.forEach(e=>e()),b.d("stopped audio level monitor for remote peers"))})}monitorAudioLevels(){return c(this,null,function*(){if(!this.store.getState(Ce)){this.shouldMonitor&&(b.i("room no longer connected, stopping audio level monitoring for remote"),this.shouldMonitor=!1);return}if(this.shouldMonitor)return;b.i("monitoring audio levels"),this.shouldMonitor=!0;let t=()=>{this.shouldMonitor?(this.logAllPeersAudioLevels(),setTimeout(t,this.intervalMs)):b.i("stopped monitoring audio levels")};setTimeout(t,1e3)})}logAllPeersAudioLevels(){return c(this,null,function*(){var r;if(!window.__triggerBeamEvent__)return;let e=this.store.getState(Me),t=e.filter(s=>!!s.audioTrack);b.d(this.TAG,"Peers Without audio track",e.filter(s=>!s.audioTrack).map(s=>s.id).join(","));let i=[];for(let s of t){let n=this.actions.getTrackById(s.audioTrack||""),o=(r=n==null?void 0:n.stream)==null?void 0:r.nativeStream;if(s.joinedAt&&o){let l=yield this.getAudioLevel(s,o);b.d(this.TAG,s.id,l),l.level>0&&i.push(l)}}if(i.length>0){let s={event:"app-audio-level",data:i};b.d("logging audio levels",JSON.stringify(i)),window.__triggerBeamEvent__(JSON.stringify(s))}})}getAudioLevel(e,t){return c(this,null,function*(){this.analysers[t.id]||(this.analysers[t.id]=this.createAnalyserNode(t));let i=this.analysers[t.id],r=this.calculateAudioLevel(i);return{peerId:e.id,peerName:e.name,userId:e.customerUserId,level:r}})}createAnalyserNode(e){this.audioContext||(this.audioContext=new AudioContext);let t=this.audioContext.createAnalyser();return this.audioContext.createMediaStreamSource(e).connect(t),t}calculateAudioLevel(e){let t=new Uint8Array(e.fftSize);e.getByteTimeDomainData(t);let i=.009,r=i;for(let o of t)r=Math.max(r,(o-128)/128);let s=(Math.log(i)-Math.log(r))/Math.log(i);return Math.ceil(Math.min(Math.max(s*100,0),100))}};var wn=2e4,Dn=1e4,St={name:"diagnostics-role",priority:1,publishParams:{allowed:["audio","video"],audio:{bitRate:32,codec:"opus"},video:{bitRate:100,codec:"vp8",frameRate:30,height:720,width:1280},screen:{bitRate:100,codec:"vp8",frameRate:10,height:1080,width:1920}},subscribeParams:{subscribeToRoles:[],maxSubsBitRate:3200},permissions:{browserRecording:!1,changeRole:!1,endRoom:!1,hlsStreaming:!1,mute:!1,pollRead:!1,pollWrite:!1,removeOthers:!1,rtmpStreaming:!1,unmute:!1}},_n="https://100ms.live/test-audio.wav";var tr=class{constructor(){this.networkScores=[];this.lastPushedAt=0}pushScore(e){!e||e<0||(this.networkScores.length===0?(this.networkScores.push(e),this.lastPushedAt=Date.now()):this.addPendingCQSTillNow())}addPendingCQSTillNow(){if(this.networkScores.length>0){let e=(Date.now()-this.lastPushedAt)/1e3;for(;e>0;)this.networkScores.push(this.networkScores[this.networkScores.length-1]),e-=1;this.lastPushedAt=Date.now()}}getCQS(){return this.networkScores.reduce((e,t)=>e+t,0)/this.networkScores.length}};var Fd=a=>!!a&&!isNaN(a),he=a=>a[a.length-1],$e=(a,e)=>{let t=a.filter(i=>Fd(e(i)));return t.reduce((i,r)=>i+(e(r)||0),0)/t.length},ir=class{constructor(e){this.sdk=e;this.peerStatsList=[];this.localAudioTrackStatsList=[];this.localVideoTrackStatsList=[];this.remoteAudioTrackStatsList=[];this.remoteVideoTrackStatsList=[]}handleStatsUpdate(e){return c(this,null,function*(){var o,l,u,p,h,T,g,f;let t=e.getLocalPeerStats();t&&this.peerStatsList.push(t);let i=(u=(l=(o=this.sdk.getLocalPeer())==null?void 0:o.audioTrack)==null?void 0:l.nativeTrack)==null?void 0:u.id,r=(T=(h=(p=this.sdk.getLocalPeer())==null?void 0:p.videoTrack)==null?void 0:h.nativeTrack)==null?void 0:T.id,s=e.getLocalTrackStats();s&&(i&&this.localAudioTrackStatsList.push(s[i]),r&&this.localVideoTrackStatsList.push(s[r]));let n=yield(f=(g=this.sdk.getWebrtcInternals())==null?void 0:g.getSubscribePeerConnection())==null?void 0:f.getStats();n==null||n.forEach(P=>{if(P.type==="inbound-rtp"){let v=P.kind==="audio"?this.remoteAudioTrackStatsList:this.remoteVideoTrackStatsList,R=lt("bytesReceived",P,he(v));v.push(M(m({},P),{bitrate:R}))}})})}buildReport(){var P,v,R,$,ce,B,de,De,Et,Pt;let e=(P=he(this.peerStatsList))==null?void 0:P.publish,t=(v=he(this.peerStatsList))==null?void 0:v.subscribe,i=e!=null&&e.responsesReceived?((e==null?void 0:e.totalRoundTripTime)||0)/e.responsesReceived:0,r=t!=null&&t.responsesReceived?((t==null?void 0:t.totalRoundTripTime)||0)/t.responsesReceived:0,s=Number(((i+r)/2*1e3).toFixed(2)),n=((R=he(this.remoteAudioTrackStatsList))==null?void 0:R.packetsReceived)||0,o=(($=he(this.remoteVideoTrackStatsList))==null?void 0:$.packetsReceived)||0,l=this.localAudioTrackStatsList.map(O=>O?$e(Object.values(O),Q=>Q.bitrate):0),u=this.localVideoTrackStatsList.map(O=>O?$e(Object.values(O),Q=>Q.bitrate):0),p=((ce=he(this.remoteAudioTrackStatsList))==null?void 0:ce.jitter)||0,h=((B=he(this.remoteVideoTrackStatsList))==null?void 0:B.jitter)||0,T=Math.max(p,h),g=he(this.localAudioTrackStatsList),f=he(this.localVideoTrackStatsList);return{combined:{roundTripTime:s,packetsReceived:n+o,packetsLost:(t==null?void 0:t.packetsLost)||0,bytesSent:(e==null?void 0:e.bytesSent)||0,bytesReceived:(t==null?void 0:t.bytesReceived)||0,bitrateSent:$e(this.peerStatsList,O=>{var Q;return(Q=O.publish)==null?void 0:Q.bitrate}),bitrateReceived:$e(this.peerStatsList,O=>{var Q;return(Q=O.subscribe)==null?void 0:Q.bitrate}),jitter:T},audio:{roundTripTime:s,packetsReceived:n,packetsLost:((de=he(this.remoteAudioTrackStatsList))==null?void 0:de.packetsLost)||0,bytesReceived:((De=he(this.remoteAudioTrackStatsList))==null?void 0:De.bytesReceived)||0,bitrateSent:$e(l,O=>O),bitrateReceived:$e(this.remoteAudioTrackStatsList,O=>O.bitrate),bytesSent:g?Object.values(g).reduce((O,Q)=>O+(Q.bytesSent||0),0):0,jitter:p},video:{roundTripTime:s,packetsLost:((Et=he(this.remoteVideoTrackStatsList))==null?void 0:Et.packetsLost)||0,bytesReceived:((Pt=he(this.remoteVideoTrackStatsList))==null?void 0:Pt.bytesReceived)||0,packetsReceived:o,bitrateSent:$e(u,O=>O),bitrateReceived:$e(this.remoteVideoTrackStatsList,O=>O.bitrate),bytesSent:f?Object.values(f).reduce((O,Q)=>O+(Q.bytesSent||0),0):0,jitter:h}}}};var Nn=(o=>(o[o.STARTING=0]="STARTING",o[o.INIT_FETCHED=1]="INIT_FETCHED",o[o.SIGNAL_CONNECTED=2]="SIGNAL_CONNECTED",o[o.ICE_ESTABLISHED=3]="ICE_ESTABLISHED",o[o.MEDIA_CAPTURED=4]="MEDIA_CAPTURED",o[o.MEDIA_PUBLISHED=5]="MEDIA_PUBLISHED",o[o.COMPLETED=6]="COMPLETED",o))(Nn||{});var On,xn,rr=class{constructor(e,t,i,r,s=wn){this.sdk=e;this.sdkListener=t;this.progressCallback=i;this.completionCallback=r;this.connectivityDuration=s;this.wsConnected=!1;this.initConnected=!1;this.isPublishICEConnected=!1;this.isSubscribeICEConnected=!1;this.gatheredPublishICECandidates=[];this.gatheredSubscribeICECandidates=[];this.errors=[];this.isAudioTrackCaptured=!1;this.isVideoTrackCaptured=!1;this.isAudioTrackPublished=!1;this.isVideoTrackPublished=!1;this.cqsCalculator=new tr;this.timestamp=Date.now();this.onRoomUpdate=this.sdkListener.onRoomUpdate.bind(this.sdkListener);this.onPeerUpdate=this.sdkListener.onPeerUpdate.bind(this.sdkListener);this.onMessageReceived=this.sdkListener.onMessageReceived.bind(this.sdkListener);this.onReconnected=this.sdkListener.onReconnected.bind(this.sdkListener);this.onRoleChangeRequest=this.sdkListener.onRoleChangeRequest.bind(this.sdkListener);this.onRoleUpdate=this.sdkListener.onRoleUpdate.bind(this.sdkListener);this.onChangeTrackStateRequest=this.sdkListener.onChangeTrackStateRequest.bind(this.sdkListener);this.onChangeMultiTrackStateRequest=this.sdkListener.onChangeMultiTrackStateRequest.bind(this.sdkListener);this.onRemovedFromRoom=this.sdkListener.onRemovedFromRoom.bind(this.sdkListener);this.onNetworkQuality=(On=this.sdkListener.onNetworkQuality)==null?void 0:On.bind(this.sdkListener);this.onPreview=this.sdkListener.onPreview.bind(this.sdkListener);this.onDeviceChange=(xn=this.sdkListener.onDeviceChange)==null?void 0:xn.bind(this.sdkListener);this.onSessionStoreUpdate=this.sdkListener.onSessionStoreUpdate.bind(this.sdkListener);this.onPollsUpdate=this.sdkListener.onPollsUpdate.bind(this.sdkListener);this.onWhiteboardUpdate=this.sdkListener.onWhiteboardUpdate.bind(this.sdkListener);this.handleConnectionQualityUpdate=e=>{let t=e.find(i=>{var r,s;return i.peerID===((s=(r=this.sdk)==null?void 0:r.store.getLocalPeer())==null?void 0:s.peerId)});this.cqsCalculator.pushScore(t==null?void 0:t.downlinkQuality)};this.statsCollector=new ir(e),this.state=0}get state(){return this._state}set state(e){var t;e===void 0||this._state!==void 0&&e<this._state||(this._state=e,(t=this.progressCallback)==null||t.call(this,e))}onICESuccess(e){e?this.isPublishICEConnected=!0:this.isSubscribeICEConnected=!0,this.isPublishICEConnected&&this.isSubscribeICEConnected&&(this.state=3)}onSelectedICECandidatePairChange(e,t){t?this.selectedPublishICECandidate=e:this.selectedSubscribeICECandidate=e}onICECandidate(e,t){t?this.gatheredPublishICECandidates.push(e):this.gatheredSubscribeICECandidates.push(e)}onMediaPublished(e){switch(e.type){case"audio":this.isAudioTrackPublished=!0;break;case"video":this.isVideoTrackPublished=!0;break;default:break}this.isVideoTrackPublished&&this.isAudioTrackPublished&&(this.state=5)}onInitSuccess(e){this.websocketURL=e,this.initConnected=!0,this.state=1}onSignallingSuccess(){this.wsConnected=!0,this.state=2}onJoin(e){var t,i;this.sdkListener.onJoin(e),(t=this.sdk.getWebrtcInternals())==null||t.onStatsChange(r=>this.statsCollector.handleStatsUpdate(r)),(i=this.sdk.getWebrtcInternals())==null||i.start(),this.cleanupTimer=window.setTimeout(()=>{this.cleanupAndReport()},this.connectivityDuration)}onError(e){this.sdkListener.onError(e),this.errors.push(e),e!=null&&e.isTerminal&&this.cleanupAndReport()}onTrackUpdate(e,t,i){if(this.sdkListener.onTrackUpdate(e,t,i),i.isLocal&&e===0){switch(t.type){case"audio":this.isAudioTrackCaptured=!0;break;case"video":this.isVideoTrackCaptured=!0;break;default:break}this.isVideoTrackCaptured&&this.isAudioTrackCaptured&&(this.state=4)}}onReconnecting(e){this.sdkListener.onReconnecting(e),this.cqsCalculator.addPendingCQSTillNow()}cleanupAndReport(){var e;clearTimeout(this.cleanupTimer),this.cleanupTimer=void 0,this.state===5&&(this.state=6),(e=this.completionCallback)==null||e.call(this,this.buildReport()),this.sdk.leave()}buildReport(){this.cqsCalculator.addPendingCQSTillNow();let e=this.cqsCalculator.getCQS(),t=this.statsCollector.buildReport();return{testTimestamp:this.timestamp,connectivityState:this.state,errors:this.errors,signallingReport:{isConnected:this.wsConnected,isInitConnected:this.initConnected,websocketUrl:this.websocketURL},mediaServerReport:{stats:t,connectionQualityScore:e,isPublishICEConnected:this.isPublishICEConnected,isSubscribeICEConnected:this.isSubscribeICEConnected,publishICECandidatePairSelected:this.selectedPublishICECandidate,subscribeICECandidatePairSelected:this.selectedSubscribeICECandidate,publishIceCandidatesGathered:this.gatheredPublishICECandidates,subscribeIceCandidatesGathered:this.gatheredSubscribeICECandidates}}}};var Xe=class{constructor(e){this.recording={server:{running:!1},browser:{running:!1},hls:{running:!1}};this.rtmp={running:!1};this.hls={running:!1,variants:[]};this.transcriptions=[];this.isNoiseCancellationEnabledFromInit=!1;this.isNoiseCancellationEnabledFromPolicy=!1;this.id=e}get isNoiseCancellationEnabled(){return this.isNoiseCancellationEnabledFromInit&&this.isNoiseCancellationEnabledFromPolicy}};var sr=(a,e,t)=>c(null,null,function*(){let r=Error("something went wrong during fetch");for(let s=0;s<4;s++)try{let n=yield fetch(a,e),o=yield n.clone().json();if(t&&t.length&&!n.ok&&t.includes(o.code))throw S.APIErrors.ServerErrors(o.code,"GET_TOKEN",o.message,!1);return n}catch(n){r=n}throw["Failed to fetch","NetworkError"].some(s=>r.message.includes(s))?S.APIErrors.EndpointUnreachable("GET_TOKEN",r.message):r});var gt=class{constructor(e,t){this.sdk=e;this.sdkListener=t;this.recordedAudio=_n;this.sdk.setIsDiagnostics(!0),this.initSdkWithLocalPeer()}get localPeer(){var e;return(e=this.sdk)==null?void 0:e.store.getLocalPeer()}checkBrowserSupport(){_t(),Dt()}requestPermission(e){return c(this,null,function*(){try{let t=yield navigator.mediaDevices.getUserMedia(e);return t.getTracks().forEach(i=>i.stop()),yield this.sdk.deviceManager.init(!0),{audio:t.getAudioTracks().length>0,video:t.getVideoTracks().length>0}}catch(t){throw xe(t,this.sdk.localTrackManager.getErrorType(!!e.video,!!e.audio))}})}startCameraCheck(e){return c(this,null,function*(){var s,n,o,l;if(this.initSdkWithLocalPeer(),!this.localPeer)throw new Error("Local peer not found");this.sdk.store.setSimulcastEnabled(!1),this.localPeer.role=M(m({},St),{publishParams:M(m({},St.publishParams),{allowed:["video"]})});let t=new Be().video(new z().deviceId(e||"default").build()).build(),i=yield(s=this.sdk)==null?void 0:s.localTrackManager.getLocalTracks({audio:!1,video:!0},t),r=i==null?void 0:i.find(u=>u.type==="video");if(!r)throw new Error("No video track found");(n=this.sdk)==null||n.deviceManager.init(!0),this.localPeer.videoTrack=r,(l=(o=this.sdk)==null?void 0:o.listener)==null||l.onPeerUpdate(9,[this.localPeer])})}stopCameraCheck(){var e,t;(t=(e=this.localPeer)==null?void 0:e.videoTrack)==null||t.cleanup(),this.localPeer&&(this.localPeer.videoTrack=void 0)}startMicCheck(s){return c(this,arguments,function*({inputDevice:e,onError:t,onStop:i,time:r=Dn}){var u,p,h,T;this.initSdkWithLocalPeer(g=>{this.stopMicCheck(),t==null||t(g)});let n=yield this.getLocalAudioTrack(e);if((u=this.sdk)==null||u.deviceManager.init(!0),!this.localPeer)throw new Error("Local peer not found");if(!n)throw new Error("No audio track found");this.localPeer.audioTrack=n,(p=this.sdk)==null||p.initPreviewTrackAudioLevelMonitor(),(T=(h=this.sdk)==null?void 0:h.listener)==null||T.onPeerUpdate(9,[this.localPeer]),this.mediaRecorder=new MediaRecorder(n.stream.nativeStream);let o=[];this.mediaRecorder.ondataavailable=function(g){o.push(g.data)},this.mediaRecorder.onstop=()=>{var f,P;let g=new Blob(o,{type:(f=this.mediaRecorder)==null?void 0:f.mimeType});this.recordedAudio=URL.createObjectURL(g),(P=this.onStopMicCheck)==null||P.call(this)},this.mediaRecorder.start();let l=setTimeout(()=>{this.stopMicCheck()},r);this.onStopMicCheck=()=>{clearTimeout(l),i==null||i()}})}stopMicCheck(){var e,t,i;(e=this.mediaRecorder)==null||e.stop(),(i=(t=this.localPeer)==null?void 0:t.audioTrack)==null||i.cleanup(),this.localPeer&&(this.localPeer.audioTrack=void 0)}getRecordedAudio(){return this.recordedAudio}startConnectivityCheck(e,t,i,r){return c(this,null,function*(){if(!this.sdk)throw new Error("SDK not found");this.connectivityCheck=new rr(this.sdk,this.sdkListener,e,t,r);let s=yield this.getAuthToken(i);yield this.sdk.leave(),yield this.sdk.join({authToken:s,userName:"diagnostics-test"},this.connectivityCheck),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:n=>{var o;(o=this.connectivityCheck)==null||o.handleConnectionQualityUpdate(n)}})})}stopConnectivityCheck(){return c(this,null,function*(){var e;return(e=this.connectivityCheck)==null?void 0:e.cleanupAndReport()})}initSdkWithLocalPeer(e){var r,s,n;this.sdkListener&&((r=this.sdk)==null||r.initStoreAndManagers(M(m({},this.sdkListener),{onError:o=>{e==null||e(o),this.sdkListener.onError(o)}})));let t=new Je({name:"diagnostics-peer",role:St,type:"regular"});(s=this.sdk)==null||s.store.addPeer(t);let i=new Xe("diagnostics-room");this.sdk.store.setRoom(i),this.sdkListener.onRoomUpdate("ROOM_PEER_COUNT_UPDATED",i),(n=this.sdk)==null||n.deviceManager.init(!0)}getAuthToken(e){return c(this,null,function*(){let t=new URL("https://api.100ms.live/v2/diagnostics/token");e&&t.searchParams.append("region",e);let i=yield sr(t.toString(),{method:"GET"},[429,500,501,502,503,504,505,506,507,508,509,510,511]),r=yield i.json();if(!i.ok)throw S.APIErrors.ServerErrors(r.code,"GET_TOKEN",r.message,!1);let{token:s}=r;if(!s)throw Error(r.message);return s})}getLocalAudioTrack(e){return c(this,null,function*(){var r;if(!this.localPeer)return;this.localPeer.role=M(m({},St),{publishParams:M(m({},St.publishParams),{allowed:["audio"]})});let t=new Be().audio(new ee().deviceId(e||"default").build()).build(),i=yield(r=this.sdk)==null?void 0:r.localTrackManager.getLocalTracks({audio:!0,video:!1},t);return i==null?void 0:i.find(s=>s.type==="audio")})}};var ar=class{constructor(e,t,i){this.isRoomJoinCalled=!1;this.ignoredMessageTypes=[];this.setProgress=({type:e,progress:t})=>{this.setState(i=>{i.playlist[e].progress=t,i.playlist[e].currentTime=this.sdk.getPlaylistManager().getCurrentTime(e)},"playlistProgress")};this.syncPlaylistState=e=>{this.setState(t=>{Object.assign(t.playlist,N.convertPlaylist(this.sdk.getPlaylistManager()))},e)};this.sendPeerUpdateNotification=(e,t)=>{let i=this.store.getState(se(t.peerId)),r=Qi[e]||"peerUpdate";if(e===8)this.syncRoomState(r),this.updateMidCallPreviewRoomState(e,t);else if([0,1].includes(e))this.syncRoomState(r),i||(i=this.store.getState(se(t.peerId)));else if([12,13,14].includes(e))this.syncRoomState(r),i||(i=this.store.getState(se(t.peerId)));else{let s=N.convertPeer(t);this.setState(n=>{let o=n.peers[s.id];Ye(o,s)&&(pe(o.auxiliaryTracks,s.auxiliaryTracks)&&(o.auxiliaryTracks=s.auxiliaryTracks),Object.assign(o,s)),i=s},r)}this.hmsNotifications.sendPeerUpdate(e,i)};this.getSDKHMSPeer=e=>this.sdk.getPeerMap()[e];this.setState=(e,t)=>this.store.namedSetState(e,t);this.store=e,this.sdk=t,this.hmsNotifications=i,this.sessionStore=new Zi(this.sdk,this.setSessionStoreValueLocally.bind(this)),this.actionBatcher=new Yi(e)}submitSessionFeedback(e,t){return this.sdk.submitSessionFeedback(e,t)}getLocalTrack(e){return this.sdk.store.getLocalPeerTracks().find(t=>t.trackId===e)}get interactivityCenter(){return this.sdk.getInteractivityCenter()}setPlaylistSettings(e){this.sdk.updatePlaylistSettings(e)}refreshDevices(){return c(this,null,function*(){yield this.sdk.refreshDevices()})}unblockAudio(){return c(this,null,function*(){yield this.sdk.getAudioOutput().unblockAutoplay()})}setVolume(e,t){return c(this,null,function*(){t?yield this.setTrackVolume(e,t):(yield this.sdk.getAudioOutput().setVolume(e),this.syncRoomState("setOutputVolume"))})}setAudioOutputDevice(e){return c(this,null,function*(){(yield this.sdk.getAudioOutput().setDevice(e))&&this.setState(i=>{i.settings.audioOutputDeviceId=e},"setAudioOutputDevice")})}setPreferredLayer(e,t){return c(this,null,function*(){var r;let i=this.getTrackById(e);if(i)if(i instanceof x){if(t==="none"){b.d("layer none will be ignored");return}if(((r=this.store.getState(Ns(e)))==null?void 0:r.preferredLayer)===t){b.d(`preferred layer is already ${t}`);return}this.setState(n=>{let o=n.tracks[e];o&&(o.preferredLayer=t)},"setPreferredLayer"),yield i.setPreferredLayer(t)}else b.d(`track ${e} is not a remote video track`);else this.logPossibleInconsistency(`track ${e} not present, unable to set preffer layer`)})}getNativeTrackById(e){var t;return(t=this.sdk.store.getTrackById(e))==null?void 0:t.nativeTrack}getTrackById(e){return this.sdk.store.getTrackById(e)}getAuthTokenByRoomCode(e,t){return this.sdk.getAuthTokenByRoomCode(e,t)}preview(e){return c(this,null,function*(){let t=this.store.getState(oe);if(t==="Preview"||t==="Connecting"){this.logPossibleInconsistency("attempting to call preview while room is in preview/connecting");return}try{t!=="Connected"&&this.setState(i=>{i.room.roomState="Connecting"},"connecting"),yield this.sdkPreviewWithListeners(e)}catch(i){throw b.e("Cannot show preview. Failed to connect to room - ",i),i}})}cancelMidCallPreview(){return c(this,null,function*(){return this.sdk.cancelMidCallPreview()})}join(e){return c(this,null,function*(){if(this.isRoomJoinCalled){this.logPossibleInconsistency("room join is called again");return}try{this.isRoomJoinCalled=!0,this.setState(t=>{t.room.roomState="Connecting"},"join"),yield this.sdkJoinWithListeners(e)}catch(t){throw this.isRoomJoinCalled=!1,b.e("Failed to connect to room - ",t),t}})}leave(){return c(this,null,function*(){let e=this.store.getState(Ce),t=!0;e||(t=!1,this.logPossibleInconsistency("room leave is called when no room is connected"));let i=this.store.getState(oe);return this.setState(r=>{r.room.roomState="Disconnecting"},"leaving"),this.sdk.leave(t).then(()=>{this.resetState("leave"),this.beamSpeakerLabelsLogger&&this.beamSpeakerLabelsLogger.stop().catch(b.e),b.i("left room")}).catch(r=>{b.e("error in leaving room - ",r),this.setState(s=>{s.room.roomState=i},"revertLeave")})})}setScreenShareEnabled(e,t){return c(this,null,function*(){typeof t=="boolean"&&(t={audioOnly:t});try{e?yield this.startScreenShare(t):yield this.stopScreenShare()}catch(i){throw this.hmsNotifications.sendError(N.convertException(i)),i}})}addTrack(e,t="regular"){return c(this,null,function*(){yield this.sdk.addTrack(e,t),this.syncRoomState("addTrack")})}removeTrack(e){return c(this,null,function*(){yield this.sdk.removeTrack(e),this.syncRoomState("removeTrack")})}setLocalAudioEnabled(e){return c(this,null,function*(){let t=this.store.getState(ue);t&&(yield this.setEnabledTrack(t,e))})}setLocalVideoEnabled(e){return c(this,null,function*(){let t=this.store.getState(ie);t&&(yield this.setEnabledTrack(t,e))})}setEnabledTrack(e,t){return c(this,null,function*(){var s;if(((s=this.store.getState().tracks[e])==null?void 0:s.enabled)===t){this.logPossibleInconsistency(`local track[${e}] enabled state - ${t}`);return}this.setState(n=>{n.tracks[e]?n.tracks[e].displayEnabled=t:this.logPossibleInconsistency("track id not found for setEnabled")},"displayEnabled");try{yield this.setEnabledSDKTrack(e,t),this.syncRoomState("setEnabled")}catch(n){throw this.setState(o=>{o.tracks[e].displayEnabled=!t},"rollbackDisplayEnabled"),this.hmsNotifications.sendError(N.convertException(n)),n}let r=t?3:2;this.hmsNotifications.sendTrackUpdate(r,e)})}autoSelectAudioOutput(e){return c(this,null,function*(){yield this.sdk.autoSelectAudioOutput(e)})}setAudioSettings(e){return c(this,null,function*(){let t=this.store.getState(ue);t&&(yield this.setSDKLocalAudioTrackSettings(t,e),this.syncRoomState("setAudioSettings"))})}setVideoSettings(e){return c(this,null,function*(){let t=this.store.getState(ie);t&&(yield this.setSDKLocalVideoTrackSettings(t,e),this.syncRoomState("setVideoSettings"))})}switchCamera(){return c(this,null,function*(){let e=this.store.getState(ie);if(e){let t=this.sdk.store.getLocalPeerTracks().find(i=>i.trackId===e);t&&(yield t.switchCamera(),this.syncRoomState("switchCamera"))}})}sendMessage(e){this.sendBroadcastMessage(e)}sendBroadcastMessage(e,t){return c(this,null,function*(){let{message_id:i,timestamp:r}=yield this.sdk.sendBroadcastMessage(e,t);this.updateMessageInStore({message:e,type:t,id:i,time:r})})}sendGroupMessage(e,t,i){return c(this,null,function*(){let r=this.store.getState(ye),s=t.map(l=>r[l]),{message_id:n,timestamp:o}=yield this.sdk.sendGroupMessage(e,s,i);this.updateMessageInStore({message:e,recipientRoles:t,type:i,id:n,time:o})})}sendDirectMessage(e,t,i){return c(this,null,function*(){let{message_id:r,timestamp:s}=yield this.sdk.sendDirectMessage(e,t,i);this.updateMessageInStore({message:e,recipientPeer:t,type:i,id:r,time:s})})}updateMessageInStore(e){var s;if(!e.message)throw b.w("sendMessage","Failed to send message",e),Error(`sendMessage Failed - ${JSON.stringify(e)}`);if(!!e.type&&this.ignoredMessageTypes.includes(e.type))return;let i=this.sdk.getLocalPeer(),r={read:!0,id:e.id,time:new Date(e.time),message:e.message,type:e.type||"chat",recipientPeer:e.recipientPeer,recipientRoles:e.recipientRoles,senderName:i==null?void 0:i.name,sender:i==null?void 0:i.peerId,senderRole:(s=i==null?void 0:i.role)==null?void 0:s.name,ignored:!1};this.setState(n=>{n.messages.byID[r.id]=r,n.messages.allIDs.push(r.id)},"newMessage")}setMessageRead(e,t){this.setState(i=>{t?i.messages.byID[t]?i.messages.byID[t].read=e:this.logPossibleInconsistency("no message with id is found"):i.messages.allIDs.forEach(r=>{i.messages.byID[r].read=e})},"setMessageRead")}attachVideo(e,t){return c(this,null,function*(){if(this.localAndVideoUnmuting(e))return new Promise(i=>{let r=this.store.subscribe(s=>c(this,null,function*(){s&&(yield this.attachVideoInternal(e,t),r(),i())}),Ki)});yield this.attachVideoInternal(e,t)})}detachVideo(e,t){return c(this,null,function*(){let i=this.getTrackById(e);(i==null?void 0:i.type)==="video"?yield this.sdk.detachVideo(i,t):(t&&(t.srcObject=null),b.d("possible inconsistency detected - no video track found to remove sink"))})}addPluginToVideoTrack(e,t){return c(this,null,function*(){return this.addRemoveVideoPlugin(e,"add",t)})}addPluginsToVideoStream(e){return c(this,null,function*(){return this.addRemoveMediaStreamVideoPlugins(e,"add")})}removePluginsFromVideoStream(e){return c(this,null,function*(){return this.addRemoveMediaStreamVideoPlugins(e,"remove")})}addPluginToAudioTrack(e){return c(this,null,function*(){return this.addRemoveAudioPlugin(e,"add")})}validateVideoPluginSupport(e){let t={};if(t.isSupported=!1,!e)return b.w("no plugin passed in for checking support"),t.errMsg="no plugin passed in for checking support",t;let i=this.store.getState(ie);if(!i)return b.w("video Track not added to local peer yet"),t.errMsg="call this function only after local peer has video track",t;let r=this.getTrackById(i);return r?t=r.validatePlugin(e):(b.w(`track ${i} not present, unable to validate plugin`),t.errMsg=`track ${i} not present, unable to validate plugin`),t}validateAudioPluginSupport(e){let t={};if(t.isSupported=!1,!e)return b.w('no plugin passed in for checking support"'),t.errMsg='no plugin passed in for checking support"',t;let i=this.store.getState(ue);if(!i)return b.w("audio track not added to local peer yet"),t.errMsg="call this function only after local peer has audio track",t;let r=this.getTrackById(i);return r?t=r.validatePlugin(e):(b.w(`track ${i} not present, unable to validate plugin`),t.errMsg=`track ${i} not present, unable to validate plugin`),t}removePluginFromVideoTrack(e){return c(this,null,function*(){return this.addRemoveVideoPlugin(e,"remove")})}removePluginFromAudioTrack(e){return c(this,null,function*(){return this.addRemoveAudioPlugin(e,"remove")})}changeRole(e,t,i=!1){return c(this,null,function*(){yield this.sdk.changeRoleOfPeer(e,t,i)})}changeRoleOfPeer(e,t,i=!1){return c(this,null,function*(){yield this.sdk.changeRoleOfPeer(e,t,i)})}changeRoleOfPeersWithRoles(e,t){return c(this,null,function*(){let i=this.sdk.getRoles().filter(r=>e.includes(r.name));yield this.sdk.changeRoleOfPeersWithRoles(i,t)})}acceptChangeRole(e){return c(this,null,function*(){let t=e.requestedBy?this.getSDKHMSPeer(e.requestedBy.id):void 0;t||b.w(`peer for which role change is requested no longer available - ${e.requestedBy}`);let i={requestedBy:t,role:e.role,token:e.token};yield this.sdk.acceptChangeRole(i),this.removeRoleChangeRequest(e)})}raiseLocalPeerHand(){return c(this,null,function*(){yield this.sdk.raiseLocalPeerHand()})}lowerLocalPeerHand(){return c(this,null,function*(){yield this.sdk.lowerLocalPeerHand()})}raiseRemotePeerHand(e){return c(this,null,function*(){yield this.sdk.raiseRemotePeerHand(e)})}lowerRemotePeerHand(e){return c(this,null,function*(){yield this.sdk.lowerRemotePeerHand(e)})}getPeer(e){return c(this,null,function*(){let t=yield this.sdk.getPeer(e);if(t)return N.convertPeer(t)})}findPeerByName(e){return c(this,null,function*(){let{offset:t,peers:i,eof:r}=yield this.sdk.findPeerByName(e);return{offset:t,eof:r,peers:i.map(s=>N.convertPeer(s))}})}getPeerListIterator(e){let t=this.sdk.getPeerListIterator(e);return{hasNext:()=>t.hasNext(),next:()=>c(this,null,function*(){return(yield t.next()).map(r=>N.convertPeer(r))}),findPeers:()=>c(this,null,function*(){return(yield t.findPeers()).map(r=>N.convertPeer(r))}),getTotal:()=>t.getTotal()}}initAppData(e){this.setState(t=>{t.appData=e},"initAppData")}setAppData(e,t,i){let r=(t==null?void 0:t.constructor.name)==="Object";this.setState(s=>{if(s.appData)i&&r?Object.assign(s.appData[e],t):s.appData[e]=t;else{let n={[e]:t};s.appData=n}},`setAppData-${e}`)}rejectChangeRole(e){this.removeRoleChangeRequest(e)}endRoom(e,t){return c(this,null,function*(){let i=this.store.getState(As);if(!(i!=null&&i.endRoom)){b.w("You are not allowed to perform this action - endRoom");return}let r=this.store.getState(oe);this.setState(s=>{s.room.roomState="Disconnecting"},"endingRoom");try{yield this.sdk.endRoom(e,t),this.resetState("endRoom")}catch(s){b.e("error in ending room - ",s),this.setState(n=>{n.room.roomState=r},"revertEndRoom")}})}removePeer(e,t){return c(this,null,function*(){var r;let i=(r=this.sdk.getLocalPeer())==null?void 0:r.peerId;e!==i&&(yield this.sdk.removePeer(e,t))})}startRTMPOrRecording(e){return c(this,null,function*(){yield this.sdk.startRTMPOrRecording(e)})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.sdk.stopRTMPAndRecording()})}startHLSStreaming(e){return c(this,null,function*(){yield this.sdk.startHLSStreaming(e)})}stopHLSStreaming(e){return c(this,null,function*(){yield this.sdk.stopHLSStreaming(e)})}startTranscription(e){return c(this,null,function*(){yield this.sdk.startTranscription(e)})}stopTranscription(e){return c(this,null,function*(){yield this.sdk.stopTranscription(e)})}updateTranscriptionConfig(e){return c(this,null,function*(){yield this.sdk.updateTranscriptionConfig(e)})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.sdk.sendHLSTimedMetadata(e)})}changeName(e){return c(this,null,function*(){yield this.sdk.changeName(e)})}changeMetadata(e){return c(this,null,function*(){typeof e!="string"&&(e=JSON.stringify(e)),yield this.sdk.changeMetadata(e)})}setSessionMetadata(e){return c(this,null,function*(){yield this.sdk.setSessionMetadata(e),this.setState(t=>{t.sessionMetadata=e},"setSessionMetadata"),this.setSessionStoreValueLocally({key:"default",value:e},"setSessionMetadata")})}populateSessionMetadata(){return c(this,null,function*(){let e=yield this.sdk.getSessionMetadata();this.setState(t=>{t.sessionMetadata=e},"populateSessionMetadata"),this.setSessionStoreValueLocally({key:"default",value:e},"populateSessionmetadata")})}setRemoteTrackEnabled(e,t){return c(this,null,function*(){if(typeof e=="string"){let i=this.getTrackById(e);i&&An(i)?yield this.sdk.changeTrackState(i,t):this.logPossibleInconsistency(`No remote track with ID ${e} found for change track state`)}else Array.isArray(e)&&e.forEach(i=>this.setRemoteTrackEnabled(i,t))})}setRemoteTracksEnabled(e){return c(this,null,function*(){let t={enabled:e.enabled,type:e.type,source:e.source};if(e.roles){let i=this.store.getState(ye);t.roles=e.roles.map(r=>i[r])}yield this.sdk.changeMultiTrackState(t)})}setLogLevel(e){b.level=e,this.sdk.setLogLevel(e)}setFrameworkInfo(e){this.sdk.setFrameworkInfo(e)}ignoreMessageTypes(e,t=!1){if(t)this.ignoredMessageTypes=e;else for(let i of e)this.ignoredMessageTypes.includes(i)||this.ignoredMessageTypes.push(i)}enableBeamSpeakerLabelsLogging(){return c(this,null,function*(){this.beamSpeakerLabelsLogger||(b.i("enabling beam speaker labels logging"),this.beamSpeakerLabelsLogger=new er(this.store,this),yield this.beamSpeakerLabelsLogger.start())})}initDiagnostics(){let e=new gt(this.sdk,{onJoin:this.onJoin.bind(this),onPreview:this.onPreview.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this),onTrackUpdate:this.onTrackUpdate.bind(this),onMessageReceived:this.onMessageReceived.bind(this),onError:this.onError.bind(this),onReconnected:this.onReconnected.bind(this),onReconnecting:this.onReconnecting.bind(this),onRoleChangeRequest:this.onRoleChangeRequest.bind(this),onRoleUpdate:this.onRoleUpdate.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onTrackInterruption:this.onTrackInterruption.bind(this),onChangeTrackStateRequest:this.onChangeTrackStateRequest.bind(this),onChangeMultiTrackStateRequest:this.onChangeMultiTrackStateRequest.bind(this),onRemovedFromRoom:this.onRemovedFromRoom.bind(this),onNetworkQuality:this.onNetworkQuality.bind(this),onSessionStoreUpdate:this.onSessionStoreUpdate.bind(this),onPollsUpdate:this.onPollsUpdate.bind(this),onWhiteboardUpdate:this.onWhiteboardUpdate.bind(this)});return this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)}),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:this.onConnectionQualityUpdate.bind(this)}),e}resetState(e="resetState"){this.isRoomJoinCalled=!1,b.cleanup(),this.setState(t=>{Object.assign(t,It())},e)}getDebugInfo(){return this.sdk.getDebugInfo()}sdkJoinWithListeners(e){return c(this,null,function*(){yield this.sdk.join(e,{onJoin:this.onJoin.bind(this),onPreview:this.onPreview.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this),onTrackUpdate:this.onTrackUpdate.bind(this),onMessageReceived:this.onMessageReceived.bind(this),onError:this.onError.bind(this),onReconnected:this.onReconnected.bind(this),onReconnecting:this.onReconnecting.bind(this),onRoleChangeRequest:this.onRoleChangeRequest.bind(this),onRoleUpdate:this.onRoleUpdate.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onTrackInterruption:this.onTrackInterruption.bind(this),onChangeTrackStateRequest:this.onChangeTrackStateRequest.bind(this),onChangeMultiTrackStateRequest:this.onChangeMultiTrackStateRequest.bind(this),onRemovedFromRoom:this.onRemovedFromRoom.bind(this),onNetworkQuality:this.onNetworkQuality.bind(this),onSessionStoreUpdate:this.onSessionStoreUpdate.bind(this),onPollsUpdate:this.onPollsUpdate.bind(this),onWhiteboardUpdate:this.onWhiteboardUpdate.bind(this),onSFUMigration:this.onSFUMigration.bind(this)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)}),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:this.onConnectionQualityUpdate.bind(this)})})}onSFUMigration(){this.syncRoomState("SFUMigration")}onRemovedFromRoom(e){var r;let t=this.store.getState(se((r=e.requestedBy)==null?void 0:r.peerId));this.hmsNotifications.sendLeaveRoom(M(m({},e),{requestedBy:t||void 0}));let i=e.roomEnded||!t?"roomEnded":"removedFromRoom";b.i(`resetting state after peer removed ${i}`,e),this.resetState(i)}onTrackInterruption(e){this.setState(t=>{let i=t.tracks[e.trackId];i&&(i.interrupted=e.started)},"trackInterruption"),this.hmsNotifications.sendTrackInterruption(e)}onDeviceChange(e){let t=e.devices;if(!t)return;let i=this.store.getState(X);if(this.setState(r=>{pe(r.devices.audioInput,t.audioInput)||(r.devices.audioInput=t.audioInput),pe(r.devices.videoInput,t.videoInput)||(r.devices.videoInput=t.videoInput),pe(r.devices.audioOutput,t.audioOutput)||(r.devices.audioOutput=t.audioOutput);let s=this.sdk.getLocalPeer();i!=null&&i.id&&s&&Object.assign(r.settings,this.getMediaSettings(s))},"deviceChange"),e.selection&&!e.internal){let r=N.convertDeviceChangeUpdate(e);this.hmsNotifications.sendDeviceChange(r)}}sdkPreviewWithListeners(e){return c(this,null,function*(){yield this.sdk.preview(e,{onPreview:this.onPreview.bind(this),onError:this.onError.bind(this),onReconnected:this.onReconnected.bind(this),onReconnecting:this.onReconnecting.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onTrackInterruption:this.onTrackInterruption.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this),onNetworkQuality:this.onNetworkQuality.bind(this),onTrackUpdate:this.onTrackUpdate.bind(this)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)})})}onNetworkQuality(e){this.setState(t=>{var r;let i=t.room.localPeer||((r=this.sdk.getLocalPeer())==null?void 0:r.peerId);i&&(t.connectionQualities[i]={peerID:i,downlinkQuality:e})},"ConnectionQuality")}onSessionStoreUpdate(e){this.setSessionStoreValueLocally(e,"sessionStoreUpdate")}onPollsUpdate(e,t){let i=Ji[e];this.setState(r=>{let s=t.reduce((n,o)=>{var l;return n[o.id]=M(m({},o),{questions:(l=o.questions)==null?void 0:l.map(u=>{var p,h;return M(m({},u),{answer:u.answer?m({},u.answer):void 0,options:(p=u.options)==null?void 0:p.map(T=>m({},T)),responses:(h=u.responses)==null?void 0:h.map(T=>m({},T))})})}),n},{});Cn(r.polls,s)},i),t.forEach(r=>this.hmsNotifications.sendPollUpdate(e,r.id))}onWhiteboardUpdate(e){this.setState(t=>{t.whiteboards[e.id]=e},"whiteboardUpdate")}startScreenShare(e){return c(this,null,function*(){this.store.getState(ji)?this.logPossibleInconsistency("start screenshare is called while it's on"):(yield this.sdk.startScreenShare(()=>this.syncRoomState("screenshareStopped"),e),this.syncRoomState("startScreenShare"))})}stopScreenShare(){return c(this,null,function*(){this.store.getState(ji)?(yield this.sdk.stopScreenShare(),this.syncRoomState("stopScreenShare")):this.logPossibleInconsistency("stop screenshare is called while it's not on")})}attachVideoInternal(e,t){return c(this,null,function*(){let i=this.getTrackById(e);i||(i=this.getLocalTrack(e)),i&&i.type==="video"?yield this.sdk.attachVideo(i,t):this.logPossibleInconsistency("no video track found to add sink")})}syncRoomState(e){e=`${e}_fullSync`,b.time(`store-sync-${e}`);let t={},i=[],r={},s={},n={},o,l=this.sdk.getPeers();for(let g of l){let f=N.convertPeer(g);t[f.id]=f,i.push(f.id),n[f.id]={peerID:f.id,downlinkQuality:g.networkQuality||-1};let P=[g.audioTrack,g.videoTrack,...g.auxiliaryTracks];for(let v of P){if(!v)continue;let R=N.convertTrack(v);r[R.id]=R}if(g.isLocal){let v=g;o=this.getPreviewFields(v),Object.assign(s,this.getMediaSettings(v))}}let u=this.sdk.getRecordingState(),p=this.sdk.getRTMPState(),h=this.sdk.getHLSState(),T=this.sdk.getTranscriptionState();this.setState(g=>{var v;g.room.peers=i;let f=g.peers,P=g.tracks;Rn(f,t),Hn(P,r),Object.assign(g.settings,s),g.room.isConnected&&Object.assign(g.connectionQualities,n),(v=g.preview)!=null&&v.localPeer&&(o!=null&&o.localPeer)?Object.assign(g.preview,o):g.preview=o,Object.assign(g.roles,N.convertRoles(this.sdk.getRoles())),Object.assign(g.playlist,N.convertPlaylist(this.sdk.getPlaylistManager())),Object.assign(g.room,N.convertRecordingStreamingState(u,p,h,T)),Object.assign(g.templateAppData,this.sdk.getTemplateAppData())},e),b.timeEnd(`store-sync-${e}`)}onPreview(e){this.setState(t=>{var i;Object.assign(t.room,N.convertRoom(e,(i=this.sdk.getLocalPeer())==null?void 0:i.peerId)),t.room.roomState="Preview"},"previewStart"),this.syncRoomState("previewSync")}onJoin(e){let t=this.sdk.getPlaylistManager();this.audioPlaylist=new zt(t,"audio",this.syncPlaylistState.bind(this),this.store),this.videoPlaylist=new zt(t,"video",this.syncRoomState.bind(this),this.store),this.syncRoomState("joinSync"),this.setState(i=>{var r;Object.assign(i.room,N.convertRoom(e,(r=this.sdk.getLocalPeer())==null?void 0:r.peerId)),i.room.isConnected=!0,i.room.roomState="Connected"},"joined"),t.onProgress(this.setProgress),t.onNewTrackStart(i=>{this.syncPlaylistState(`${i.type}PlaylistUpdate`)}),t.onPlaylistEnded(i=>{this.syncPlaylistState(`${i}PlaylistEnded`)}),t.onCurrentTrackEnded(i=>{this.hmsNotifications.sendPlaylistTrackEnded(N.convertPlaylistItem(t,i)),this.syncPlaylistState(`${i.type}PlaylistItemEnded`)})}onRoomUpdate(e,t){this.setState(i=>{var r;Object.assign(i.room,N.convertRoom(t,(r=this.sdk.getLocalPeer())==null?void 0:r.peerId))},e),e==="TRANSCRIPTION_STATE_UPDATED"&&this.hmsNotifications.sendTranscriptionUpdate(t.transcriptions)}onPeerUpdate(e,t){if(![4,5].includes(e)){if(Array.isArray(t)){let i=this.store.getState(Y),r=t.filter(n=>!i[n.peerId]);if(this.syncRoomState("peersJoined"),this.store.getState(Ce)){let n=[];for(let o of t){let l=this.store.getState(se(o.peerId));l&&n.push(l)}this.hmsNotifications.sendPeerList(n)}else r.forEach(n=>{let o=this.store.getState(se(n.peerId));o&&this.hmsNotifications.sendPeerUpdate(0,o)});return}this.sendPeerUpdateNotification(e,t)}}onTrackUpdate(e,t,i){if(e===1)this.hmsNotifications.sendTrackUpdate(e,t.trackId),this.handleTrackRemove(t,i);else if([0,1].includes(e)){let r=Qt[e];this.syncRoomState(r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}else{let r=Qt[e]||"trackUpdate",s=N.convertTrack(t);this.setState(n=>{let o=n.tracks[s.id];Ye(o,s)&&($s(o,s),Object.assign(o,s))},r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}}onMessageReceived(e){let t=N.convertMessage(e,this.store.getState(Ie));t.read=!1,t.ignored=this.ignoredMessageTypes.includes(t.type),t.type==="hms_transcript"&&(t.ignored=!0),this.putMessageInStore(t),this.hmsNotifications.sendMessageReceived(t)}putMessageInStore(e){e.ignored||this.actionBatcher.setState(t=>{t.messages.byID[e.id]=e,t.messages.allIDs.push(e.id)},"newMessage",150)}onAudioLevelUpdate(e){this.setState(t=>{let i={};e.forEach(s=>{if(!s.track||!s.peer)return;let n=s.track.trackId;i[n]=s.audioLevel,t.speakers[n]||(t.speakers[n]={audioLevel:s.audioLevel,peerID:s.peer.peerId,trackID:n})});let r=Object.entries(t.speakers);for(let[s,n]of r)n.audioLevel=i[s]||0,n.audioLevel===0&&delete t.speakers[s]},"audioLevel")}onConnectionQualityUpdate(e){this.setState(t=>{e.forEach(i=>{let r=i.peerID;r&&(t.connectionQualities[r]?Object.assign(t.connectionQualities[r],i):t.connectionQualities[r]=i)})},"connectionQuality")}onChangeTrackStateRequest(e){var s;let t=this.store.getState(se((s=e.requestedBy)==null?void 0:s.peerId)),i=this.getStoreLocalTrackIDfromSDKTrack(e.track),r=this.store.getState(Kt(i));if(!r)return this.logPossibleInconsistency(`Not found track for which track state change was requested, ${e.track}`);e.enabled||this.syncRoomState("changeTrackStateRequest"),this.hmsNotifications.sendChangeTrackStateRequest({requestedBy:t||void 0,track:r,enabled:e.enabled})}onChangeMultiTrackStateRequest(e){var s;let t=this.store.getState(se((s=e.requestedBy)==null?void 0:s.peerId));e.enabled||this.syncRoomState("changeMultiTrackStateRequest");let i=[],r=this.store.getState(_);for(let n of e.tracks){let o=this.getStoreLocalTrackIDfromSDKTrack(n);o&&r[o]&&i.push(r[o])}this.hmsNotifications.sendChangeMultiTrackStateRequest({requestedBy:t||void 0,tracks:i,enabled:e.enabled,type:e.type,source:e.source})}onReconnected(){this.syncRoomState("reconnectedSync"),this.hmsNotifications.sendReconnected(),this.setState(e=>{e.room.roomState=e.room.isConnected?"Connected":"Preview"},"reconnected")}onReconnecting(e){let t=N.convertException(e);b.e("Reconnection: received error from sdk",t),this.hmsNotifications.sendReconnecting(t),this.setState(i=>{i.room.roomState="Reconnecting",i.errors.push(t)},"reconnecting")}onError(e){let t=N.convertException(e);t.isTerminal?(this.leave().then(()=>b.e("error from SDK, left room.")),this.setState(i=>{i.room.roomState="Failed",i.errors.push(t)},"errorTerminal")):this.store.getState().errors.length<50&&this.setState(r=>{r.errors.push(t)},"error"),this.syncRoomState("errorSync"),this.hmsNotifications.sendError(t),b.e("received error from sdk",t instanceof k?`${t}`:t)}handleTrackRemove(e,t){this.setState(i=>{let r=i.peers[t.peerId],s=i.tracks,n=e.trackId;if(r)if(n===r.audioTrack)delete r.audioTrack;else if(n===r.videoTrack)delete r.videoTrack;else{let o=r.auxiliaryTracks.indexOf(n);o>-1&&r.auxiliaryTracks.splice(o,1)}delete s[n]},"trackRemoved")}setEnabledSDKTrack(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setEnabled(t):this.logPossibleInconsistency(`track ${e} not present, unable to enabled/disable`)})}setSDKLocalVideoTrackSettings(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setSettings(t):this.logPossibleInconsistency(`local track ${e} not present, unable to set settings`)})}setSDKLocalAudioTrackSettings(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setSettings(t):this.logPossibleInconsistency(`local track ${e} not present, unable to set settings`)})}getMediaSettings(e){var s;let t=this.store.getState(ks),i=e.audioTrack,r=e.videoTrack;return{audioInputDeviceId:(i==null?void 0:i.settings.deviceId)||t.audioInputDeviceId,videoInputDeviceId:(r==null?void 0:r.settings.deviceId)||t.videoInputDeviceId,audioOutputDeviceId:(s=this.sdk.getAudioOutput().getDevice())==null?void 0:s.deviceId,audioMode:(i==null?void 0:i.settings.audioMode)||"voice"}}getPreviewFields(e){var i,r;if(!e.isInPreview())return;let t=N.convertPeer(e);return{localPeer:t.id,audioTrack:t.audioTrack,videoTrack:t.videoTrack,asRole:((i=e.asRole)==null?void 0:i.name)||((r=e.role)==null?void 0:r.name)}}setTrackVolume(e,t){return c(this,null,function*(){let i=this.getTrackById(t);i?i instanceof Oe?(yield i.setVolume(e),this.setState(r=>{let s=r.tracks[t];s&&s.type==="audio"&&(s.volume=e)},"trackVolume")):b.w(`track ${t} is not an audio track`):this.logPossibleInconsistency(`track ${t} not present, unable to set volume`)})}localAndVideoUnmuting(e){let t=this.store.getState(X);if((t==null?void 0:t.videoTrack)!==e)return!1;let i=this.store.getState(Ps),r=this.store.getState(Ki);return i&&!r}logPossibleInconsistency(e){b.w("possible inconsistency detected - ",e)}addRemoveVideoPlugin(e,t,i){return c(this,null,function*(){if(!e){b.w("Invalid plugin received in store");return}let r=this.store.getState(ie);if(r){let s=this.getLocalTrack(r);s?(t==="add"?yield s.addPlugin(e,i):t==="remove"&&(yield s.removePlugin(e)),this.syncRoomState(`${t}VideoPlugin`)):this.logPossibleInconsistency(`track ${r} not present, unable to ${t} plugin`)}})}addRemoveMediaStreamVideoPlugins(e,t){return c(this,null,function*(){if(e.length===0){b.w("Invalid plugin received in store");return}let i=this.store.getState(ie);if(i){let r=this.getLocalTrack(i);r?(t==="add"?yield r.addStreamPlugins(e):t==="remove"&&(yield r.removeStreamPlugins(e)),this.syncRoomState(`${t}MediaStreamPlugin`)):this.logPossibleInconsistency(`track ${i} not present, unable to ${t} plugin`)}})}addRemoveAudioPlugin(e,t){return c(this,null,function*(){try{if(!e){b.w("Invalid plugin received in store");return}let i=this.store.getState(ue);if(i){let r=this.getLocalTrack(i);r?(t==="add"?yield r.addPlugin(e):t==="remove"&&(yield r.removePlugin(e)),this.syncRoomState(`${t}AudioPlugin`)):this.logPossibleInconsistency(`track ${i} not present, unable to ${t} plugin`)}}catch(i){console.error(i)}})}onRoleChangeRequest(e){this.setState(t=>{t.roleChangeRequests.length===0&&t.roleChangeRequests.push(N.convertRoleChangeRequest(e))},"roleChangeRequest")}removeRoleChangeRequest(e){this.setState(t=>{let i=t.roleChangeRequests.findIndex(r=>r.token===e.token);i!==-1&&t.roleChangeRequests.splice(i,1)},"removeRoleChangeRequest")}onRoleUpdate(){this.syncRoomState("roleUpdate")}getStoreLocalTrackIDfromSDKTrack(e){return this.store.getState(Es).find(i=>{var r;return((r=this.getTrackById(i))==null?void 0:r.trackId)===e.trackId})}updateMidCallPreviewRoomState(e,t){t.isLocal&&e===8&&this.store.getState(bs)&&this.setState(i=>{i.room.roomState="Connected"},"midCallPreviewCompleted")}setSessionStoreValueLocally(e,t="setSessionStore"){let i=Array.isArray(e)?e:[e];this.setState(r=>{i.forEach(s=>{r.sessionStore[s.key]=s.value})},t)}hasActiveElements(e){let t=Object.keys(this.store.getState().whiteboards).length>0,i=Object.keys(this.store.getState().polls).length>0,r=Object.keys(this.store.getState().peers).length>0,s=e.getState().remoteTrackStats;return r&&(t||i||Object.values(s).some(n=>n&&typeof n.bitrate=="number"&&n.bitrate>0))}};var nr=a=>F?`${a} ${document.title}`:a;var or=class{constructor(e,t){this.eventBus=e;this.listener=t;this.TAG="[NetworkTestManager]";this.controller=new AbortController;this.start=e=>c(this,null,function*(){var u;if(!e)return;let{url:t,timeout:i,scoreMap:r}=e,s=this.controller.signal,n=Date.now(),o=0,l=te(i).then(()=>{this.controller.abort()});try{let h=(u=(yield fetch(`${t}?${Date.now()}`,{signal:s})).body)==null?void 0:u.getReader();if(!h)throw Error("unable to process request");let T=()=>c(this,null,function*(){if(h)try{let g=!1;for(;!g;){let{value:f,done:P}=yield h.read();g=P,f&&(o+=f.byteLength,this.sendScore({scoreMap:r,downloadedSize:o,startTime:n}))}}catch(g){g.name!=="AbortError"&&d.d(this.TAG,g)}});return Promise.race([T(),l]).then(()=>{this.sendScore({scoreMap:r,downloadedSize:o,startTime:n,finished:!0})}).catch(g=>{d.d(this.TAG,g),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:g.message}))})}catch(p){p.name!=="AbortError"?(d.d(this.TAG,p),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:p.message}))):d.d(this.TAG,p)}});this.stop=()=>{this.controller.signal.aborted||this.controller.abort()};this.sendScore=({scoreMap:e,downloadedSize:t,startTime:i,finished:r=!1})=>{let s=(Date.now()-i)/1e3,o=t/1024/s*8,l=-1;for(let u in e){let p=e[u];o>=p.low&&(!p.high||o<=p.high)&&(l=Number(u))}this.updateScoreToListener(l),r&&this.eventBus.analytics.publish(y.previewNetworkQuality({score:l,downLink:o.toFixed(2)}))}}updateScoreToListener(e){var t,i;e!==this.score&&(this.score=e,(i=(t=this.listener)==null?void 0:t.onNetworkQuality)==null||i.call(t,e))}};var Yt=class{constructor(e,t,i,r,s,n){this.store=e;this.transport=t;this.deviceManager=i;this.publish=r;this.removeAuxiliaryTrack=s;this.listener=n;this.handleLocalPeerRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){var s;let r=this.store.getLocalPeer();r&&(yield this.diffRolesAndPublishTracks({oldRole:e,newRole:t}),(s=this.listener)==null||s.onPeerUpdate(8,r))});this.diffRolesAndPublishTracks=i=>c(this,[i],function*({oldRole:e,newRole:t}){var g,f,P,v,R,$;let r=new Set(e.publishParams.allowed),s=new Set(t.publishParams.allowed),n=this.removeTrack(r,s,"video"),o=this.removeTrack(r,s,"audio"),l=this.removeTrack(r,s,"screen"),u=this.hasSimulcastDifference((g=e.publishParams.simulcast)==null?void 0:g.video,(f=t.publishParams.simulcast)==null?void 0:f.video),p=this.hasSimulcastDifference((P=e.publishParams.simulcast)==null?void 0:P.screen,(v=t.publishParams.simulcast)==null?void 0:v.screen),h=($=(R=this.store.getLocalPeer())==null?void 0:R.videoTrack)==null?void 0:$.enabled;yield this.removeAudioTrack(o),yield this.removeVideoTracks(n||u),yield this.removeScreenTracks(l||p);let T=this.getSettings();u&&(T.isVideoMuted=!h),yield this.publish(T),yield this.syncDevices(T,t)})}syncDevices(e,t){return c(this,null,function*(){(!e.isAudioMuted||!e.isVideoMuted)&&t.publishParams.allowed.length>0&&(yield this.deviceManager.init(!0))})}removeVideoTracks(e){return c(this,null,function*(){var i;if(!e)return;let t=this.store.getLocalPeer();t!=null&&t.videoTrack&&(t.videoTrack.isPublished?yield this.transport.unpublish([t.videoTrack]):yield t.videoTrack.cleanup(),(i=this.listener)==null||i.onTrackUpdate(1,t.videoTrack,t),t.videoTrack=void 0),yield this.removeAuxTracks(r=>r.source!=="screen"&&r.type==="video")})}removeAudioTrack(e){return c(this,null,function*(){var i;if(!e)return;let t=this.store.getLocalPeer();t!=null&&t.audioTrack&&(t.audioTrack.isPublished?yield this.transport.unpublish([t.audioTrack]):yield t.audioTrack.cleanup(),(i=this.listener)==null||i.onTrackUpdate(1,t.audioTrack,t),t.audioTrack=void 0),yield this.removeAuxTracks(r=>r.source!=="screen"&&r.type==="audio")})}removeScreenTracks(e){return c(this,null,function*(){e&&(yield this.removeAuxTracks(t=>t.source==="screen"))})}removeAuxTracks(e){return c(this,null,function*(){let t=this.store.getLocalPeer();if(t!=null&&t.auxiliaryTracks){let i=[...t.auxiliaryTracks];for(let r of i)e(r)&&(yield this.removeAuxiliaryTrack(r.trackId))}})}removeTrack(e,t,i){return e.has(i)&&!t.has(i)}hasSimulcastDifference(e,t){var i,r,s;return!e&&!t?!1:((i=e==null?void 0:e.layers)==null?void 0:i.length)!==((r=t==null?void 0:t.layers)==null?void 0:r.length)?!0:!!((s=e==null?void 0:e.layers)!=null&&s.some(n=>{var l;let o=(l=t==null?void 0:t.layers)==null?void 0:l.find(u=>u.rid===n.rid);return(o==null?void 0:o.maxBitrate)!==n.maxBitrate||(o==null?void 0:o.maxFramerate)!==n.maxFramerate}))}getSettings(){let{isAudioMuted:e,isVideoMuted:t}=this.getMutedStatus(),{audioInputDeviceId:i,audioOutputDeviceId:r}=this.getAudioDeviceSettings(),s=this.getVideoInputDeviceId();return{isAudioMuted:e,isVideoMuted:t,audioInputDeviceId:i,audioOutputDeviceId:r,videoDeviceId:s}}getMutedStatus(){var t,i,r;let e=(t=this.store.getConfig())==null?void 0:t.settings;return{isAudioMuted:(i=e==null?void 0:e.isAudioMuted)!=null?i:!0,isVideoMuted:(r=e==null?void 0:e.isVideoMuted)!=null?r:!0}}getAudioDeviceSettings(){var r,s,n;let e=(r=this.store.getConfig())==null?void 0:r.settings,t=((s=this.deviceManager.currentSelection.audioInput)==null?void 0:s.deviceId)||(e==null?void 0:e.audioInputDeviceId)||"default",i=((n=this.deviceManager.currentSelection.audioOutput)==null?void 0:n.deviceId)||(e==null?void 0:e.audioOutputDeviceId)||"default";return{audioInputDeviceId:t,audioOutputDeviceId:i}}getVideoInputDeviceId(){var t,i;let e=(t=this.store.getConfig())==null?void 0:t.settings;return((i=this.deviceManager.currentSelection.videoInput)==null?void 0:i.deviceId)||(e==null?void 0:e.videoDeviceId)||"default"}};var qs=class{constructor(){this.TAG="[HTTPAnalyticsTransport]";this.failedEvents=new Ee("client-events");this.isConnected=!0;this.env=null;this.websocketURL=""}setEnv(e){this.env=e,this.flushFailedEvents()}setWebsocketEndpoint(e){this.websocketURL=e}sendEvent(e){if(!this.env){this.addEventToStorage(e);return}let t={event:e.name,payload:e.properties,event_id:String(e.timestamp),peer:e.metadata.peer,timestamp:e.timestamp,device_id:e.device_id,cluster:{websocket_url:this.websocketURL}},i=this.env==="prod"?Ra:Ha;fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.metadata.token}`,user_agent_v2:e.metadata.userAgent},body:JSON.stringify(t)}).then(r=>{if(r.status===401){this.removeFromStorage(e);return}if(r.status!==200)throw Error(r.statusText);this.removeFromStorage(e)}).catch(r=>{d.v(this.TAG,"Failed to send event",r,e),this.addEventToStorage(e)})}flushFailedEvents(){let e=this.failedEvents.get();e==null||e.forEach(t=>this.sendEvent(t))}addEventToStorage(e){let t=this.failedEvents.get()||[];t.find(i=>i.timestamp===e.timestamp)||(t.length===100&&t.shift(),t.push(e),this.failedEvents.set(t))}removeFromStorage(e){let t=this.failedEvents.get()||[],i=t.findIndex(r=>r.timestamp===e.timestamp);i>-1&&(t.splice(i,1),this.failedEvents.set(t))}},Le=new qs;var Xt=class{constructor(e){this.type=e.type,this.source=e.source||"regular",this.description="",e instanceof Ne?(this.mute=!e.enabled,this.track_id=e.publishedTrackId,this.stream_id=e.stream.id):(this.mute=e.mute,this.track_id=e.track_id,this.stream_id=e.stream_id)}};var Zt=class{constructor(){this.TAG="[Store]:";this.knownRoles={};this.peers={};this.tracks=new Map;this.peerTrackStates={};this.speakers=[];this.roleDetailsArrived=!1;this.env="prod";this.simulcastEnabled=!1;this.userAgent=Nt(this.env);this.polls=new Map;this.whiteboards=new Map;this.addPermissionToRole=(e,t,i,r)=>{var n;if(!this.knownRoles[e]){d.d(this.TAG,`role ${e} is not present in given roles`,this.knownRoles);return}let s=this.knownRoles[e].permissions;t==="transcriptions"&&r?s[t]=M(m({},s[t]),{[r]:[i]}):t==="whiteboard"&&(s[t]||(s[t]=[]),(n=s[t])==null||n.push(i))};this.addWhiteboardPluginToRole=e=>{var i,r,s;let t=e==null?void 0:e.permissions;(i=t==null?void 0:t.admin)==null||i.forEach(n=>this.addPermissionToRole(n,"whiteboard","admin")),(r=t==null?void 0:t.reader)==null||r.forEach(n=>this.addPermissionToRole(n,"whiteboard","read")),(s=t==null?void 0:t.writer)==null||s.forEach(n=>this.addPermissionToRole(n,"whiteboard","write"))};this.addTranscriptionsPluginToRole=(e=[])=>{var t,i;for(let r of e)(i=(t=r.permissions)==null?void 0:t.admin)==null||i.forEach(s=>this.addPermissionToRole(s,"transcriptions","admin",r.mode)),r.translation&&this.room&&(this.room.translationConfig||(this.room.translationConfig={}),this.room.translationConfig[r.mode]=r.translation)};this.handleNoiseCancellationPlugin=e=>{this.room&&(this.room.isNoiseCancellationEnabledFromPolicy=!!(e!=null&&e.enabled))}}getConfig(){return this.config}setSimulcastEnabled(e){this.simulcastEnabled=e}removeRemoteTracks(){this.tracks.forEach(e=>{(e instanceof le||e instanceof x)&&(this.removeTrack(e),delete this.peerTrackStates[e.trackId])})}getEnv(){return this.env}getPublishParams(){let e=this.getLocalPeer(),t=(e==null?void 0:e.asRole)||(e==null?void 0:e.role);return t==null?void 0:t.publishParams}getRoom(){return this.room}getPolicyForRole(e){return this.knownRoles[e]}getKnownRoles(){return this.knownRoles}getTemplateAppData(){return this.templateAppData}getLocalPeer(){if(this.localPeerId&&this.peers[this.localPeerId])return this.peers[this.localPeerId]}getRemotePeers(){return Object.values(this.peers).filter(e=>!e.isLocal)}getPeers(){return Object.values(this.peers)}getPeerMap(){return this.peers}getPeerById(e){if(this.peers[e])return this.peers[e]}getTracksMap(){return this.tracks}getTracks(){return Array.from(this.tracks.values())}getVideoTracks(){return this.getTracks().filter(e=>e.type==="video")}getRemoteVideoTracks(){return this.getTracks().filter(e=>e instanceof x)}getAudioTracks(){return this.getTracks().filter(e=>e.type==="audio")}getPeerTracks(e){let t=e?this.peers[e]:void 0,i=[];return t!=null&&t.videoTrack&&i.push(t.videoTrack),t!=null&&t.audioTrack&&i.push(t.audioTrack),i.concat((t==null?void 0:t.auxiliaryTracks)||[])}getLocalPeerTracks(){return this.getPeerTracks(this.localPeerId)}hasTrack(e){return this.tracks.has(e)}getTrackById(e){var r,s;let t=Array.from(this.tracks.values()).find(n=>n.trackId===e);if(t)return t;let i=this.getLocalPeer();if(i){if((r=i.audioTrack)!=null&&r.isPublishedTrackId(e))return i.audioTrack;if((s=i.videoTrack)!=null&&s.isPublishedTrackId(e))return i.videoTrack}}getPeerByTrackId(e){let t=Array.from(this.tracks.values()).find(i=>i.trackId===e);return t!=null&&t.peerId?this.peers[t.peerId]:void 0}getSpeakers(){return this.speakers}getSpeakerPeers(){return this.speakers.map(e=>e.peer)}getUserAgent(){return this.userAgent}createAndSetUserAgent(e){this.userAgent=Nt(this.env,e)}setRoom(e){this.room=e}setKnownRoles(e){var i,r,s;if(this.knownRoles=e.known_roles,this.addPluginsToRoles(e.plugins),this.handleNoiseCancellationPlugin((i=e.plugins)==null?void 0:i.noiseCancellation),this.roleDetailsArrived=!0,this.templateAppData=e.app_data,!this.simulcastEnabled)return;let t=(r=this.knownRoles[e.name])==null?void 0:r.publishParams;this.videoLayers=this.convertSimulcastLayers((s=t.simulcast)==null?void 0:s.video),this.updatePeersPolicy()}hasRoleDetailsArrived(){return this.roleDetailsArrived}setConfig(e){var t,i,r;if(ae.rememberDevices(!!e.rememberDeviceSelection),e.rememberDeviceSelection){let s=ae.getSelection();s&&(e.settings||(e.settings={}),(t=s.audioInput)!=null&&t.deviceId&&(e.settings.audioInputDeviceId=e.settings.audioInputDeviceId||s.audioInput.deviceId),(i=s.audioOutput)!=null&&i.deviceId&&(e.settings.audioOutputDeviceId=e.settings.audioOutputDeviceId||s.audioOutput.deviceId),(r=s.videoInput)!=null&&r.deviceId&&(e.settings.videoDeviceId=e.settings.videoDeviceId||s.videoInput.deviceId))}e.autoManageVideo=e.autoManageVideo!==!1,e.autoManageWakeLock=e.autoManageWakeLock!==!1,this.config=e,this.setEnv()}addPeer(e){this.peers[e.peerId]=e,e.isLocal&&(this.localPeerId=e.peerId)}addTrack(e){this.tracks.set(e,e)}getTrackState(e){return this.peerTrackStates[e]}setTrackState(e){this.peerTrackStates[e.trackInfo.track_id]=e}removeTrackState(e){delete this.peerTrackStates[e]}removePeer(e){this.localPeerId===e&&(this.localPeerId=void 0),delete this.peers[e]}removeTrack(e){this.tracks.delete(e)}updateSpeakers(e){this.speakers=e}updateAudioOutputVolume(e){return c(this,null,function*(){yield Promise.all(this.getAudioTracks().map(t=>t.setVolume(e)))})}updateAudioOutputDevice(e){return c(this,null,function*(){let t=[];this.getAudioTracks().forEach(s=>{s instanceof le&&t.push(s.setOutputDevice(e))});let r=(yield Promise.allSettled(t)).filter(s=>s.status==="rejected");if(r.length>0)throw new Error(`updateAudioOutputDevice: ${r.length}/${t.length} track(s) failed to switch sink: ${r[0].reason}`)})}getSimulcastLayers(e){var t;return!this.simulcastEnabled||!["screen","regular"].includes(e)?[]:e==="screen"?[]:((t=this.videoLayers)==null?void 0:t.layers)||[]}convertSimulcastLayers(e){if(e)return M(m({},e),{layers:(e.layers||[]).map(t=>M(m({},t),{maxBitrate:t.maxBitrate*1e3}))})}getSimulcastDefinitionsForPeer(e,t){var o,l,u;if([!e||!e.role,t==="screen",!this.simulcastEnabled].some(p=>!!p))return[];let i=this.getPolicyForRole(e.role.name).publishParams,r,s,n;return t==="regular"?(r=(o=i.simulcast)==null?void 0:o.video,s=i.video.width,n=i.video.height):t==="screen"&&(r=(l=i.simulcast)==null?void 0:l.screen,s=i.screen.width,n=i.screen.height),((u=r==null?void 0:r.layers)==null?void 0:u.map(p=>{let h=Ue[p.rid],T={width:Math.floor(s/p.scaleResolutionDownBy),height:Math.floor(n/p.scaleResolutionDownBy)};return{layer:h,resolution:T}}))||[]}setPoll(e){this.polls.set(e.id,e)}getPoll(e){return this.polls.get(e)}setWhiteboard(e){this.whiteboards.set(e.id,e)}getWhiteboards(){return this.whiteboards}getWhiteboard(e){return e?this.whiteboards.get(e):this.whiteboards.values().next().value}getErrorListener(){return this.errorListener}cleanup(){let e=this.getTracks();for(let t of e)t.cleanup();this.room=void 0,this.config=void 0,this.localPeerId=void 0,this.roleDetailsArrived=!1}setErrorListener(e){this.errorListener=e}updatePeersPolicy(){this.getPeers().forEach(e=>{var t;if(!e.role){(t=this.errorListener)==null||t.onError(S.GenericErrors.InvalidRole("VALIDATION",""));return}e.role=this.getPolicyForRole(e.role.name)})}addPluginsToRoles(e){e&&Object.keys(e).forEach(t=>{let i=t;switch(i){case"whiteboard":{this.addWhiteboardPluginToRole(e[i]);break}case"transcriptions":{this.addTranscriptionsPluginToRole(e[i]);break}default:break}})}setEnv(){var r;let t=((r=this.config)==null?void 0:r.initEndpoint).split("https://")[1],i="prod";t.startsWith("prod")?i="prod":t.startsWith("qa")?i="qa":t.startsWith("dev")&&(i="dev"),this.env=i,Le.setEnv(i)}};var cr=class{constructor(){this.TAG="[WakeLockManager]";this.wakeLock=null;this.acquireLock=()=>c(this,null,function*(){yield this.requestWakeLock(),document==null||document.addEventListener("visibilitychange",this.visibilityHandler)});this.cleanup=()=>c(this,null,function*(){if(this.wakeLock&&!this.wakeLock.released)try{yield this.wakeLock.release(),d.d(this.TAG,"Wake lock released")}catch(e){let t=e;d.w(this.TAG,"Error while releasing wake lock",`name=${t.name}, message=${t.message}`)}document==null||document.removeEventListener("visibilitychange",this.visibilityHandler),this.wakeLock=null});this.visibilityHandler=()=>c(this,null,function*(){(document==null?void 0:document.visibilityState)==="visible"&&(!this.wakeLock||this.wakeLock.released)&&(d.d(this.TAG,"Re-acquiring wake lock due to visibility change"),yield this.requestWakeLock())});this.requestWakeLock=()=>c(this,null,function*(){try{if(!("wakeLock"in navigator)){d.d(this.TAG,"Wake lock feature not supported");return}this.wakeLock=yield navigator.wakeLock.request("screen"),d.d(this.TAG,"Wake lock acquired")}catch(e){let t=e;d.w(this.TAG,"Error acquiring wake lock",`name=${t.name}, message=${t.message}`)}})}};var dr=class{constructor(e){this.store=e;this.bufferSize=100;this.TAG="[AnalyticsEventsService]";this.transport=null;this.pendingEvents=[];this.level=1}setTransport(e){this.transport=e}reset(){this.transport=null,this.pendingEvents=[]}queue(e){if(e.level>=this.level&&(this.pendingEvents.push(e),this.pendingEvents.length>this.bufferSize)){let t=this.pendingEvents.shift();d.d(this.TAG,"Max buffer size reached","Removed event to accommodate new events",t)}return this}flushFailedClientEvents(){Le.flushFailedEvents()}flush(){var e;try{for(;this.pendingEvents.length>0;){let t=this.pendingEvents.shift();t&&(t.metadata.peer.peer_id=(e=this.store.getLocalPeer())==null?void 0:e.peerId,t.metadata.userAgent=this.store.getUserAgent(),this.transport&&this.transport.transportProvider.isConnected?this.transport.sendEvent(t):this.sendClientEventOnHTTP(t))}}catch(t){d.w(this.TAG,"Flush Failed",t)}}sendClientEventOnHTTP(e){var r,s,n,o;let t=this.store.getRoom(),i=this.store.getLocalPeer();e.metadata.token=(r=this.store.getConfig())==null?void 0:r.authToken,e.metadata.peer={session_id:t==null?void 0:t.sessionId,room_id:t==null?void 0:t.id,room_name:t==null?void 0:t.name,template_id:t==null?void 0:t.templateId,joined_at:(s=t==null?void 0:t.joinedAt)==null?void 0:s.getTime(),session_started_at:(n=t==null?void 0:t.startedAt)==null?void 0:n.getTime(),role:(o=i==null?void 0:i.role)==null?void 0:o.name,user_name:i==null?void 0:i.name,user_data:i==null?void 0:i.metadata,peer_id:i==null?void 0:i.peerId},Le.sendEvent(e)}};var Bn=require("uuid");var Un={autoplayFailed:void 0,initialized:!1,autoplayCheckPromise:void 0},ei=class{constructor(e,t,i){this.store=e;this.deviceManager=t;this.eventBus=i;this.autoPausedTracks=new Set;this.TAG="[AudioSinkManager]:";this.volume=100;this.state=m({},Un);this.handleAudioPaused=e=>c(this,null,function*(){d.d(this.TAG,"Audio Paused",e.target.id);let t=this.store.getTrackById(e.target.id);t&&this.autoPausedTracks.add(t)});this.handleTrackUpdate=({track:e})=>{d.d(this.TAG,"Track updated",`${e}`)};this.handleTrackAdd=r=>c(this,[r],function*({track:e,peer:t,callListener:i=!0}){var o,l,u,p;let s=document.createElement("audio");s.style.display="none",s.id=e.trackId;let n=(o=e.getRequestedVolume())!=null?o:this.volume;s.volume=n/100,s.addEventListener("pause",this.handleAudioPaused),s.onerror=()=>c(this,null,function*(){var T,g;d.e(this.TAG,"error on audio element",s.error);let h=S.TracksErrors.AudioPlaybackError(`Audio playback error for track - ${e.trackId} code - ${(T=s==null?void 0:s.error)==null?void 0:T.code}`);this.eventBus.analytics.publish(y.audioPlaybackError(h)),((g=s==null?void 0:s.error)==null?void 0:g.code)===MediaError.MEDIA_ERR_DECODE&&(this.removeAudioElement(s,e),yield te(500),yield this.handleTrackAdd({track:e,peer:t,callListener:!1}),this.state.autoplayFailed||this.eventBus.analytics.publish(y.audioRecovered("Audio recovered after media decode error")))}),e.setAudioElement(s),d.d(this.TAG,"Audio track added",`${e}`),this.init(),(l=this.audioSink)==null||l.append(s),this.outputDevice&&(yield e.setOutputDevice(this.outputDevice)),s.srcObject=new MediaStream([e.nativeTrack]),i&&((u=this.listener)==null||u.onTrackUpdate(0,e,t)),yield this.handleAutoplayError(e),e.setVolume((p=e.getRequestedVolume())!=null?p:this.volume).catch(h=>d.e(this.TAG,"Could not apply audio subscription state",`${e}`,h))});this.handleAutoplayError=e=>c(this,null,function*(){if(this.state.autoplayFailed===void 0&&(this.state.autoplayCheckPromise||(this.state.autoplayCheckPromise=new Promise(t=>{this.playAudioFor(e).then(t)})),yield this.state.autoplayCheckPromise),this.state.autoplayFailed){this.autoPausedTracks.add(e);return}yield this.playAudioFor(e)});this.handleAudioDeviceChange=e=>c(this,null,function*(){e.isUserSelection||e.error||!e.selection||e.type==="video"||(yield this.unpauseAudioTracks())});this.handleTrackRemove=e=>{this.autoPausedTracks.delete(e);let t=document.getElementById(e.trackId);t&&this.removeAudioElement(t,e),this.audioSink&&this.audioSink.childElementCount===0&&(this.state.autoplayCheckPromise=void 0,this.state.autoplayFailed=void 0),d.d(this.TAG,"Audio track removed",`${e}`)};this.unpauseAudioTracks=()=>c(this,null,function*(){let e=[];this.autoPausedTracks.forEach(t=>{e.push(this.playAudioFor(t))}),yield Promise.all(e)});this.removeAudioElement=(e,t)=>{e&&(d.d(this.TAG,"removing audio element",`${t}`),e.removeEventListener("pause",this.handleAudioPaused),e.srcObject=null,e.remove(),t.setAudioElement(null))};this.eventBus.audioTrackAdded.subscribe(this.handleTrackAdd),this.eventBus.audioTrackRemoved.subscribe(this.handleTrackRemove),this.eventBus.audioTrackUpdate.subscribe(this.handleTrackUpdate),this.eventBus.deviceChange.subscribe(this.handleAudioDeviceChange),this.eventBus.localVideoUnmutedNatively.subscribe(this.unpauseAudioTracks),this.eventBus.localAudioUnmutedNatively.subscribe(this.unpauseAudioTracks)}setListener(e){this.listener=e}get outputDevice(){return this.deviceManager.outputDevice}getVolume(){return this.volume}setVolume(e){return c(this,null,function*(){if(!(e>=0&&e<=100))throw Error("Please pass a valid number between 0-100");this.volume=e,yield this.store.updateAudioOutputVolume(e)})}unblockAutoplay(){return c(this,null,function*(){this.autoPausedTracks.size>0&&(yield this.unpauseAudioTracks()),yield ne.resumeContext()})}init(e){if(this.state.initialized||this.audioSink)return;this.state.initialized=!0;let t=document.createElement("div");t.id=`HMS-SDK-audio-sink-${(0,Bn.v4)()}`,(e&&document.getElementById(e)||document.body).append(t),this.audioSink=t,d.d(this.TAG,"audio sink created",this.audioSink)}cleanup(){var e;(e=this.audioSink)==null||e.remove(),this.audioSink=void 0,this.eventBus.audioTrackAdded.unsubscribe(this.handleTrackAdd),this.eventBus.audioTrackRemoved.unsubscribe(this.handleTrackRemove),this.eventBus.audioTrackUpdate.unsubscribe(this.handleTrackUpdate),this.eventBus.deviceChange.unsubscribe(this.handleAudioDeviceChange),this.eventBus.localVideoUnmutedNatively.unsubscribe(this.unpauseAudioTracks),this.eventBus.localAudioUnmutedNatively.unsubscribe(this.unpauseAudioTracks),this.autoPausedTracks=new Set,this.state=m({},Un)}playAudioFor(e){return c(this,null,function*(){let t=e.getAudioElement();if(!t){d.w(this.TAG,"No audio element found on track",e.trackId);return}try{yield t.play(),this.state.autoplayFailed=!1,this.autoPausedTracks.delete(e),d.d(this.TAG,"Played track",`${e}`)}catch(i){this.autoPausedTracks.add(e),d.w(this.TAG,"Failed to play track",`${e}`,i);let r=i;if(!this.state.autoplayFailed&&r.name==="NotAllowedError"){this.state.autoplayFailed=!0;let s=S.TracksErrors.AutoplayBlocked("AUTOPLAY","");s.addNativeError(r),this.eventBus.analytics.publish(y.autoplayError()),this.eventBus.autoplayError.publish(s)}}})}};var lr=class{constructor(e){this.eventBus=e;this.pluginUsage=new Map;this.pluginLastAddedAt=new Map;this.getPluginUsage=e=>{if(this.pluginUsage.has(e)||this.pluginUsage.set(e,0),this.pluginLastAddedAt.has(e)){let i=this.pluginLastAddedAt.get(e)||0,r=i?Date.now()-i:0;this.pluginUsage.set(e,(this.pluginUsage.get(e)||0)+r),this.pluginLastAddedAt.delete(e)}return this.pluginUsage.get(e)};this.updatePluginUsageData=e=>{var i;let t=((i=e.properties)==null?void 0:i.plugin_name)||"";switch(e.name){case"mediaPlugin.toggled.on":case"mediaPlugin.added":{let r=e.properties.added_at||Date.now();this.pluginLastAddedAt.set(t,r);break}case"mediaPlugin.toggled.off":case"mediaPlugin.failed":case"mediaPlugin.stats":{if(this.pluginLastAddedAt.has(t)){let r=e.properties.duration||(Date.now()-(this.pluginLastAddedAt.get(t)||0))/1e3;this.pluginUsage.set(t,(this.pluginUsage.get(t)||0)+Math.max(r,0)*1e3),this.pluginLastAddedAt.delete(t)}break}default:}};this.cleanup=()=>{this.pluginLastAddedAt.clear(),this.pluginUsage.clear()};this.eventBus.analytics.subscribe(t=>this.updatePluginUsageData(t))}};var ti=class{constructor(e,t){this.store=e;this.eventBus=t;this.audioInput=[];this.audioOutput=[];this.videoInput=[];this.hasWebcamPermission=!1;this.hasMicrophonePermission=!1;this.currentSelection={audioInput:void 0,videoInput:void 0,audioOutput:void 0};this.TAG="[Device Manager]:";this.initialized=!1;this.videoInputChanged=!1;this.audioInputChanged=!1;this.earpieceSelected=!1;this.timer=null;this.updateOutputDevice=(e,t)=>c(this,null,function*(){let i=this.audioOutput.find(r=>r.deviceId===e);if(!i){d.d(this.TAG,"updateOutputDevice - requested device not in the enumerated audioOutput list",`{
97
97
  deviceId: ${e};
98
98
  available: ${this.audioOutput.map(r=>r.deviceId).join(", ")};
99
99
  }`);return}try{yield this.store.updateAudioOutputDevice(i)}catch(r){d.w(this.TAG,"updateOutputDevice failed; keeping previous selection",i.label,r);return}return this.outputDevice=i,this.eventBus.analytics.publish(y.deviceChange({isUserSelection:t,selection:{audioOutput:i},devices:this.getDevices(),type:"audioOutput"})),ae.updateSelection("audioOutput",{deviceId:i.deviceId,groupId:i.groupId}),i});this.getCurrentSelection=()=>{var n,o;let e=this.store.getLocalPeer(),t=this.createIdentifier((n=e==null?void 0:e.audioTrack)==null?void 0:n.getMediaTrackSettings()),i=this.createIdentifier((o=e==null?void 0:e.videoTrack)==null?void 0:o.getMediaTrackSettings()),r=this.audioInput.find(l=>this.createIdentifier(l)===t),s=this.videoInput.find(l=>this.createIdentifier(l)===i);return{audioInput:r,videoInput:s,audioOutput:this.outputDevice}};this.computeChange=(e,t)=>e.length!==t.length?!0:t.some(i=>!e.includes(this.createIdentifier(i)));this.enumerateDevices=()=>c(this,null,function*(){try{let e=yield navigator.mediaDevices.enumerateDevices(),t=this.videoInput.map(this.createIdentifier),i=this.audioInput.map(this.createIdentifier);this.audioInput=[],this.audioOutput=[],this.videoInput=[],e.forEach(r=>{r.kind==="audioinput"&&r.label?(this.hasMicrophonePermission=!0,this.audioInput.push(r)):r.kind==="audiooutput"?this.audioOutput.push(r):r.kind==="videoinput"&&r.label&&(this.hasWebcamPermission=!0,this.videoInput.push(r))}),this.videoInputChanged=this.computeChange(t,this.videoInput),this.audioInputChanged=this.computeChange(i,this.audioInput),ae.setDevices({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput]}),this.logDevices("Enumerate Devices")}catch(e){d.e(this.TAG,"Failed enumerating devices",e)}});this.updateToActualDefaultDevice=()=>c(this,null,function*(){var r,s,n,o,l;let e=this.store.getLocalPeer();if(!((s=(r=this.store.getConfig())==null?void 0:r.settings)!=null&&s.videoDeviceId)&&(e!=null&&e.videoTrack)&&(yield e.videoTrack.setSettings({deviceId:(n=this.videoInput[0])==null?void 0:n.deviceId},!0)),!((l=(o=this.store.getConfig())==null?void 0:o.settings)==null?void 0:l.audioInputDeviceId)&&(e!=null&&e.audioTrack)){let u=()=>{var T;let h=this.audioInput.find(g=>!g.label.toLowerCase().includes("iphone"));return Ta()&&h?h==null?void 0:h.deviceId:(T=this.getNewAudioInputDevice())==null?void 0:T.deviceId};u()&&(yield e.audioTrack.setSettings({deviceId:u()},!0))}});this.handleDeviceChange=Di(()=>c(this,null,function*(){yield this.enumerateDevices(),this.logDevices("After Device Change");let e=this.store.getLocalPeer();yield this.setOutputDevice(!0),yield this.handleAudioInputDeviceChange(e==null?void 0:e.audioTrack),yield this.handleVideoInputDeviceChange(e==null?void 0:e.videoTrack),this.eventBus.analytics.publish(y.deviceChange({selection:this.getCurrentSelection(),type:"change",devices:this.getDevices()}))}),500).bind(this);this.handleAudioInputDeviceChange=e=>c(this,null,function*(){if(!e){d.d(this.TAG,"No Audio track on local peer");return}if(!this.audioInputChanged){d.d(this.TAG,"No Change in AudioInput Device");return}let t=this.getNewAudioInputDevice();if(!t||!t.deviceId){this.eventBus.analytics.publish(y.deviceChange({selection:{audioInput:t},error:S.TracksErrors.SelectedDeviceMissing("audio"),devices:this.getDevices(),type:"audioInput"})),d.e(this.TAG,"Audio device not found"),this.eventBus.deviceChange.publish({error:S.TracksErrors.SelectedDeviceMissing("audio"),selection:t,type:"audioInput",devices:this.getDevices()});return}let{settings:i}=e,r=new ee().codec(i.codec).maxBitrate(i.maxBitrate).deviceId(t.deviceId).audioMode(i.audioMode).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"audioInput"}),this.logDevices("Audio Device Change Success")}catch(s){d.e(this.TAG,"[Audio Device Change]",s),this.eventBus.analytics.publish(y.deviceChange({selection:{audioInput:t},devices:this.getDevices(),type:"audioInput",error:s})),this.eventBus.deviceChange.publish({error:s,selection:t,type:"audioInput",devices:this.getDevices()})}});this.handleVideoInputDeviceChange=e=>c(this,null,function*(){if(!e){d.d(this.TAG,"No video track on local peer");return}if(!this.videoInputChanged){d.d(this.TAG,"No Change in VideoInput Device");return}let t=this.videoInput[0];if(!t||!t.deviceId){this.eventBus.analytics.publish(y.deviceChange({selection:{videoInput:t},error:S.TracksErrors.SelectedDeviceMissing("video"),devices:this.getDevices(),type:"video"})),d.e(this.TAG,"Video device not found"),this.eventBus.deviceChange.publish({error:S.TracksErrors.SelectedDeviceMissing("video"),selection:t,type:"video",devices:this.getDevices()});return}let{settings:i}=e,r=new z().codec(i.codec).maxBitrate(i.maxBitrate).maxFramerate(i.maxFramerate).setWidth(i.width).setHeight(i.height).deviceId(t.deviceId).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"video"}),this.logDevices("Video Device Change Success")}catch(s){d.e(this.TAG,"[Video Device Change]",s),this.eventBus.analytics.publish(y.deviceChange({selection:{videoInput:t},devices:this.getDevices(),type:"video",error:s})),this.eventBus.deviceChange.publish({error:s,type:"video",selection:t,devices:this.getDevices()})}});this.startPollingForDevices=()=>c(this,null,function*(){let{earpiece:e}=this.categorizeAudioInputDevices();e&&(this.timer=setTimeout(()=>{c(this,null,function*(){yield this.enumerateDevices(),yield this.autoSelectAudioOutput(),this.startPollingForDevices()})},5e3))});this.autoSelectAudioOutput=e=>c(this,null,function*(){var u,p;let{bluetoothDevice:t,earpiece:i,speakerPhone:r,wired:s}=this.categorizeAudioInputDevices(),n=(u=this.store.getLocalPeer())==null?void 0:u.audioTrack;if(!n||!i)return;let o=this.getManuallySelectedAudioDevice(),l=(o==null?void 0:o.deviceId)||(t==null?void 0:t.deviceId)||(s==null?void 0:s.deviceId)||(r==null?void 0:r.deviceId);if(!(!e&&n.settings.deviceId===l&&this.earpieceSelected))try{(!this.earpieceSelected||e)&&((t==null?void 0:t.deviceId)===l?this.earpieceSelected=!0:(d.d(this.TAG,"selecting earpiece"),yield n.setSettings({deviceId:i==null?void 0:i.deviceId},!0),e&&(yield te(e)),this.earpieceSelected=!0)),yield n.setSettings({deviceId:l},!0);let h=(p=this.audioInput.find(T=>T.deviceId===l))==null?void 0:p.groupId;this.eventBus.deviceChange.publish({isUserSelection:!1,type:"audioInput",selection:{deviceId:l,groupId:h},devices:this.getDevices(),internal:!0})}catch(h){this.eventBus.error.publish(h)}});let i=({enabled:r,track:s})=>r&&s.source==="regular";this.eventBus.localVideoEnabled.waitFor(i).then(()=>{this.videoInput.length===0&&this.init(!0)}),this.eventBus.localAudioEnabled.waitFor(i).then(()=>{this.audioInput.length===0&&this.init(!0)}),this.eventBus.deviceChange.subscribe(({type:r,isUserSelection:s,selection:n})=>{if(s){let o=r==="video"?"videoInput":r,l=this[o].find(u=>this.createIdentifier(u)===this.createIdentifier(n));this.eventBus.analytics.publish(y.deviceChange({selection:{[o]:l},devices:this.getDevices(),type:r,isUserSelection:s}))}})}init(e=!1,t=!0){return c(this,null,function*(){this.initialized&&!e||(!this.initialized&&navigator.mediaDevices.addEventListener("devicechange",this.handleDeviceChange),this.initialized=!0,yield this.enumerateDevices(),e||(yield this.updateToActualDefaultDevice(),this.startPollingForDevices()),yield this.autoSelectAudioOutput(),this.logDevices("Init"),yield this.setOutputDevice(),this.eventBus.deviceChange.publish({devices:this.getDevices()}),t&&this.eventBus.analytics.publish(y.deviceChange({selection:this.getCurrentSelection(),type:"list",devices:this.getDevices()})))})}getDevices(){return{audioInput:this.audioInput,audioOutput:this.audioOutput,videoInput:this.videoInput}}cleanup(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.initialized=!1,this.earpieceSelected=!1,this.audioInput=[],this.audioOutput=[],this.videoInput=[],this.outputDevice=void 0,navigator.mediaDevices.removeEventListener("devicechange",this.handleDeviceChange)}createIdentifier(e){return e?`${e.deviceId}${e.groupId}`:""}getNewAudioInputDevice(){var i,r;let e=this.getManuallySelectedAudioDevice();if(e)return e;(r=(i=this.store.getLocalPeer())==null?void 0:i.audioTrack)==null||r.resetManuallySelectedDeviceId();let t=this.audioInput.find(s=>s.deviceId==="default");return t?this.audioInput.find(n=>n.deviceId!=="default"&&t.label.includes(n.label)):this.audioInput[0]}setOutputDevice(e=!1){return c(this,null,function*(){let t=this.getNewAudioInputDevice(),i=this.createIdentifier(this.outputDevice);this.outputDevice=this.getAudioOutputDeviceMatchingInput(t),this.outputDevice||(this.outputDevice=this.audioOutput.find(r=>this.createIdentifier(r)===i),this.outputDevice||(this.outputDevice=this.audioOutput.find(r=>r.deviceId==="default")||this.audioOutput[0])),yield this.store.updateAudioOutputDevice(this.outputDevice),e&&i!==this.createIdentifier(this.outputDevice)&&(this.eventBus.analytics.publish(y.deviceChange({selection:{audioOutput:this.outputDevice},devices:this.getDevices(),type:"audioOutput"})),this.eventBus.deviceChange.publish({selection:this.outputDevice,type:"audioOutput",devices:this.getDevices()}))})}getManuallySelectedAudioDevice(){let e=this.store.getLocalPeer(),t=e==null?void 0:e.audioTrack;return this.audioInput.find(i=>i.deviceId===(t==null?void 0:t.getManuallySelectedDeviceId()))}categorizeAudioInputDevices(){let e=null,t=null,i=null,r=null;for(let s of this.audioInput){let n=Ci(s.label);n==="SPEAKERPHONE"?t=s:n==="WIRED"?i=s:n==="BLUETOOTH"?e=s:n==="EARPIECE"&&(r=s)}return{bluetoothDevice:e,speakerPhone:t,wired:i,earpiece:r}}getAudioOutputDeviceMatchingInput(e){var n,o;let t=((o=(n=this.store.getConfig())==null?void 0:n.settings)==null?void 0:o.speakerAutoSelectionBlacklist)||[];if(t==="all"||!e)return;let i=e.label.toLowerCase()||"";if(t.some(l=>i.includes(l.toLowerCase())))return;let r=this.audioOutput.find(l=>e.deviceId!=="default"&&l.label===e.label);if(r)return r;let s=this.audioOutput.find(l=>l.groupId===e.groupId&&l.deviceId!=="default");if(s)return s}logDevices(e=""){d.d(this.TAG,e,JSON.stringify({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput],selected:this.getCurrentSelection()},null,4))}};var ur=class{constructor(e,t){this.deviceManager=e;this.audioSinkManager=t}getVolume(){return this.audioSinkManager.getVolume()}setVolume(e){return e>=0&&e<=100?this.audioSinkManager.setVolume(e):Promise.reject(Error("Please pass a valid number between 0-100"))}getDevice(){return this.deviceManager.outputDevice}setDevice(e){return c(this,null,function*(){d.d("[AudioOutputManager]","setDevice requested",e);let t=yield this.deviceManager.updateOutputDevice(e,!0);if(d.d("[AudioOutputManager]","setDevice result",`{
100
100
  requested: ${e};
101
101
  applied: ${t==null?void 0:t.label};
102
102
  appliedId: ${t==null?void 0:t.deviceId};
103
- }`),t)try{yield this.unblockAutoplay()}catch(i){d.w("[AudioOutputManager]","unblockAutoplay failed after setDevice",i)}return t})}unblockAutoplay(){return c(this,null,function*(){yield this.audioSinkManager.unblockAutoplay(),yield ne.resumeContext()})}};var ii=class{static handleError(e){if(e.status===404)throw S.APIErrors.EndpointUnreachable("FEEDBACK",e.statusText);if(e.status>=400)throw S.APIErrors.ServerErrors(e.status,"FEEDBACK",e==null?void 0:e.statusText)}static sendFeedback(s){return c(this,arguments,function*({token:e,eventEndpoint:t="https://event.100ms.live",info:i,feedback:r}){d.d(this.TAG,`sendFeedback: feedbackEndpoint=${t} peerId=${i.peer.peer_id} session=${i.peer.session_id} `);let n=new URL("v2/client/feedback",t),o=M(m({},i),{payload:r});try{let l=yield fetch(n,{headers:{Authorization:`Bearer ${e}`},body:JSON.stringify(o),method:"POST"});try{this.handleError(l);return}catch(u){throw d.e(this.TAG,"error",u.message,l.status),u instanceof k?u:S.APIErrors.ServerErrors(l.status,"FEEDBACK",u.message)}}catch(l){let u=l;throw["Failed to fetch","NetworkError","ECONNRESET"].some(p=>u.message.includes(p))?S.APIErrors.EndpointUnreachable("FEEDBACK",u.message):u}})}};ii.TAG="[FeedbackService]";var Vn=require("eventemitter2");var U=class{constructor(e,t){this.eventName=e;this.eventEmitter=t;this.publish=e=>{this.eventEmitter.emit(this.eventName,e)};this.subscribe=e=>{this.eventEmitter.on(this.eventName,e)};this.subscribeOnce=e=>{this.eventEmitter.once(this.eventName,e)};this.unsubscribe=e=>{this.eventEmitter.off(this.eventName,e)};this.waitFor=e=>this.eventEmitter.waitFor(this.eventName,{filter:e});this.removeAllListeners=()=>{this.eventEmitter.removeAllListeners(this.eventName)}}};var Tt=class{constructor(){this.eventEmitter=new Vn.EventEmitter2;this.analytics=new U(G.ANALYTICS,this.eventEmitter);this.deviceChange=new U(G.DEVICE_CHANGE,this.eventEmitter);this.localAudioEnabled=new U(G.LOCAL_AUDIO_ENABLED,this.eventEmitter);this.localVideoEnabled=new U(G.LOCAL_VIDEO_ENABLED,this.eventEmitter);this.localVideoUnmutedNatively=new U(G.LOCAL_VIDEO_UNMUTED_NATIVELY,this.eventEmitter);this.localAudioUnmutedNatively=new U(G.LOCAL_AUDIO_UNMUTED_NATIVELY,this.eventEmitter);this.statsUpdate=new U(G.STATS_UPDATE,this.eventEmitter);this.trackDegraded=new U(G.TRACK_DEGRADED,this.eventEmitter);this.trackRestored=new U(G.TRACK_RESTORED,this.eventEmitter);this.trackAudioLevelUpdate=new U(G.TRACK_AUDIO_LEVEL_UPDATE,this.eventEmitter);this.audioPluginFailed=new U(G.AUDIO_PLUGIN_FAILED,this.eventEmitter);this.localAudioSilence=new U(G.LOCAL_AUDIO_SILENCE,this.eventEmitter);this.trackInterruption=new U(G.TRACK_INTERRUPTION,this.eventEmitter);this.policyChange=new U(G.POLICY_CHANGE,this.eventEmitter);this.localRoleUpdate=new U(G.LOCAL_ROLE_UPDATE,this.eventEmitter);this.audioTrackUpdate=new U(G.AUDIO_TRACK_UPDATE,this.eventEmitter);this.audioTrackAdded=new U(G.AUDIO_TRACK_ADDED,this.eventEmitter);this.audioTrackRemoved=new U(G.AUDIO_TRACK_REMOVED,this.eventEmitter);this.autoplayError=new U(G.AUTOPLAY_ERROR,this.eventEmitter);this.leave=new U(G.LEAVE,this.eventEmitter);this.error=new U(G.ERROR,this.eventEmitter)}};var pr=class{constructor(e,t,i){this.store=e;this.listener=t;this.audioListener=i}handleActiveSpeakers(e){var s,n,o;let t=e["speaker-list"],i=t.map(l=>({audioLevel:l.level,peer:this.store.getPeerById(l.peer_id),track:this.store.getTrackById(l.track_id)}));(s=this.audioListener)==null||s.onAudioLevelUpdate(i),this.store.updateSpeakers(i);let r=t[0];if(r){let l=this.store.getPeerById(r.peer_id);(n=this.listener)==null||n.onPeerUpdate(4,l)}else(o=this.listener)==null||o.onPeerUpdate(5,null)}};var hr=class{constructor(e){this.listener=e;this.TAG="[BroadcastManager]"}handleNotification(e,t){e==="on-broadcast"&&this.handleBroadcast(t)}handleBroadcast(e){var t,i;d.d(this.TAG,`Received Message from sender=${(t=e==null?void 0:e.peer)==null?void 0:t.peer_id}: ${e}`),(i=this.listener)==null||i.onMessageReceived(e)}};var mr=class{constructor(e,t){this.store=e;this.listener=t}handleQualityUpdate(e){var r;let i=e.peers.map(s=>{let n=this.store.getPeerById(s.peer_id);return n&&n.updateNetworkQuality(s.downlink_score),{peerID:s.peer_id,downlinkQuality:s.downlink_score}});(r=this.listener)==null||r.onConnectionQualityUpdate(i)}};var ft=class{constructor(e,t,i){this.store=e;this.eventBus=t;this.listener=i;this.TAG="[TrackManager]";this.tracksToProcess=new Map;this.handleTrackAdd=e=>{d.d(this.TAG,"ONTRACKADD",`${e}`),this.tracksToProcess.set(e.trackId,e),this.processPendingTracks()};this.handleTrackRemovedPermanently=e=>{d.d(this.TAG,"ONTRACKREMOVE permanently",e),Object.keys(e.tracks).forEach(i=>{var o;let r=this.store.getTrackState(i);if(!r)return;let s=this.store.getTrackById(i);if(!s){d.d(this.TAG,"Track not found in store");return}s.type==="audio"&&this.eventBus.audioTrackRemoved.publish(s),this.store.removeTrack(s);let n=this.store.getPeerById(r.peerId);n&&(this.removePeerTracks(n,s),(o=this.listener)==null||o.onTrackUpdate(1,s,n))})};this.handleTrackLayerUpdate=e=>{for(let t in e.tracks){let i=e.tracks[t],r=this.store.getTrackById(t);!r||!this.store.getPeerByTrackId(t)||r instanceof x&&this.setLayer(r,i)}};this.handleTrackUpdate=(e,t=!0)=>{var s,n;let i=this.store.getPeerById(e.peer.peer_id),r=e.peer;if(!i&&!r){d.d(this.TAG,"Track Update ignored - Peer not added to store");return}i||(i=be(r,this.store),this.store.addPeer(i));for(let o in e.tracks){let l=Object.assign({},(s=this.store.getTrackState(o))==null?void 0:s.trackInfo),u=e.tracks[o],p=this.store.getTrackById(o);if(this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:m(m({},l),u)}),!p||this.tracksToProcess.has(o))this.processTrackInfo(u,e.peer.peer_id,t),this.processPendingTracks();else{this.logIfRejected(p.setEnabled(!u.mute),p);let h=this.processTrackUpdate(p,l,u);h&&((n=this.listener)==null||n.onTrackUpdate(h,p,i))}}};this.processTrackInfo=(e,t,i)=>{};this.processPendingTracks=()=>{new Map(this.tracksToProcess).forEach(t=>{var s;let i=this.store.getTrackState(t.trackId);if(!i){d.d(this.TAG,"TrackState not added to store",`peerId - ${t.peerId}`,`trackId -${t.trackId}`);return}let r=this.store.getPeerById(i.peerId);if(!r){d.d(this.TAG,"Peer not added to store, peerId",i.peerId);return}t.source=i.trackInfo.source,t.peerId=r.peerId,t.logIdentifier=r.name,this.logIfRejected(t.setEnabled(!i.trackInfo.mute),t),this.addAudioTrack(r,t),this.addVideoTrack(r,t),t.type==="audio"?this.eventBus.audioTrackAdded.publish({track:t,peer:r}):(s=this.listener)==null||s.onTrackUpdate(0,t,r),this.tracksToProcess.delete(t.trackId)})}}logIfRejected(e,t){e.catch(i=>d.e(this.TAG,"could not apply mute state",`${t}`,i))}handleTrackMetadataAdd(e){d.d(this.TAG,"TRACK_METADATA_ADD",JSON.stringify(e,null,2));for(let t in e.tracks){let i=e.tracks[t];this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:i})}this.processPendingTracks()}handleTrackRemove(e,t=!0){var s;d.d(this.TAG,"ONTRACKREMOVE",`${e}`);let i=this.store.getTrackState(e.trackId);if(!i)return;if(!this.store.hasTrack(e)){d.d(this.TAG,"Track not found in store");return}if(t){this.store.removeTrack(e);let n=this.store.getPeerById(i.peerId);if(!n)return;this.removePeerTracks(n,e),(s=this.listener)==null||s.onTrackUpdate(1,e,n),e.type==="audio"&&this.eventBus.audioTrackRemoved.publish(e)}}setLayer(e,t){var s,n;let i=this.store.getPeerByTrackId(e.trackId);if(!i)return;e.setLayerFromServer(t)?(s=this.listener)==null||s.onTrackUpdate(5,e,i):(n=this.listener)==null||n.onTrackUpdate(6,e,i)}removePeerTracks(e,t){let i=e.auxiliaryTracks.indexOf(t);i>-1?(e.auxiliaryTracks.splice(i,1),d.d(this.TAG,"auxiliary track removed",`${t}`)):t.type==="audio"&&e.audioTrack===t?(e.audioTrack=void 0,d.d(this.TAG,"audio track removed",`${t}`)):t.type==="video"&&e.videoTrack===t&&(e.videoTrack=void 0,d.d(this.TAG,"video track removed",`${t}`))}addAudioTrack(e,t){var i;t.type==="audio"&&(t.source==="regular"&&(!e.audioTrack||((i=e.audioTrack)==null?void 0:i.trackId)===t.trackId)?e.audioTrack=t:e.auxiliaryTracks.push(t),this.store.addTrack(t),d.d(this.TAG,"audio track added",`${t}`))}addVideoTrack(e,t){if(t.type!=="video")return;let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);if(i.setSimulcastDefinitons(r),this.addAsPrimaryVideoTrack(e,i))e.videoTrack?e.videoTrack.replaceTrack(i):e.videoTrack=i,this.store.addTrack(e.videoTrack);else{let s=e.auxiliaryTracks.findIndex(n=>n.trackId===i.trackId);s===-1?(e.auxiliaryTracks.push(i),this.store.addTrack(i)):(e.auxiliaryTracks[s].replaceTrack(i),this.store.addTrack(e.auxiliaryTracks[s]))}d.d(this.TAG,"video track added",`${t}`)}addAsPrimaryVideoTrack(e,t){var i;return t.source==="regular"&&(!e.videoTrack||((i=e.videoTrack)==null?void 0:i.trackId)===t.trackId)}processTrackUpdate(e,t,i){let r;return t.mute!==i.mute?(r=i.mute?2:3,e.type==="audio"&&this.eventBus.audioTrackUpdate.publish({track:e,enabled:!i.mute})):t.description!==i.description&&(r=4),r}};var Sr=class extends ft{constructor(t,i,r,s){super(t,i,s);this.transport=r;this.TAG="[OnDemandTrackManager]";this.processTrackInfo=(t,i,r=!0)=>{var u,p;if(t.type!=="video")return;let s=this.store.getPeerById(i);if(!s||!this.isPeerRoleSubscribed(i)){d.d(this.TAG,`no peer in store for peerId: ${i}`);return}let n=new Re(new MediaStream,this.transport.getSubscribeConnection()),o=Te.getEmptyVideoTrack();o.enabled=!t.mute;let l=new x(n,o,t.source,(u=this.store.getRoom())==null?void 0:u.disableNoneLayerRequest);l.setTrackId(t.track_id),l.peerId=s.peerId,l.logIdentifier=s.name,this.addVideoTrack(s,l),r&&((p=this.listener)==null||p.onTrackUpdate(0,s.videoTrack,s))}}handleTrackMetadataAdd(t){super.handleTrackMetadataAdd(t);for(let i in t.tracks)t.tracks[i].type==="video"&&this.processTrackInfo(t.tracks[i],t.peer.peer_id)}handleTrackRemove(t){let i=t.type==="video"&&t.source==="regular";super.handleTrackRemove(t,!i),i&&this.processTrackInfo({track_id:t.trackId,mute:!t.enabled,type:t.type,source:t.source,stream_id:t.stream.id},t.peerId,!1)}addAsPrimaryVideoTrack(t,i){return i.source!=="regular"?!1:!t.videoTrack||t.videoTrack.trackId===i.trackId?!0:t.videoTrack.enabled&&ve(t.videoTrack.nativeTrack)}isPeerRoleSubscribed(t){var s,n,o,l;if(!t)return!0;let i=this.store.getLocalPeer(),r=this.store.getPeerById(t);return r&&((l=(n=(s=i==null?void 0:i.role)==null?void 0:s.subscribeParams)==null?void 0:n.subscribeToRoles)==null?void 0:l.includes((o=r.role)==null?void 0:o.name))}};var gr=class{constructor(e,t,i,r){this.store=e;this.peerManager=t;this.trackManager=i;this.listener=r;this.TAG="[PeerListManager]";this.handleInitialPeerList=e=>{let t=Object.values(e.peers);this.peerManager.handlePeerList(t)};this.handleReconnectPeerList=e=>{this.handleRepeatedPeerList(e.peers)};this.handlePreviewRoomState=e=>{if(!this.store.hasRoleDetailsArrived())return;let t=e.peers;if(t==null){e.peer_count===0&&this.handleRepeatedPeerList({});return}Object.keys(t).forEach(i=>{t[i].tracks={},t[i].is_from_room_state=!0}),this.handleRepeatedPeerList(t)};this.handleRepeatedPeerList=e=>{let t=this.store.getRemotePeers(),i=Object.values(e),r=t.filter(n=>!e[n.peerId]);r.length>0&&d.d(this.TAG,`${r}`),r.forEach(n=>{var l;let o={peer_id:n.peerId,role:((l=n.role)==null?void 0:l.name)||"",info:{name:n.name,data:n.metadata||"",user_id:n.customerUserId||"",type:n.type},tracks:{},groups:[],realtime:n.realtime};this.peerManager.handlePeerLeave(o)});let s=[];i.forEach(n=>{let o=this.store.getPeerById(n.peer_id),l=Object.values(n.tracks);o&&(this.store.getPeerTracks(o.peerId).forEach(p=>{var h;n.tracks[p.trackId]||(this.removePeerTrack(o,p.trackId),(h=this.listener)==null||h.onTrackUpdate(1,p,o))}),l.forEach(p=>{this.store.getTrackById(p.track_id)||this.store.setTrackState({peerId:o.peerId,trackInfo:p})}),this.trackManager.handleTrackUpdate({peer:n,tracks:n.tracks},!1),this.peerManager.handlePeerUpdate(n)),s.push(n)}),s.length>0&&this.peerManager.handlePeerList(s)}}handleNotification(e,t,i){if(e==="peer-list"){let r=t;i?(d.d(this.TAG,"RECONNECT_PEER_LIST event",JSON.stringify(r,null,2)),this.handleReconnectPeerList(r)):(d.d(this.TAG,"PEER_LIST event",JSON.stringify(r,null,2)),this.handleInitialPeerList(r))}else if(e==="room-state"){let r=t;this.handlePreviewRoomState(r)}}removePeerTrack(e,t){var i,r;if(d.d(this.TAG,`removing track - ${t} from ${e}`),((i=e.audioTrack)==null?void 0:i.trackId)===t)e.audioTrack=void 0;else if(((r=e.videoTrack)==null?void 0:r.trackId)===t)e.videoTrack=void 0;else{let s=e.auxiliaryTracks.findIndex(n=>n.trackId===t);s>=0&&e.auxiliaryTracks.splice(s,1)}}};var L=a=>a?new Date(a):void 0;var Tr=class{constructor(e,t,i){this.store=e;this.trackManager=t;this.listener=i;this.TAG="[PeerManager]";this.handlePeerList=e=>{var r,s;if(e.length===0){(r=this.listener)==null||r.onPeerUpdate(9,[]);return}let t=[],i=new Set(e.map(n=>n.peer_id));this.store.getRemotePeers().forEach(({peerId:n,fromRoomState:o})=>{!i.has(n)&&o&&this.store.removePeer(n)});for(let n of e)t.push(this.makePeer(n));(s=this.listener)==null||s.onPeerUpdate(9,t),this.trackManager.processPendingTracks()};this.handlePeerJoin=e=>{var i;let t=this.makePeer(e);(i=this.listener)==null||i.onPeerUpdate(0,t),this.trackManager.processPendingTracks()};this.handlePeerLeave=e=>{var i,r,s,n;let t=this.store.getPeerById(e.peer_id);this.store.removePeer(e.peer_id),d.d(this.TAG,"PEER_LEAVE",e.peer_id,`remainingPeers=${this.store.getPeers().length}`),t&&(t.audioTrack&&((i=this.listener)==null||i.onTrackUpdate(1,t.audioTrack,t)),t.videoTrack&&((r=this.listener)==null||r.onTrackUpdate(1,t.videoTrack,t)),(s=t.auxiliaryTracks)==null||s.forEach(o=>{var l;(l=this.listener)==null||l.onTrackUpdate(1,o,t)}),(n=this.listener)==null||n.onPeerUpdate(1,t))}}handleNotification(e,t){switch(e){case"on-peer-join":{let i=t;this.handlePeerJoin(i);break}case"on-peer-leave":{let i=t;this.handlePeerLeave(i);break}case"on-peer-update":this.handlePeerUpdate(t);break;default:break}}handlePeerUpdate(e){var s,n,o,l,u;let t=this.store.getPeerById(e.peer_id);if(!t&&e.realtime){t=this.makePeer(e),(s=this.listener)==null||s.onPeerUpdate(t.isHandRaised?12:14,t);return}if(t&&!t.isLocal&&!e.realtime){this.store.removePeer(t.peerId),(n=this.listener)==null||n.onPeerUpdate(13,t);return}if(!t){d.d(this.TAG,`peer ${e.peer_id} not found`);return}if(t.role&&t.role.name!==e.role){let p=this.store.getPolicyForRole(e.role);t.updateRole(p),this.updateSimulcastLayersForPeer(t),(o=this.listener)==null||o.onPeerUpdate(8,t)}let i=t.isHandRaised;t.updateGroups(e.groups);let r=(l=e.groups)==null?void 0:l.includes(He);i!==r&&((u=this.listener)==null||u.onPeerUpdate(12,t)),this.handlePeerInfoUpdate(m({peer:t},e.info))}handlePeerInfoUpdate({peer:e,name:t,data:i}){var r,s;e&&(t&&e.name!==t&&(e.updateName(t),(r=this.listener)==null||r.onPeerUpdate(10,e)),i&&e.metadata!==i&&(e.updateMetadata(i),(s=this.listener)==null||s.onPeerUpdate(11,e)))}makePeer(e){let t=this.store.getPeerById(e.peer_id);t||(t=be(e,this.store),t.realtime=e.realtime,t.joinedAt=L(e.joined_at),t.fromRoomState=!!e.is_from_room_state,this.store.addPeer(t),d.d(this.TAG,"adding to the peerList",`${t}`));for(let i in e.tracks){let r=e.tracks[i];this.store.setTrackState({peerId:e.peer_id,trackInfo:r}),r.type==="video"&&this.trackManager.processTrackInfo(r,e.peer_id,!1)}return t}updateSimulcastLayersForPeer(e){this.store.getPeerTracks(e.peerId).forEach(t=>{if(t.type==="video"&&["regular","screen"].includes(t.source)){let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);i.setSimulcastDefinitons(r)}})}};var fr=class{constructor(e,t){this.store=e;this.eventBus=t}handlePolicyChange(e){let t=this.store.getLocalPeer();if(t&&!t.role){let r=e.known_roles[e.name];t.updateRole(r)}this.store.setKnownRoles(e);let i=this.store.getRoom();i?i.templateId=e.template_id:d.w("[PolicyChangeManager]","on policy change - room not present"),this.updateLocalPeerRole(e),this.eventBus.policyChange.publish(e)}updateLocalPeerRole(e){var i;let t=this.store.getLocalPeer();if(t!=null&&t.role&&t.role.name!==e.name){let r=this.store.getPolicyForRole(e.name),s=t.role;t.updateRole(r),r.name===((i=t.asRole)==null?void 0:i.name)&&delete t.asRole,this.eventBus.localRoleUpdate.publish({oldRole:s,newRole:r})}}};var Ks=(f=>(f.FLAG_SERVER_SUB_DEGRADATION="subscribeDegradation",f.FLAG_SERVER_SIMULCAST="simulcast",f.FLAG_NON_WEBRTC_DISABLE_OFFER="nonWebRTCDisableOffer",f.FLAG_PUBLISH_STATS="publishStats",f.FLAG_SUBSCRIBE_STATS="subscribeStats",f.FLAG_ON_DEMAND_TRACKS="onDemandTracks",f.FLAG_DISABLE_VIDEO_TRACK_AUTO_UNSUBSCRIBE="disableVideoTrackAutoUnsubscribe",f.FLAG_WHITEBOARD_ENABLED="whiteboardEnabled",f.FLAG_EFFECTS_SDK_ENABLED="effectsSDKEnabled",f.FLAG_VB_ENABLED="vb",f.FLAG_HIPAA_ENABLED="hipaa",f.FLAG_NOISE_CANCELLATION="noiseCancellation",f.FLAG_SCALE_SCREENSHARE_BASED_ON_PIXELS="scaleScreenshareBasedOnPixels",f.FLAG_DISABLE_NONE_LAYER_REQUEST="disableNoneLayerRequest",f))(Ks||{});var ri=(a,e,t)=>{let i=t==="qa"?Da:wa,r=new URL(i);return r.searchParams.set("endpoint",`https://${e}`),r.searchParams.set("token",a),r.toString()};var vr=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.TAG="[HMSWhiteboardInteractivityCenter]"}get isEnabled(){return this.transport.isFlagEnabled("whiteboardEnabled")}open(e){return c(this,null,function*(){var n;if(!this.isEnabled)return d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e==null?void 0:e.id),i=t==null?void 0:t.id;if(t||(i=(yield this.transport.signal.createWhiteboard(this.getCreateOptionsWithDefaults(e))).id),!i)throw new Error(`Whiteboard ID: ${i} not found`);let r=yield this.transport.signal.getWhiteboard({id:i}),s=M(m({},t),{title:e==null?void 0:e.title,attributes:e==null?void 0:e.attributes,id:r.id,url:ri(r.token,r.addr,this.store.getEnv()),token:r.token,addr:r.addr,owner:r.owner,permissions:r.permissions||[],open:!0});this.store.setWhiteboard(s),(n=this.listener)==null||n.onWhiteboardUpdate(s)})}close(e){return c(this,null,function*(){var r;if(!this.isEnabled)return d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e);if(!t)throw new Error(`Whiteboard ID: ${e} not found`);let i={id:t.id,title:t.title,open:!1};this.store.setWhiteboard(i),(r=this.listener)==null||r.onWhiteboardUpdate(i)})}setListener(e){this.listener=e}handleLocalRoleUpdate(){return c(this,null,function*(){var t,i,r;let e=this.store.getWhiteboards();for(let s of e.values())if(s.url){let n=yield this.transport.signal.getWhiteboard({id:s.id}),o=this.store.getLocalPeer(),u=(o==null?void 0:o.customerUserId)===n.owner?(i=(t=o.role)==null?void 0:t.permissions.whiteboard)==null?void 0:i.includes("admin"):n.permissions.length>0,p=M(m({},s),{id:n.id,url:ri(n.token,n.addr,this.store.getEnv()),token:n.token,addr:n.addr,owner:n.owner,permissions:n.permissions,open:u});this.store.setWhiteboard(p),(r=this.listener)==null||r.onWhiteboardUpdate(p)}})}getCreateOptionsWithDefaults(e){var n;let t=Object.values(this.store.getKnownRoles()),i=[],r=[],s=[];return t.forEach(o=>{var l,u,p;(l=o.permissions.whiteboard)!=null&&l.includes("read")&&i.push(o.name),(u=o.permissions.whiteboard)!=null&&u.includes("write")&&r.push(o.name),(p=o.permissions.whiteboard)!=null&&p.includes("admin")&&s.push(o.name)}),{title:(e==null?void 0:e.title)||`${(n=this.store.getRoom())==null?void 0:n.id} Whiteboard`,reader:(e==null?void 0:e.reader)||i,writer:(e==null?void 0:e.writer)||r,admin:(e==null?void 0:e.admin)||s}}};var si=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.whiteboard=new vr(e,t,i)}setListener(e){this.listener=e,this.whiteboard.setListener(e)}createPoll(e){return c(this,null,function*(){var n,o;let t={customerID:"userid",peerID:"peerid",userName:"username"},{poll_id:i}=yield this.transport.signal.setPollInfo(M(m({},e),{mode:e.mode?t[e.mode]:void 0,poll_id:e.id,vote:e.rolesThatCanVote,responses:e.rolesThatCanViewResponses}));e.id||(e.id=i),Array.isArray(e.questions)&&(yield this.addQuestionsToPoll(e.id,e.questions));let r=yield this.transport.signal.getPollQuestions({poll_id:e.id,index:0,count:50}),s=Mr(M(m({},e),{poll_id:e.id,state:"created",created_by:(n=this.store.getLocalPeer())==null?void 0:n.peerId}));s.questions=r.questions.map(({question:l,options:u,answer:p})=>M(m({},l),{options:u,answer:p})),(o=this.listener)==null||o.onPollsUpdate(0,[s])})}startPoll(e){return c(this,null,function*(){typeof e=="string"?yield this.transport.signal.startPoll({poll_id:e}):(yield this.createPoll(e),yield this.transport.signal.startPoll({poll_id:e.id}))})}addQuestionsToPoll(e,t){return c(this,null,function*(){t.length>0&&(yield this.transport.signal.setPollQuestions({poll_id:e,questions:t.map((i,r)=>this.createQuestionSetParams(i,r))}))})}stopPoll(e){return c(this,null,function*(){yield this.transport.signal.stopPoll({poll_id:e})})}addResponsesToPoll(e,t){return c(this,null,function*(){let i=this.store.getPoll(e);if(!i)throw new Error("Invalid poll ID - Poll not found");let r=t.map(s=>{var o,l;let n=this.getQuestionInPoll(i,s.questionIndex);return n.type==="single-choice"?(s.option=s.option||((o=s.options)==null?void 0:o[0])||-1,delete s.text,delete s.options):n.type==="multiple-choice"?((l=s.options)==null||l.sort(),delete s.text,delete s.option):(delete s.option,delete s.options),s.skipped&&(delete s.option,delete s.options,delete s.text),m({duration:0,type:n.type,question:s.questionIndex},s)});yield this.transport.signal.setPollResponses({poll_id:e,responses:r})})}fetchLeaderboard(e,t,i){return c(this,null,function*(){var p,h;let r=this.store.getPoll(e);if(!r)throw new Error("Invalid poll ID - Poll not found");let s=(h=(p=this.store.getLocalPeer())==null?void 0:p.role)==null?void 0:h.permissions,n=!!(s!=null&&s.pollRead||s!=null&&s.pollWrite);if(r.anonymous||r.state!=="stopped"||!n)return{entries:[],hasNext:!1};let o=yield this.transport.signal.fetchPollLeaderboard({poll_id:r.id,count:i,offset:t}),l={avgScore:o.avg_score,avgTime:o.avg_time,votedUsers:o.voted_users,totalUsers:o.total_users,correctUsers:o.correct_users};return{entries:o.questions.map(T=>({position:T.position,totalResponses:T.total_responses,correctResponses:T.correct_responses,duration:T.duration,peer:T.peer,score:T.score})),hasNext:!o.last,summary:l}})}getPollResponses(e,t){return c(this,null,function*(){var s,n;let i=yield this.transport.signal.getPollResponses({poll_id:e.id,index:0,count:50,self:t}),r=JSON.parse(JSON.stringify(e));(s=i.responses)==null||s.forEach(({response:o,peer:l,final:u})=>{var h,T;let p=(h=e==null?void 0:e.questions)==null?void 0:h.find(g=>g.index===o.question);if(p){let g={id:o.response_id,questionIndex:o.question,option:o.option,options:o.options,text:o.text,responseFinal:u,peer:{peerid:l.peerid,userHash:l.hash,userid:l.userid,username:l.username},skipped:o.skipped,type:o.type,update:o.update},f=p.responses&&!t?[...p.responses]:[];(T=r.questions)!=null&&T[o.question-1]&&(r.questions[o.question-1].responses=[...f,g])}}),this.store.setPoll(r),(n=this.listener)==null||n.onPollsUpdate(4,[r])})}getPolls(){return c(this,null,function*(){var s,n,o;let e=yield this.transport.signal.getPollsList({count:50,state:"started"}),t=[],i=(n=(s=this.store.getLocalPeer())==null?void 0:s.role)==null?void 0:n.permissions.pollWrite,r=[...e.polls];if(i){let l=yield this.transport.signal.getPollsList({count:50,state:"created"}),u=yield this.transport.signal.getPollsList({count:50,state:"stopped"});r=[...l.polls,...r,...u.polls]}for(let l of r){let u=yield this.transport.signal.getPollQuestions({poll_id:l.poll_id,index:0,count:50}),p=Mr(l),h=this.store.getPoll(l.poll_id);p.questions=u.questions.map(({question:T,options:g,answer:f},P)=>{var v,A;return M(m({},T),{options:g,answer:f,responses:(A=(v=h==null?void 0:h.questions)==null?void 0:v[P])==null?void 0:A.responses})}),t.push(p),this.store.setPoll(p)}return(o=this.listener)==null||o.onPollsUpdate(3,t),t})}createQuestionSetParams(e,t){var n,o;if(e.index){let l=(n=e.options)==null?void 0:n.map((u,p)=>M(m({},u),{index:p+1}));return{question:M(m({},e),{index:t+1}),options:l,answer:e.answer}}let i=M(m({},e),{index:t+1}),r,s=e.answer||{hidden:!1};return Array.isArray(e.options)&&["single-choice","multiple-choice"].includes(e.type)?(r=(o=e.options)==null?void 0:o.map((l,u)=>({index:u+1,text:l.text,weight:l.weight})),e.type==="single-choice"?s.option=e.options.findIndex(l=>l.isCorrectAnswer)+1||void 0:s.options=e.options.map((l,u)=>l.isCorrectAnswer?u+1:void 0).filter(l=>!!l)):(s==null||delete s.options,s==null||delete s.option),{question:i,options:r,answer:s}}getQuestionInPoll(e,t){var r;let i=(r=e==null?void 0:e.questions)==null?void 0:r.find(s=>s.index===t);if(!i)throw new Error("Invalid question index - Question not found in poll");return i}},Mr=a=>{let e={userid:"customerID",peerid:"peerID",username:"userName"};return{id:a.poll_id,title:a.title,startedBy:a.started_by,createdBy:a.created_by,anonymous:a.anonymous,type:a.type,duration:a.duration,locked:a.locked,mode:a.mode?e[a.mode]:void 0,visibility:a.visibility,rolesThatCanVote:a.vote||[],rolesThatCanViewResponses:a.responses||[],state:a.state,stoppedBy:a.stopped_by,startedAt:L(a.started_at),stoppedAt:L(a.stopped_at),createdAt:L(a.created_at)}};var yr=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){switch(e){case"on-poll-start":{this.handlePollStart(t);break}case"on-poll-stop":{this.handlePollStop(t);break}case"on-poll-stats":this.handlePollStats(t);break;default:break}}handlePollStart(e){return c(this,null,function*(){var i,r;let t=[];for(let s of e.polls){let n=this.store.getPoll(s.poll_id);if(n&&n.state==="started"){(i=this.listener)==null||i.onPollsUpdate(1,[n]);return}let o=yield this.transport.signal.getPollQuestions({poll_id:s.poll_id,index:0,count:50}),l=Mr(s);l.questions=o.questions.map(({question:u,options:p,answer:h})=>M(m({},u),{options:p,answer:h})),yield this.updatePollResponses(l,!0),t.push(l),this.store.setPoll(l)}(r=this.listener)==null||r.onPollsUpdate(1,t)})}handlePollStop(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let s=this.store.getPoll(r.poll_id);if(s){s.state="stopped",s.stoppedAt=L(r.stopped_at),s.stoppedBy=r.stopped_by;let n=yield this.transport.signal.getPollResult({poll_id:r.poll_id});this.updatePollResult(s,n),t.push(s)}}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(2,t))})}handlePollStats(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let s=this.store.getPoll(r.poll_id);if(!s)return;this.updatePollResult(s,r),t.push(s)}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(4,t))})}updatePollResult(e,t){var i;e.result=m({},e.result),e.result.totalUsers=t.user_count,e.result.maxUsers=t.max_user,e.result.totalResponses=t.total_response,(i=t.questions)==null||i.forEach(r=>{var n,o;let s=(n=e.questions)==null?void 0:n.find(l=>l.index===r.question);s&&(s.result=m({},s.result),s.result.correctResponses=r.correct,s.result.skippedCount=r.skipped,s.result.totalResponses=r.total,(o=r.options)==null||o.forEach((l,u)=>{var h;let p=(h=s.options)==null?void 0:h[u];p&&p.voteCount!==l&&(p.voteCount=l)}))})}updatePollResponses(e,t){return c(this,null,function*(){var r;(r=(yield this.transport.signal.getPollResponses({poll_id:e.id,index:0,count:50,self:t})).responses)==null||r.forEach(({response:s,peer:n,final:o})=>{var p;let l=(p=e==null?void 0:e.questions)==null?void 0:p.find(h=>h.index===s.question);if(!l)return;let u={id:s.response_id,questionIndex:s.question,option:s.option,options:s.options,text:s.text,responseFinal:o,peer:{peerid:n.peerid,userHash:n.hash,userid:n.userid,username:n.username},skipped:s.skipped,type:s.type,update:s.update};Array.isArray(l.responses)&&l.responses.length>0?l.responses.find(({id:h})=>h===u.id)||l.responses.push(u):l.responses=[u]})})}};var kr=class{constructor(e,t){this.store=e;this.listener=t}handleNotification(e,t){switch(e){case"on-role-change-request":this.handleRoleChangeRequest(t);break;case"on-track-update-request":this.handleTrackUpdateRequest(t);break;case"on-change-track-mute-state-request":this.handleChangeTrackStateRequest(t);break;default:return}}handleRoleChangeRequest(e){var i;let t={requestedBy:e.requested_by?this.store.getPeerById(e.requested_by):void 0,role:this.store.getPolicyForRole(e.role),token:e.token};(i=this.listener)==null||i.onRoleChangeRequest(t)}handleTrackUpdateRequest(e){let{requested_by:t,track_id:i,mute:r}=e,s=t?this.store.getPeerById(t):void 0,n=this.store.getLocalPeerTracks().find(l=>l.publishedTrackId===i);if(!n)return;let o=()=>{var l;(l=this.listener)==null||l.onChangeTrackStateRequest({requestedBy:s,track:n,enabled:!r})};if(r){if(n.enabled===!r)return;n.setEnabled(!r).then(o)}else o()}handleChangeTrackStateRequest(e){var u;let{type:t,source:i,value:r,requested_by:s}=e,n=s?this.store.getPeerById(s):void 0,o=!r,l=this.getTracksToBeUpdated({type:t,source:i,enabled:o});if(l.length!==0)if(o)(u=this.listener)==null||u.onChangeMultiTrackStateRequest({requestedBy:n,tracks:l,type:t,source:i,enabled:!0});else{let p=[];for(let h of l)p.push(h.setEnabled(!1));Promise.all(p).then(()=>{var h;(h=this.listener)==null||h.onChangeMultiTrackStateRequest({requestedBy:n,tracks:l,enabled:!1})})}}getTracksToBeUpdated({type:e,source:t,enabled:i}){let s=this.store.getLocalPeerTracks();return e&&(s=s.filter(n=>n.type===e)),t&&(s=s.filter(n=>n.source===t)),s.filter(n=>n.enabled!==i)}};var Er=class{constructor(e,t){this.store=e;this.listener=t;this.TAG="[RoomUpdateManager]"}handleNotification(e,t){switch(e){case"peer-list":this.onRoomState(t.room);break;case"on-rtmp-update":this.updateRTMPStatus(t);break;case"on-record-update":this.updateRecordingStatus(t);break;case"room-state":this.handlePreviewRoomState(t);break;case"room-info":this.handleRoomInfo(t);break;case"session-info":this.handleSessionInfo(t);break;case"on-hls-update":this.updateHLSStatus(t);break;case"on-transcription-update":this.handleTranscriptionStatus([t]);break;default:break}}handleRoomInfo(e){let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.description=e.description,t.large_room_optimization=e.large_room_optimization,t.max_size=e.max_size,t.name=e.name}handleSessionInfo(e){var i;let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.sessionId=e.session_id,t.peerCount!==e.peer_count&&(t.peerCount=e.peer_count,(i=this.listener)==null||i.onRoomUpdate("ROOM_PEER_COUNT_UPDATED",t))}handlePreviewRoomState(e){let{room:t}=e;this.onRoomState(t)}onRoomState(e){var u,p,h,T;let{recording:t,streaming:i,transcriptions:r,session_id:s,started_at:n,name:o}=e,l=this.store.getRoom();if(!l){d.w(this.TAG,"on room state - room not present");return}l.name=o,l.rtmp.running=this.isStreamingRunning((u=i==null?void 0:i.rtmp)==null?void 0:u.state),l.rtmp.startedAt=L((p=i==null?void 0:i.rtmp)==null?void 0:p.started_at),l.rtmp.state=(h=i==null?void 0:i.rtmp)==null?void 0:h.state,l.recording.server=this.getPeerListSFURecording(t),l.recording.browser=this.getPeerListBrowserRecording(t),l.recording.hls=this.getPeerListHLSRecording(t),l.hls=this.convertHls(i==null?void 0:i.hls),l.transcriptions=this.addTranscriptionDetail(r),l.sessionId=s,l.startedAt=L(n),(T=this.listener)==null||T.onRoomUpdate("RECORDING_STATE_UPDATED",l)}addTranscriptionDetail(e){return e?e.map(t=>({state:t.state,mode:t.mode,initialised_at:L(t.initialised_at),started_at:L(t.started_at),stopped_at:L(t.stopped_at),updated_at:L(t.updated_at),error:this.toSdkError(t==null?void 0:t.error),translation:t.translation})):[]}isRecordingRunning(e){return e?!["none","paused","stopped","failed"].includes(e):!1}isStreamingRunning(e){return e?!["none","stopped","failed"].includes(e):!1}initHLS(e){let t=this.store.getRoom(),i={running:!0,variants:[]};return t?(e!=null&&e.variants&&e.variants.forEach((r,s)=>{var n,o,l;r.state!=="initialised"?i.variants.push({meetingURL:r==null?void 0:r.meetingURL,url:r==null?void 0:r.url,metadata:r==null?void 0:r.metadata,playlist_type:r==null?void 0:r.playlist_type,startedAt:L((n=e==null?void 0:e.variants)==null?void 0:n[s].started_at),initialisedAt:L((o=e==null?void 0:e.variants)==null?void 0:o[s].initialised_at),state:r.state,stream_type:r==null?void 0:r.stream_type}):i.variants.push({initialisedAt:L((l=e==null?void 0:e.variants)==null?void 0:l[s].initialised_at),url:""})}),i):(d.w(this.TAG,"on hls - room not present"),i)}updateHLSStatus(e){var r;let t=this.store.getRoom(),i=e.variants&&e.variants.length>0?e.variants.some(s=>this.isStreamingRunning(s.state)):!1;if(!t){d.w(this.TAG,"on hls - room not present");return}e.enabled=i,t.hls=this.convertHls(e),(r=this.listener)==null||r.onRoomUpdate("HLS_STREAMING_STATE_UPDATED",t)}handleTranscriptionStatus(e){var i;let t=this.store.getRoom();if(!t){d.w(this.TAG,"on transcription - room not present");return}t.transcriptions=this.addTranscriptionDetail(e)||[],(i=this.listener)==null||i.onRoomUpdate("TRANSCRIPTION_STATE_UPDATED",t)}convertHls(e){var r;if(e!=null&&e.variants&&e.variants.length>0?e.variants.some(s=>s.state==="initialised"):!1)return this.initHLS(e);let i={running:!!(e!=null&&e.enabled),variants:[],error:this.toSdkError(e==null?void 0:e.error)};return(r=e==null?void 0:e.variants)==null||r.forEach(s=>{i.variants.push({meetingURL:s==null?void 0:s.meeting_url,url:s==null?void 0:s.url,metadata:s==null?void 0:s.metadata,playlist_type:s==null?void 0:s.playlist_type,startedAt:L(s==null?void 0:s.started_at),initialisedAt:L(s==null?void 0:s.initialised_at),state:s.state,stream_type:s==null?void 0:s.stream_type})}),i}getHLSRecording(e){var r,s;let t={running:!1},i=this.isRecordingRunning(e==null?void 0:e.state);return(i||(e==null?void 0:e.state)==="paused")&&(t={running:i,singleFilePerLayer:!!((r=e==null?void 0:e.hls_recording)!=null&&r.single_file_per_layer),hlsVod:!!((s=e==null?void 0:e.hls_recording)!=null&&s.hls_vod),startedAt:L(e==null?void 0:e.started_at),initialisedAt:L(e==null?void 0:e.initialised_at),state:e==null?void 0:e.state,error:this.toSdkError(e==null?void 0:e.error)}),t}getPeerListHLSRecording(e){var r,s;let t=e==null?void 0:e.hls;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),initialisedAt:L(t==null?void 0:t.initialised_at),state:t==null?void 0:t.state,singleFilePerLayer:(r=t==null?void 0:t.config)==null?void 0:r.single_file_per_layer,hlsVod:(s=t==null?void 0:t.config)==null?void 0:s.hls_vod}}getPeerListBrowserRecording(e){let t=e==null?void 0:e.browser;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}getPeerListSFURecording(e){let t=e==null?void 0:e.sfu;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}updateRecordingStatus(e){var s;let t=this.store.getRoom(),i=this.isRecordingRunning(e.state);if(!t){d.w(this.TAG,`set recording status running=${i} - room not present`);return}let r;e.type==="sfu"?(t.recording.server={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e.state},r="SERVER_RECORDING_STATE_UPDATED"):e.type==="HLS"?(t.recording.hls=this.getHLSRecording(e),r="RECORDING_STATE_UPDATED"):(t.recording.browser={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e==null?void 0:e.state},r="BROWSER_RECORDING_STATE_UPDATED"),(s=this.listener)==null||s.onRoomUpdate(r,t)}updateRTMPStatus(e){var r,s;let t=this.store.getRoom(),i=this.isStreamingRunning(e.state);if(!t){d.w(this.TAG,"on policy change - room not present");return}if(!i){t.rtmp={running:i,state:e.state,error:this.toSdkError(e.error)},(r=this.listener)==null||r.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t);return}t.rtmp={running:i,startedAt:i?L(e.started_at):void 0,state:e.state,error:this.toSdkError(e.error)},(s=this.listener)==null||s.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t)}toSdkError(e){if(!(e!=null&&e.code))return;let t=e.message||"error in streaming/recording",i=new k(e.code,"ServerErrors","NONE",t,t);return d.e(this.TAG,"error in streaming/recording",i),i}};var Pr=class{constructor(e,t){this.store=e;this.listener=t}handleNotification(e,t){e==="on-metadata-change"&&this.handleMetadataChange(t)}handleMetadataChange(e){var i;let t=e.values.map(r=>({key:r.key,value:r.data,updatedAt:L(r.updated_at),updatedBy:r.updated_by?this.store.getPeerById(r.updated_by):void 0}));(i=this.listener)==null||i.onSessionStoreUpdate(t)}};var br=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){e==="on-whiteboard-update"&&this.handleWhiteboardUpdate(t)}handleWhiteboardUpdate(e){return c(this,null,function*(){var o;let t=this.store.getLocalPeer(),i=this.store.getWhiteboard(e.id),r=e.owner===(t==null?void 0:t.peerId)||e.owner===(t==null?void 0:t.customerUserId),s=e.state==="open",n={id:e.id,title:e.title,attributes:e.attributes};if(n.open=r?i==null?void 0:i.open:s,n.owner=n.open?e.owner:void 0,n.open)if(r)n.url=i==null?void 0:i.url,n.token=i==null?void 0:i.token,n.addr=i==null?void 0:i.addr,n.permissions=i==null?void 0:i.permissions;else{let l=yield this.transport.signal.getWhiteboard({id:e.id});n.url=ri(l.token,l.addr,this.store.getEnv()),n.token=l.token,n.addr=l.addr,n.permissions=l.permissions,n.open=l.permissions.length>0}this.store.setWhiteboard(n),(o=this.listener)==null||o.onWhiteboardUpdate(n)})}};var Ir=class{constructor(e,t,i,r,s,n){this.store=e;this.transport=i;this.listener=r;this.audioListener=s;this.connectionQualityListener=n;this.TAG="[HMSNotificationManager]";this.hasConsistentRoomStateArrived=!1;this.ignoreNotification=e=>{if(e==="peer-list")this.hasConsistentRoomStateArrived=!0;else if(e==="room-state")return this.hasConsistentRoomStateArrived;return!1};this.handleTrackAdd=e=>{this.trackManager.handleTrackAdd(e)};this.handleTrackRemove=e=>{this.trackManager.handleTrackRemove(e)};this.updateLocalPeer=({name:e,metadata:t})=>{let i=this.store.getLocalPeer();this.peerManager.handlePeerInfoUpdate({peer:i,name:e,data:t})};let o=this.transport.isFlagEnabled("onDemandTracks");this.trackManager=o?new Sr(this.store,t,this.transport,this.listener):new ft(this.store,t,this.listener),this.peerManager=new Tr(this.store,this.trackManager,this.listener),this.peerListManager=new gr(this.store,this.peerManager,this.trackManager,this.listener),this.broadcastManager=new hr(this.listener),this.policyChangeManager=new fr(this.store,t),this.requestManager=new kr(this.store,this.listener),this.activeSpeakerManager=new pr(this.store,this.listener,this.audioListener),this.connectionQualityManager=new mr(this.store,this.connectionQualityListener),this.roomUpdateManager=new Er(this.store,this.listener),this.sessionMetadataManager=new Pr(this.store,this.listener),this.pollsManager=new yr(this.store,this.transport,this.listener),this.whiteboardManager=new br(this.store,this.transport,this.listener)}setListener(e){this.listener=e,this.trackManager.listener=e,this.peerManager.listener=e,this.peerListManager.listener=e,this.broadcastManager.listener=e,this.requestManager.listener=e,this.activeSpeakerManager.listener=e,this.roomUpdateManager.listener=e,this.sessionMetadataManager.listener=e,this.pollsManager.listener=e,this.whiteboardManager.listener=e}setAudioListener(e){this.audioListener=e,this.activeSpeakerManager.audioListener=e}setConnectionQualityListener(e){this.connectionQualityListener=e,this.connectionQualityManager.listener=e}handleNotification(e,t=!1){var s,n;let i=e.method,r=e.params;["active-speakers","sfu-stats","on-connection-quality-update",void 0].includes(i)||d.d(this.TAG,`Received notification - ${i}`,{notification:r}),i==="sfu-stats"&&(s=window.HMS)!=null&&s.ON_SFU_STATS&&typeof((n=window.HMS)==null?void 0:n.ON_SFU_STATS)=="function"&&window.HMS.ON_SFU_STATS(e.params),!this.ignoreNotification(i)&&(this.roomUpdateManager.handleNotification(i,r),this.peerManager.handleNotification(i,r),this.requestManager.handleNotification(i,r),this.peerListManager.handleNotification(i,r,t),this.broadcastManager.handleNotification(i,r),this.sessionMetadataManager.handleNotification(i,r),this.pollsManager.handleNotification(i,r),this.whiteboardManager.handleNotification(i,r),this.handleIsolatedMethods(i,r))}handleIsolatedMethods(e,t){switch(e){case"on-track-add":{this.trackManager.handleTrackMetadataAdd(t);break}case"on-track-update":{this.trackManager.handleTrackUpdate(t);break}case"on-track-remove":{if(!t.peer){d.d(this.TAG,`Ignoring sfu notification - ${e}`,{notification:t});return}this.trackManager.handleTrackRemovedPermanently(t);break}case"on-track-layer-update":{this.trackManager.handleTrackLayerUpdate(t);break}case"active-speakers":this.activeSpeakerManager.handleActiveSpeakers(t);break;case"on-connection-quality-update":this.connectionQualityManager.handleQualityUpdate(t);break;case"on-policy-change":this.policyChangeManager.handlePolicyChange(t);break;case"node-info":this.transport.setSFUNodeId(t.sfu_node_id);break;default:break}}};var Ar=class{constructor(e){this.transport=e;this.observedKeys=new Set}get(e){return c(this,null,function*(){let{data:t,updated_at:i}=yield this.transport.signal.getSessionMetadata(e);return{value:t,updatedAt:L(i)}})}set(e,t){return c(this,null,function*(){let{data:i,updated_at:r}=yield this.transport.signal.setSessionMetadata({key:e,data:t}),s=L(r);return{value:i,updatedAt:s}})}observe(e){return c(this,null,function*(){let t=new Set(this.observedKeys);if(e.forEach(i=>this.observedKeys.add(i)),this.observedKeys.size!==t.size)try{yield this.transport.signal.listenMetadataChange(Array.from(this.observedKeys))}catch(i){throw this.observedKeys=t,i}})}unobserve(e){return c(this,null,function*(){let t=new Set(this.observedKeys);if(this.observedKeys=new Set([...this.observedKeys].filter(i=>!e.includes(i))),this.observedKeys.size!==t.size)try{yield this.transport.signal.listenMetadataChange(Array.from(this.observedKeys))}catch(i){throw this.observedKeys=t,i}})}};var Rr=class{constructor(e,t,i="",r="",s="https://prod-init.100ms.live/init",n=!1,o){this.authToken=e;this.peerId=t;this.peerName=i;this.data=r;this.endpoint=s;this.autoSubscribeVideo=n;this.iceServers=o}};var Z=(s=>(s[s.ConnectFailed=0]="ConnectFailed",s[s.SignalDisconnect=1]="SignalDisconnect",s[s.JoinWSMessageFailed=2]="JoinWSMessageFailed",s[s.PublishIceConnectionFailed=3]="PublishIceConnectionFailed",s[s.SubscribeIceConnectionFailed=4]="SubscribeIceConnectionFailed",s))(Z||{}),Fn={0:[],1:[],2:[1],3:[1],4:[1]};var Hr=(o=>(o.Disconnected="Disconnected",o.Connecting="Connecting",o.Joined="Joined",o.Preview="Preview",o.Failed="Failed",o.Reconnecting="Reconnecting",o.Leaving="Leaving",o))(Hr||{});var Cr=class{constructor(e){this.promise=new Promise((t,i)=>{this.resolve=t,this.reject=i,e(t,i)})}};var Lr=class{constructor(e,t){this.onStateChange=e;this.sendEvent=t;this.TAG="[RetryScheduler]";this.inProgress=new Map;this.retryTaskIds=[]}schedule(o){return c(this,arguments,function*({category:e,error:t,task:i,originalState:r,maxRetryTime:s=6e4,changeState:n=!0}){yield this.scheduleTask({category:e,error:t,changeState:n,task:i,originalState:r,maxRetryTime:s,failedAt:Date.now()})})}reset(){this.retryTaskIds.forEach(e=>clearTimeout(e)),this.retryTaskIds=[],this.inProgress.clear()}isTaskInProgress(e){return!!this.inProgress.get(e)}scheduleTask(u){return c(this,arguments,function*({category:e,error:t,changeState:i,task:r,originalState:s,failedAt:n,maxRetryTime:o=6e4,failedRetryCount:l=0}){if(d.d(this.TAG,"schedule: ",{category:Z[e],error:t}),l===0){let v=this.inProgress.get(e);if(v){d.d(this.TAG,`schedule: Already a task for ${Z[e]} scheduled, waiting for its completion`),yield v.promise;return}let A=new Cr(($,ce)=>{});this.inProgress.set(e,A),this.sendEvent(t,e)}let p=!1,h=Fn[e];for(let v in h){let A=h[parseInt(v)];try{let $=this.inProgress.get(A);$&&(d.d(this.TAG,`schedule: Suspending retry task of ${Z[e]}, waiting for ${Z[A]} to recover`),yield $.promise,d.d(this.TAG,`schedule: Resuming retry task ${Z[e]} as it's dependency ${Z[A]} is recovered`))}catch($){d.d(this.TAG,`schedule: Stopping retry task of ${Z[e]} as it's dependency ${Z[A]} failed to recover`),p=!0;break}}let T=v=>{if(this.inProgress.delete(e),this.sendEvent(v,e),this.reset(),i)this.onStateChange("Failed",v);else throw v},g=Date.now()-n;if(g>=o||p)return t.description+=`. [${Z[e]}] Could not recover after ${g} milliseconds`,p&&(t.description+=` Could not recover all of it's required dependencies - [${h.map(v=>Z[v]).toString()}]`),t.isTerminal=!0,T(t);i&&this.onStateChange("Reconnecting",t);let f=this.getDelayForRetryCount(e);d.d(this.TAG,`schedule: [${Z[e]}] [failedRetryCount=${l}] Scheduling retry task in ${f}ms`);let P;try{P=yield this.setTimeoutPromise(r,f)}catch(v){P=!1;let A=v;if(A.isTerminal)return d.e(this.TAG,`[${Z[e]}] Un-caught terminal exception ${A.name} in retry-task`,v),T(A);d.w(this.TAG,`[${Z[e]}] Un-caught exception ${A.name} in retry-task, initiating retry`,v)}if(P){let v=this.inProgress.get(e);this.inProgress.delete(e),v==null||v.resolve(l),i&&this.inProgress.size===0&&this.onStateChange(s),d.d(this.TAG,`schedule: [${Z[e]}] [failedRetryCount=${l}] Recovered \u267B\uFE0F after ${g}ms`)}else yield this.scheduleTask({category:e,error:t,changeState:i,task:r,originalState:s,maxRetryTime:o,failedAt:n,failedRetryCount:l+1})})}getDelayForRetryCount(e){let t=e===2?Math.random()*2:Math.random(),i=0;return e===2?i=2+t:e===1&&(i=1),i*1e3}setTimeoutPromise(e,t){return c(this,null,function*(){return new Promise((i,r)=>{let s=window.setTimeout(()=>c(this,null,function*(){try{let n=yield e();n&&this.retryTaskIds.splice(this.retryTaskIds.indexOf(s),1),i(n)}catch(n){r(n)}}),t);this.retryTaskIds.push(s)})})}};var wr=class extends Ve{constructor(){super(100);this.localStorage=new Ee("hms-analytics");this.localStorage.clear(),this.initLocalStorageQueue()}enqueue(t){super.enqueue(t),this.localStorage.set(this.storage)}dequeue(){let t=super.dequeue();return this.localStorage.set(this.storage),t}initLocalStorageQueue(){var t;(t=this.localStorage.get())==null||t.forEach(i=>{let r=new C(i);super.enqueue(r)})}};var Dr=class{constructor(){this.TAG="[AnalyticsTransport]";this.eventCount=0;this.lastResetTime=Date.now();this.MAX_EVENTS_PER_MINUTE=200;this.RESET_INTERVAL_MS=6e4}checkRateLimit(){let e=Date.now();if(e-this.lastResetTime>=this.RESET_INTERVAL_MS&&(this.eventCount=0,this.lastResetTime=e),this.eventCount>=this.MAX_EVENTS_PER_MINUTE)throw new Error("Too many events being sent, please check the implementation.");this.eventCount++}sendEvent(e){try{this.checkRateLimit()}catch(t){throw d.w(this.TAG,"Rate limit exceeded",t),t}try{this.sendSingleEvent(e),this.flushFailedEvents()}catch(t){d.w(this.TAG,"sendEvent failed",t)}}flushFailedEvents(e){var t;try{for(d.d(this.TAG,"Flushing failed events",this.failedEvents);this.failedEvents.size()>0;){let i=this.failedEvents.dequeue();i&&(((t=i.metadata)==null?void 0:t.peer.peer_id)===e||!i.metadata.peer.peer_id?this.sendSingleEvent(i):Le.sendEvent(i))}}catch(i){d.w(this.TAG,"flushFailedEvents failed",i)}}sendSingleEvent(e){try{this.transportProvider.sendEvent(e),d.d(this.TAG,"Sent event",e.name,e)}catch(t){throw d.w(this.TAG,`${this.transportProvider.TAG}.sendEvent failed, adding to local storage events`,{event:e,error:t}),this.failedEvents.enqueue(e),t}}};var _r=class extends Dr{constructor(t){super();this.transportProvider=t;this.failedEvents=new wr}};var vt=class{constructor(e,t,i,r){this.store=e;this.eventBus=t;this.sampleWindowSize=i;this.pushInterval=r;this.shouldSendEvent=!1;this.sequenceNum=1;this.start()}start(){this.shouldSendEvent||(this.stop(),this.shouldSendEvent=!0,this.eventBus.statsUpdate.subscribe(this.handleStatsUpdate.bind(this)),this.startLoop().catch(e=>d.e("[StatsAnalytics]",e.message)))}stop(){this.shouldSendEvent&&this.sendEvent(),this.eventBus.statsUpdate.unsubscribe(this.handleStatsUpdate.bind(this)),this.shouldSendEvent=!1}startLoop(){return c(this,null,function*(){for(;this.shouldSendEvent;)yield te(this.pushInterval*1e3),this.sendEvent()})}sendEvent(){this.trackAnalytics.forEach(e=>{e.clearSamples()})}cleanTrackAnalyticsAndCreateSample(e){this.trackAnalytics.forEach(t=>{!this.store.hasTrack(t.track)&&!(t.samples.length>0)&&this.trackAnalytics.delete(t.track_id)}),e&&this.trackAnalytics.forEach(t=>{t.createSample()})}},Mt=class{constructor({track:e,ssrc:t,rid:i,kind:r,sampleWindowSize:s}){this.samples=[];this.tempStats=[];this.track=e,this.ssrc=t,this.rid=i,this.kind=r,this.track_id=this.track.trackId,this.source=this.track.source,this.sampleWindowSize=s}pushTempStat(e){this.tempStats.push(e)}createSample(){this.tempStats.length!==0&&(this.samples.push(this.collateSample()),this.prevLatestStat=this.getLatestStat(),this.tempStats.length=0)}clearSamples(){this.samples.length=0}getLatestStat(){return this.tempStats[this.tempStats.length-1]}getFirstStat(){return this.tempStats[0]}calculateSum(e){if(typeof this.getLatestStat()[e]=="number")return this.tempStats.reduce((i,r)=>i+(r[e]||0),0)}calculateAverage(e,t=!0){let i=this.calculateSum(e),r=i!==void 0?i/this.tempStats.length:void 0;return r!==void 0?t?Math.round(r):r:void 0}calculateDifferenceForSample(e){var r;let t=Number((r=this.prevLatestStat)==null?void 0:r[e])||0;return(Number(this.getLatestStat()[e])||0)-t}calculateDifferenceAverage(e,t=!0){let i=this.calculateDifferenceForSample(e)/this.tempStats.length;return t?Math.round(i):i}calculateInstancesOfHigh(e,t){if(typeof this.getLatestStat()[e]=="number")return this.tempStats.reduce((r,s)=>r+((s[e]||0)>t?1:0),0)}},Nr=(a,e)=>a&&e&&(a.frameWidth!==e.frameWidth||a.frameHeight!==e.frameHeight),Or=(a,e)=>a&&e&&a.enabled!==e.enabled,ai=a=>Object.entries(a).filter(([,e])=>e!==void 0).reduce((e,[t,i])=>(e[t]=i,e),{});var xr=class{constructor(){this.worstState=void 0;this.TAG="[CPUPressureMonitor]";this.stateRanking={nominal:0,fair:1,serious:2,critical:3};this.init()}init(){return c(this,null,function*(){if(!("PressureObserver"in window)){d.d(this.TAG,"PressureObserver API not available");return}try{this.observer=new PressureObserver(e=>{if(e.length>0){let t=e[e.length-1].state;this.updateWorstState(t)}}),yield this.observer.observe("cpu",{sampleInterval:1e4}),this.worstState="nominal",d.d(this.TAG,"CPU pressure monitoring started")}catch(e){d.e(this.TAG,"Failed to initialize CPU pressure monitoring",e)}})}updateWorstState(e){if(this.worstState===void 0){this.worstState=e;return}this.stateRanking[e]>this.stateRanking[this.worstState]&&(this.worstState=e,d.d(this.TAG,`New worst CPU state: ${this.worstState}`))}getWorstState(){return this.worstState}resetWorstState(){this.worstState!==void 0&&(this.worstState="nominal",d.d(this.TAG,"CPU worst state reset to nominal"))}stop(){if(this.observer)try{this.observer.disconnect(),d.d(this.TAG,"CPU pressure monitoring stopped")}catch(e){d.e(this.TAG,"Error stopping CPU pressure monitoring",e)}}};var ni=class extends vt{constructor(t,i,r,s){super(t,i,r,s);this.trackAnalytics=new Map;this.cpuPressureMonitor=new xr}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(n=>{n.track.type==="audio"?t.push(n.toAnalytics()):n.track.type==="video"&&i.push(n.toAnalytics())}),{audio:t,video:i,joined_at:(s=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:s.getTime(),sequence_num:this.sequenceNum++,max_window_sec:30}}sendEvent(){this.eventBus.analytics.publish(y.publishStats(this.toAnalytics())),super.sendEvent()}stop(){var t;super.stop(),(t=this.cpuPressureMonitor)==null||t.stop()}handleStatsUpdate(t){let i=!1,r=t.getLocalTrackStats();Object.keys(r).forEach(s=>{let n=r[s],o=this.store.getLocalPeerTracks().find(l=>l.getTrackIDBeingSent()===s);Object.keys(n).forEach(l=>{var g,f,P;let u=n[l];if(!o)return;let p=this.getTrackIdentifier(o.trackId,u),h=M(m({},u),{availableOutgoingBitrate:(f=(g=t.getLocalPeerStats())==null?void 0:g.publish)==null?void 0:f.availableOutgoingBitrate});if(p&&this.trackAnalytics.has(p))(P=this.trackAnalytics.get(p))==null||P.pushTempStat(h);else if(o){let v=new js({track:o,sampleWindowSize:this.sampleWindowSize,rid:u.rid,ssrc:u.ssrc.toString(),kind:u.kind,cpuPressureMonitor:this.cpuPressureMonitor});v.pushTempStat(h),this.trackAnalytics.set(this.getTrackIdentifier(o.trackId,u),v)}let T=this.trackAnalytics.get(p);T!=null&&T.shouldCreateSample()&&(i=!0)})}),this.cleanTrackAnalyticsAndCreateSample(i)}getTrackIdentifier(t,i){return i.rid?`${t}:${i.rid}`:t}},js=class extends Mt{constructor(t){super(t);this.samples=[];this.getQualityLimitation=t=>{let i=t.qualityLimitationDurations;return i&&{bandwidth_sec:i.bandwidth,cpu_sec:i.cpu,other_sec:i.other}};this.getSourceStats=t=>{if(!t.sourceStatsAvailable)return{};let i=t.sourceFrameHeight?{height_px:t.sourceFrameHeight,width_px:t.sourceFrameWidth}:void 0,r=this.calculateDifferenceForSample("sourceFrames"),s=this.calculateDifferenceForSample("framesEncoded"),n=r&&s?Math.max(0,r-s):void 0;return{source_resolution:i,source_avg_fps:this.calculateAverage("sourceFramesPerSecond"),source_total_frames:r,source_total_frames_dropped:n}};this.collateSample=()=>{var p,h,T,g,f,P;let t=this.getFirstStat(),i=this.getLatestStat(),r=i.frameHeight?{height_px:i.frameHeight,width_px:i.frameWidth}:void 0,s=this.calculateAverage("jitter",!1),n=this.calculateAverage("roundTripTime",!1),o=(p=this.cpuPressureMonitor)==null?void 0:p.getWorstState();(h=this.cpuPressureMonitor)==null||h.resetWorstState();let l=(g=(T=this.track).getMediaTrackSettings)==null?void 0:g.call(T),u=(P=(f=this.track).getPluginsMetrics)==null?void 0:P.call(f);return ai(m({timestamp:Date.now(),sample_start_ts:t.timestamp,sample_end_ts:i.timestamp,sample_duration_ms:i.timestamp-t.timestamp,avg_available_outgoing_bitrate_bps:this.calculateAverage("availableOutgoingBitrate"),avg_bitrate_bps:this.calculateAverage("bitrate"),avg_fps:this.calculateAverage("framesPerSecond"),total_packets_lost:i.packetsLost,total_packets_sent:i.packetsSent,total_packet_sent_delay_sec:parseFloat(this.calculateDifferenceForSample("totalPacketSendDelay").toFixed(4)),total_fir_count:this.calculateDifferenceForSample("firCount"),total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount"),avg_jitter_ms:s?Math.round(s*1e3):void 0,avg_round_trip_time_ms:n?Math.round(n*1e3):void 0,total_quality_limitation:this.getQualityLimitation(i),resolution:r,cpu_pressure_state:o,track_settings:l,effects_metrics:u&&Object.keys(u).length>0?u:void 0},this.getSourceStats(i)))};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===30||Or(i,r)||i.kind==="video"&&Nr(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples});this.cpuPressureMonitor=t.cpuPressureMonitor}};var oi=class extends vt{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(n=>{n.track.type==="audio"?t.push(n.toAnalytics()):n.track.type==="video"&&i.push(n.toAnalytics())}),{audio:t,video:i,joined_at:(s=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:s.getTime(),sequence_num:this.sequenceNum++,max_window_sec:10}}sendEvent(){this.eventBus.analytics.publish(y.subscribeStats(this.toAnalytics())),super.sendEvent()}handleStatsUpdate(t){let i=t.getAllRemoteTracksStats(),r=!1;Object.keys(i).forEach(s=>{var f,P;let n=this.store.getTrackById(s),o=i[s],l=(f=this.trackAnalytics.get(s))==null?void 0:f.getLatestStat(),p=((v,A)=>{let $=(A==null?void 0:A.jitterBufferDelay)||0,ce=(A==null?void 0:A.jitterBufferEmittedCount)||0,B=((v==null?void 0:v.jitterBufferDelay)||0)-$,de=((v==null?void 0:v.jitterBufferEmittedCount)||0)-ce;return de>0?B*1e3/de:(A==null?void 0:A.calculatedJitterBufferDelay)||0})(o,l),h=this.calculateAvSyncForStat(o,t),T=M(m({},o),{calculatedJitterBufferDelay:p,avSync:h});if(o.kind==="video"){let v=n.getPreferredLayerDefinition();T.expectedFrameHeight=v==null?void 0:v.resolution.height,T.expectedFrameWidth=v==null?void 0:v.resolution.width}if(this.trackAnalytics.has(s))(P=this.trackAnalytics.get(s))==null||P.pushTempStat(T);else if(n){let v=new Js({track:n,sampleWindowSize:this.sampleWindowSize,ssrc:o.ssrc.toString(),kind:o.kind});v.pushTempStat(T),this.trackAnalytics.set(s,v)}let g=this.trackAnalytics.get(s);g!=null&&g.shouldCreateSample()&&(r=!0)}),this.cleanTrackAnalyticsAndCreateSample(r)}calculateAvSyncForStat(t,i){if(!t.peerID||!t.estimatedPlayoutTimestamp||t.kind!=="video")return;let r=this.store.getPeerById(t.peerID),s=r==null?void 0:r.audioTrack,n=r==null?void 0:r.videoTrack;if(!(s&&n&&s.enabled&&n.enabled))return Ot;let l=i.getRemoteTrackStats(s.trackId);if(!l)return Ot;if(l.estimatedPlayoutTimestamp)return l.estimatedPlayoutTimestamp-t.estimatedPlayoutTimestamp}},Js=class extends Mt{constructor(){super(...arguments);this.samples=[];this.collateSample=()=>{let t=this.getLatestStat(),i=this.getFirstStat(),r={timestamp:Date.now(),sample_start_ts:i.timestamp,sample_end_ts:t.timestamp,sample_duration_ms:t.timestamp-i.timestamp,total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount"),avg_jitter_buffer_delay:this.calculateAverage("calculatedJitterBufferDelay",!1),avg_bitrate_bps:this.calculateAverage("bitrate")};if(t.kind==="video")return ai(M(m({},r),{avg_av_sync_ms:this.calculateAvgAvSyncForSample(),avg_frames_received_per_sec:this.calculateDifferenceAverage("framesReceived"),avg_frames_dropped_per_sec:this.calculateDifferenceAverage("framesDropped"),avg_frames_decoded_per_sec:this.calculateDifferenceAverage("framesDecoded"),frame_width:this.calculateAverage("frameWidth"),frame_height:this.calculateAverage("frameHeight"),expected_frame_width:this.calculateAverage("expectedFrameWidth"),expected_frame_height:this.calculateAverage("expectedFrameHeight"),pause_count:this.calculateDifferenceForSample("pauseCount"),pause_duration_seconds:this.calculateDifferenceForSample("totalPausesDuration"),freeze_count:this.calculateDifferenceForSample("freezeCount"),freeze_duration_seconds:this.calculateDifferenceForSample("totalFreezesDuration")}));{let s=(t.concealedSamples||0)-(t.silentConcealedSamples||0)-((i.concealedSamples||0)-(i.silentConcealedSamples||0));return ai(M(m({},r),{audio_level:this.calculateInstancesOfHigh("audioLevel",.05),audio_concealed_samples:s,audio_total_samples_received:this.calculateDifferenceForSample("totalSamplesReceived"),audio_concealment_events:this.calculateDifferenceForSample("concealmentEvents"),fec_packets_discarded:this.calculateDifferenceForSample("fecPacketsDiscarded"),fec_packets_received:this.calculateDifferenceForSample("fecPacketsReceived"),total_samples_duration:this.calculateDifferenceForSample("totalSamplesDuration"),total_packets_received:this.calculateDifferenceForSample("packetsReceived"),total_packets_lost:this.calculateDifferenceForSample("packetsLost")}))}};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===10||Or(i,r)||i.kind==="video"&&Nr(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}calculateAvgAvSyncForSample(){let i=this.tempStats.map(r=>r.avSync).filter(r=>r!==void 0&&r!==Ot);return i.length===0?Ot:i.reduce((r,s)=>r+s,0)/i.length}};var yt=(t=>(t[t.Publish=0]="Publish",t[t.Subscribe=1]="Subscribe",t))(yt||{});var ci=We(require("sdp-transform"));function Gn(a,e){var r;let t=ci.parse(a.sdp);if(!((r=t.origin)!=null&&r.username.startsWith("mozilla")))return a;let i=e?Array.from(e.values()):[];return t.media.forEach(s=>{var l,u,p;let n=(l=s.msid)==null?void 0:l.split(" ")[0],o=(u=i.find(h=>h.type===s.type&&h.stream_id===n))==null?void 0:u.track_id;o&&(s.msid=(p=s.msid)==null?void 0:p.replace(/\s(.+)/,` ${o}`))}),{type:a.type,sdp:ci.write(t)}}function $n(a,e){var s;if(!(a!=null&&a.sdp)||!e)return;let i=ci.parse(a.sdp).media.find(n=>W(n.mid)&&parseInt(n.mid)===parseInt(e));return(s=i==null?void 0:i.msid)==null?void 0:s.split(" ")[1]}function Wn(a){return a.sdp.includes("usedtx=1")?a:{type:a.type,sdp:a.sdp.replace("useinbandfec=1","useinbandfec=1;usedtx=1")}}var we="[HMSConnection]",Ze=class{constructor(e,t){this.candidates=new Array;this.role=e,this.signal=t}get iceConnectionState(){return this.nativeConnection.iceConnectionState}get connectionState(){return this.nativeConnection.connectionState}get action(){return this.role===0?"PUBLISH":"SUBSCRIBE"}setSfuNodeId(e){this.sfuNodeId=e}addTransceiver(e,t){return this.nativeConnection.addTransceiver(e,t)}createOffer(e,t){return c(this,null,function*(){try{let i=yield this.nativeConnection.createOffer(t);return d.d(we,`[role=${this.role}] createOffer offer=${JSON.stringify(i,null,1)}`),Wn(Gn(i,e))}catch(i){throw S.WebrtcErrors.CreateOfferFailed(this.action,i.message)}})}createAnswer(e=void 0){return c(this,null,function*(){try{let t=yield this.nativeConnection.createAnswer(e);return d.d(we,`[role=${this.role}] createAnswer answer=${JSON.stringify(t,null,1)}`),t}catch(t){throw S.WebrtcErrors.CreateAnswerFailed(this.action,t.message)}})}setLocalDescription(e){return c(this,null,function*(){try{d.d(we,`[role=${this.role}] setLocalDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setLocalDescription(e)}catch(t){throw S.WebrtcErrors.SetLocalDescriptionFailed(this.action,t.message)}})}setRemoteDescription(e){return c(this,null,function*(){try{d.d(we,`[role=${this.role}] setRemoteDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setRemoteDescription(e)}catch(t){throw S.WebrtcErrors.SetRemoteDescriptionFailed(this.action,t.message)}})}addIceCandidate(e){return c(this,null,function*(){if(this.nativeConnection.signalingState==="closed"){d.d(we,`[role=${this.role}] addIceCandidate signalling state closed`);return}d.d(we,`[role=${this.role}] addIceCandidate candidate=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.addIceCandidate(e)})}get remoteDescription(){return this.nativeConnection.remoteDescription}getSenders(){return this.nativeConnection.getSenders()}handleSelectedIceCandidatePairs(){try{(this.role===0?this.getSenders():this.getReceivers()).forEach(t=>{var r;let i=(r=t.track)==null?void 0:r.kind;if(t.transport){let s=t.transport.iceTransport,n=()=>{typeof s.getSelectedCandidatePair=="function"&&(this.selectedCandidatePair=s.getSelectedCandidatePair(),this.selectedCandidatePair&&(this.observer.onSelectedCandidatePairChange(this.selectedCandidatePair),d.d(we,`${yt[this.role]} connection`,`selected ${i||"unknown"} candidate pair`,JSON.stringify(this.selectedCandidatePair,null,2))))};typeof s.onselectedcandidatepairchange=="function"&&(s.onselectedcandidatepairchange=n),n()}})}catch(e){d.w(we,`Error in logging selected ice candidate pair for ${yt[this.role]} connection`,e)}}removeTrack(e){this.nativeConnection.signalingState!=="closed"&&this.nativeConnection.removeTrack(e)}setMaxBitrateAndFramerate(e,t){return c(this,null,function*(){let i=(t==null?void 0:t.maxBitrate)||e.settings.maxBitrate,r=e instanceof q&&e.settings.maxFramerate,s=this.getSenders().find(n=>{var o;return((o=n==null?void 0:n.track)==null?void 0:o.id)===e.getTrackIDBeingSent()});if(s){let n=s.getParameters();n.encodings.length===1&&(i&&(n.encodings[0].maxBitrate=i*1e3),r&&(n.encodings[0].maxFramerate=r)),yield s.setParameters(n)}else d.w(we,`no sender found to setMaxBitrate for track - ${e.trackId}, sentTrackId - ${e.getTrackIDBeingSent()}`)})}getStats(){return c(this,null,function*(){return yield this.nativeConnection.getStats()})}close(){this.nativeConnection.close()}getReceivers(){return this.nativeConnection.getReceivers()}};var di=class extends Ze{constructor(t,i,r){super(0,t);this.TAG="[HMSPublishConnection]";this.observer=r,this.nativeConnection=new RTCPeerConnection(i),this.channel=this.nativeConnection.createDataChannel(bi,{protocol:"SCTP"}),this.channel.onerror=s=>d.e(this.TAG,`publish data channel onerror ${s}`,s),this.nativeConnection.onicecandidate=({candidate:s})=>{s&&(this.observer.onIceCandidate(s),t.trickle(this.role,s))},this.nativeConnection.oniceconnectionstatechange=()=>{this.observer.onIceConnectionChange(this.nativeConnection.iceConnectionState)},this.nativeConnection.onconnectionstatechange=()=>{this.observer.onConnectionStateChange(this.nativeConnection.connectionState),this.nativeConnection.sctp&&(this.nativeConnection.sctp.transport.onstatechange=()=>{var s;this.observer.onDTLSTransportStateChange((s=this.nativeConnection.sctp)==null?void 0:s.transport.state)},this.nativeConnection.sctp.transport.onerror=s=>{var n;this.observer.onDTLSTransportError(new Error((n=s==null?void 0:s.error)==null?void 0:n.errorDetail)||"DTLS Transport failed")})}}close(){super.close(),this.channel.close()}initAfterJoin(){this.nativeConnection.onnegotiationneeded=()=>c(this,null,function*(){d.d(this.TAG,"onnegotiationneeded"),yield this.observer.onRenegotiationNeeded()})}};var Kn=We(require("eventemitter2")),jn=require("uuid");var li=class{constructor(e,t,i=""){this.TAG="[HMSDataChannel]";this.nativeChannel=e,this.observer=t,this.metadata=i,e.onmessage=r=>{this.observer.onMessage(r.data)}}get id(){return this.nativeChannel.id}get label(){return this.nativeChannel.label}get readyState(){return this.nativeChannel.readyState}send(e){d.d(this.TAG,`[${this.metadata}] Sending [size=${e.length}] message=${e}`),this.nativeChannel.send(e)}close(){this.nativeChannel.close()}};var qn=(a,e)=>`${a}:${e}`,ui=class extends Ze{constructor(t,i,r,s,n){super(1,t);this.isFlagEnabled=r;this.eventBus=n;this.TAG="[HMSSubscribeConnection]";this.remoteStreams=new Map;this.MAX_RETRIES=3;this.RESPONSE_TIMEOUT=1e4;this.UNPROVEN_CHANNEL_TIMEOUT=500;this.channelProven=!1;this.pendingMessageQueue=[];this.latestRequestPerState=new Map;this.closed=!1;this.pendingAborts=new Set;this.eventEmitter=new Kn.default({maxListeners:60});this.abortOnClose=t=>c(this,null,function*(){if(this.closed)throw t.catch(()=>{}),t.cancel("connection closed"),Error("Subscribe connection closed");let i,r=new Promise((s,n)=>{i=n});this.pendingAborts.add(i);try{return yield Promise.race([t,r])}finally{this.pendingAborts.delete(i),t.cancel("request settled")}});this.handlePendingApiMessages=()=>{this.eventEmitter.emit("open",!0),this.pendingMessageQueue.length>0&&(d.d(this.TAG,"Found pending message queue, sending messages"),this.pendingMessageQueue.forEach(t=>this.sendOverApiDataChannel(t)),this.pendingMessageQueue.length=0)};this.sendMessage=(t,i,r)=>c(this,null,function*(){let s=()=>this.latestRequestPerState.get(r)!==i,n=()=>(d.d(this.TAG,`Dropping ${i} - ${this.closed?"closed":"superseded"}`,t),{id:i,dropped:!0}),o,l,u=!1;for(let p=0;p<this.MAX_RETRIES;p++){o=void 0;let h=!1,T=!1;if(s())return n();try{if(yield this.waitForChannelOpen(),s())return n();this.apiChannel.send(t),h=!0;let f=!u;u=!0,T=f&&!this.channelProven,o=yield this.waitForResponse(i,f)}catch(f){if(l=f,d.w(this.TAG,`Attempt failed for ${i}`,{request:t,try:p+1,error:f}),this.closed)break;s()||this.publishRequestEvent(y.subscribeRequestRetry,r,{attempt:p,unproven:T,sent:h});continue}let g=o.error;if(g){if(g.code===404)return d.d(this.TAG,`Track not found ${i}`,{request:t,try:p+1,error:g}),o;if(d.d(this.TAG,`Failed sending ${i}`,{request:t,try:p+1,error:g}),!(Math.floor(g.code/100)===5||g.code===429)){if(s())return n();throw Error(`code=${g.code}, message=${g.message} - ${i} not retried`)}if(p<this.MAX_RETRIES-1){let P=(2+Math.random()*2)*1e3;yield Fe(P)}}else break}if(o!=null&&o.error){if(s())return n();throw Error(`code=${o.error.code}, message=${o.error.message} - ${i} after ${this.MAX_RETRIES} tries`)}if(o)return o;if(s()||this.closed)return n();throw this.publishRequestEvent(y.subscribeRequestUnanswered,r,{attempts:this.MAX_RETRIES}),Error(`No response from SFU for ${i} after ${this.MAX_RETRIES} tries - ${t}`,{cause:l})});this.waitForChannelOpen=()=>c(this,null,function*(){var t;((t=this.apiChannel)==null?void 0:t.readyState)!=="open"&&(yield this.abortOnClose(this.eventEmitter.waitFor("open",{timeout:this.RESPONSE_TIMEOUT})))});this.waitForResponse=(t,i)=>c(this,null,function*(){let r=i&&!this.channelProven,s=yield this.abortOnClose(this.eventEmitter.waitFor("message",{filter:o=>o.includes(t),timeout:r?this.UNPROVEN_CHANNEL_TIMEOUT:this.RESPONSE_TIMEOUT})),n=JSON.parse(s[0]);return d.d(this.TAG,`response for ${t} -`,JSON.stringify(n,null,2)),n});this.observer=s,this.nativeConnection=new RTCPeerConnection(i),this.initNativeConnectionCallbacks()}initNativeConnectionCallbacks(){this.nativeConnection.oniceconnectionstatechange=()=>{this.observer.onIceConnectionChange(this.nativeConnection.iceConnectionState)},this.nativeConnection.onconnectionstatechange=()=>{this.observer.onConnectionStateChange(this.nativeConnection.connectionState)},this.nativeConnection.ondatachannel=t=>{t.channel.label===bi&&(this.channelProven=!1,this.apiChannel=new li(t.channel,{onMessage:i=>{this.channelProven=!0,this.eventEmitter.emit("message",i),this.observer.onApiChannelMessage(i)}},`role=${this.role}`),t.channel.onopen=this.handlePendingApiMessages)},this.nativeConnection.onicecandidate=t=>{t.candidate!==null&&(this.observer.onIceCandidate(t.candidate),this.signal.trickle(this.role,t.candidate))},this.nativeConnection.ontrack=t=>{var p;let i=t.streams[0],r=i.id;if(!this.remoteStreams.has(r)){let h=new Re(i,this);this.remoteStreams.set(r,h)}i.addEventListener("removetrack",h=>{if(h.track.id!==t.track.id)return;let T=s.tracks.findIndex(g=>{var f;return g.nativeTrack.id===h.track.id&&t.transceiver.mid===((f=g.transceiver)==null?void 0:f.mid)});if(T>=0){let g=s.tracks[T];this.observer.onTrackRemove(g),s.tracks.splice(T,1),s.tracks.length===0&&this.remoteStreams.delete(r)}});let s=this.remoteStreams.get(r),n=t.track.kind==="audio",o=n?le:x,l=n?new o(s,t.track):new o(s,t.track,void 0,this.isFlagEnabled("disableNoneLayerRequest"));t.track.kind==="video"&&s.setVideoLayerLocally("none","addTrack","subscribeConnection"),l.transceiver=t.transceiver;let u=$n(this.remoteDescription,(p=t.transceiver)==null?void 0:p.mid);u&&l.setSdpTrackId(u),s.tracks.push(l),this.observer.onTrackAdd(l)}}cancelPendingRequest(t,i){this.latestRequestPerState.delete(qn(t,i))}sendOverApiDataChannel(t){this.apiChannel&&this.apiChannel.readyState==="open"?this.apiChannel.send(t):(d.w(this.TAG,`API Data channel not ${this.apiChannel?"open":"present"}, queueing`,t),this.pendingMessageQueue.push(t))}sendOverApiDataChannelWithResponse(t){return c(this,null,function*(){let i=(0,jn.v4)();if(t.method==="prefer-video-track-state"&&this.isFlagEnabled("disableVideoTrackAutoUnsubscribe")&&t.params.max_spatial_layer==="none")return d.d(this.TAG,"video auto unsubscribe is disabled, request is ignored"),{id:i,dropped:!0};let r=JSON.stringify(m({id:i,jsonrpc:"2.0"},t)),s=qn(t.method,t.params.track_id);this.latestRequestPerState.set(s,i);try{return yield this.sendMessage(r,i,s)}finally{this.latestRequestPerState.get(s)===i&&this.latestRequestPerState.delete(s)}})}close(){var t;this.closed=!0,super.close(),(t=this.apiChannel)==null||t.close(),this.pendingAborts.forEach(i=>i(Error("Subscribe connection closed"))),this.pendingAborts.clear()}publishRequestEvent(t,i,r){var n;let s=i.indexOf(":");(n=this.eventBus)==null||n.analytics.publish(t(M(m({},r),{method:i.slice(0,s),trackId:i.slice(s+1)})))}};var Qn=(a,e)=>!e||e.length===0?a:e.map(i=>({urls:i.urls,credentialType:"password",credential:i.password,username:i.userName}));var Br="[InitService]",pi=class{static handleError(e,t){switch(e.status){case 404:throw S.APIErrors.EndpointUnreachable("INIT",t.message||e.statusText);case 200:break;default:throw S.APIErrors.ServerErrors(t.code||e.status,"INIT",t.message||(e==null?void 0:e.statusText))}}static fetchInitConfig(o){return c(this,arguments,function*({token:e,peerId:t,userAgent:i,initEndpoint:r="https://prod-init.100ms.live",region:s="",iceServers:n}){d.d(Br,`fetchInitConfig: initEndpoint=${r} token=${e} peerId=${t} region=${s} `);let l=qd(r,t,i,s);try{let u=yield fetch(l,{headers:{Authorization:`Bearer ${e}`}});try{let p=yield u.clone().json();return this.handleError(u,p),d.d(Br,`config is ${JSON.stringify(p,null,2)}`),Kd(p,n)}catch(p){let h=yield u.text();throw d.e(Br,"json error",p.message,h),p instanceof k?p:S.APIErrors.ServerErrors(u.status,"INIT",p.message)}}catch(u){let p=u;throw["Failed to fetch","NetworkError","ECONNRESET"].some(h=>p.message.includes(h))?S.APIErrors.EndpointUnreachable("INIT",p.message):p}})}};function qd(a,e,t,i){try{let r=new URL("/init",a);return i&&i.trim().length>0&&r.searchParams.set("region",i.trim()),r.searchParams.set("peer_id",e),r.searchParams.set("user_agent_v2",t),r.toString()}catch(r){let s=r;throw d.e(Br,s.name,s.message),s}}function Kd(a,e){var t;return M(m({},a),{rtcConfiguration:M(m({},a.rtcConfiguration),{iceServers:Qn((t=a.rtcConfiguration)==null?void 0:t.ice_servers,e)})})}var Jn=require("uuid");var hi=class{constructor(e){this.TAG="[SIGNAL]: ";this.pongResponseTimes=new Ve(5);this.isJoinCompleted=!1;this.pendingTrickle=[];this.socket=null;this.callbacks=new Map;this._isConnected=!1;this.id=0;this.onCloseHandler=()=>{};this.resolvePingOnAnyResponse=()=>{this.callbacks.forEach((e,t)=>{var i;((i=e.metadata)==null?void 0:i.method)==="ping"&&(e.resolve({timestamp:Date.now()}),this.callbacks.delete(t))})};this.offlineListener=()=>{d.d(this.TAG,"Window network offline"),this.setIsConnected(!1,"Window network offline")};this.onlineListener=()=>{d.d(this.TAG,"Window network online"),this.observer.onNetworkOnline()};this.observer=e,window.addEventListener("offline",this.offlineListener),window.addEventListener("online",this.onlineListener),this.onMessageHandler=this.onMessageHandler.bind(this)}get isConnected(){return this._isConnected}setSfuNodeId(e){this.sfuNodeId=e}setIsConnected(e,t=""){d.d(this.TAG,`isConnected set id: ${this.id}, oldValue: ${this._isConnected}, newValue: ${e}`),this._isConnected!==e&&(this._isConnected&&!e?(this._isConnected=e,this.rejectPendingCalls(t),this.observer.onOffline(t)):!this._isConnected&&e&&(this._isConnected=e,this.observer.onOnline()))}getPongResponseTimes(){return this.pongResponseTimes.toList()}internalCall(e,t){return c(this,null,function*(){var s;let i=(0,Jn.v4)(),r={method:e,params:t,id:i,jsonrpc:"2.0"};(s=this.socket)==null||s.send(JSON.stringify(r));try{return yield new Promise((o,l)=>{this.callbacks.set(i,{resolve:o,reject:l,metadata:{method:e}})})}catch(n){if(n instanceof k)throw n;let o=n;throw S.WebsocketMethodErrors.ServerErrors(Number(o.code),Yr(e),o.message)}})}notify(e,t){var r,s;let i={method:e,params:t};((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN&&((s=this.socket)==null||s.send(JSON.stringify(i)))}open(e){return new Promise((t,i)=>{let r=!1;this.socket&&(this.socket.close(),this.socket.removeEventListener("close",this.onCloseHandler),this.socket.removeEventListener("message",this.onMessageHandler)),this.socket=new WebSocket(e);let s=()=>{d.e(this.TAG,"Error from websocket"),r=!0,i(S.WebSocketConnectionErrors.FailedToConnect("JOIN","Error opening websocket connection"))};this.onCloseHandler=o=>{d.w(`Websocket closed code=${o.code}`),r?this.setIsConnected(!1,`code: ${o.code}${o.code!==1e3?", unexpected websocket close":""}`):(r=!0,i(S.WebSocketConnectionErrors.AbnormalClose("JOIN",`Error opening websocket connection - websocket closed unexpectedly with code=${o.code}`)))},this.socket.addEventListener("error",s);let n=()=>{var o,l;r=!0,t(),this.setIsConnected(!0),this.id++,(o=this.socket)==null||o.removeEventListener("open",n),(l=this.socket)==null||l.removeEventListener("error",s),this.pingPongLoop(this.id)};this.socket.addEventListener("open",n),this.socket.addEventListener("close",this.onCloseHandler),this.socket.addEventListener("message",this.onMessageHandler)})}close(){return c(this,null,function*(){window.removeEventListener("offline",this.offlineListener),window.removeEventListener("online",this.onlineListener),this.socket?(this.socket.close(1e3,"Normal Close"),this.setIsConnected(!1,"code: 1000, normal websocket close"),this.socket.removeEventListener("close",this.onCloseHandler),this.socket.removeEventListener("message",this.onMessageHandler)):this.setIsConnected(!1,"websocket not connected yet")})}join(e,t,i,r,s,n,o){return c(this,null,function*(){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("JOIN","Failed to send join over WS connection");let l={name:e,disableVidAutoSub:i,data:t,offer:o,server_sub_degrade:r,simulcast:s,onDemandTracks:n},u=yield this.internalCall("join",l);return this.isJoinCompleted=!0,this.pendingTrickle.forEach(({target:p,candidate:h})=>this.trickle(p,h)),this.pendingTrickle.length=0,d.d(this.TAG,`join: response=${JSON.stringify(u,null,1)}`),u})}trickle(e,t){this.isJoinCompleted?this.notify("trickle",{target:e,candidate:t,sfu_node_id:this.sfuNodeId}):this.pendingTrickle.push({target:e,candidate:t})}offer(e,t){return c(this,null,function*(){return yield this.call("offer",{desc:e,tracks:Object.fromEntries(t),sfu_node_id:this.sfuNodeId})})}answer(e){this.notify("answer",{desc:e,sfu_node_id:this.sfuNodeId})}trackUpdate(e){this.notify("track-update",{tracks:Object.fromEntries(e)})}broadcast(e){return c(this,null,function*(){return yield this.call("broadcast",e)})}leave(e){this.notify("leave",{client_reason:e})}endRoom(e,t){return c(this,null,function*(){yield this.call("end-room",{lock:e,reason:t})})}sendEvent(e){if(!this.isConnected)throw Error(`${this.TAG} not connected. Could not send event ${e}`);this.notify("analytics",e.toSignalParams())}ping(e){let t=Date.now(),i=new Promise(s=>{setTimeout(()=>{s(Date.now()-t)},e+1)}),r=this.internalCall("ping",{timestamp:t}).then(()=>Date.now()-t).catch(()=>Date.now()-t);return Promise.race([i,r])}requestRoleChange(e){return c(this,null,function*(){yield this.call("role-change-request",e)})}requestBulkRoleChange(e){return c(this,null,function*(){yield this.call("role-change-request",e)})}acceptRoleChangeRequest(e){return c(this,null,function*(){yield this.call("role-change",e)})}requestTrackStateChange(e){return c(this,null,function*(){yield this.call("track-update-request",e)})}requestMultiTrackStateChange(e){return c(this,null,function*(){yield this.call("change-track-mute-state-request",e)})}removePeer(e){return c(this,null,function*(){yield this.call("peer-leave-request",e)})}startRTMPOrRecording(e){return c(this,null,function*(){yield this.call("rtmp-start",m({},e))})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.call("rtmp-stop",{})})}startHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-start",m({},e))})}stopHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-stop",m({},e))})}startTranscription(e){return c(this,null,function*(){yield this.call("transcription-start",m({},e))})}stopTranscription(e){return c(this,null,function*(){yield this.call("transcription-stop",m({},e))})}updateTranscriptionConfig(e){return c(this,null,function*(){yield this.call("transcription-config-update",m({},e))})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.call("hls-timed-metadata",m({},e))})}updatePeer(e){return c(this,null,function*(){yield this.call("peer-update",m({},e))})}getPeer(e){return c(this,null,function*(){return yield this.call("get-peer",m({},e))})}joinGroup(e){return c(this,null,function*(){return yield this.call("group-join",{name:e})})}leaveGroup(e){return c(this,null,function*(){return yield this.call("group-leave",{name:e})})}addToGroup(e,t){return c(this,null,function*(){yield this.call("group-add",{name:t,peer_id:e})})}removeFromGroup(e,t){return c(this,null,function*(){yield this.call("group-remove",{name:t,peer_id:e})})}peerIterNext(e){return c(this,null,function*(){return yield this.call("peer-iter-next",e)})}findPeers(e){return c(this,null,function*(){return yield this.call("find-peer",e)})}findPeerByName(e){return c(this,null,function*(){return yield this.call("peer-name-search",e)})}setSessionMetadata(e){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("set-metadata",m({},e))}listenMetadataChange(e){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to observe session store key due to network disconnection");return this.call("listen-metadata-change",{keys:e})}getSessionMetadata(e){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("get-metadata",{key:e})}setPollInfo(e){return this.call("poll-info-set",m({},e))}getPollInfo(e){return this.call("poll-info-get",m({},e))}setPollQuestions(e){return this.call("poll-questions-set",m({},e))}startPoll(e){return this.call("poll-start",m({},e))}stopPoll(e){return this.call("poll-stop",m({},e))}getPollQuestions(e){return this.call("poll-questions-get",m({},e))}setPollResponses(e){return this.call("poll-response",m({},e))}getPollResponses(e){return this.call("poll-responses",m({},e))}getPollsList(e){return this.call("poll-list",m({},e))}getPollResult(e){return this.call("poll-result",m({},e))}createWhiteboard(e){return this.validateConnection(),this.call("whiteboard-create",m({},e))}getWhiteboard(e){return this.validateConnection(),this.call("whiteboard-get",m({},e))}fetchPollLeaderboard(e){return this.call("poll-leaderboard",m({},e))}validateConnection(){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to send message due to network disconnection")}onMessageHandler(e){let t=e.data,i=JSON.parse(t);if(this.resolvePingOnAnyResponse(),i.id)this.handleResponseWithId(i);else if(i.method)this.handleResponseWithMethod(i);else throw Error(`WebSocket message has no 'method' or 'id' field, message=${i}`)}handleResponseWithId(e){let t=e,i=t.id;if(this.callbacks.has(i)){let r=this.callbacks.get(i);this.callbacks.delete(i),t.result?r.resolve(t.result):r.reject(t.error)}else this.observer.onNotification(t)}handleResponseWithMethod(e){switch(e.method){case"offer":this.observer.onOffer(e.params);break;case"trickle":this.observer.onTrickle(e.params);break;case"on-error":this.observer.onServerError(S.WebsocketMethodErrors.ServerErrors(Number(e.params.code),"on-error",e.params.message));break;case"on-warning":d.w(this.TAG,e.params);break;default:this.observer.onNotification(e);break}}rejectPendingCalls(e=""){this.callbacks.forEach((t,i)=>{var r,s,n,o;((r=t.metadata)==null?void 0:r.method)!=="ping"&&(d.e(this.TAG,`rejecting pending callback ${(s=t.metadata)==null?void 0:s.method}, id=${i}`),t.reject(S.WebSocketConnectionErrors.WebSocketConnectionLost((n=t.metadata)!=null&&n.method?Yr((o=t.metadata)==null?void 0:o.method):"RECONNECT_SIGNAL",e)),this.callbacks.delete(i))})}pingPongLoop(e){return c(this,null,function*(){var i,r;let t=((i=window.HMS)==null?void 0:i.PING_TIMEOUT)||12e3;if(this.isConnected){let s=yield this.ping(t);this.pongResponseTimes.enqueue(s),s>t?(d.d(this.TAG,`Pong timeout ${e}, pageHidden=${ga()}`),this.id===e&&this.setIsConnected(!1,"ping pong failure")):setTimeout(()=>{this.id===e&&this.pingPongLoop(e)},((r=window.HMS)==null?void 0:r.PING_INTERVAL)||3e3)}})}call(e,t){return c(this,null,function*(){let r=S.WebsocketMethodErrors.ServerErrors(500,e,`Default ${e} error`),s;for(s=1;s<=3;s++)try{return this.validateConnection(),d.d(this.TAG,`Try number ${s} sending ${e}`,t),yield this.internalCall(e,t)}catch(n){if(r=n,d.e(this.TAG,`Failed sending ${e} try: ${s}`,{method:e,params:t,error:r}),!(parseInt(`${r.code/100}`)===5||r.code===429||r.code===1003))break;let l=(2+Math.random()*2)*1e3;yield Fe(l)}throw d.e(`Sending ${e} over WS failed after ${Math.min(s,3)} retries`,{method:e,params:t,error:r}),r})}};var zn=()=>{if(!F||typeof navigator.connection=="undefined")return;let a=navigator.connection;return{downlink:a.downlink,downlinkMax:a.downlinkMax,effectiveType:a.effectiveType,rtt:a.rtt,saveData:a.saveData,type:a.type}};var R="[HMSTransport]:",mi=class{constructor(e,t,i,r,s,n,o){this.observer=e;this.deviceManager=t;this.store=i;this.eventBus=r;this.analyticsEventsService=s;this.analyticsTimer=n;this.pluginUsageTracker=o;this.state="Disconnected";this.trackStates=new Map;this.publishConnection=null;this.subscribeConnection=null;this.maxSubscribeBitrate=0;this.joinRetryCount=0;this.publishDisconnectTimer=0;this.onScreenshareStop=()=>{};this.screenStream=new Set;this.callbacks=new Map;this.setListener=e=>{this.listener=e};this.setOnScreenshareStop=e=>{this.onScreenshareStop=e};this.signalObserver={onOffer:e=>c(this,null,function*(){try{if(!this.subscribeConnection)return;if(e.sfu_node_id&&this.subscribeConnection.sfuNodeId&&this.subscribeConnection.sfuNodeId!==e.sfu_node_id){d.d(R,"ignoring old offer");return}yield this.subscribeConnection.setRemoteDescription(e),d.d(R,`[SUBSCRIBE] Adding ${this.subscribeConnection.candidates.length} ice-candidates`,this.subscribeConnection.candidates);for(let i of this.subscribeConnection.candidates)yield this.subscribeConnection.addIceCandidate(i);this.subscribeConnection.candidates.length=0;let t=yield this.subscribeConnection.createAnswer();yield this.subscribeConnection.setLocalDescription(t),this.signal.answer(t),d.d(R,"[role=SUBSCRIBE] onOffer renegotiation DONE \u2705")}catch(t){d.d(R,"[role=SUBSCRIBE] onOffer renegotiation FAILED \u274C",t);let i;t instanceof k?i=t:i=S.GenericErrors.Unknown("SUBSCRIBE",t.message),yield this.observer.onStateChange("Failed",i),this.eventBus.analytics.publish(y.subscribeFail(i))}}),onTrickle:e=>c(this,null,function*(){let t=e.target===0?this.publishConnection:this.subscribeConnection;t!=null&&t.remoteDescription?yield t.addIceCandidate(e.candidate):t==null||t.candidates.push(e.candidate)}),onNotification:e=>this.observer.onNotification(e),onServerError:e=>c(this,null,function*(){yield this.observer.onStateChange("Failed",e)}),onFailure:e=>{this.joinParameters&&this.retryScheduler.schedule({category:1,error:e,task:this.retrySignalDisconnectTask,originalState:this.state})},onOffline:e=>c(this,null,function*(){d.d(R,"socket offline",Hr[this.state]);try{this.state!=="Leaving"&&this.joinParameters&&this.retryScheduler.schedule({category:1,error:S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL",e),task:this.retrySignalDisconnectTask,originalState:this.state})}catch(t){console.error(t)}}),onOnline:()=>{var e;d.d(R,"socket online",Hr[this.state]),this.analyticsSignalTransport.flushFailedEvents((e=this.store.getLocalPeer())==null?void 0:e.peerId)},onNetworkOnline:()=>{this.analyticsEventsService.flushFailedClientEvents()}};this.signal=new hi(this.signalObserver);this.analyticsSignalTransport=new _r(this.signal);this.publishDtlsStateTimer=0;this.lastPublishDtlsState="new";this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){!this.doesRoleNeedWebRTC(e)&&this.doesRoleNeedWebRTC(t)&&(d.d(R,"Local peer role updated to webrtc role, creating PeerConnections and performing inital publish negotiation \u23F3"),this.createPeerConnections(),yield this.negotiateOnFirstPublish())});this.retryPublishIceFailedTask=()=>c(this,null,function*(){if(this.publishConnection){let e=new Promise((t,i)=>{this.callbacks.set(st,{promise:{resolve:t,reject:i},action:"RESTART_ICE",extra:{}})});yield this.performPublishRenegotiation({iceRestart:this.publishConnection.connectionState!=="connected"}),yield e}return!0});this.retrySubscribeIceFailedTask=()=>c(this,null,function*(){if(this.subscribeConnection&&this.subscribeConnection.connectionState!=="connected"){let e=new Promise((i,r)=>{this.callbacks.set(at,{promise:{resolve:i,reject:r},action:"RESTART_ICE",extra:{}})}),t=new Promise(i=>{setTimeout(i,6e4,!1)});return Promise.race([e,t])}return!0});this.retrySignalDisconnectTask=()=>c(this,null,function*(){var t;if(!this.joinParameters||this.state==="Leaving")return!1;d.d(R,"retrySignalDisconnectTask",{signalConnected:this.signal.isConnected}),this.signal.isConnected||(yield this.internalConnect(this.joinParameters.authToken,this.joinParameters.endpoint,this.joinParameters.peerId,this.joinParameters.iceServers));let e=(t=this.store.getRoom())!=null&&t.joinedAt?this.signal.isConnected&&(yield this.retryPublishIceFailedTask()):this.signal.isConnected;return this.signal.trackUpdate(this.trackStates),e});this.webrtcInternals=new Vi(this.store,this.eventBus);let l=(u,p)=>c(this,null,function*(){u!==this.state&&(this.state=u,yield this.observer.onStateChange(this.state,p))});this.retryScheduler=new Lr(l,this.sendErrorAnalyticsEvent.bind(this)),this.eventBus.statsUpdate.subscribe(u=>{var h,T;let p=((T=(h=u.getLocalPeerStats())==null?void 0:h.subscribe)==null?void 0:T.bitrate)||0;this.maxSubscribeBitrate=Math.max(this.maxSubscribeBitrate,p)}),this.eventBus.localAudioEnabled.subscribe(({track:u,enabled:p})=>this.trackUpdate(u,p)),this.eventBus.localVideoEnabled.subscribe(({track:u,enabled:p})=>this.trackUpdate(u,p))}getWebsocketEndpoint(){if(this.initConfig)return this.initConfig.endpoint}getWebrtcInternals(){return this.webrtcInternals}isFlagEnabled(e){var r;let t=(r=this.initConfig)==null?void 0:r.config;return((t==null?void 0:t.enabledFlags)||[]).includes(e)}setConnectivityListener(e){this.connectivityListener=e}preview(e,t,i,r,s=!1,n){return c(this,null,function*(){let o=yield this.connect(e,t,i,r,s,n);return this.state="Preview",this.observer.onStateChange(this.state),o})}join(e,t,i,r,s=!1,n){return c(this,null,function*(){d.d(R,"join: started \u23F0");try{(!this.signal.isConnected||!this.initConfig)&&(yield this.connect(e,r,t,i,s,n)),this.validateNotDisconnected("connect"),this.initConfig&&(yield this.waitForLocalRoleAvailability(),yield this.createConnectionsAndNegotiateJoin(i,s),this.initStatsAnalytics(),d.d(R,"\u2705 join: Negotiated over PUBLISH connection"))}catch(o){d.e(R,`join: failed \u274C [token=${e}]`,o),this.state="Failed";let l=o;throw l.isTerminal=l.isTerminal||l.code===500,yield this.observer.onStateChange(this.state,l),l}d.d(R,"\u2705 join: successful"),this.state="Joined",this.observer.onStateChange(this.state)})}connect(e,t,i,r,s=!1,n){return c(this,null,function*(){this.setTransportStateForConnect(),this.joinParameters=new Rr(e,i,r.name,r.metaData,t,s,n);try{return yield this.internalConnect(e,t,i,n)}catch(o){if(!(o instanceof k))throw o;if([E.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,E.WebSocketConnectionErrors.FAILED_TO_CONNECT,E.WebSocketConnectionErrors.ABNORMAL_CLOSE].includes(o.code)||o.code.toString().startsWith("5")||o.code.toString().startsWith("429")||o.code===E.APIErrors.ENDPOINT_UNREACHABLE&&!navigator.onLine){let u=()=>c(this,null,function*(){return yield this.internalConnect(e,t,i,n),!!(this.initConfig&&this.initConfig.endpoint)});yield this.retryScheduler.schedule({category:0,error:o,task:u,originalState:this.state,changeState:!1})}else throw o}})}leave(i){return c(this,arguments,function*(e,t="user request"){var r,s,n;this.retryScheduler.reset(),this.joinParameters=void 0,d.d(R,"leaving in transport");try{let o=this.pluginUsageTracker.getPluginUsage("HMSKrispPlugin");if(o&&this.eventBus.analytics.publish(y.getKrispUsage(o)),this.state="Leaving",(r=this.publishStatsAnalytics)==null||r.stop(),(s=this.subscribeStatsAnalytics)==null||s.stop(),(n=this.webrtcInternals)==null||n.cleanup(),this.clearPeerConnections(),e)try{this.signal.leave(t),d.d(R,"signal leave done")}catch(l){d.w(R,"failed to send leave on websocket to server",l)}this.analyticsEventsService.flushFailedClientEvents(),this.analyticsEventsService.reset(),yield this.signal.close()}catch(o){this.eventBus.analytics.publish(y.disconnect(o)),d.e(R,"leave: FAILED \u274C",o)}finally{this.state="Disconnected",this.observer.onStateChange(this.state)}})}publish(e){return c(this,null,function*(){var t;for(let i of e)try{yield this.publishTrack(i),(t=this.connectivityListener)==null||t.onMediaPublished(i)}catch(r){this.eventBus.analytics.publish(y.publish({devices:this.deviceManager.getDevices(),error:r}))}})}unpublish(e){return c(this,null,function*(){for(let t of e)yield this.unpublishTrack(t)})}setSFUNodeId(e){var t,i;this.signal.setSfuNodeId(e),this.sfuNodeId?e&&this.sfuNodeId!==e&&(this.sfuNodeId=e,this.handleSFUMigration()):(this.sfuNodeId=e,(t=this.publishConnection)==null||t.setSfuNodeId(e),(i=this.subscribeConnection)==null||i.setSfuNodeId(e))}handleSFUMigration(){return c(this,null,function*(){var s,n;d.time("sfu migration"),this.clearPeerConnections();let e=this.store.getPeerMap();this.store.removeRemoteTracks();for(let o in e){let l=e[o];l.isLocal||(l.audioTrack=void 0,l.videoTrack=void 0,l.auxiliaryTracks=[])}let t=this.store.getLocalPeer();if(!t)return;this.createPeerConnections(),this.trackStates.clear(),yield this.negotiateOnFirstPublish();let i=new Map;if(t.audioTrack){let o=t.audioTrack.stream;i.get(o.id)||i.set(o.id,new fe(new MediaStream));let l=t.audioTrack.clone(i.get(o.id));this.store.removeTrack(t.audioTrack),t.audioTrack.cleanup(),yield this.publishTrack(l),t.audioTrack=l}if(t.videoTrack){let o=t.videoTrack.stream;i.get(o.id)||i.set(o.id,new fe(new MediaStream)),this.store.removeTrack(t.videoTrack);let l=t.videoTrack.clone(i.get(o.id));t.videoTrack.cleanup(),yield this.publishTrack(l),t.videoTrack=l}let r=[];for(;t.auxiliaryTracks.length>0;){let o=t.auxiliaryTracks.shift();if(o){let l=o.stream;i.get(l.id)||i.set(l.id,new fe(o.source==="screen"?l.nativeStream.clone():new MediaStream)),this.store.removeTrack(o);let u=o.clone(i.get(l.id));u.type==="video"&&u.source==="screen"&&(this.screenStream.add(l.nativeStream),this.screenStream.add(u.stream.nativeStream),u.nativeTrack.addEventListener("ended",this.onScreenshareStop)),o.cleanup(),yield this.publishTrack(u),r.push(u)}}t.auxiliaryTracks=r,i.clear(),(n=(s=this.listener)==null?void 0:s.onSFUMigration)==null||n.call(s),d.timeEnd("sfu migration")})}trackUpdate(e,t){var s;let r=Array.from(this.trackStates.values()).find(n=>e.type===n.type&&e.source===n.source);if(r){let n=new Xt(M(m({},r),{mute:!t}));this.trackStates.set(r.track_id,n),d.d(R,"Track Update",this.trackStates,e),this.signal.trackUpdate(new Map([[r.track_id,n]]));let o=this.store.getLocalPeer();o&&t===e.enabled&&((s=this.listener)==null||s.onTrackUpdate(t?3:2,e,o))}}publishTrack(e){return c(this,null,function*(){e.publishedTrackId=e.getTrackIDBeingSent(),d.d(R,`\u23F3 publishTrack: trackId=${e.trackId}, toPublishTrackId=${e.publishedTrackId}`,`${e}`),this.trackStates.set(e.publishedTrackId,new Xt(e));let t=new Promise((s,n)=>{this.callbacks.set(st,{promise:{resolve:s,reject:n},action:"PUBLISH",extra:{}})}),i=e.stream;i.setConnection(this.publishConnection);let r=this.store.getSimulcastLayers(e.source);i.addTransceiver(e,r),d.time(`publish-${e.trackId}-${e.type}`),yield t,d.timeEnd(`publish-${e.trackId}-${e.type}`),this.store.addTrack(e),yield i.setMaxBitrateAndFramerate(e).then(()=>{d.d(R,`Setting maxBitrate=${e.settings.maxBitrate} kpbs${e instanceof q?` and maxFramerate=${e.settings.maxFramerate}`:""} for ${e.source} ${e.type} ${e.trackId}`)}).catch(s=>d.w(R,"Failed setting maxBitrate and maxFramerate",s)),e.isPublished=!0,d.d(R,`\u2705 publishTrack: trackId=${e.trackId}`,`${e}`,this.callbacks)})}unpublishTrack(e){return c(this,null,function*(){if(d.d(R,`\u23F3 unpublishTrack: trackId=${e.trackId}`,`${e}`),e.publishedTrackId&&this.trackStates.has(e.publishedTrackId))this.trackStates.delete(e.publishedTrackId);else{let s=Array.from(this.trackStates.values()).find(n=>e.type===n.type&&e.source===n.source);s&&this.trackStates.delete(s.track_id)}let t=new Promise((r,s)=>{this.callbacks.set(st,{promise:{resolve:r,reject:s},action:"UNPUBLISH",extra:{}})});e.stream.removeSender(e),yield t,yield e.cleanup(),e.source==="screen"&&this.screenStream&&this.screenStream.forEach(r=>{r.getTracks().forEach(s=>{s.stop()}),this.screenStream.delete(r)}),this.store.removeTrack(e),d.d(R,`\u2705 unpublishTrack: trackId=${e.trackId}`,this.callbacks)})}clearPeerConnections(){return c(this,null,function*(){var e,t;clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0,clearTimeout(this.publishDisconnectTimer),this.publishDisconnectTimer=0,this.lastPublishDtlsState="new",(e=this.publishConnection)==null||e.close(),(t=this.subscribeConnection)==null||t.close(),this.publishConnection=null,this.subscribeConnection=null})}waitForLocalRoleAvailability(){if(!this.store.hasRoleDetailsArrived())return new Promise(e=>{this.eventBus.policyChange.subscribeOnce(()=>e())})}createConnectionsAndNegotiateJoin(e,t=!1){return c(this,null,function*(){let i=this.doesLocalPeerNeedWebRTC();i&&this.createPeerConnections(),this.analyticsTimer.start("join_response_time"),yield this.negotiateJoinWithRetry({name:e.name,data:e.metaData,autoSubscribeVideo:t,isWebRTC:i}),this.analyticsTimer.end("join_response_time")})}createPeerConnections(){var t,i,r;let e=(s,n,o=!1)=>{(["disconnected","failed"].includes(n)?d.w.bind(d):d.d.bind(d))(R,`${yt[s]} ${o?"ice":""} connection state change: ${n}`)};if(this.initConfig){let s={onRenegotiationNeeded:()=>c(this,null,function*(){yield this.performPublishRenegotiation()}),onDTLSTransportStateChange:o=>{var p,h,T;if((o==="failed"?d.w.bind(d):d.d.bind(d))(R,`Publisher on dtls transport state change: ${o}`),!o||this.lastPublishDtlsState===o||(this.lastPublishDtlsState=o,this.publishDtlsStateTimer!==0&&(clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0),o!=="connecting"&&o!=="failed"))return;let u=(T=(h=(p=this.initConfig)==null?void 0:p.config)==null?void 0:h.dtlsStateTimeouts)==null?void 0:T[o];!u||u<=0||(this.publishDtlsStateTimer=window.setTimeout(()=>{var f;let g=(f=this.publishConnection)==null?void 0:f.nativeConnection.connectionState;if(g&&o&&g===o){let P=S.WebrtcErrors.ICEFailure("PUBLISH",`DTLS transport state ${o} timeout:${u}ms`,!0);this.eventBus.analytics.publish(y.disconnect(P)),this.observer.onFailure(P)}},u))},onDTLSTransportError:o=>{d.e(R,`onDTLSTransportError ${o.name} ${o.message}`,o),this.eventBus.analytics.publish(y.disconnect(o))},onIceConnectionChange:o=>c(this,null,function*(){e(0,o,!0)}),onConnectionStateChange:o=>c(this,null,function*(){var l,u,p,h,T,g,f,P;e(0,o,!1),o!=="new"&&(o==="connected"?((l=this.connectivityListener)==null||l.onICESuccess(!0),(u=this.publishConnection)==null||u.handleSelectedIceCandidatePairs()):o==="failed"?yield this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEFailure("PUBLISH",`local candidate - ${(T=(h=(p=this.publishConnection)==null?void 0:p.selectedCandidatePair)==null?void 0:h.local)==null?void 0:T.candidate}; remote candidate - ${(P=(f=(g=this.publishConnection)==null?void 0:g.selectedCandidatePair)==null?void 0:f.remote)==null?void 0:P.candidate}`)):this.publishDisconnectTimer=window.setTimeout(()=>{var v,A,$,ce,B,de,De;((v=this.publishConnection)==null?void 0:v.connectionState)!=="connected"&&this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEDisconnected("PUBLISH",`local candidate - ${(ce=($=(A=this.publishConnection)==null?void 0:A.selectedCandidatePair)==null?void 0:$.local)==null?void 0:ce.candidate}; remote candidate - ${(De=(de=(B=this.publishConnection)==null?void 0:B.selectedCandidatePair)==null?void 0:de.remote)==null?void 0:De.candidate}`))},5e3))}),onIceCandidate:o=>{var l;(l=this.connectivityListener)==null||l.onICECandidate(o,!0)},onSelectedCandidatePairChange:o=>{var l;(l=this.connectivityListener)==null||l.onSelectedICECandidatePairChange(o,!0)}},n={onApiChannelMessage:o=>{this.observer.onNotification(JSON.parse(o))},onTrackAdd:o=>{d.d(R,"[Subscribe] onTrackAdd",`${o}`),this.observer.onTrackAdd(o)},onTrackRemove:o=>{d.d(R,"[Subscribe] onTrackRemove",`${o}`),this.observer.onTrackRemove(o)},onIceConnectionChange:o=>c(this,null,function*(){var l;if(e(1,o,!0),o==="connected"){let u=this.callbacks.get(at);this.callbacks.delete(at),(l=this.connectivityListener)==null||l.onICESuccess(!1),u&&u.promise.resolve(!0)}}),onConnectionStateChange:o=>c(this,null,function*(){var l,u,p,h,T,g,f;if(e(1,o,!1),o==="failed")yield this.handleIceConnectionFailure(1,S.WebrtcErrors.ICEFailure("SUBSCRIBE",`local candidate - ${(p=(u=(l=this.subscribeConnection)==null?void 0:l.selectedCandidatePair)==null?void 0:u.local)==null?void 0:p.candidate}; remote candidate - ${(g=(T=(h=this.subscribeConnection)==null?void 0:h.selectedCandidatePair)==null?void 0:T.remote)==null?void 0:g.candidate}`));else if(o==="disconnected")setTimeout(()=>{var P,v,A,$,ce,B,de;((P=this.subscribeConnection)==null?void 0:P.connectionState)==="disconnected"&&this.handleIceConnectionFailure(1,S.WebrtcErrors.ICEDisconnected("SUBSCRIBE",`local candidate - ${($=(A=(v=this.subscribeConnection)==null?void 0:v.selectedCandidatePair)==null?void 0:A.local)==null?void 0:$.candidate}; remote candidate - ${(de=(B=(ce=this.subscribeConnection)==null?void 0:ce.selectedCandidatePair)==null?void 0:B.remote)==null?void 0:de.candidate}`))},5e3);else if(o==="connected"){(f=this.subscribeConnection)==null||f.handleSelectedIceCandidatePairs();let P=this.callbacks.get(at);this.callbacks.delete(at),P&&P.promise.resolve(!0)}}),onIceCandidate:o=>{var l;(l=this.connectivityListener)==null||l.onICECandidate(o,!1)},onSelectedCandidatePairChange:o=>{var l;(l=this.connectivityListener)==null||l.onSelectedICECandidatePairChange(o,!1)}};this.publishConnection||(this.publishConnection=new di(this.signal,this.initConfig.rtcConfiguration,s)),this.subscribeConnection||(this.subscribeConnection=new ui(this.signal,this.initConfig.rtcConfiguration,this.isFlagEnabled.bind(this),n,this.eventBus))}(r=this.webrtcInternals)==null||r.setPeerConnections({publish:(t=this.publishConnection)==null?void 0:t.nativeConnection,subscribe:(i=this.subscribeConnection)==null?void 0:i.nativeConnection})}negotiateJoinWithRetry(s){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r=!0}){try{yield this.negotiateJoin({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r})}catch(n){d.e(R,"Join negotiation failed \u274C",n);let o=n instanceof k?n:S.WebsocketMethodErrors.ServerErrors(500,"JOIN",`Websocket join error - ${n.message}`),l=parseInt(`${o.code/100}`)===5||[E.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,429].includes(o.code);if(o.code===410&&(o.isTerminal=!0),l){this.joinRetryCount=0,o.isTerminal=!1;let u=()=>c(this,null,function*(){return this.joinRetryCount++,yield this.negotiateJoin({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r})});yield this.retryScheduler.schedule({category:2,error:o,task:u,originalState:"Joined",changeState:!1})}else throw n}})}negotiateJoin(s){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r=!0}){return r?yield this.negotiateJoinWebRTC({name:e,data:t,autoSubscribeVideo:i}):yield this.negotiateJoinNonWebRTC({name:e,data:t,autoSubscribeVideo:i})})}negotiateJoinWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){if(d.d(R,"\u23F3 join: Negotiating over PUBLISH connection"),!this.publishConnection)return d.e(R,"Publish peer connection not found, cannot negotiate"),!1;let s=yield this.publishConnection.createOffer();yield this.publishConnection.setLocalDescription(s);let n=this.isFlagEnabled("subscribeDegradation"),o=this.isFlagEnabled("simulcast"),l=this.isFlagEnabled("onDemandTracks"),u=yield this.signal.join(e,t,!i,n,o,l,s);this.setSFUNodeId(u==null?void 0:u.sfu_node_id),yield this.publishConnection.setRemoteDescription(u);for(let p of this.publishConnection.candidates)yield this.publishConnection.addIceCandidate(p);return this.publishConnection.initAfterJoin(),!!u})}negotiateJoinNonWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){d.d(R,"\u23F3 join: Negotiating Non-WebRTC");let s=this.isFlagEnabled("subscribeDegradation"),n=this.isFlagEnabled("simulcast"),o=this.isFlagEnabled("onDemandTracks"),l=yield this.signal.join(e,t,!i,s,n,o);return this.setSFUNodeId(l==null?void 0:l.sfu_node_id),!!l})}negotiateOnFirstPublish(){return c(this,null,function*(){if(d.d(R,"\u23F3 Negotiating offer over PUBLISH connection"),!this.publishConnection)return d.e(R,"Publish peer connection not found, cannot negotiate"),!1;try{let e=yield this.publishConnection.createOffer(this.trackStates);yield this.publishConnection.setLocalDescription(e);let t=yield this.signal.offer(e,this.trackStates);yield this.publishConnection.setRemoteDescription(t);for(let i of this.publishConnection.candidates)yield this.publishConnection.addIceCandidate(i);return this.publishConnection.initAfterJoin(),!!t}catch(e){if(e instanceof k&&e.code===421)return!0;throw e}})}performPublishRenegotiation(e){return c(this,null,function*(){d.d(R,"\u23F3 [role=PUBLISH] onRenegotiationNeeded START",this.trackStates);let t=this.callbacks.get(st);if(!t){d.w(R,"no callback found for renegotiation");return}if(!this.publishConnection){d.e(R,"Publish peer connection not found, cannot renegotiate");return}try{let i=yield this.publishConnection.createOffer(this.trackStates,e);yield this.publishConnection.setLocalDescription(i),d.time("renegotiation-offer-exchange");let r=yield this.signal.offer(i,this.trackStates);this.callbacks.delete(st),d.timeEnd("renegotiation-offer-exchange"),yield this.publishConnection.setRemoteDescription(r),t.promise.resolve(!0),d.d(R,"[role=PUBLISH] onRenegotiationNeeded DONE \u2705")}catch(i){let r;i instanceof k?r=i:r=S.GenericErrors.Unknown("PUBLISH",i.message),r.code===421?t.promise.resolve(!0):t.promise.reject(r),d.d(R,"[role=PUBLISH] onRenegotiationNeeded FAILED \u274C")}})}handleIceConnectionFailure(e,t){return c(this,null,function*(){this.retryScheduler.isTaskInProgress(e===0?3:4)||(e===0?this.retryScheduler.schedule({category:3,error:t,task:this.retryPublishIceFailedTask,originalState:"Joined"}):this.retryScheduler.schedule({category:4,error:t,task:this.retrySubscribeIceFailedTask,originalState:"Joined"}))})}internalConnect(e,t,i,r){return c(this,null,function*(){var n,o,l;d.d(R,"connect: started \u23F0");let s=new Date;try{this.analyticsTimer.start("init_response_time"),this.initConfig=yield pi.fetchInitConfig({token:e,peerId:i,userAgent:this.store.getUserAgent(),initEndpoint:t,iceServers:r}),(n=this.connectivityListener)==null||n.onInitSuccess(this.initConfig.endpoint);let u=this.store.getRoom();return u&&(u.effectsKey=(o=this.initConfig.config.vb)==null?void 0:o.effectsKey,u.isEffectsEnabled=this.isFlagEnabled("effectsSDKEnabled"),u.disableNoneLayerRequest=this.isFlagEnabled("disableNoneLayerRequest"),u.isVBEnabled=this.isFlagEnabled("vb"),u.isHipaaEnabled=this.isFlagEnabled("hipaa"),u.isNoiseCancellationEnabledFromInit=this.isFlagEnabled("noiseCancellation")),this.analyticsTimer.end("init_response_time"),Le.setWebsocketEndpoint(this.initConfig.endpoint),this.validateNotDisconnected("post init"),yield this.openSignal(e,i),this.observer.onConnected(),(l=this.connectivityListener)==null||l.onSignallingSuccess(),this.store.setSimulcastEnabled(this.isFlagEnabled("simulcast")),d.d(R,"Adding Analytics Transport: JsonRpcSignal"),this.analyticsEventsService.setTransport(this.analyticsSignalTransport),this.analyticsEventsService.flush(),this.initConfig}catch(u){throw this.state!=="Reconnecting"&&this.eventBus.analytics.publish(y.connect(u,this.getAdditionalAnalyticsProperties(),s,new Date,t)),d.e(R,"\u274C internal connect: failed",u),u}})}validateNotDisconnected(e){if(this.state==="Disconnected")throw d.w(R,"aborting join as transport state is disconnected"),S.GenericErrors.ValidationFailed(`leave called before join could complete - stage=${e}`)}openSignal(e,t){return c(this,null,function*(){if(!this.initConfig)throw S.APIErrors.InitConfigNotAvailable("INIT","Init Config not found");d.d(R,"\u23F3 internal connect: connecting to ws endpoint",this.initConfig.endpoint);let i=new URL(this.initConfig.endpoint);i.searchParams.set("peer",t),i.searchParams.set("token",e),i.searchParams.set("user_agent_v2",this.store.getUserAgent()),i.searchParams.set("protocol_version",Ca),i.searchParams.set("protocol_spec",La),this.endpoint=i.toString(),this.analyticsTimer.start("ws_connect_time"),yield this.signal.open(this.endpoint),this.analyticsTimer.end("ws_connect_time"),this.analyticsTimer.start("on_policy_change_time"),this.analyticsTimer.start("room_state_time"),d.d(R,"\u2705 internal connect: connected to ws endpoint")})}initStatsAnalytics(){var e,t;this.isFlagEnabled("publishStats")&&(this.publishStatsAnalytics=new ni(this.store,this.eventBus,this.getValueFromInitConfig("publishStats","maxSampleWindowSize",30),this.getValueFromInitConfig("publishStats","maxSamplePushInterval",300)),(e=this.getWebrtcInternals())==null||e.start()),this.isFlagEnabled("subscribeStats")&&(this.subscribeStatsAnalytics=new oi(this.store,this.eventBus,this.getValueFromInitConfig("subscribeStats","maxSampleWindowSize",10),this.getValueFromInitConfig("subscribeStats","maxSamplePushInterval",60)),(t=this.getWebrtcInternals())==null||t.start())}getValueFromInitConfig(e,t,i){var r,s;return((s=(r=this.initConfig)==null?void 0:r.config[e])==null?void 0:s[t])||i}doesRoleNeedWebRTC(e){var r,s;if(!this.isFlagEnabled("nonWebRTCDisableOffer"))return!0;let t=!!(e.publishParams.allowed&&((r=e.publishParams.allowed)==null?void 0:r.length)>0),i=!!(e.subscribeParams.subscribeToRoles&&((s=e.subscribeParams.subscribeToRoles)==null?void 0:s.length)>0);return t||i}doesLocalPeerNeedWebRTC(){var t;let e=(t=this.store.getLocalPeer())==null?void 0:t.role;return e?this.doesRoleNeedWebRTC(e):!0}setTransportStateForConnect(){if(this.state==="Failed"&&(this.state="Disconnected"),this.state!=="Disconnected"&&this.state!=="Reconnecting")throw S.WebsocketMethodErrors.AlreadyJoined("JOIN",`Cannot join a meeting in ${this.state} state`);this.state==="Disconnected"&&(this.state="Connecting",this.observer.onStateChange(this.state))}sendErrorAnalyticsEvent(e,t){let i=this.getAdditionalAnalyticsProperties(),r;switch(t){case 0:r=y.connect(e,i);break;case 1:r=y.disconnect(e,i);break;case 2:r=y.join({error:e,time:this.analyticsTimer.getTimeTaken("join_time"),init_response_time:this.analyticsTimer.getTimeTaken("init_response_time"),ws_connect_time:this.analyticsTimer.getTimeTaken("ws_connect_time"),on_policy_change_time:this.analyticsTimer.getTimeTaken("on_policy_change_time"),local_audio_track_time:this.analyticsTimer.getTimeTaken("local_audio_track_time"),local_video_track_time:this.analyticsTimer.getTimeTaken("local_video_track_time"),retries_join:this.joinRetryCount});break;case 3:r=y.publish({error:e});break;case 4:r=y.subscribeFail(e);break}this.eventBus.analytics.publish(r)}getSubscribeConnection(){return this.subscribeConnection}getAdditionalAnalyticsProperties(){var n,o,l,u,p,h,T,g;let e=zn(),t=typeof document!="undefined"&&document.hidden,i=this.store.getRemoteVideoTracks().filter(f=>f.degraded).length,r=(u=(l=(o=(n=this.getWebrtcInternals())==null?void 0:n.getCurrentStats())==null?void 0:o.getLocalPeerStats())==null?void 0:l.publish)==null?void 0:u.bitrate,s=(g=(T=(h=(p=this.getWebrtcInternals())==null?void 0:p.getCurrentStats())==null?void 0:h.getLocalPeerStats())==null?void 0:T.subscribe)==null?void 0:g.bitrate;return{network_info:e,document_hidden:t,num_degraded_tracks:i,bitrate:{publish:r,subscribe:s},max_sub_bitrate:this.maxSubscribeBitrate,recent_pong_response_times:this.signal.getPongResponseTimes(),transport_state:this.state}}};function Vr(a){if(!a||a.length===0)throw S.APIErrors.InvalidTokenFormat("INIT","Token cannot be an empty string or undefined or null");let e=a.split(".");if(e.length!==3)throw S.APIErrors.InvalidTokenFormat("INIT","Expected 3 '.' separate fields - header, payload and signature respectively");let t=atob(e[1]);try{let i=JSON.parse(t);return{roomId:i.room_id,userId:i.user_id,role:i.role}}catch(i){throw S.APIErrors.InvalidTokenFormat("INIT",`couldn't parse to json - ${i.message}`)}}var Xn={published:!1,isInitialised:!1,isReconnecting:!1,isPreviewInProgress:!1,isPreviewCalled:!1,isJoinInProgress:!1,deviceManagersInitialised:!1},Fr=class{constructor(){this.TAG="[HMSSdk]:";this.transportState="Disconnected";this.analyticsTimer=new Ii;this.sdkState=m({},Xn);this.isDiagnostics=!1;this.playlistSettings={video:{bitrate:is},audio:{bitrate:rs}};this.handleAutoplayError=e=>{var t,i;(i=(t=this.errorListener)==null?void 0:t.onError)==null||i.call(t,e)};this.observer={onNotification:e=>{var t;if(e.method==="on-peer-leave-request"){this.handlePeerLeaveRequest(e.params);return}switch(e.method){case"on-policy-change":this.analyticsTimer.end("on_policy_change_time");break;case"peer-list":this.analyticsTimer.end("peer_list_time"),this.sendJoinAnalyticsEvent(this.sdkState.isPreviewCalled);break;case"room-state":this.analyticsTimer.end("room_state_time");break;default:}(t=this.notificationManager)==null||t.handleNotification(e,this.sdkState.isReconnecting)},onConnected:()=>{this.initNotificationManager()},onTrackAdd:e=>{var t;(t=this.notificationManager)==null||t.handleTrackAdd(e)},onTrackRemove:e=>{var t;(t=this.notificationManager)==null||t.handleTrackRemove(e)},onFailure:e=>{var t;(t=this.errorListener)==null||t.onError(e)},onStateChange:(e,t)=>c(this,null,function*(){var r,s;let i=n=>c(this,null,function*(){var o,l;yield this.internalLeave(!0,n),!this.sdkState.isPreviewInProgress&&!this.sdkState.isJoinInProgress&&((l=(o=this.errorListener)==null?void 0:o.onError)==null||l.call(o,n)),this.sdkState.isReconnecting=!1});switch(e){case"Preview":case"Joined":this.initNotificationManager(),this.transportState==="Reconnecting"&&((r=this.listener)==null||r.onReconnected());break;case"Failed":yield i(t);break;case"Reconnecting":this.sdkState.isReconnecting=!0,(s=this.listener)==null||s.onReconnecting(t);break}this.transportState=e,d.d(this.TAG,"Transport State Change",this.transportState)})};this.handlePeerLeaveRequest=e=>{var r;let t=e.requested_by?this.store.getPeerById(e.requested_by):void 0,i={roomEnded:e.room_end,reason:e.reason,requestedBy:t};(r=this.listener)==null||r.onRemovedFromRoom(i),this.internalLeave(!1)};this.handlePreviewError=e=>{var t;this.analyticsTimer.end("preview_time"),e&&((t=this.errorListener)==null||t.onError(e)),this.sendPreviewAnalyticsEvent(e),this.sdkState.isPreviewInProgress=!1};this.handleTrackInterruption=e=>{var t,i;d.d(this.TAG,"Track interruption",`{
103
+ }`),t)try{yield this.unblockAutoplay()}catch(i){d.w("[AudioOutputManager]","unblockAutoplay failed after setDevice",i)}return t})}unblockAutoplay(){return c(this,null,function*(){yield this.audioSinkManager.unblockAutoplay(),yield ne.resumeContext()})}};var ii=class{static handleError(e){if(e.status===404)throw S.APIErrors.EndpointUnreachable("FEEDBACK",e.statusText);if(e.status>=400)throw S.APIErrors.ServerErrors(e.status,"FEEDBACK",e==null?void 0:e.statusText)}static sendFeedback(s){return c(this,arguments,function*({token:e,eventEndpoint:t="https://event.100ms.live",info:i,feedback:r}){d.d(this.TAG,`sendFeedback: feedbackEndpoint=${t} peerId=${i.peer.peer_id} session=${i.peer.session_id} `);let n=new URL("v2/client/feedback",t),o=M(m({},i),{payload:r});try{let l=yield fetch(n,{headers:{Authorization:`Bearer ${e}`},body:JSON.stringify(o),method:"POST"});try{this.handleError(l);return}catch(u){throw d.e(this.TAG,"error",u.message,l.status),u instanceof k?u:S.APIErrors.ServerErrors(l.status,"FEEDBACK",u.message)}}catch(l){let u=l;throw["Failed to fetch","NetworkError","ECONNRESET"].some(p=>u.message.includes(p))?S.APIErrors.EndpointUnreachable("FEEDBACK",u.message):u}})}};ii.TAG="[FeedbackService]";var Vn=require("eventemitter2");var U=class{constructor(e,t){this.eventName=e;this.eventEmitter=t;this.publish=e=>{this.eventEmitter.emit(this.eventName,e)};this.subscribe=e=>{this.eventEmitter.on(this.eventName,e)};this.subscribeOnce=e=>{this.eventEmitter.once(this.eventName,e)};this.unsubscribe=e=>{this.eventEmitter.off(this.eventName,e)};this.waitFor=e=>this.eventEmitter.waitFor(this.eventName,{filter:e});this.removeAllListeners=()=>{this.eventEmitter.removeAllListeners(this.eventName)}}};var Tt=class{constructor(){this.eventEmitter=new Vn.EventEmitter2;this.analytics=new U(G.ANALYTICS,this.eventEmitter);this.deviceChange=new U(G.DEVICE_CHANGE,this.eventEmitter);this.localAudioEnabled=new U(G.LOCAL_AUDIO_ENABLED,this.eventEmitter);this.localVideoEnabled=new U(G.LOCAL_VIDEO_ENABLED,this.eventEmitter);this.localVideoUnmutedNatively=new U(G.LOCAL_VIDEO_UNMUTED_NATIVELY,this.eventEmitter);this.localAudioUnmutedNatively=new U(G.LOCAL_AUDIO_UNMUTED_NATIVELY,this.eventEmitter);this.statsUpdate=new U(G.STATS_UPDATE,this.eventEmitter);this.trackDegraded=new U(G.TRACK_DEGRADED,this.eventEmitter);this.trackRestored=new U(G.TRACK_RESTORED,this.eventEmitter);this.trackAudioLevelUpdate=new U(G.TRACK_AUDIO_LEVEL_UPDATE,this.eventEmitter);this.audioPluginFailed=new U(G.AUDIO_PLUGIN_FAILED,this.eventEmitter);this.localAudioSilence=new U(G.LOCAL_AUDIO_SILENCE,this.eventEmitter);this.trackInterruption=new U(G.TRACK_INTERRUPTION,this.eventEmitter);this.policyChange=new U(G.POLICY_CHANGE,this.eventEmitter);this.localRoleUpdate=new U(G.LOCAL_ROLE_UPDATE,this.eventEmitter);this.audioTrackUpdate=new U(G.AUDIO_TRACK_UPDATE,this.eventEmitter);this.audioTrackAdded=new U(G.AUDIO_TRACK_ADDED,this.eventEmitter);this.audioTrackRemoved=new U(G.AUDIO_TRACK_REMOVED,this.eventEmitter);this.autoplayError=new U(G.AUTOPLAY_ERROR,this.eventEmitter);this.leave=new U(G.LEAVE,this.eventEmitter);this.error=new U(G.ERROR,this.eventEmitter)}};var pr=class{constructor(e,t,i){this.store=e;this.listener=t;this.audioListener=i}handleActiveSpeakers(e){var s,n,o;let t=e["speaker-list"],i=t.map(l=>({audioLevel:l.level,peer:this.store.getPeerById(l.peer_id),track:this.store.getTrackById(l.track_id)}));(s=this.audioListener)==null||s.onAudioLevelUpdate(i),this.store.updateSpeakers(i);let r=t[0];if(r){let l=this.store.getPeerById(r.peer_id);(n=this.listener)==null||n.onPeerUpdate(4,l)}else(o=this.listener)==null||o.onPeerUpdate(5,null)}};var hr=class{constructor(e){this.listener=e;this.TAG="[BroadcastManager]"}handleNotification(e,t){e==="on-broadcast"&&this.handleBroadcast(t)}handleBroadcast(e){var t,i;d.d(this.TAG,`Received Message from sender=${(t=e==null?void 0:e.peer)==null?void 0:t.peer_id}: ${e}`),(i=this.listener)==null||i.onMessageReceived(e)}};var mr=class{constructor(e,t){this.store=e;this.listener=t}handleQualityUpdate(e){var r;let i=e.peers.map(s=>{let n=this.store.getPeerById(s.peer_id);return n&&n.updateNetworkQuality(s.downlink_score),{peerID:s.peer_id,downlinkQuality:s.downlink_score}});(r=this.listener)==null||r.onConnectionQualityUpdate(i)}};var ft=class{constructor(e,t,i){this.store=e;this.eventBus=t;this.listener=i;this.TAG="[TrackManager]";this.tracksToProcess=new Map;this.handleTrackAdd=e=>{d.d(this.TAG,"ONTRACKADD",`${e}`),this.tracksToProcess.set(e.trackId,e),this.processPendingTracks()};this.handleTrackRemovedPermanently=e=>{d.d(this.TAG,"ONTRACKREMOVE permanently",e),Object.keys(e.tracks).forEach(i=>{var o;let r=this.store.getTrackState(i);if(!r)return;let s=this.store.getTrackById(i);if(!s){d.d(this.TAG,"Track not found in store");return}s.type==="audio"&&this.eventBus.audioTrackRemoved.publish(s),this.store.removeTrack(s);let n=this.store.getPeerById(r.peerId);n&&(this.removePeerTracks(n,s),(o=this.listener)==null||o.onTrackUpdate(1,s,n))})};this.handleTrackLayerUpdate=e=>{for(let t in e.tracks){let i=e.tracks[t],r=this.store.getTrackById(t);!r||!this.store.getPeerByTrackId(t)||r instanceof x&&this.setLayer(r,i)}};this.handleTrackUpdate=(e,t=!0)=>{var s,n;let i=this.store.getPeerById(e.peer.peer_id),r=e.peer;if(!i&&!r){d.d(this.TAG,"Track Update ignored - Peer not added to store");return}i||(i=be(r,this.store),this.store.addPeer(i));for(let o in e.tracks){let l=Object.assign({},(s=this.store.getTrackState(o))==null?void 0:s.trackInfo),u=e.tracks[o],p=this.store.getTrackById(o);if(this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:m(m({},l),u)}),!p||this.tracksToProcess.has(o))this.processTrackInfo(u,e.peer.peer_id,t),this.processPendingTracks();else{this.logIfRejected(p.setEnabled(!u.mute),p);let h=this.processTrackUpdate(p,l,u);h&&((n=this.listener)==null||n.onTrackUpdate(h,p,i))}}};this.processTrackInfo=(e,t,i)=>{};this.processPendingTracks=()=>{new Map(this.tracksToProcess).forEach(t=>{var s;let i=this.store.getTrackState(t.trackId);if(!i){d.d(this.TAG,"TrackState not added to store",`peerId - ${t.peerId}`,`trackId -${t.trackId}`);return}let r=this.store.getPeerById(i.peerId);if(!r){d.d(this.TAG,"Peer not added to store, peerId",i.peerId);return}t.source=i.trackInfo.source,t.peerId=r.peerId,t.logIdentifier=r.name,this.logIfRejected(t.setEnabled(!i.trackInfo.mute),t),this.addAudioTrack(r,t),this.addVideoTrack(r,t),t.type==="audio"?this.eventBus.audioTrackAdded.publish({track:t,peer:r}):(s=this.listener)==null||s.onTrackUpdate(0,t,r),this.tracksToProcess.delete(t.trackId)})}}logIfRejected(e,t){e.catch(i=>d.e(this.TAG,"could not apply mute state",`${t}`,i))}handleTrackMetadataAdd(e){d.d(this.TAG,"TRACK_METADATA_ADD",JSON.stringify(e,null,2));for(let t in e.tracks){let i=e.tracks[t];this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:i})}this.processPendingTracks()}handleTrackRemove(e,t=!0){var s;d.d(this.TAG,"ONTRACKREMOVE",`${e}`);let i=this.store.getTrackState(e.trackId);if(!i)return;if(!this.store.hasTrack(e)){d.d(this.TAG,"Track not found in store");return}if(t){this.store.removeTrack(e);let n=this.store.getPeerById(i.peerId);if(!n)return;this.removePeerTracks(n,e),(s=this.listener)==null||s.onTrackUpdate(1,e,n),e.type==="audio"&&this.eventBus.audioTrackRemoved.publish(e)}}setLayer(e,t){var s,n;let i=this.store.getPeerByTrackId(e.trackId);if(!i)return;e.setLayerFromServer(t)?(s=this.listener)==null||s.onTrackUpdate(5,e,i):(n=this.listener)==null||n.onTrackUpdate(6,e,i)}removePeerTracks(e,t){let i=e.auxiliaryTracks.indexOf(t);i>-1?(e.auxiliaryTracks.splice(i,1),d.d(this.TAG,"auxiliary track removed",`${t}`)):t.type==="audio"&&e.audioTrack===t?(e.audioTrack=void 0,d.d(this.TAG,"audio track removed",`${t}`)):t.type==="video"&&e.videoTrack===t&&(e.videoTrack=void 0,d.d(this.TAG,"video track removed",`${t}`))}addAudioTrack(e,t){var i;t.type==="audio"&&(t.source==="regular"&&(!e.audioTrack||((i=e.audioTrack)==null?void 0:i.trackId)===t.trackId)?e.audioTrack=t:e.auxiliaryTracks.push(t),this.store.addTrack(t),d.d(this.TAG,"audio track added",`${t}`))}addVideoTrack(e,t){if(t.type!=="video")return;let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);if(i.setSimulcastDefinitons(r),this.addAsPrimaryVideoTrack(e,i))e.videoTrack?e.videoTrack.replaceTrack(i):e.videoTrack=i,this.store.addTrack(e.videoTrack);else{let s=e.auxiliaryTracks.findIndex(n=>n.trackId===i.trackId);s===-1?(e.auxiliaryTracks.push(i),this.store.addTrack(i)):(e.auxiliaryTracks[s].replaceTrack(i),this.store.addTrack(e.auxiliaryTracks[s]))}d.d(this.TAG,"video track added",`${t}`)}addAsPrimaryVideoTrack(e,t){var i;return t.source==="regular"&&(!e.videoTrack||((i=e.videoTrack)==null?void 0:i.trackId)===t.trackId)}processTrackUpdate(e,t,i){let r;return t.mute!==i.mute?(r=i.mute?2:3,e.type==="audio"&&this.eventBus.audioTrackUpdate.publish({track:e,enabled:!i.mute})):t.description!==i.description&&(r=4),r}};var Sr=class extends ft{constructor(t,i,r,s){super(t,i,s);this.transport=r;this.TAG="[OnDemandTrackManager]";this.processTrackInfo=(t,i,r=!0)=>{var u,p;if(t.type!=="video")return;let s=this.store.getPeerById(i);if(!s||!this.isPeerRoleSubscribed(i)){d.d(this.TAG,`no peer in store for peerId: ${i}`);return}let n=new Re(new MediaStream,this.transport.getSubscribeConnection()),o=Te.getEmptyVideoTrack();o.enabled=!t.mute;let l=new x(n,o,t.source,(u=this.store.getRoom())==null?void 0:u.disableNoneLayerRequest);l.setTrackId(t.track_id),l.peerId=s.peerId,l.logIdentifier=s.name,this.addVideoTrack(s,l),r&&((p=this.listener)==null||p.onTrackUpdate(0,s.videoTrack,s))}}handleTrackMetadataAdd(t){super.handleTrackMetadataAdd(t);for(let i in t.tracks)t.tracks[i].type==="video"&&this.processTrackInfo(t.tracks[i],t.peer.peer_id)}handleTrackRemove(t){let i=t.type==="video"&&t.source==="regular";super.handleTrackRemove(t,!i),i&&this.processTrackInfo({track_id:t.trackId,mute:!t.enabled,type:t.type,source:t.source,stream_id:t.stream.id},t.peerId,!1)}addAsPrimaryVideoTrack(t,i){return i.source!=="regular"?!1:!t.videoTrack||t.videoTrack.trackId===i.trackId?!0:t.videoTrack.enabled&&ve(t.videoTrack.nativeTrack)}isPeerRoleSubscribed(t){var s,n,o,l;if(!t)return!0;let i=this.store.getLocalPeer(),r=this.store.getPeerById(t);return r&&((l=(n=(s=i==null?void 0:i.role)==null?void 0:s.subscribeParams)==null?void 0:n.subscribeToRoles)==null?void 0:l.includes((o=r.role)==null?void 0:o.name))}};var gr=class{constructor(e,t,i,r){this.store=e;this.peerManager=t;this.trackManager=i;this.listener=r;this.TAG="[PeerListManager]";this.handleInitialPeerList=e=>{let t=Object.values(e.peers);this.peerManager.handlePeerList(t)};this.handleReconnectPeerList=e=>{this.handleRepeatedPeerList(e.peers)};this.handlePreviewRoomState=e=>{if(!this.store.hasRoleDetailsArrived())return;let t=e.peers;if(t==null){e.peer_count===0&&this.handleRepeatedPeerList({});return}Object.keys(t).forEach(i=>{t[i].tracks={},t[i].is_from_room_state=!0}),this.handleRepeatedPeerList(t)};this.handleRepeatedPeerList=e=>{let t=this.store.getRemotePeers(),i=Object.values(e),r=t.filter(n=>!e[n.peerId]);r.length>0&&d.d(this.TAG,`${r}`),r.forEach(n=>{var l;let o={peer_id:n.peerId,role:((l=n.role)==null?void 0:l.name)||"",info:{name:n.name,data:n.metadata||"",user_id:n.customerUserId||"",type:n.type},tracks:{},groups:[],realtime:n.realtime};this.peerManager.handlePeerLeave(o)});let s=[];i.forEach(n=>{let o=this.store.getPeerById(n.peer_id),l=Object.values(n.tracks);o&&(this.store.getPeerTracks(o.peerId).forEach(p=>{var h;n.tracks[p.trackId]||(this.removePeerTrack(o,p.trackId),(h=this.listener)==null||h.onTrackUpdate(1,p,o))}),l.forEach(p=>{this.store.getTrackById(p.track_id)||this.store.setTrackState({peerId:o.peerId,trackInfo:p})}),this.trackManager.handleTrackUpdate({peer:n,tracks:n.tracks},!1),this.peerManager.handlePeerUpdate(n)),s.push(n)}),s.length>0&&this.peerManager.handlePeerList(s)}}handleNotification(e,t,i){if(e==="peer-list"){let r=t;i?(d.d(this.TAG,"RECONNECT_PEER_LIST event",JSON.stringify(r,null,2)),this.handleReconnectPeerList(r)):(d.d(this.TAG,"PEER_LIST event",JSON.stringify(r,null,2)),this.handleInitialPeerList(r))}else if(e==="room-state"){let r=t;this.handlePreviewRoomState(r)}}removePeerTrack(e,t){var i,r;if(d.d(this.TAG,`removing track - ${t} from ${e}`),((i=e.audioTrack)==null?void 0:i.trackId)===t)e.audioTrack=void 0;else if(((r=e.videoTrack)==null?void 0:r.trackId)===t)e.videoTrack=void 0;else{let s=e.auxiliaryTracks.findIndex(n=>n.trackId===t);s>=0&&e.auxiliaryTracks.splice(s,1)}}};var L=a=>a?new Date(a):void 0;var Tr=class{constructor(e,t,i){this.store=e;this.trackManager=t;this.listener=i;this.TAG="[PeerManager]";this.handlePeerList=e=>{var r,s;if(e.length===0){(r=this.listener)==null||r.onPeerUpdate(9,[]);return}let t=[],i=new Set(e.map(n=>n.peer_id));this.store.getRemotePeers().forEach(({peerId:n,fromRoomState:o})=>{!i.has(n)&&o&&this.store.removePeer(n)});for(let n of e)t.push(this.makePeer(n));(s=this.listener)==null||s.onPeerUpdate(9,t),this.trackManager.processPendingTracks()};this.handlePeerJoin=e=>{var i;let t=this.makePeer(e);(i=this.listener)==null||i.onPeerUpdate(0,t),this.trackManager.processPendingTracks()};this.handlePeerLeave=e=>{var i,r,s,n;let t=this.store.getPeerById(e.peer_id);this.store.removePeer(e.peer_id),d.d(this.TAG,"PEER_LEAVE",e.peer_id,`remainingPeers=${this.store.getPeers().length}`),t&&(t.audioTrack&&((i=this.listener)==null||i.onTrackUpdate(1,t.audioTrack,t)),t.videoTrack&&((r=this.listener)==null||r.onTrackUpdate(1,t.videoTrack,t)),(s=t.auxiliaryTracks)==null||s.forEach(o=>{var l;(l=this.listener)==null||l.onTrackUpdate(1,o,t)}),(n=this.listener)==null||n.onPeerUpdate(1,t))}}handleNotification(e,t){switch(e){case"on-peer-join":{let i=t;this.handlePeerJoin(i);break}case"on-peer-leave":{let i=t;this.handlePeerLeave(i);break}case"on-peer-update":this.handlePeerUpdate(t);break;default:break}}handlePeerUpdate(e){var s,n,o,l,u;let t=this.store.getPeerById(e.peer_id);if(!t&&e.realtime){t=this.makePeer(e),(s=this.listener)==null||s.onPeerUpdate(t.isHandRaised?12:14,t);return}if(t&&!t.isLocal&&!e.realtime){this.store.removePeer(t.peerId),(n=this.listener)==null||n.onPeerUpdate(13,t);return}if(!t){d.d(this.TAG,`peer ${e.peer_id} not found`);return}if(t.role&&t.role.name!==e.role){let p=this.store.getPolicyForRole(e.role);t.updateRole(p),this.updateSimulcastLayersForPeer(t),(o=this.listener)==null||o.onPeerUpdate(8,t)}let i=t.isHandRaised;t.updateGroups(e.groups);let r=(l=e.groups)==null?void 0:l.includes(He);i!==r&&((u=this.listener)==null||u.onPeerUpdate(12,t)),this.handlePeerInfoUpdate(m({peer:t},e.info))}handlePeerInfoUpdate({peer:e,name:t,data:i}){var r,s;e&&(t&&e.name!==t&&(e.updateName(t),(r=this.listener)==null||r.onPeerUpdate(10,e)),i&&e.metadata!==i&&(e.updateMetadata(i),(s=this.listener)==null||s.onPeerUpdate(11,e)))}makePeer(e){let t=this.store.getPeerById(e.peer_id);t||(t=be(e,this.store),t.realtime=e.realtime,t.joinedAt=L(e.joined_at),t.fromRoomState=!!e.is_from_room_state,this.store.addPeer(t),d.d(this.TAG,"adding to the peerList",`${t}`));for(let i in e.tracks){let r=e.tracks[i];this.store.setTrackState({peerId:e.peer_id,trackInfo:r}),r.type==="video"&&this.trackManager.processTrackInfo(r,e.peer_id,!1)}return t}updateSimulcastLayersForPeer(e){this.store.getPeerTracks(e.peerId).forEach(t=>{if(t.type==="video"&&["regular","screen"].includes(t.source)){let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);i.setSimulcastDefinitons(r)}})}};var fr=class{constructor(e,t){this.store=e;this.eventBus=t}handlePolicyChange(e){let t=this.store.getLocalPeer();if(t&&!t.role){let r=e.known_roles[e.name];t.updateRole(r)}this.store.setKnownRoles(e);let i=this.store.getRoom();i?i.templateId=e.template_id:d.w("[PolicyChangeManager]","on policy change - room not present"),this.updateLocalPeerRole(e),this.eventBus.policyChange.publish(e)}updateLocalPeerRole(e){var i;let t=this.store.getLocalPeer();if(t!=null&&t.role&&t.role.name!==e.name){let r=this.store.getPolicyForRole(e.name),s=t.role;t.updateRole(r),r.name===((i=t.asRole)==null?void 0:i.name)&&delete t.asRole,this.eventBus.localRoleUpdate.publish({oldRole:s,newRole:r})}}};var Ks=(f=>(f.FLAG_SERVER_SUB_DEGRADATION="subscribeDegradation",f.FLAG_SERVER_SIMULCAST="simulcast",f.FLAG_NON_WEBRTC_DISABLE_OFFER="nonWebRTCDisableOffer",f.FLAG_PUBLISH_STATS="publishStats",f.FLAG_SUBSCRIBE_STATS="subscribeStats",f.FLAG_ON_DEMAND_TRACKS="onDemandTracks",f.FLAG_DISABLE_VIDEO_TRACK_AUTO_UNSUBSCRIBE="disableVideoTrackAutoUnsubscribe",f.FLAG_WHITEBOARD_ENABLED="whiteboardEnabled",f.FLAG_EFFECTS_SDK_ENABLED="effectsSDKEnabled",f.FLAG_VB_ENABLED="vb",f.FLAG_HIPAA_ENABLED="hipaa",f.FLAG_NOISE_CANCELLATION="noiseCancellation",f.FLAG_SCALE_SCREENSHARE_BASED_ON_PIXELS="scaleScreenshareBasedOnPixels",f.FLAG_DISABLE_NONE_LAYER_REQUEST="disableNoneLayerRequest",f))(Ks||{});var ri=(a,e,t)=>{let i=t==="qa"?Da:wa,r=new URL(i);return r.searchParams.set("endpoint",`https://${e}`),r.searchParams.set("token",a),r.toString()};var vr=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.TAG="[HMSWhiteboardInteractivityCenter]"}get isEnabled(){return this.transport.isFlagEnabled("whiteboardEnabled")}open(e){return c(this,null,function*(){var n;if(!this.isEnabled)return d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e==null?void 0:e.id),i=t==null?void 0:t.id;if(t||(i=(yield this.transport.signal.createWhiteboard(this.getCreateOptionsWithDefaults(e))).id),!i)throw new Error(`Whiteboard ID: ${i} not found`);let r=yield this.transport.signal.getWhiteboard({id:i}),s=M(m({},t),{title:e==null?void 0:e.title,attributes:e==null?void 0:e.attributes,id:r.id,url:ri(r.token,r.addr,this.store.getEnv()),token:r.token,addr:r.addr,owner:r.owner,permissions:r.permissions||[],open:!0});this.store.setWhiteboard(s),(n=this.listener)==null||n.onWhiteboardUpdate(s)})}close(e){return c(this,null,function*(){var r;if(!this.isEnabled)return d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e);if(!t)throw new Error(`Whiteboard ID: ${e} not found`);let i={id:t.id,title:t.title,open:!1};this.store.setWhiteboard(i),(r=this.listener)==null||r.onWhiteboardUpdate(i)})}setListener(e){this.listener=e}handleLocalRoleUpdate(){return c(this,null,function*(){var t,i,r;let e=this.store.getWhiteboards();for(let s of e.values())if(s.url){let n=yield this.transport.signal.getWhiteboard({id:s.id}),o=this.store.getLocalPeer(),u=(o==null?void 0:o.customerUserId)===n.owner?(i=(t=o.role)==null?void 0:t.permissions.whiteboard)==null?void 0:i.includes("admin"):n.permissions.length>0,p=M(m({},s),{id:n.id,url:ri(n.token,n.addr,this.store.getEnv()),token:n.token,addr:n.addr,owner:n.owner,permissions:n.permissions,open:u});this.store.setWhiteboard(p),(r=this.listener)==null||r.onWhiteboardUpdate(p)}})}getCreateOptionsWithDefaults(e){var n;let t=Object.values(this.store.getKnownRoles()),i=[],r=[],s=[];return t.forEach(o=>{var l,u,p;(l=o.permissions.whiteboard)!=null&&l.includes("read")&&i.push(o.name),(u=o.permissions.whiteboard)!=null&&u.includes("write")&&r.push(o.name),(p=o.permissions.whiteboard)!=null&&p.includes("admin")&&s.push(o.name)}),{title:(e==null?void 0:e.title)||`${(n=this.store.getRoom())==null?void 0:n.id} Whiteboard`,reader:(e==null?void 0:e.reader)||i,writer:(e==null?void 0:e.writer)||r,admin:(e==null?void 0:e.admin)||s}}};var si=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.whiteboard=new vr(e,t,i)}setListener(e){this.listener=e,this.whiteboard.setListener(e)}createPoll(e){return c(this,null,function*(){var n,o;let t={customerID:"userid",peerID:"peerid",userName:"username"},{poll_id:i}=yield this.transport.signal.setPollInfo(M(m({},e),{mode:e.mode?t[e.mode]:void 0,poll_id:e.id,vote:e.rolesThatCanVote,responses:e.rolesThatCanViewResponses}));e.id||(e.id=i),Array.isArray(e.questions)&&(yield this.addQuestionsToPoll(e.id,e.questions));let r=yield this.transport.signal.getPollQuestions({poll_id:e.id,index:0,count:50}),s=Mr(M(m({},e),{poll_id:e.id,state:"created",created_by:(n=this.store.getLocalPeer())==null?void 0:n.peerId}));s.questions=r.questions.map(({question:l,options:u,answer:p})=>M(m({},l),{options:u,answer:p})),(o=this.listener)==null||o.onPollsUpdate(0,[s])})}startPoll(e){return c(this,null,function*(){typeof e=="string"?yield this.transport.signal.startPoll({poll_id:e}):(yield this.createPoll(e),yield this.transport.signal.startPoll({poll_id:e.id}))})}addQuestionsToPoll(e,t){return c(this,null,function*(){t.length>0&&(yield this.transport.signal.setPollQuestions({poll_id:e,questions:t.map((i,r)=>this.createQuestionSetParams(i,r))}))})}stopPoll(e){return c(this,null,function*(){yield this.transport.signal.stopPoll({poll_id:e})})}addResponsesToPoll(e,t){return c(this,null,function*(){let i=this.store.getPoll(e);if(!i)throw new Error("Invalid poll ID - Poll not found");let r=t.map(s=>{var o,l;let n=this.getQuestionInPoll(i,s.questionIndex);return n.type==="single-choice"?(s.option=s.option||((o=s.options)==null?void 0:o[0])||-1,delete s.text,delete s.options):n.type==="multiple-choice"?((l=s.options)==null||l.sort(),delete s.text,delete s.option):(delete s.option,delete s.options),s.skipped&&(delete s.option,delete s.options,delete s.text),m({duration:0,type:n.type,question:s.questionIndex},s)});yield this.transport.signal.setPollResponses({poll_id:e,responses:r})})}fetchLeaderboard(e,t,i){return c(this,null,function*(){var p,h;let r=this.store.getPoll(e);if(!r)throw new Error("Invalid poll ID - Poll not found");let s=(h=(p=this.store.getLocalPeer())==null?void 0:p.role)==null?void 0:h.permissions,n=!!(s!=null&&s.pollRead||s!=null&&s.pollWrite);if(r.anonymous||r.state!=="stopped"||!n)return{entries:[],hasNext:!1};let o=yield this.transport.signal.fetchPollLeaderboard({poll_id:r.id,count:i,offset:t}),l={avgScore:o.avg_score,avgTime:o.avg_time,votedUsers:o.voted_users,totalUsers:o.total_users,correctUsers:o.correct_users};return{entries:o.questions.map(T=>({position:T.position,totalResponses:T.total_responses,correctResponses:T.correct_responses,duration:T.duration,peer:T.peer,score:T.score})),hasNext:!o.last,summary:l}})}getPollResponses(e,t){return c(this,null,function*(){var s,n;let i=yield this.transport.signal.getPollResponses({poll_id:e.id,index:0,count:50,self:t}),r=JSON.parse(JSON.stringify(e));(s=i.responses)==null||s.forEach(({response:o,peer:l,final:u})=>{var h,T;let p=(h=e==null?void 0:e.questions)==null?void 0:h.find(g=>g.index===o.question);if(p){let g={id:o.response_id,questionIndex:o.question,option:o.option,options:o.options,text:o.text,responseFinal:u,peer:{peerid:l.peerid,userHash:l.hash,userid:l.userid,username:l.username},skipped:o.skipped,type:o.type,update:o.update},f=p.responses&&!t?[...p.responses]:[];(T=r.questions)!=null&&T[o.question-1]&&(r.questions[o.question-1].responses=[...f,g])}}),this.store.setPoll(r),(n=this.listener)==null||n.onPollsUpdate(4,[r])})}getPolls(){return c(this,null,function*(){var s,n,o;let e=yield this.transport.signal.getPollsList({count:50,state:"started"}),t=[],i=(n=(s=this.store.getLocalPeer())==null?void 0:s.role)==null?void 0:n.permissions.pollWrite,r=[...e.polls];if(i){let l=yield this.transport.signal.getPollsList({count:50,state:"created"}),u=yield this.transport.signal.getPollsList({count:50,state:"stopped"});r=[...l.polls,...r,...u.polls]}for(let l of r){let u=yield this.transport.signal.getPollQuestions({poll_id:l.poll_id,index:0,count:50}),p=Mr(l),h=this.store.getPoll(l.poll_id);p.questions=u.questions.map(({question:T,options:g,answer:f},P)=>{var v,R;return M(m({},T),{options:g,answer:f,responses:(R=(v=h==null?void 0:h.questions)==null?void 0:v[P])==null?void 0:R.responses})}),t.push(p),this.store.setPoll(p)}return(o=this.listener)==null||o.onPollsUpdate(3,t),t})}createQuestionSetParams(e,t){var n,o;if(e.index){let l=(n=e.options)==null?void 0:n.map((u,p)=>M(m({},u),{index:p+1}));return{question:M(m({},e),{index:t+1}),options:l,answer:e.answer}}let i=M(m({},e),{index:t+1}),r,s=e.answer||{hidden:!1};return Array.isArray(e.options)&&["single-choice","multiple-choice"].includes(e.type)?(r=(o=e.options)==null?void 0:o.map((l,u)=>({index:u+1,text:l.text,weight:l.weight})),e.type==="single-choice"?s.option=e.options.findIndex(l=>l.isCorrectAnswer)+1||void 0:s.options=e.options.map((l,u)=>l.isCorrectAnswer?u+1:void 0).filter(l=>!!l)):(s==null||delete s.options,s==null||delete s.option),{question:i,options:r,answer:s}}getQuestionInPoll(e,t){var r;let i=(r=e==null?void 0:e.questions)==null?void 0:r.find(s=>s.index===t);if(!i)throw new Error("Invalid question index - Question not found in poll");return i}},Mr=a=>{let e={userid:"customerID",peerid:"peerID",username:"userName"};return{id:a.poll_id,title:a.title,startedBy:a.started_by,createdBy:a.created_by,anonymous:a.anonymous,type:a.type,duration:a.duration,locked:a.locked,mode:a.mode?e[a.mode]:void 0,visibility:a.visibility,rolesThatCanVote:a.vote||[],rolesThatCanViewResponses:a.responses||[],state:a.state,stoppedBy:a.stopped_by,startedAt:L(a.started_at),stoppedAt:L(a.stopped_at),createdAt:L(a.created_at)}};var yr=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){switch(e){case"on-poll-start":{this.handlePollStart(t);break}case"on-poll-stop":{this.handlePollStop(t);break}case"on-poll-stats":this.handlePollStats(t);break;default:break}}handlePollStart(e){return c(this,null,function*(){var i,r;let t=[];for(let s of e.polls){let n=this.store.getPoll(s.poll_id);if(n&&n.state==="started"){(i=this.listener)==null||i.onPollsUpdate(1,[n]);return}let o=yield this.transport.signal.getPollQuestions({poll_id:s.poll_id,index:0,count:50}),l=Mr(s);l.questions=o.questions.map(({question:u,options:p,answer:h})=>M(m({},u),{options:p,answer:h})),yield this.updatePollResponses(l,!0),t.push(l),this.store.setPoll(l)}(r=this.listener)==null||r.onPollsUpdate(1,t)})}handlePollStop(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let s=this.store.getPoll(r.poll_id);if(s){s.state="stopped",s.stoppedAt=L(r.stopped_at),s.stoppedBy=r.stopped_by;let n=yield this.transport.signal.getPollResult({poll_id:r.poll_id});this.updatePollResult(s,n),t.push(s)}}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(2,t))})}handlePollStats(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let s=this.store.getPoll(r.poll_id);if(!s)return;this.updatePollResult(s,r),t.push(s)}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(4,t))})}updatePollResult(e,t){var i;e.result=m({},e.result),e.result.totalUsers=t.user_count,e.result.maxUsers=t.max_user,e.result.totalResponses=t.total_response,(i=t.questions)==null||i.forEach(r=>{var n,o;let s=(n=e.questions)==null?void 0:n.find(l=>l.index===r.question);s&&(s.result=m({},s.result),s.result.correctResponses=r.correct,s.result.skippedCount=r.skipped,s.result.totalResponses=r.total,(o=r.options)==null||o.forEach((l,u)=>{var h;let p=(h=s.options)==null?void 0:h[u];p&&p.voteCount!==l&&(p.voteCount=l)}))})}updatePollResponses(e,t){return c(this,null,function*(){var r;(r=(yield this.transport.signal.getPollResponses({poll_id:e.id,index:0,count:50,self:t})).responses)==null||r.forEach(({response:s,peer:n,final:o})=>{var p;let l=(p=e==null?void 0:e.questions)==null?void 0:p.find(h=>h.index===s.question);if(!l)return;let u={id:s.response_id,questionIndex:s.question,option:s.option,options:s.options,text:s.text,responseFinal:o,peer:{peerid:n.peerid,userHash:n.hash,userid:n.userid,username:n.username},skipped:s.skipped,type:s.type,update:s.update};Array.isArray(l.responses)&&l.responses.length>0?l.responses.find(({id:h})=>h===u.id)||l.responses.push(u):l.responses=[u]})})}};var kr=class{constructor(e,t){this.store=e;this.listener=t}handleNotification(e,t){switch(e){case"on-role-change-request":this.handleRoleChangeRequest(t);break;case"on-track-update-request":this.handleTrackUpdateRequest(t);break;case"on-change-track-mute-state-request":this.handleChangeTrackStateRequest(t);break;default:return}}handleRoleChangeRequest(e){var i;let t={requestedBy:e.requested_by?this.store.getPeerById(e.requested_by):void 0,role:this.store.getPolicyForRole(e.role),token:e.token};(i=this.listener)==null||i.onRoleChangeRequest(t)}handleTrackUpdateRequest(e){let{requested_by:t,track_id:i,mute:r}=e,s=t?this.store.getPeerById(t):void 0,n=this.store.getLocalPeerTracks().find(l=>l.publishedTrackId===i);if(!n)return;let o=()=>{var l;(l=this.listener)==null||l.onChangeTrackStateRequest({requestedBy:s,track:n,enabled:!r})};if(r){if(n.enabled===!r)return;n.setEnabled(!r).then(o)}else o()}handleChangeTrackStateRequest(e){var u;let{type:t,source:i,value:r,requested_by:s}=e,n=s?this.store.getPeerById(s):void 0,o=!r,l=this.getTracksToBeUpdated({type:t,source:i,enabled:o});if(l.length!==0)if(o)(u=this.listener)==null||u.onChangeMultiTrackStateRequest({requestedBy:n,tracks:l,type:t,source:i,enabled:!0});else{let p=[];for(let h of l)p.push(h.setEnabled(!1));Promise.all(p).then(()=>{var h;(h=this.listener)==null||h.onChangeMultiTrackStateRequest({requestedBy:n,tracks:l,enabled:!1})})}}getTracksToBeUpdated({type:e,source:t,enabled:i}){let s=this.store.getLocalPeerTracks();return e&&(s=s.filter(n=>n.type===e)),t&&(s=s.filter(n=>n.source===t)),s.filter(n=>n.enabled!==i)}};var Er=class{constructor(e,t){this.store=e;this.listener=t;this.TAG="[RoomUpdateManager]"}handleNotification(e,t){switch(e){case"peer-list":this.onRoomState(t.room);break;case"on-rtmp-update":this.updateRTMPStatus(t);break;case"on-record-update":this.updateRecordingStatus(t);break;case"room-state":this.handlePreviewRoomState(t);break;case"room-info":this.handleRoomInfo(t);break;case"session-info":this.handleSessionInfo(t);break;case"on-hls-update":this.updateHLSStatus(t);break;case"on-transcription-update":this.handleTranscriptionStatus([t]);break;default:break}}handleRoomInfo(e){let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.description=e.description,t.large_room_optimization=e.large_room_optimization,t.max_size=e.max_size,t.name=e.name}handleSessionInfo(e){var i;let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.sessionId=e.session_id,t.peerCount!==e.peer_count&&(t.peerCount=e.peer_count,(i=this.listener)==null||i.onRoomUpdate("ROOM_PEER_COUNT_UPDATED",t))}handlePreviewRoomState(e){let{room:t}=e;this.onRoomState(t)}onRoomState(e){var u,p,h,T;let{recording:t,streaming:i,transcriptions:r,session_id:s,started_at:n,name:o}=e,l=this.store.getRoom();if(!l){d.w(this.TAG,"on room state - room not present");return}l.name=o,l.rtmp.running=this.isStreamingRunning((u=i==null?void 0:i.rtmp)==null?void 0:u.state),l.rtmp.startedAt=L((p=i==null?void 0:i.rtmp)==null?void 0:p.started_at),l.rtmp.state=(h=i==null?void 0:i.rtmp)==null?void 0:h.state,l.recording.server=this.getPeerListSFURecording(t),l.recording.browser=this.getPeerListBrowserRecording(t),l.recording.hls=this.getPeerListHLSRecording(t),l.hls=this.convertHls(i==null?void 0:i.hls),l.transcriptions=this.addTranscriptionDetail(r),l.sessionId=s,l.startedAt=L(n),(T=this.listener)==null||T.onRoomUpdate("RECORDING_STATE_UPDATED",l)}addTranscriptionDetail(e){return e?e.map(t=>({state:t.state,mode:t.mode,initialised_at:L(t.initialised_at),started_at:L(t.started_at),stopped_at:L(t.stopped_at),updated_at:L(t.updated_at),error:this.toSdkError(t==null?void 0:t.error),translation:t.translation})):[]}isRecordingRunning(e){return e?!["none","paused","stopped","failed"].includes(e):!1}isStreamingRunning(e){return e?!["none","stopped","failed"].includes(e):!1}initHLS(e){let t=this.store.getRoom(),i={running:!0,variants:[]};return t?(e!=null&&e.variants&&e.variants.forEach((r,s)=>{var n,o,l;r.state!=="initialised"?i.variants.push({meetingURL:r==null?void 0:r.meetingURL,url:r==null?void 0:r.url,metadata:r==null?void 0:r.metadata,playlist_type:r==null?void 0:r.playlist_type,startedAt:L((n=e==null?void 0:e.variants)==null?void 0:n[s].started_at),initialisedAt:L((o=e==null?void 0:e.variants)==null?void 0:o[s].initialised_at),state:r.state,stream_type:r==null?void 0:r.stream_type}):i.variants.push({initialisedAt:L((l=e==null?void 0:e.variants)==null?void 0:l[s].initialised_at),url:""})}),i):(d.w(this.TAG,"on hls - room not present"),i)}updateHLSStatus(e){var r;let t=this.store.getRoom(),i=e.variants&&e.variants.length>0?e.variants.some(s=>this.isStreamingRunning(s.state)):!1;if(!t){d.w(this.TAG,"on hls - room not present");return}e.enabled=i,t.hls=this.convertHls(e),(r=this.listener)==null||r.onRoomUpdate("HLS_STREAMING_STATE_UPDATED",t)}handleTranscriptionStatus(e){var i;let t=this.store.getRoom();if(!t){d.w(this.TAG,"on transcription - room not present");return}t.transcriptions=this.addTranscriptionDetail(e)||[],(i=this.listener)==null||i.onRoomUpdate("TRANSCRIPTION_STATE_UPDATED",t)}convertHls(e){var r;if(e!=null&&e.variants&&e.variants.length>0?e.variants.some(s=>s.state==="initialised"):!1)return this.initHLS(e);let i={running:!!(e!=null&&e.enabled),variants:[],error:this.toSdkError(e==null?void 0:e.error)};return(r=e==null?void 0:e.variants)==null||r.forEach(s=>{i.variants.push({meetingURL:s==null?void 0:s.meeting_url,url:s==null?void 0:s.url,metadata:s==null?void 0:s.metadata,playlist_type:s==null?void 0:s.playlist_type,startedAt:L(s==null?void 0:s.started_at),initialisedAt:L(s==null?void 0:s.initialised_at),state:s.state,stream_type:s==null?void 0:s.stream_type})}),i}getHLSRecording(e){var r,s;let t={running:!1},i=this.isRecordingRunning(e==null?void 0:e.state);return(i||(e==null?void 0:e.state)==="paused")&&(t={running:i,singleFilePerLayer:!!((r=e==null?void 0:e.hls_recording)!=null&&r.single_file_per_layer),hlsVod:!!((s=e==null?void 0:e.hls_recording)!=null&&s.hls_vod),startedAt:L(e==null?void 0:e.started_at),initialisedAt:L(e==null?void 0:e.initialised_at),state:e==null?void 0:e.state,error:this.toSdkError(e==null?void 0:e.error)}),t}getPeerListHLSRecording(e){var r,s;let t=e==null?void 0:e.hls;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),initialisedAt:L(t==null?void 0:t.initialised_at),state:t==null?void 0:t.state,singleFilePerLayer:(r=t==null?void 0:t.config)==null?void 0:r.single_file_per_layer,hlsVod:(s=t==null?void 0:t.config)==null?void 0:s.hls_vod}}getPeerListBrowserRecording(e){let t=e==null?void 0:e.browser;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}getPeerListSFURecording(e){let t=e==null?void 0:e.sfu;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}updateRecordingStatus(e){var s;let t=this.store.getRoom(),i=this.isRecordingRunning(e.state);if(!t){d.w(this.TAG,`set recording status running=${i} - room not present`);return}let r;e.type==="sfu"?(t.recording.server={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e.state},r="SERVER_RECORDING_STATE_UPDATED"):e.type==="HLS"?(t.recording.hls=this.getHLSRecording(e),r="RECORDING_STATE_UPDATED"):(t.recording.browser={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e==null?void 0:e.state},r="BROWSER_RECORDING_STATE_UPDATED"),(s=this.listener)==null||s.onRoomUpdate(r,t)}updateRTMPStatus(e){var r,s;let t=this.store.getRoom(),i=this.isStreamingRunning(e.state);if(!t){d.w(this.TAG,"on policy change - room not present");return}if(!i){t.rtmp={running:i,state:e.state,error:this.toSdkError(e.error)},(r=this.listener)==null||r.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t);return}t.rtmp={running:i,startedAt:i?L(e.started_at):void 0,state:e.state,error:this.toSdkError(e.error)},(s=this.listener)==null||s.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t)}toSdkError(e){if(!(e!=null&&e.code))return;let t=e.message||"error in streaming/recording",i=new k(e.code,"ServerErrors","NONE",t,t);return d.e(this.TAG,"error in streaming/recording",i),i}};var Pr=class{constructor(e,t){this.store=e;this.listener=t}handleNotification(e,t){e==="on-metadata-change"&&this.handleMetadataChange(t)}handleMetadataChange(e){var i;let t=e.values.map(r=>({key:r.key,value:r.data,updatedAt:L(r.updated_at),updatedBy:r.updated_by?this.store.getPeerById(r.updated_by):void 0}));(i=this.listener)==null||i.onSessionStoreUpdate(t)}};var br=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){e==="on-whiteboard-update"&&this.handleWhiteboardUpdate(t)}handleWhiteboardUpdate(e){return c(this,null,function*(){var o;let t=this.store.getLocalPeer(),i=this.store.getWhiteboard(e.id),r=e.owner===(t==null?void 0:t.peerId)||e.owner===(t==null?void 0:t.customerUserId),s=e.state==="open",n={id:e.id,title:e.title,attributes:e.attributes};if(n.open=r?i==null?void 0:i.open:s,n.owner=n.open?e.owner:void 0,n.open)if(r)n.url=i==null?void 0:i.url,n.token=i==null?void 0:i.token,n.addr=i==null?void 0:i.addr,n.permissions=i==null?void 0:i.permissions;else{let l=yield this.transport.signal.getWhiteboard({id:e.id});n.url=ri(l.token,l.addr,this.store.getEnv()),n.token=l.token,n.addr=l.addr,n.permissions=l.permissions,n.open=l.permissions.length>0}this.store.setWhiteboard(n),(o=this.listener)==null||o.onWhiteboardUpdate(n)})}};var Ir=class{constructor(e,t,i,r,s,n){this.store=e;this.transport=i;this.listener=r;this.audioListener=s;this.connectionQualityListener=n;this.TAG="[HMSNotificationManager]";this.hasConsistentRoomStateArrived=!1;this.ignoreNotification=e=>{if(e==="peer-list")this.hasConsistentRoomStateArrived=!0;else if(e==="room-state")return this.hasConsistentRoomStateArrived;return!1};this.handleTrackAdd=e=>{this.trackManager.handleTrackAdd(e)};this.handleTrackRemove=e=>{this.trackManager.handleTrackRemove(e)};this.updateLocalPeer=({name:e,metadata:t})=>{let i=this.store.getLocalPeer();this.peerManager.handlePeerInfoUpdate({peer:i,name:e,data:t})};let o=this.transport.isFlagEnabled("onDemandTracks");this.trackManager=o?new Sr(this.store,t,this.transport,this.listener):new ft(this.store,t,this.listener),this.peerManager=new Tr(this.store,this.trackManager,this.listener),this.peerListManager=new gr(this.store,this.peerManager,this.trackManager,this.listener),this.broadcastManager=new hr(this.listener),this.policyChangeManager=new fr(this.store,t),this.requestManager=new kr(this.store,this.listener),this.activeSpeakerManager=new pr(this.store,this.listener,this.audioListener),this.connectionQualityManager=new mr(this.store,this.connectionQualityListener),this.roomUpdateManager=new Er(this.store,this.listener),this.sessionMetadataManager=new Pr(this.store,this.listener),this.pollsManager=new yr(this.store,this.transport,this.listener),this.whiteboardManager=new br(this.store,this.transport,this.listener)}setListener(e){this.listener=e,this.trackManager.listener=e,this.peerManager.listener=e,this.peerListManager.listener=e,this.broadcastManager.listener=e,this.requestManager.listener=e,this.activeSpeakerManager.listener=e,this.roomUpdateManager.listener=e,this.sessionMetadataManager.listener=e,this.pollsManager.listener=e,this.whiteboardManager.listener=e}setAudioListener(e){this.audioListener=e,this.activeSpeakerManager.audioListener=e}setConnectionQualityListener(e){this.connectionQualityListener=e,this.connectionQualityManager.listener=e}handleNotification(e,t=!1){var s,n;let i=e.method,r=e.params;["active-speakers","sfu-stats","on-connection-quality-update",void 0].includes(i)||d.d(this.TAG,`Received notification - ${i}`,{notification:r}),i==="sfu-stats"&&(s=window.HMS)!=null&&s.ON_SFU_STATS&&typeof((n=window.HMS)==null?void 0:n.ON_SFU_STATS)=="function"&&window.HMS.ON_SFU_STATS(e.params),!this.ignoreNotification(i)&&(this.roomUpdateManager.handleNotification(i,r),this.peerManager.handleNotification(i,r),this.requestManager.handleNotification(i,r),this.peerListManager.handleNotification(i,r,t),this.broadcastManager.handleNotification(i,r),this.sessionMetadataManager.handleNotification(i,r),this.pollsManager.handleNotification(i,r),this.whiteboardManager.handleNotification(i,r),this.handleIsolatedMethods(i,r))}handleIsolatedMethods(e,t){switch(e){case"on-track-add":{this.trackManager.handleTrackMetadataAdd(t);break}case"on-track-update":{this.trackManager.handleTrackUpdate(t);break}case"on-track-remove":{if(!t.peer){d.d(this.TAG,`Ignoring sfu notification - ${e}`,{notification:t});return}this.trackManager.handleTrackRemovedPermanently(t);break}case"on-track-layer-update":{this.trackManager.handleTrackLayerUpdate(t);break}case"active-speakers":this.activeSpeakerManager.handleActiveSpeakers(t);break;case"on-connection-quality-update":this.connectionQualityManager.handleQualityUpdate(t);break;case"on-policy-change":this.policyChangeManager.handlePolicyChange(t);break;case"node-info":this.transport.setSFUNodeId(t.sfu_node_id);break;default:break}}};var Ar=class{constructor(e){this.transport=e;this.observedKeys=new Set}get(e){return c(this,null,function*(){let{data:t,updated_at:i}=yield this.transport.signal.getSessionMetadata(e);return{value:t,updatedAt:L(i)}})}set(e,t){return c(this,null,function*(){let{data:i,updated_at:r}=yield this.transport.signal.setSessionMetadata({key:e,data:t}),s=L(r);return{value:i,updatedAt:s}})}observe(e){return c(this,null,function*(){let t=new Set(this.observedKeys);if(e.forEach(i=>this.observedKeys.add(i)),this.observedKeys.size!==t.size)try{yield this.transport.signal.listenMetadataChange(Array.from(this.observedKeys))}catch(i){throw this.observedKeys=t,i}})}unobserve(e){return c(this,null,function*(){let t=new Set(this.observedKeys);if(this.observedKeys=new Set([...this.observedKeys].filter(i=>!e.includes(i))),this.observedKeys.size!==t.size)try{yield this.transport.signal.listenMetadataChange(Array.from(this.observedKeys))}catch(i){throw this.observedKeys=t,i}})}};var Rr=class{constructor(e,t,i="",r="",s="https://prod-init.100ms.live/init",n=!1,o){this.authToken=e;this.peerId=t;this.peerName=i;this.data=r;this.endpoint=s;this.autoSubscribeVideo=n;this.iceServers=o}};var Z=(s=>(s[s.ConnectFailed=0]="ConnectFailed",s[s.SignalDisconnect=1]="SignalDisconnect",s[s.JoinWSMessageFailed=2]="JoinWSMessageFailed",s[s.PublishIceConnectionFailed=3]="PublishIceConnectionFailed",s[s.SubscribeIceConnectionFailed=4]="SubscribeIceConnectionFailed",s))(Z||{}),Fn={0:[],1:[],2:[1],3:[1],4:[1]};var Hr=(o=>(o.Disconnected="Disconnected",o.Connecting="Connecting",o.Joined="Joined",o.Preview="Preview",o.Failed="Failed",o.Reconnecting="Reconnecting",o.Leaving="Leaving",o))(Hr||{});var Cr=class{constructor(e){this.promise=new Promise((t,i)=>{this.resolve=t,this.reject=i,e(t,i)})}};var Lr=class{constructor(e,t){this.onStateChange=e;this.sendEvent=t;this.TAG="[RetryScheduler]";this.inProgress=new Map;this.retryTaskIds=[]}schedule(o){return c(this,arguments,function*({category:e,error:t,task:i,originalState:r,maxRetryTime:s=6e4,changeState:n=!0}){yield this.scheduleTask({category:e,error:t,changeState:n,task:i,originalState:r,maxRetryTime:s,failedAt:Date.now()})})}reset(){this.retryTaskIds.forEach(e=>clearTimeout(e)),this.retryTaskIds=[],this.inProgress.clear()}isTaskInProgress(e){return!!this.inProgress.get(e)}scheduleTask(u){return c(this,arguments,function*({category:e,error:t,changeState:i,task:r,originalState:s,failedAt:n,maxRetryTime:o=6e4,failedRetryCount:l=0}){if(d.d(this.TAG,"schedule: ",{category:Z[e],error:t}),l===0){let v=this.inProgress.get(e);if(v){d.d(this.TAG,`schedule: Already a task for ${Z[e]} scheduled, waiting for its completion`),yield v.promise;return}let R=new Cr(($,ce)=>{});this.inProgress.set(e,R),this.sendEvent(t,e)}let p=!1,h=Fn[e];for(let v in h){let R=h[parseInt(v)];try{let $=this.inProgress.get(R);$&&(d.d(this.TAG,`schedule: Suspending retry task of ${Z[e]}, waiting for ${Z[R]} to recover`),yield $.promise,d.d(this.TAG,`schedule: Resuming retry task ${Z[e]} as it's dependency ${Z[R]} is recovered`))}catch($){d.d(this.TAG,`schedule: Stopping retry task of ${Z[e]} as it's dependency ${Z[R]} failed to recover`),p=!0;break}}let T=v=>{if(this.inProgress.delete(e),this.sendEvent(v,e),this.reset(),i)this.onStateChange("Failed",v);else throw v},g=Date.now()-n;if(g>=o||p)return t.description+=`. [${Z[e]}] Could not recover after ${g} milliseconds`,p&&(t.description+=` Could not recover all of it's required dependencies - [${h.map(v=>Z[v]).toString()}]`),t.isTerminal=!0,T(t);i&&this.onStateChange("Reconnecting",t);let f=this.getDelayForRetryCount(e);d.d(this.TAG,`schedule: [${Z[e]}] [failedRetryCount=${l}] Scheduling retry task in ${f}ms`);let P;try{P=yield this.setTimeoutPromise(r,f)}catch(v){P=!1;let R=v;if(R.isTerminal)return d.e(this.TAG,`[${Z[e]}] Un-caught terminal exception ${R.name} in retry-task`,v),T(R);d.w(this.TAG,`[${Z[e]}] Un-caught exception ${R.name} in retry-task, initiating retry`,v)}if(P){let v=this.inProgress.get(e);this.inProgress.delete(e),v==null||v.resolve(l),i&&this.inProgress.size===0&&this.onStateChange(s),d.d(this.TAG,`schedule: [${Z[e]}] [failedRetryCount=${l}] Recovered \u267B\uFE0F after ${g}ms`)}else yield this.scheduleTask({category:e,error:t,changeState:i,task:r,originalState:s,maxRetryTime:o,failedAt:n,failedRetryCount:l+1})})}getDelayForRetryCount(e){let t=e===2?Math.random()*2:Math.random(),i=0;return e===2?i=2+t:e===1&&(i=1),i*1e3}setTimeoutPromise(e,t){return c(this,null,function*(){return new Promise((i,r)=>{let s=window.setTimeout(()=>c(this,null,function*(){try{let n=yield e();n&&this.retryTaskIds.splice(this.retryTaskIds.indexOf(s),1),i(n)}catch(n){r(n)}}),t);this.retryTaskIds.push(s)})})}};var wr=class extends Ve{constructor(){super(100);this.localStorage=new Ee("hms-analytics");this.localStorage.clear(),this.initLocalStorageQueue()}enqueue(t){super.enqueue(t),this.localStorage.set(this.storage)}dequeue(){let t=super.dequeue();return this.localStorage.set(this.storage),t}initLocalStorageQueue(){var t;(t=this.localStorage.get())==null||t.forEach(i=>{let r=new C(i);super.enqueue(r)})}};var Dr=class{constructor(){this.TAG="[AnalyticsTransport]";this.eventCount=0;this.lastResetTime=Date.now();this.MAX_EVENTS_PER_MINUTE=200;this.RESET_INTERVAL_MS=6e4}checkRateLimit(){let e=Date.now();if(e-this.lastResetTime>=this.RESET_INTERVAL_MS&&(this.eventCount=0,this.lastResetTime=e),this.eventCount>=this.MAX_EVENTS_PER_MINUTE)throw new Error("Too many events being sent, please check the implementation.");this.eventCount++}sendEvent(e){try{this.checkRateLimit()}catch(t){throw d.w(this.TAG,"Rate limit exceeded",t),t}try{this.sendSingleEvent(e),this.flushFailedEvents()}catch(t){d.w(this.TAG,"sendEvent failed",t)}}flushFailedEvents(e){var t;try{for(d.d(this.TAG,"Flushing failed events",this.failedEvents);this.failedEvents.size()>0;){let i=this.failedEvents.dequeue();i&&(((t=i.metadata)==null?void 0:t.peer.peer_id)===e||!i.metadata.peer.peer_id?this.sendSingleEvent(i):Le.sendEvent(i))}}catch(i){d.w(this.TAG,"flushFailedEvents failed",i)}}sendSingleEvent(e){try{this.transportProvider.sendEvent(e),d.d(this.TAG,"Sent event",e.name,e)}catch(t){throw d.w(this.TAG,`${this.transportProvider.TAG}.sendEvent failed, adding to local storage events`,{event:e,error:t}),this.failedEvents.enqueue(e),t}}};var _r=class extends Dr{constructor(t){super();this.transportProvider=t;this.failedEvents=new wr}};var vt=class{constructor(e,t,i,r){this.store=e;this.eventBus=t;this.sampleWindowSize=i;this.pushInterval=r;this.shouldSendEvent=!1;this.sequenceNum=1;this.start()}start(){this.shouldSendEvent||(this.stop(),this.shouldSendEvent=!0,this.eventBus.statsUpdate.subscribe(this.handleStatsUpdate.bind(this)),this.startLoop().catch(e=>d.e("[StatsAnalytics]",e.message)))}stop(){this.shouldSendEvent&&this.sendEvent(),this.eventBus.statsUpdate.unsubscribe(this.handleStatsUpdate.bind(this)),this.shouldSendEvent=!1}startLoop(){return c(this,null,function*(){for(;this.shouldSendEvent;)yield te(this.pushInterval*1e3),this.sendEvent()})}sendEvent(){this.trackAnalytics.forEach(e=>{e.clearSamples()})}cleanTrackAnalyticsAndCreateSample(e){this.trackAnalytics.forEach(t=>{!this.store.hasTrack(t.track)&&!(t.samples.length>0)&&this.trackAnalytics.delete(t.track_id)}),e&&this.trackAnalytics.forEach(t=>{t.createSample()})}},Mt=class{constructor({track:e,ssrc:t,rid:i,kind:r,sampleWindowSize:s}){this.samples=[];this.tempStats=[];this.track=e,this.ssrc=t,this.rid=i,this.kind=r,this.track_id=this.track.trackId,this.source=this.track.source,this.sampleWindowSize=s}pushTempStat(e){this.tempStats.push(e)}createSample(){this.tempStats.length!==0&&(this.samples.push(this.collateSample()),this.prevLatestStat=this.getLatestStat(),this.tempStats.length=0)}clearSamples(){this.samples.length=0}getLatestStat(){return this.tempStats[this.tempStats.length-1]}getFirstStat(){return this.tempStats[0]}calculateSum(e){if(typeof this.getLatestStat()[e]=="number")return this.tempStats.reduce((i,r)=>i+(r[e]||0),0)}calculateAverage(e,t=!0){let i=this.calculateSum(e),r=i!==void 0?i/this.tempStats.length:void 0;return r!==void 0?t?Math.round(r):r:void 0}calculateDifferenceForSample(e){var r;let t=Number((r=this.prevLatestStat)==null?void 0:r[e])||0;return(Number(this.getLatestStat()[e])||0)-t}calculateDifferenceAverage(e,t=!0){let i=this.calculateDifferenceForSample(e)/this.tempStats.length;return t?Math.round(i):i}calculateInstancesOfHigh(e,t){if(typeof this.getLatestStat()[e]=="number")return this.tempStats.reduce((r,s)=>r+((s[e]||0)>t?1:0),0)}},Nr=(a,e)=>a&&e&&(a.frameWidth!==e.frameWidth||a.frameHeight!==e.frameHeight),Or=(a,e)=>a&&e&&a.enabled!==e.enabled,ai=a=>Object.entries(a).filter(([,e])=>e!==void 0).reduce((e,[t,i])=>(e[t]=i,e),{});var xr=class{constructor(){this.worstState=void 0;this.TAG="[CPUPressureMonitor]";this.stateRanking={nominal:0,fair:1,serious:2,critical:3};this.init()}init(){return c(this,null,function*(){if(!("PressureObserver"in window)){d.d(this.TAG,"PressureObserver API not available");return}try{this.observer=new PressureObserver(e=>{if(e.length>0){let t=e[e.length-1].state;this.updateWorstState(t)}}),yield this.observer.observe("cpu",{sampleInterval:1e4}),this.worstState="nominal",d.d(this.TAG,"CPU pressure monitoring started")}catch(e){d.e(this.TAG,"Failed to initialize CPU pressure monitoring",e)}})}updateWorstState(e){if(this.worstState===void 0){this.worstState=e;return}this.stateRanking[e]>this.stateRanking[this.worstState]&&(this.worstState=e,d.d(this.TAG,`New worst CPU state: ${this.worstState}`))}getWorstState(){return this.worstState}resetWorstState(){this.worstState!==void 0&&(this.worstState="nominal",d.d(this.TAG,"CPU worst state reset to nominal"))}stop(){if(this.observer)try{this.observer.disconnect(),d.d(this.TAG,"CPU pressure monitoring stopped")}catch(e){d.e(this.TAG,"Error stopping CPU pressure monitoring",e)}}};var ni=class extends vt{constructor(t,i,r,s){super(t,i,r,s);this.trackAnalytics=new Map;this.cpuPressureMonitor=new xr}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(n=>{n.track.type==="audio"?t.push(n.toAnalytics()):n.track.type==="video"&&i.push(n.toAnalytics())}),{audio:t,video:i,joined_at:(s=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:s.getTime(),sequence_num:this.sequenceNum++,max_window_sec:30}}sendEvent(){this.eventBus.analytics.publish(y.publishStats(this.toAnalytics())),super.sendEvent()}stop(){var t;super.stop(),(t=this.cpuPressureMonitor)==null||t.stop()}handleStatsUpdate(t){let i=!1,r=t.getLocalTrackStats();Object.keys(r).forEach(s=>{let n=r[s],o=this.store.getLocalPeerTracks().find(l=>l.getTrackIDBeingSent()===s);Object.keys(n).forEach(l=>{var g,f,P;let u=n[l];if(!o)return;let p=this.getTrackIdentifier(o.trackId,u),h=M(m({},u),{availableOutgoingBitrate:(f=(g=t.getLocalPeerStats())==null?void 0:g.publish)==null?void 0:f.availableOutgoingBitrate});if(p&&this.trackAnalytics.has(p))(P=this.trackAnalytics.get(p))==null||P.pushTempStat(h);else if(o){let v=new js({track:o,sampleWindowSize:this.sampleWindowSize,rid:u.rid,ssrc:u.ssrc.toString(),kind:u.kind,cpuPressureMonitor:this.cpuPressureMonitor});v.pushTempStat(h),this.trackAnalytics.set(this.getTrackIdentifier(o.trackId,u),v)}let T=this.trackAnalytics.get(p);T!=null&&T.shouldCreateSample()&&(i=!0)})}),this.cleanTrackAnalyticsAndCreateSample(i)}getTrackIdentifier(t,i){return i.rid?`${t}:${i.rid}`:t}},js=class extends Mt{constructor(t){super(t);this.samples=[];this.getQualityLimitation=t=>{let i=t.qualityLimitationDurations;return i&&{bandwidth_sec:i.bandwidth,cpu_sec:i.cpu,other_sec:i.other}};this.getSourceStats=t=>{if(!t.sourceStatsAvailable)return{};let i=t.sourceFrameHeight?{height_px:t.sourceFrameHeight,width_px:t.sourceFrameWidth}:void 0,r=this.calculateDifferenceForSample("sourceFrames"),s=this.calculateDifferenceForSample("framesEncoded"),n=r&&s?Math.max(0,r-s):void 0;return{source_resolution:i,source_avg_fps:this.calculateAverage("sourceFramesPerSecond"),source_total_frames:r,source_total_frames_dropped:n}};this.collateSample=()=>{var p,h,T,g,f,P;let t=this.getFirstStat(),i=this.getLatestStat(),r=i.frameHeight?{height_px:i.frameHeight,width_px:i.frameWidth}:void 0,s=this.calculateAverage("jitter",!1),n=this.calculateAverage("roundTripTime",!1),o=(p=this.cpuPressureMonitor)==null?void 0:p.getWorstState();(h=this.cpuPressureMonitor)==null||h.resetWorstState();let l=(g=(T=this.track).getMediaTrackSettings)==null?void 0:g.call(T),u=(P=(f=this.track).getPluginsMetrics)==null?void 0:P.call(f);return ai(m({timestamp:Date.now(),sample_start_ts:t.timestamp,sample_end_ts:i.timestamp,sample_duration_ms:i.timestamp-t.timestamp,avg_available_outgoing_bitrate_bps:this.calculateAverage("availableOutgoingBitrate"),avg_bitrate_bps:this.calculateAverage("bitrate"),avg_fps:this.calculateAverage("framesPerSecond"),total_packets_lost:i.packetsLost,total_packets_sent:i.packetsSent,total_packet_sent_delay_sec:parseFloat(this.calculateDifferenceForSample("totalPacketSendDelay").toFixed(4)),total_fir_count:this.calculateDifferenceForSample("firCount"),total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount"),avg_jitter_ms:s?Math.round(s*1e3):void 0,avg_round_trip_time_ms:n?Math.round(n*1e3):void 0,total_quality_limitation:this.getQualityLimitation(i),resolution:r,cpu_pressure_state:o,track_settings:l,effects_metrics:u&&Object.keys(u).length>0?u:void 0},this.getSourceStats(i)))};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===30||Or(i,r)||i.kind==="video"&&Nr(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples});this.cpuPressureMonitor=t.cpuPressureMonitor}};var oi=class extends vt{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(n=>{n.track.type==="audio"?t.push(n.toAnalytics()):n.track.type==="video"&&i.push(n.toAnalytics())}),{audio:t,video:i,joined_at:(s=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:s.getTime(),sequence_num:this.sequenceNum++,max_window_sec:10}}sendEvent(){this.eventBus.analytics.publish(y.subscribeStats(this.toAnalytics())),super.sendEvent()}handleStatsUpdate(t){let i=t.getAllRemoteTracksStats(),r=!1;Object.keys(i).forEach(s=>{var f,P;let n=this.store.getTrackById(s),o=i[s],l=(f=this.trackAnalytics.get(s))==null?void 0:f.getLatestStat(),p=((v,R)=>{let $=(R==null?void 0:R.jitterBufferDelay)||0,ce=(R==null?void 0:R.jitterBufferEmittedCount)||0,B=((v==null?void 0:v.jitterBufferDelay)||0)-$,de=((v==null?void 0:v.jitterBufferEmittedCount)||0)-ce;return de>0?B*1e3/de:(R==null?void 0:R.calculatedJitterBufferDelay)||0})(o,l),h=this.calculateAvSyncForStat(o,t),T=M(m({},o),{calculatedJitterBufferDelay:p,avSync:h});if(o.kind==="video"){let v=n.getPreferredLayerDefinition();T.expectedFrameHeight=v==null?void 0:v.resolution.height,T.expectedFrameWidth=v==null?void 0:v.resolution.width}if(this.trackAnalytics.has(s))(P=this.trackAnalytics.get(s))==null||P.pushTempStat(T);else if(n){let v=new Js({track:n,sampleWindowSize:this.sampleWindowSize,ssrc:o.ssrc.toString(),kind:o.kind});v.pushTempStat(T),this.trackAnalytics.set(s,v)}let g=this.trackAnalytics.get(s);g!=null&&g.shouldCreateSample()&&(r=!0)}),this.cleanTrackAnalyticsAndCreateSample(r)}calculateAvSyncForStat(t,i){if(!t.peerID||!t.estimatedPlayoutTimestamp||t.kind!=="video")return;let r=this.store.getPeerById(t.peerID),s=r==null?void 0:r.audioTrack,n=r==null?void 0:r.videoTrack;if(!(s&&n&&s.enabled&&n.enabled))return Ot;let l=i.getRemoteTrackStats(s.trackId);if(!l)return Ot;if(l.estimatedPlayoutTimestamp)return l.estimatedPlayoutTimestamp-t.estimatedPlayoutTimestamp}},Js=class extends Mt{constructor(){super(...arguments);this.samples=[];this.collateSample=()=>{let t=this.getLatestStat(),i=this.getFirstStat(),r={timestamp:Date.now(),sample_start_ts:i.timestamp,sample_end_ts:t.timestamp,sample_duration_ms:t.timestamp-i.timestamp,total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount"),avg_jitter_buffer_delay:this.calculateAverage("calculatedJitterBufferDelay",!1),avg_bitrate_bps:this.calculateAverage("bitrate")};if(t.kind==="video")return ai(M(m({},r),{avg_av_sync_ms:this.calculateAvgAvSyncForSample(),avg_frames_received_per_sec:this.calculateDifferenceAverage("framesReceived"),avg_frames_dropped_per_sec:this.calculateDifferenceAverage("framesDropped"),avg_frames_decoded_per_sec:this.calculateDifferenceAverage("framesDecoded"),frame_width:this.calculateAverage("frameWidth"),frame_height:this.calculateAverage("frameHeight"),expected_frame_width:this.calculateAverage("expectedFrameWidth"),expected_frame_height:this.calculateAverage("expectedFrameHeight"),pause_count:this.calculateDifferenceForSample("pauseCount"),pause_duration_seconds:this.calculateDifferenceForSample("totalPausesDuration"),freeze_count:this.calculateDifferenceForSample("freezeCount"),freeze_duration_seconds:this.calculateDifferenceForSample("totalFreezesDuration")}));{let s=(t.concealedSamples||0)-(t.silentConcealedSamples||0)-((i.concealedSamples||0)-(i.silentConcealedSamples||0));return ai(M(m({},r),{audio_level:this.calculateInstancesOfHigh("audioLevel",.05),audio_concealed_samples:s,audio_total_samples_received:this.calculateDifferenceForSample("totalSamplesReceived"),audio_concealment_events:this.calculateDifferenceForSample("concealmentEvents"),fec_packets_discarded:this.calculateDifferenceForSample("fecPacketsDiscarded"),fec_packets_received:this.calculateDifferenceForSample("fecPacketsReceived"),total_samples_duration:this.calculateDifferenceForSample("totalSamplesDuration"),total_packets_received:this.calculateDifferenceForSample("packetsReceived"),total_packets_lost:this.calculateDifferenceForSample("packetsLost")}))}};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===10||Or(i,r)||i.kind==="video"&&Nr(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}calculateAvgAvSyncForSample(){let i=this.tempStats.map(r=>r.avSync).filter(r=>r!==void 0&&r!==Ot);return i.length===0?Ot:i.reduce((r,s)=>r+s,0)/i.length}};var yt=(t=>(t[t.Publish=0]="Publish",t[t.Subscribe=1]="Subscribe",t))(yt||{});var ci=We(require("sdp-transform"));function Gn(a,e){var r;let t=ci.parse(a.sdp);if(!((r=t.origin)!=null&&r.username.startsWith("mozilla")))return a;let i=e?Array.from(e.values()):[];return t.media.forEach(s=>{var l,u,p;let n=(l=s.msid)==null?void 0:l.split(" ")[0],o=(u=i.find(h=>h.type===s.type&&h.stream_id===n))==null?void 0:u.track_id;o&&(s.msid=(p=s.msid)==null?void 0:p.replace(/\s(.+)/,` ${o}`))}),{type:a.type,sdp:ci.write(t)}}function $n(a,e){var s;if(!(a!=null&&a.sdp)||!e)return;let i=ci.parse(a.sdp).media.find(n=>W(n.mid)&&parseInt(n.mid)===parseInt(e));return(s=i==null?void 0:i.msid)==null?void 0:s.split(" ")[1]}function Wn(a){return a.sdp.includes("usedtx=1")?a:{type:a.type,sdp:a.sdp.replace("useinbandfec=1","useinbandfec=1;usedtx=1")}}var we="[HMSConnection]",Ze=class{constructor(e,t){this.candidates=new Array;this.role=e,this.signal=t}get iceConnectionState(){return this.nativeConnection.iceConnectionState}get connectionState(){return this.nativeConnection.connectionState}get signalingState(){return this.nativeConnection.signalingState}get action(){return this.role===0?"PUBLISH":"SUBSCRIBE"}setSfuNodeId(e){this.sfuNodeId=e}addTransceiver(e,t){return this.nativeConnection.addTransceiver(e,t)}createOffer(e,t){return c(this,null,function*(){try{let i=yield this.nativeConnection.createOffer(t);return d.d(we,`[role=${this.role}] createOffer offer=${JSON.stringify(i,null,1)}`),Wn(Gn(i,e))}catch(i){throw S.WebrtcErrors.CreateOfferFailed(this.action,i.message)}})}createAnswer(e=void 0){return c(this,null,function*(){try{let t=yield this.nativeConnection.createAnswer(e);return d.d(we,`[role=${this.role}] createAnswer answer=${JSON.stringify(t,null,1)}`),t}catch(t){throw S.WebrtcErrors.CreateAnswerFailed(this.action,t.message)}})}setLocalDescription(e){return c(this,null,function*(){try{d.d(we,`[role=${this.role}] setLocalDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setLocalDescription(e)}catch(t){throw S.WebrtcErrors.SetLocalDescriptionFailed(this.action,t.message)}})}setRemoteDescription(e){return c(this,null,function*(){try{d.d(we,`[role=${this.role}] setRemoteDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setRemoteDescription(e)}catch(t){throw S.WebrtcErrors.SetRemoteDescriptionFailed(this.action,t.message)}})}addIceCandidate(e){return c(this,null,function*(){if(this.nativeConnection.signalingState==="closed"){d.d(we,`[role=${this.role}] addIceCandidate signalling state closed`);return}d.d(we,`[role=${this.role}] addIceCandidate candidate=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.addIceCandidate(e)})}get remoteDescription(){return this.nativeConnection.remoteDescription}getSenders(){return this.nativeConnection.getSenders()}handleSelectedIceCandidatePairs(){try{(this.role===0?this.getSenders():this.getReceivers()).forEach(t=>{var r;let i=(r=t.track)==null?void 0:r.kind;if(t.transport){let s=t.transport.iceTransport,n=()=>{typeof s.getSelectedCandidatePair=="function"&&(this.selectedCandidatePair=s.getSelectedCandidatePair(),this.selectedCandidatePair&&(this.observer.onSelectedCandidatePairChange(this.selectedCandidatePair),d.d(we,`${yt[this.role]} connection`,`selected ${i||"unknown"} candidate pair`,JSON.stringify(this.selectedCandidatePair,null,2))))};typeof s.onselectedcandidatepairchange=="function"&&(s.onselectedcandidatepairchange=n),n()}})}catch(e){d.w(we,`Error in logging selected ice candidate pair for ${yt[this.role]} connection`,e)}}removeTrack(e){this.nativeConnection.signalingState!=="closed"&&this.nativeConnection.removeTrack(e)}setMaxBitrateAndFramerate(e,t){return c(this,null,function*(){let i=(t==null?void 0:t.maxBitrate)||e.settings.maxBitrate,r=e instanceof q&&e.settings.maxFramerate,s=this.getSenders().find(n=>{var o;return((o=n==null?void 0:n.track)==null?void 0:o.id)===e.getTrackIDBeingSent()});if(s){let n=s.getParameters();n.encodings.length===1&&(i&&(n.encodings[0].maxBitrate=i*1e3),r&&(n.encodings[0].maxFramerate=r)),yield s.setParameters(n)}else d.w(we,`no sender found to setMaxBitrate for track - ${e.trackId}, sentTrackId - ${e.getTrackIDBeingSent()}`)})}getStats(){return c(this,null,function*(){return yield this.nativeConnection.getStats()})}close(){this.nativeConnection.close()}getReceivers(){return this.nativeConnection.getReceivers()}};var di=class extends Ze{constructor(t,i,r){super(0,t);this.TAG="[HMSPublishConnection]";this.observer=r,this.nativeConnection=new RTCPeerConnection(i),this.channel=this.nativeConnection.createDataChannel(bi,{protocol:"SCTP"}),this.channel.onerror=s=>d.e(this.TAG,`publish data channel onerror ${s}`,s),this.nativeConnection.onicecandidate=({candidate:s})=>{s&&(this.observer.onIceCandidate(s),t.trickle(this.role,s))},this.nativeConnection.oniceconnectionstatechange=()=>{this.observer.onIceConnectionChange(this.nativeConnection.iceConnectionState)},this.nativeConnection.onconnectionstatechange=()=>{this.observer.onConnectionStateChange(this.nativeConnection.connectionState),this.nativeConnection.sctp&&(this.nativeConnection.sctp.transport.onstatechange=()=>{var s;this.observer.onDTLSTransportStateChange((s=this.nativeConnection.sctp)==null?void 0:s.transport.state)},this.nativeConnection.sctp.transport.onerror=s=>{var n;this.observer.onDTLSTransportError(new Error((n=s==null?void 0:s.error)==null?void 0:n.errorDetail)||"DTLS Transport failed")})}}close(){super.close(),this.channel.close()}initAfterJoin(){this.nativeConnection.onnegotiationneeded=()=>c(this,null,function*(){d.d(this.TAG,"onnegotiationneeded"),yield this.observer.onRenegotiationNeeded()})}};var Kn=We(require("eventemitter2")),jn=require("uuid");var li=class{constructor(e,t,i=""){this.TAG="[HMSDataChannel]";this.nativeChannel=e,this.observer=t,this.metadata=i,e.onmessage=r=>{this.observer.onMessage(r.data)}}get id(){return this.nativeChannel.id}get label(){return this.nativeChannel.label}get readyState(){return this.nativeChannel.readyState}send(e){d.d(this.TAG,`[${this.metadata}] Sending [size=${e.length}] message=${e}`),this.nativeChannel.send(e)}close(){this.nativeChannel.close()}};var qn=(a,e)=>`${a}:${e}`,ui=class extends Ze{constructor(t,i,r,s,n){super(1,t);this.isFlagEnabled=r;this.eventBus=n;this.TAG="[HMSSubscribeConnection]";this.remoteStreams=new Map;this.MAX_RETRIES=3;this.RESPONSE_TIMEOUT=1e4;this.UNPROVEN_CHANNEL_TIMEOUT=500;this.channelProven=!1;this.pendingMessageQueue=[];this.latestRequestPerState=new Map;this.closed=!1;this.pendingAborts=new Set;this.eventEmitter=new Kn.default({maxListeners:60});this.abortOnClose=t=>c(this,null,function*(){if(this.closed)throw t.catch(()=>{}),t.cancel("connection closed"),Error("Subscribe connection closed");let i,r=new Promise((s,n)=>{i=n});this.pendingAborts.add(i);try{return yield Promise.race([t,r])}finally{this.pendingAborts.delete(i),t.cancel("request settled")}});this.handlePendingApiMessages=()=>{this.eventEmitter.emit("open",!0),this.pendingMessageQueue.length>0&&(d.d(this.TAG,"Found pending message queue, sending messages"),this.pendingMessageQueue.forEach(t=>this.sendOverApiDataChannel(t)),this.pendingMessageQueue.length=0)};this.sendMessage=(t,i,r)=>c(this,null,function*(){let s=()=>this.latestRequestPerState.get(r)!==i,n=()=>(d.d(this.TAG,`Dropping ${i} - ${this.closed?"closed":"superseded"}`,t),{id:i,dropped:!0}),o,l,u=!1;for(let p=0;p<this.MAX_RETRIES;p++){o=void 0;let h=!1,T=!1;if(s())return n();try{if(yield this.waitForChannelOpen(),s())return n();this.apiChannel.send(t),h=!0;let f=!u;u=!0,T=f&&!this.channelProven,o=yield this.waitForResponse(i,f)}catch(f){if(l=f,d.w(this.TAG,`Attempt failed for ${i}`,{request:t,try:p+1,error:f}),this.closed)break;s()||this.publishRequestEvent(y.subscribeRequestRetry,r,{attempt:p,unproven:T,sent:h});continue}let g=o.error;if(g){if(g.code===404)return d.d(this.TAG,`Track not found ${i}`,{request:t,try:p+1,error:g}),o;if(d.d(this.TAG,`Failed sending ${i}`,{request:t,try:p+1,error:g}),!(Math.floor(g.code/100)===5||g.code===429)){if(s())return n();throw Error(`code=${g.code}, message=${g.message} - ${i} not retried`)}if(p<this.MAX_RETRIES-1){let P=(2+Math.random()*2)*1e3;yield Fe(P)}}else break}if(o!=null&&o.error){if(s())return n();throw Error(`code=${o.error.code}, message=${o.error.message} - ${i} after ${this.MAX_RETRIES} tries`)}if(o)return o;if(s()||this.closed)return n();throw this.publishRequestEvent(y.subscribeRequestUnanswered,r,{attempts:this.MAX_RETRIES}),Error(`No response from SFU for ${i} after ${this.MAX_RETRIES} tries - ${t}`,{cause:l})});this.waitForChannelOpen=()=>c(this,null,function*(){var t;((t=this.apiChannel)==null?void 0:t.readyState)!=="open"&&(yield this.abortOnClose(this.eventEmitter.waitFor("open",{timeout:this.RESPONSE_TIMEOUT})))});this.waitForResponse=(t,i)=>c(this,null,function*(){let r=i&&!this.channelProven,s=yield this.abortOnClose(this.eventEmitter.waitFor("message",{filter:o=>o.includes(t),timeout:r?this.UNPROVEN_CHANNEL_TIMEOUT:this.RESPONSE_TIMEOUT})),n=JSON.parse(s[0]);return d.d(this.TAG,`response for ${t} -`,JSON.stringify(n,null,2)),n});this.observer=s,this.nativeConnection=new RTCPeerConnection(i),this.initNativeConnectionCallbacks()}initNativeConnectionCallbacks(){this.nativeConnection.oniceconnectionstatechange=()=>{this.observer.onIceConnectionChange(this.nativeConnection.iceConnectionState)},this.nativeConnection.onconnectionstatechange=()=>{this.observer.onConnectionStateChange(this.nativeConnection.connectionState)},this.nativeConnection.ondatachannel=t=>{t.channel.label===bi&&(this.channelProven=!1,this.apiChannel=new li(t.channel,{onMessage:i=>{this.channelProven=!0,this.eventEmitter.emit("message",i),this.observer.onApiChannelMessage(i)}},`role=${this.role}`),t.channel.onopen=this.handlePendingApiMessages)},this.nativeConnection.onicecandidate=t=>{t.candidate!==null&&(this.observer.onIceCandidate(t.candidate),this.signal.trickle(this.role,t.candidate))},this.nativeConnection.ontrack=t=>{var p;let i=t.streams[0],r=i.id;if(!this.remoteStreams.has(r)){let h=new Re(i,this);this.remoteStreams.set(r,h)}i.addEventListener("removetrack",h=>{if(h.track.id!==t.track.id)return;let T=s.tracks.findIndex(g=>{var f;return g.nativeTrack.id===h.track.id&&t.transceiver.mid===((f=g.transceiver)==null?void 0:f.mid)});if(T>=0){let g=s.tracks[T];this.observer.onTrackRemove(g),s.tracks.splice(T,1),s.tracks.length===0&&this.remoteStreams.delete(r)}});let s=this.remoteStreams.get(r),n=t.track.kind==="audio",o=n?le:x,l=n?new o(s,t.track):new o(s,t.track,void 0,this.isFlagEnabled("disableNoneLayerRequest"));t.track.kind==="video"&&s.setVideoLayerLocally("none","addTrack","subscribeConnection"),l.transceiver=t.transceiver;let u=$n(this.remoteDescription,(p=t.transceiver)==null?void 0:p.mid);u&&l.setSdpTrackId(u),s.tracks.push(l),this.observer.onTrackAdd(l)}}cancelPendingRequest(t,i){this.latestRequestPerState.delete(qn(t,i))}sendOverApiDataChannel(t){this.apiChannel&&this.apiChannel.readyState==="open"?this.apiChannel.send(t):(d.w(this.TAG,`API Data channel not ${this.apiChannel?"open":"present"}, queueing`,t),this.pendingMessageQueue.push(t))}sendOverApiDataChannelWithResponse(t){return c(this,null,function*(){let i=(0,jn.v4)();if(t.method==="prefer-video-track-state"&&this.isFlagEnabled("disableVideoTrackAutoUnsubscribe")&&t.params.max_spatial_layer==="none")return d.d(this.TAG,"video auto unsubscribe is disabled, request is ignored"),{id:i,dropped:!0};let r=JSON.stringify(m({id:i,jsonrpc:"2.0"},t)),s=qn(t.method,t.params.track_id);this.latestRequestPerState.set(s,i);try{return yield this.sendMessage(r,i,s)}finally{this.latestRequestPerState.get(s)===i&&this.latestRequestPerState.delete(s)}})}close(){var t;this.closed=!0,super.close(),(t=this.apiChannel)==null||t.close(),this.pendingAborts.forEach(i=>i(Error("Subscribe connection closed"))),this.pendingAborts.clear()}publishRequestEvent(t,i,r){var n;let s=i.indexOf(":");(n=this.eventBus)==null||n.analytics.publish(t(M(m({},r),{method:i.slice(0,s),trackId:i.slice(s+1)})))}};var Qn=(a,e)=>!e||e.length===0?a:e.map(i=>({urls:i.urls,credentialType:"password",credential:i.password,username:i.userName}));var Br="[InitService]",pi=class{static handleError(e,t){switch(e.status){case 404:throw S.APIErrors.EndpointUnreachable("INIT",t.message||e.statusText);case 200:break;default:throw S.APIErrors.ServerErrors(t.code||e.status,"INIT",t.message||(e==null?void 0:e.statusText))}}static fetchInitConfig(o){return c(this,arguments,function*({token:e,peerId:t,userAgent:i,initEndpoint:r="https://prod-init.100ms.live",region:s="",iceServers:n}){d.d(Br,`fetchInitConfig: initEndpoint=${r} token=${e} peerId=${t} region=${s} `);let l=qd(r,t,i,s);try{let u=yield fetch(l,{headers:{Authorization:`Bearer ${e}`}});try{let p=yield u.clone().json();return this.handleError(u,p),d.d(Br,`config is ${JSON.stringify(p,null,2)}`),Kd(p,n)}catch(p){let h=yield u.text();throw d.e(Br,"json error",p.message,h),p instanceof k?p:S.APIErrors.ServerErrors(u.status,"INIT",p.message)}}catch(u){let p=u;throw["Failed to fetch","NetworkError","ECONNRESET"].some(h=>p.message.includes(h))?S.APIErrors.EndpointUnreachable("INIT",p.message):p}})}};function qd(a,e,t,i){try{let r=new URL("/init",a);return i&&i.trim().length>0&&r.searchParams.set("region",i.trim()),r.searchParams.set("peer_id",e),r.searchParams.set("user_agent_v2",t),r.toString()}catch(r){let s=r;throw d.e(Br,s.name,s.message),s}}function Kd(a,e){var t;return M(m({},a),{rtcConfiguration:M(m({},a.rtcConfiguration),{iceServers:Qn((t=a.rtcConfiguration)==null?void 0:t.ice_servers,e)})})}var Jn=require("uuid");var hi=class{constructor(e){this.TAG="[SIGNAL]: ";this.pongResponseTimes=new Ve(5);this.isJoinCompleted=!1;this.pendingTrickle=[];this.socket=null;this.callbacks=new Map;this._isConnected=!1;this.id=0;this.onCloseHandler=()=>{};this.resolvePingOnAnyResponse=()=>{this.callbacks.forEach((e,t)=>{var i;((i=e.metadata)==null?void 0:i.method)==="ping"&&(e.resolve({timestamp:Date.now()}),this.callbacks.delete(t))})};this.offlineListener=()=>{d.d(this.TAG,"Window network offline"),this.setIsConnected(!1,"Window network offline")};this.onlineListener=()=>{d.d(this.TAG,"Window network online"),this.observer.onNetworkOnline()};this.observer=e,window.addEventListener("offline",this.offlineListener),window.addEventListener("online",this.onlineListener),this.onMessageHandler=this.onMessageHandler.bind(this)}get isConnected(){return this._isConnected}setSfuNodeId(e){this.sfuNodeId=e}setIsConnected(e,t=""){d.d(this.TAG,`isConnected set id: ${this.id}, oldValue: ${this._isConnected}, newValue: ${e}`),this._isConnected!==e&&(this._isConnected&&!e?(this._isConnected=e,this.rejectPendingCalls(t),this.observer.onOffline(t)):!this._isConnected&&e&&(this._isConnected=e,this.observer.onOnline()))}getPongResponseTimes(){return this.pongResponseTimes.toList()}internalCall(e,t){return c(this,null,function*(){var s;let i=(0,Jn.v4)(),r={method:e,params:t,id:i,jsonrpc:"2.0"};(s=this.socket)==null||s.send(JSON.stringify(r));try{return yield new Promise((o,l)=>{this.callbacks.set(i,{resolve:o,reject:l,metadata:{method:e}})})}catch(n){if(n instanceof k)throw n;let o=n;throw S.WebsocketMethodErrors.ServerErrors(Number(o.code),Yr(e),o.message)}})}notify(e,t){var r,s;let i={method:e,params:t};((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN&&((s=this.socket)==null||s.send(JSON.stringify(i)))}open(e){return new Promise((t,i)=>{let r=!1;this.socket&&(this.socket.close(),this.socket.removeEventListener("close",this.onCloseHandler),this.socket.removeEventListener("message",this.onMessageHandler)),this.socket=new WebSocket(e);let s=()=>{d.e(this.TAG,"Error from websocket"),r=!0,i(S.WebSocketConnectionErrors.FailedToConnect("JOIN","Error opening websocket connection"))};this.onCloseHandler=o=>{d.w(`Websocket closed code=${o.code}`),r?this.setIsConnected(!1,`code: ${o.code}${o.code!==1e3?", unexpected websocket close":""}`):(r=!0,i(S.WebSocketConnectionErrors.AbnormalClose("JOIN",`Error opening websocket connection - websocket closed unexpectedly with code=${o.code}`)))},this.socket.addEventListener("error",s);let n=()=>{var o,l;r=!0,t(),this.setIsConnected(!0),this.id++,(o=this.socket)==null||o.removeEventListener("open",n),(l=this.socket)==null||l.removeEventListener("error",s),this.pingPongLoop(this.id)};this.socket.addEventListener("open",n),this.socket.addEventListener("close",this.onCloseHandler),this.socket.addEventListener("message",this.onMessageHandler)})}close(){return c(this,null,function*(){window.removeEventListener("offline",this.offlineListener),window.removeEventListener("online",this.onlineListener),this.socket?(this.socket.close(1e3,"Normal Close"),this.setIsConnected(!1,"code: 1000, normal websocket close"),this.socket.removeEventListener("close",this.onCloseHandler),this.socket.removeEventListener("message",this.onMessageHandler)):this.setIsConnected(!1,"websocket not connected yet")})}join(e,t,i,r,s,n,o){return c(this,null,function*(){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("JOIN","Failed to send join over WS connection");let l={name:e,disableVidAutoSub:i,data:t,offer:o,server_sub_degrade:r,simulcast:s,onDemandTracks:n},u=yield this.internalCall("join",l);return this.isJoinCompleted=!0,this.pendingTrickle.forEach(({target:p,candidate:h})=>this.trickle(p,h)),this.pendingTrickle.length=0,d.d(this.TAG,`join: response=${JSON.stringify(u,null,1)}`),u})}trickle(e,t){this.isJoinCompleted?this.notify("trickle",{target:e,candidate:t,sfu_node_id:this.sfuNodeId}):this.pendingTrickle.push({target:e,candidate:t})}offer(e,t){return c(this,null,function*(){return yield this.call("offer",{desc:e,tracks:Object.fromEntries(t),sfu_node_id:this.sfuNodeId})})}answer(e){this.notify("answer",{desc:e,sfu_node_id:this.sfuNodeId})}trackUpdate(e){this.notify("track-update",{tracks:Object.fromEntries(e)})}broadcast(e){return c(this,null,function*(){return yield this.call("broadcast",e)})}leave(e){this.notify("leave",{client_reason:e})}endRoom(e,t){return c(this,null,function*(){yield this.call("end-room",{lock:e,reason:t})})}sendEvent(e){if(!this.isConnected)throw Error(`${this.TAG} not connected. Could not send event ${e}`);this.notify("analytics",e.toSignalParams())}ping(e){let t=Date.now(),i=new Promise(s=>{setTimeout(()=>{s(Date.now()-t)},e+1)}),r=this.internalCall("ping",{timestamp:t}).then(()=>Date.now()-t).catch(()=>Date.now()-t);return Promise.race([i,r])}requestRoleChange(e){return c(this,null,function*(){yield this.call("role-change-request",e)})}requestBulkRoleChange(e){return c(this,null,function*(){yield this.call("role-change-request",e)})}acceptRoleChangeRequest(e){return c(this,null,function*(){yield this.call("role-change",e)})}requestTrackStateChange(e){return c(this,null,function*(){yield this.call("track-update-request",e)})}requestMultiTrackStateChange(e){return c(this,null,function*(){yield this.call("change-track-mute-state-request",e)})}removePeer(e){return c(this,null,function*(){yield this.call("peer-leave-request",e)})}startRTMPOrRecording(e){return c(this,null,function*(){yield this.call("rtmp-start",m({},e))})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.call("rtmp-stop",{})})}startHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-start",m({},e))})}stopHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-stop",m({},e))})}startTranscription(e){return c(this,null,function*(){yield this.call("transcription-start",m({},e))})}stopTranscription(e){return c(this,null,function*(){yield this.call("transcription-stop",m({},e))})}updateTranscriptionConfig(e){return c(this,null,function*(){yield this.call("transcription-config-update",m({},e))})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.call("hls-timed-metadata",m({},e))})}updatePeer(e){return c(this,null,function*(){yield this.call("peer-update",m({},e))})}getPeer(e){return c(this,null,function*(){return yield this.call("get-peer",m({},e))})}joinGroup(e){return c(this,null,function*(){return yield this.call("group-join",{name:e})})}leaveGroup(e){return c(this,null,function*(){return yield this.call("group-leave",{name:e})})}addToGroup(e,t){return c(this,null,function*(){yield this.call("group-add",{name:t,peer_id:e})})}removeFromGroup(e,t){return c(this,null,function*(){yield this.call("group-remove",{name:t,peer_id:e})})}peerIterNext(e){return c(this,null,function*(){return yield this.call("peer-iter-next",e)})}findPeers(e){return c(this,null,function*(){return yield this.call("find-peer",e)})}findPeerByName(e){return c(this,null,function*(){return yield this.call("peer-name-search",e)})}setSessionMetadata(e){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("set-metadata",m({},e))}listenMetadataChange(e){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to observe session store key due to network disconnection");return this.call("listen-metadata-change",{keys:e})}getSessionMetadata(e){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("get-metadata",{key:e})}setPollInfo(e){return this.call("poll-info-set",m({},e))}getPollInfo(e){return this.call("poll-info-get",m({},e))}setPollQuestions(e){return this.call("poll-questions-set",m({},e))}startPoll(e){return this.call("poll-start",m({},e))}stopPoll(e){return this.call("poll-stop",m({},e))}getPollQuestions(e){return this.call("poll-questions-get",m({},e))}setPollResponses(e){return this.call("poll-response",m({},e))}getPollResponses(e){return this.call("poll-responses",m({},e))}getPollsList(e){return this.call("poll-list",m({},e))}getPollResult(e){return this.call("poll-result",m({},e))}createWhiteboard(e){return this.validateConnection(),this.call("whiteboard-create",m({},e))}getWhiteboard(e){return this.validateConnection(),this.call("whiteboard-get",m({},e))}fetchPollLeaderboard(e){return this.call("poll-leaderboard",m({},e))}validateConnection(){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to send message due to network disconnection")}onMessageHandler(e){let t=e.data,i=JSON.parse(t);if(this.resolvePingOnAnyResponse(),i.id)this.handleResponseWithId(i);else if(i.method)this.handleResponseWithMethod(i);else throw Error(`WebSocket message has no 'method' or 'id' field, message=${i}`)}handleResponseWithId(e){let t=e,i=t.id;if(this.callbacks.has(i)){let r=this.callbacks.get(i);this.callbacks.delete(i),t.result?r.resolve(t.result):r.reject(t.error)}else this.observer.onNotification(t)}handleResponseWithMethod(e){switch(e.method){case"offer":this.observer.onOffer(e.params);break;case"trickle":this.observer.onTrickle(e.params);break;case"on-error":this.observer.onServerError(S.WebsocketMethodErrors.ServerErrors(Number(e.params.code),"on-error",e.params.message));break;case"on-warning":d.w(this.TAG,e.params);break;default:this.observer.onNotification(e);break}}rejectPendingCalls(e=""){this.callbacks.forEach((t,i)=>{var r,s,n,o;((r=t.metadata)==null?void 0:r.method)!=="ping"&&(d.e(this.TAG,`rejecting pending callback ${(s=t.metadata)==null?void 0:s.method}, id=${i}`),t.reject(S.WebSocketConnectionErrors.WebSocketConnectionLost((n=t.metadata)!=null&&n.method?Yr((o=t.metadata)==null?void 0:o.method):"RECONNECT_SIGNAL",e)),this.callbacks.delete(i))})}pingPongLoop(e){return c(this,null,function*(){var i,r;let t=((i=window.HMS)==null?void 0:i.PING_TIMEOUT)||12e3;if(this.isConnected){let s=yield this.ping(t);this.pongResponseTimes.enqueue(s),s>t?(d.d(this.TAG,`Pong timeout ${e}, pageHidden=${ga()}`),this.id===e&&this.setIsConnected(!1,"ping pong failure")):setTimeout(()=>{this.id===e&&this.pingPongLoop(e)},((r=window.HMS)==null?void 0:r.PING_INTERVAL)||3e3)}})}call(e,t){return c(this,null,function*(){let r=S.WebsocketMethodErrors.ServerErrors(500,e,`Default ${e} error`),s;for(s=1;s<=3;s++)try{return this.validateConnection(),d.d(this.TAG,`Try number ${s} sending ${e}`,t),yield this.internalCall(e,t)}catch(n){if(r=n,d.e(this.TAG,`Failed sending ${e} try: ${s}`,{method:e,params:t,error:r}),!(parseInt(`${r.code/100}`)===5||r.code===429||r.code===1003))break;let l=(2+Math.random()*2)*1e3;yield Fe(l)}throw d.e(`Sending ${e} over WS failed after ${Math.min(s,3)} retries`,{method:e,params:t,error:r}),r})}};var zn=()=>{if(!F||typeof navigator.connection=="undefined")return;let a=navigator.connection;return{downlink:a.downlink,downlinkMax:a.downlinkMax,effectiveType:a.effectiveType,rtt:a.rtt,saveData:a.saveData,type:a.type}};var A="[HMSTransport]:",mi=class{constructor(e,t,i,r,s,n,o){this.observer=e;this.deviceManager=t;this.store=i;this.eventBus=r;this.analyticsEventsService=s;this.analyticsTimer=n;this.pluginUsageTracker=o;this.state="Disconnected";this.trackStates=new Map;this.publishConnection=null;this.subscribeConnection=null;this.maxSubscribeBitrate=0;this.joinRetryCount=0;this.publishDisconnectTimer=0;this.onScreenshareStop=()=>{};this.screenStream=new Set;this.callbacks=new Map;this.setListener=e=>{this.listener=e};this.setOnScreenshareStop=e=>{this.onScreenshareStop=e};this.signalObserver={onOffer:e=>c(this,null,function*(){try{if(!this.subscribeConnection)return;if(e.sfu_node_id&&this.subscribeConnection.sfuNodeId&&this.subscribeConnection.sfuNodeId!==e.sfu_node_id){d.d(A,"ignoring old offer");return}yield this.subscribeConnection.setRemoteDescription(e),d.d(A,`[SUBSCRIBE] Adding ${this.subscribeConnection.candidates.length} ice-candidates`,this.subscribeConnection.candidates);for(let i of this.subscribeConnection.candidates)yield this.subscribeConnection.addIceCandidate(i);this.subscribeConnection.candidates.length=0;let t=yield this.subscribeConnection.createAnswer();yield this.subscribeConnection.setLocalDescription(t),this.signal.answer(t),d.d(A,"[role=SUBSCRIBE] onOffer renegotiation DONE \u2705")}catch(t){d.d(A,"[role=SUBSCRIBE] onOffer renegotiation FAILED \u274C",t);let i;t instanceof k?i=t:i=S.GenericErrors.Unknown("SUBSCRIBE",t.message),yield this.observer.onStateChange("Failed",i),this.eventBus.analytics.publish(y.subscribeFail(i))}}),onTrickle:e=>c(this,null,function*(){let t=e.target===0?this.publishConnection:this.subscribeConnection;t!=null&&t.remoteDescription?yield t.addIceCandidate(e.candidate):t==null||t.candidates.push(e.candidate)}),onNotification:e=>this.observer.onNotification(e),onServerError:e=>c(this,null,function*(){yield this.observer.onStateChange("Failed",e)}),onFailure:e=>{this.joinParameters&&this.retryScheduler.schedule({category:1,error:e,task:this.retrySignalDisconnectTask,originalState:this.state})},onOffline:e=>c(this,null,function*(){d.d(A,"socket offline",Hr[this.state]);try{this.state!=="Leaving"&&this.joinParameters&&this.retryScheduler.schedule({category:1,error:S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL",e),task:this.retrySignalDisconnectTask,originalState:this.state})}catch(t){console.error(t)}}),onOnline:()=>{var e;d.d(A,"socket online",Hr[this.state]),this.analyticsSignalTransport.flushFailedEvents((e=this.store.getLocalPeer())==null?void 0:e.peerId)},onNetworkOnline:()=>{this.analyticsEventsService.flushFailedClientEvents()}};this.signal=new hi(this.signalObserver);this.analyticsSignalTransport=new _r(this.signal);this.publishDtlsStateTimer=0;this.lastPublishDtlsState="new";this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){!this.doesRoleNeedWebRTC(e)&&this.doesRoleNeedWebRTC(t)&&(d.d(A,"Local peer role updated to webrtc role, creating PeerConnections and performing inital publish negotiation \u23F3"),this.createPeerConnections(),yield this.negotiateOnFirstPublish())});this.retryPublishIceFailedTask=()=>c(this,null,function*(){if(this.publishConnection){let e=new Promise((t,i)=>{this.callbacks.set(st,{promise:{resolve:t,reject:i},action:"RESTART_ICE",extra:{}})});yield this.performPublishRenegotiation({iceRestart:this.publishConnection.connectionState!=="connected"}),yield e}return!0});this.retrySubscribeIceFailedTask=()=>c(this,null,function*(){if(this.subscribeConnection&&this.subscribeConnection.connectionState!=="connected"){let e=new Promise((i,r)=>{this.callbacks.set(at,{promise:{resolve:i,reject:r},action:"RESTART_ICE",extra:{}})}),t=new Promise(i=>{setTimeout(i,6e4,!1)});return Promise.race([e,t])}return!0});this.retrySignalDisconnectTask=()=>c(this,null,function*(){var t;if(!this.joinParameters||this.state==="Leaving")return!1;d.d(A,"retrySignalDisconnectTask",{signalConnected:this.signal.isConnected}),this.signal.isConnected||(yield this.internalConnect(this.joinParameters.authToken,this.joinParameters.endpoint,this.joinParameters.peerId,this.joinParameters.iceServers));let e=(t=this.store.getRoom())!=null&&t.joinedAt?this.signal.isConnected&&(yield this.retryPublishIceFailedTask()):this.signal.isConnected;return this.signal.trackUpdate(this.trackStates),e});this.webrtcInternals=new Vi(this.store,this.eventBus);let l=(u,p)=>c(this,null,function*(){u!==this.state&&(this.state=u,yield this.observer.onStateChange(this.state,p))});this.retryScheduler=new Lr(l,this.sendErrorAnalyticsEvent.bind(this)),this.eventBus.statsUpdate.subscribe(u=>{var h,T;let p=((T=(h=u.getLocalPeerStats())==null?void 0:h.subscribe)==null?void 0:T.bitrate)||0;this.maxSubscribeBitrate=Math.max(this.maxSubscribeBitrate,p)}),this.eventBus.localAudioEnabled.subscribe(({track:u,enabled:p})=>this.trackUpdate(u,p)),this.eventBus.localVideoEnabled.subscribe(({track:u,enabled:p})=>this.trackUpdate(u,p))}getWebsocketEndpoint(){if(this.initConfig)return this.initConfig.endpoint}getWebrtcInternals(){return this.webrtcInternals}isFlagEnabled(e){var r;let t=(r=this.initConfig)==null?void 0:r.config;return((t==null?void 0:t.enabledFlags)||[]).includes(e)}setConnectivityListener(e){this.connectivityListener=e}preview(e,t,i,r,s=!1,n){return c(this,null,function*(){let o=yield this.connect(e,t,i,r,s,n);return this.state="Preview",this.observer.onStateChange(this.state),o})}join(e,t,i,r,s=!1,n){return c(this,null,function*(){d.d(A,"join: started \u23F0");try{(!this.signal.isConnected||!this.initConfig)&&(yield this.connect(e,r,t,i,s,n)),this.validateNotDisconnected("connect"),this.initConfig&&(yield this.waitForLocalRoleAvailability(),yield this.createConnectionsAndNegotiateJoin(i,s),this.initStatsAnalytics(),d.d(A,"\u2705 join: Negotiated over PUBLISH connection"))}catch(o){d.e(A,`join: failed \u274C [token=${e}]`,o),this.state="Failed";let l=o;throw l.isTerminal=l.isTerminal||l.code===500,yield this.observer.onStateChange(this.state,l),l}d.d(A,"\u2705 join: successful"),this.state="Joined",this.observer.onStateChange(this.state)})}connect(e,t,i,r,s=!1,n){return c(this,null,function*(){this.setTransportStateForConnect(),this.joinParameters=new Rr(e,i,r.name,r.metaData,t,s,n);try{return yield this.internalConnect(e,t,i,n)}catch(o){if(!(o instanceof k))throw o;if([E.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,E.WebSocketConnectionErrors.FAILED_TO_CONNECT,E.WebSocketConnectionErrors.ABNORMAL_CLOSE].includes(o.code)||o.code.toString().startsWith("5")||o.code.toString().startsWith("429")||o.code===E.APIErrors.ENDPOINT_UNREACHABLE&&!navigator.onLine){let u=()=>c(this,null,function*(){return yield this.internalConnect(e,t,i,n),!!(this.initConfig&&this.initConfig.endpoint)});yield this.retryScheduler.schedule({category:0,error:o,task:u,originalState:this.state,changeState:!1})}else throw o}})}leave(i){return c(this,arguments,function*(e,t="user request"){var r,s,n;this.retryScheduler.reset(),this.joinParameters=void 0,d.d(A,"leaving in transport");try{let o=this.pluginUsageTracker.getPluginUsage("HMSKrispPlugin");if(o&&this.eventBus.analytics.publish(y.getKrispUsage(o)),this.state="Leaving",(r=this.publishStatsAnalytics)==null||r.stop(),(s=this.subscribeStatsAnalytics)==null||s.stop(),(n=this.webrtcInternals)==null||n.cleanup(),this.clearPeerConnections(),e)try{this.signal.leave(t),d.d(A,"signal leave done")}catch(l){d.w(A,"failed to send leave on websocket to server",l)}this.analyticsEventsService.flushFailedClientEvents(),this.analyticsEventsService.reset(),yield this.signal.close()}catch(o){this.eventBus.analytics.publish(y.disconnect(o)),d.e(A,"leave: FAILED \u274C",o)}finally{this.state="Disconnected",this.observer.onStateChange(this.state)}})}publish(e){return c(this,null,function*(){var t;for(let i of e)try{yield this.publishTrack(i),(t=this.connectivityListener)==null||t.onMediaPublished(i)}catch(r){this.eventBus.analytics.publish(y.publish({devices:this.deviceManager.getDevices(),error:r}))}})}unpublish(e){return c(this,null,function*(){for(let t of e)yield this.unpublishTrack(t)})}setSFUNodeId(e){var t,i;this.signal.setSfuNodeId(e),this.sfuNodeId?e&&this.sfuNodeId!==e&&(this.sfuNodeId=e,this.handleSFUMigration()):(this.sfuNodeId=e,(t=this.publishConnection)==null||t.setSfuNodeId(e),(i=this.subscribeConnection)==null||i.setSfuNodeId(e))}handleSFUMigration(){return c(this,null,function*(){var s,n;d.time("sfu migration"),this.clearPeerConnections();let e=this.store.getPeerMap();this.store.removeRemoteTracks();for(let o in e){let l=e[o];l.isLocal||(l.audioTrack=void 0,l.videoTrack=void 0,l.auxiliaryTracks=[])}let t=this.store.getLocalPeer();if(!t)return;this.createPeerConnections(),this.trackStates.clear(),yield this.negotiateOnFirstPublish();let i=new Map;if(t.audioTrack){let o=t.audioTrack.stream;i.get(o.id)||i.set(o.id,new fe(new MediaStream));let l=t.audioTrack.clone(i.get(o.id));this.store.removeTrack(t.audioTrack),t.audioTrack.cleanup(),yield this.publishTrack(l),t.audioTrack=l}if(t.videoTrack){let o=t.videoTrack.stream;i.get(o.id)||i.set(o.id,new fe(new MediaStream)),this.store.removeTrack(t.videoTrack);let l=t.videoTrack.clone(i.get(o.id));t.videoTrack.cleanup(),yield this.publishTrack(l),t.videoTrack=l}let r=[];for(;t.auxiliaryTracks.length>0;){let o=t.auxiliaryTracks.shift();if(o){let l=o.stream;i.get(l.id)||i.set(l.id,new fe(o.source==="screen"?l.nativeStream.clone():new MediaStream)),this.store.removeTrack(o);let u=o.clone(i.get(l.id));u.type==="video"&&u.source==="screen"&&(this.screenStream.add(l.nativeStream),this.screenStream.add(u.stream.nativeStream),u.nativeTrack.addEventListener("ended",this.onScreenshareStop)),o.cleanup(),yield this.publishTrack(u),r.push(u)}}t.auxiliaryTracks=r,i.clear(),(n=(s=this.listener)==null?void 0:s.onSFUMigration)==null||n.call(s),d.timeEnd("sfu migration")})}trackUpdate(e,t){var s;let r=Array.from(this.trackStates.values()).find(n=>e.type===n.type&&e.source===n.source);if(r){let n=new Xt(M(m({},r),{mute:!t}));this.trackStates.set(r.track_id,n),d.d(A,"Track Update",this.trackStates,e),this.signal.trackUpdate(new Map([[r.track_id,n]]));let o=this.store.getLocalPeer();o&&t===e.enabled&&((s=this.listener)==null||s.onTrackUpdate(t?3:2,e,o))}}publishTrack(e){return c(this,null,function*(){e.publishedTrackId=e.getTrackIDBeingSent(),d.d(A,`\u23F3 publishTrack: trackId=${e.trackId}, toPublishTrackId=${e.publishedTrackId}`,`${e}`),this.trackStates.set(e.publishedTrackId,new Xt(e));let t=new Promise((s,n)=>{this.callbacks.set(st,{promise:{resolve:s,reject:n},action:"PUBLISH",extra:{}})}),i=e.stream;i.setConnection(this.publishConnection);let r=this.store.getSimulcastLayers(e.source);i.addTransceiver(e,r),d.time(`publish-${e.trackId}-${e.type}`),yield t,d.timeEnd(`publish-${e.trackId}-${e.type}`),this.store.addTrack(e),yield i.setMaxBitrateAndFramerate(e).then(()=>{d.d(A,`Setting maxBitrate=${e.settings.maxBitrate} kpbs${e instanceof q?` and maxFramerate=${e.settings.maxFramerate}`:""} for ${e.source} ${e.type} ${e.trackId}`)}).catch(s=>d.w(A,"Failed setting maxBitrate and maxFramerate",s)),e.isPublished=!0,d.d(A,`\u2705 publishTrack: trackId=${e.trackId}`,`${e}`,this.callbacks)})}unpublishTrack(e){return c(this,null,function*(){if(d.d(A,`\u23F3 unpublishTrack: trackId=${e.trackId}`,`${e}`),e.publishedTrackId&&this.trackStates.has(e.publishedTrackId))this.trackStates.delete(e.publishedTrackId);else{let s=Array.from(this.trackStates.values()).find(n=>e.type===n.type&&e.source===n.source);s&&this.trackStates.delete(s.track_id)}let t=new Promise((r,s)=>{this.callbacks.set(st,{promise:{resolve:r,reject:s},action:"UNPUBLISH",extra:{}})});e.stream.removeSender(e),yield t,yield e.cleanup(),e.source==="screen"&&this.screenStream&&this.screenStream.forEach(r=>{r.getTracks().forEach(s=>{s.stop()}),this.screenStream.delete(r)}),this.store.removeTrack(e),d.d(A,`\u2705 unpublishTrack: trackId=${e.trackId}`,this.callbacks)})}clearPeerConnections(){return c(this,null,function*(){var e,t;clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0,clearTimeout(this.publishDisconnectTimer),this.publishDisconnectTimer=0,this.lastPublishDtlsState="new",(e=this.publishConnection)==null||e.close(),(t=this.subscribeConnection)==null||t.close(),this.publishConnection=null,this.subscribeConnection=null})}waitForLocalRoleAvailability(){if(!this.store.hasRoleDetailsArrived())return new Promise(e=>{this.eventBus.policyChange.subscribeOnce(()=>e())})}createConnectionsAndNegotiateJoin(e,t=!1){return c(this,null,function*(){let i=this.doesLocalPeerNeedWebRTC();i&&this.createPeerConnections(),this.analyticsTimer.start("join_response_time"),yield this.negotiateJoinWithRetry({name:e.name,data:e.metaData,autoSubscribeVideo:t,isWebRTC:i}),this.analyticsTimer.end("join_response_time")})}createPeerConnections(){var t,i,r;let e=(s,n,o=!1)=>{(["disconnected","failed"].includes(n)?d.w.bind(d):d.d.bind(d))(A,`${yt[s]} ${o?"ice":""} connection state change: ${n}`)};if(this.initConfig){let s={onRenegotiationNeeded:()=>c(this,null,function*(){yield this.performPublishRenegotiation()}),onDTLSTransportStateChange:o=>{var p,h,T;if((o==="failed"?d.w.bind(d):d.d.bind(d))(A,`Publisher on dtls transport state change: ${o}`),!o||this.lastPublishDtlsState===o||(this.lastPublishDtlsState=o,this.publishDtlsStateTimer!==0&&(clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0),o!=="connecting"&&o!=="failed"))return;let u=(T=(h=(p=this.initConfig)==null?void 0:p.config)==null?void 0:h.dtlsStateTimeouts)==null?void 0:T[o];!u||u<=0||(this.publishDtlsStateTimer=window.setTimeout(()=>{var f;let g=(f=this.publishConnection)==null?void 0:f.nativeConnection.connectionState;if(g&&o&&g===o){let P=S.WebrtcErrors.ICEFailure("PUBLISH",`DTLS transport state ${o} timeout:${u}ms`,!0);this.eventBus.analytics.publish(y.disconnect(P)),this.observer.onFailure(P)}},u))},onDTLSTransportError:o=>{d.e(A,`onDTLSTransportError ${o.name} ${o.message}`,o),this.eventBus.analytics.publish(y.disconnect(o))},onIceConnectionChange:o=>c(this,null,function*(){e(0,o,!0)}),onConnectionStateChange:o=>c(this,null,function*(){var l,u,p,h,T,g,f,P;e(0,o,!1),o!=="new"&&(o==="connected"?((l=this.connectivityListener)==null||l.onICESuccess(!0),(u=this.publishConnection)==null||u.handleSelectedIceCandidatePairs()):o==="failed"?yield this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEFailure("PUBLISH",`local candidate - ${(T=(h=(p=this.publishConnection)==null?void 0:p.selectedCandidatePair)==null?void 0:h.local)==null?void 0:T.candidate}; remote candidate - ${(P=(f=(g=this.publishConnection)==null?void 0:g.selectedCandidatePair)==null?void 0:f.remote)==null?void 0:P.candidate}`)):this.publishDisconnectTimer=window.setTimeout(()=>{var v,R,$,ce,B,de,De;((v=this.publishConnection)==null?void 0:v.connectionState)!=="connected"&&this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEDisconnected("PUBLISH",`local candidate - ${(ce=($=(R=this.publishConnection)==null?void 0:R.selectedCandidatePair)==null?void 0:$.local)==null?void 0:ce.candidate}; remote candidate - ${(De=(de=(B=this.publishConnection)==null?void 0:B.selectedCandidatePair)==null?void 0:de.remote)==null?void 0:De.candidate}`))},5e3))}),onIceCandidate:o=>{var l;(l=this.connectivityListener)==null||l.onICECandidate(o,!0)},onSelectedCandidatePairChange:o=>{var l;(l=this.connectivityListener)==null||l.onSelectedICECandidatePairChange(o,!0)}},n={onApiChannelMessage:o=>{this.observer.onNotification(JSON.parse(o))},onTrackAdd:o=>{d.d(A,"[Subscribe] onTrackAdd",`${o}`),this.observer.onTrackAdd(o)},onTrackRemove:o=>{d.d(A,"[Subscribe] onTrackRemove",`${o}`),this.observer.onTrackRemove(o)},onIceConnectionChange:o=>c(this,null,function*(){var l;if(e(1,o,!0),o==="connected"){let u=this.callbacks.get(at);this.callbacks.delete(at),(l=this.connectivityListener)==null||l.onICESuccess(!1),u&&u.promise.resolve(!0)}}),onConnectionStateChange:o=>c(this,null,function*(){var l,u,p,h,T,g,f;if(e(1,o,!1),o==="failed")yield this.handleIceConnectionFailure(1,S.WebrtcErrors.ICEFailure("SUBSCRIBE",`local candidate - ${(p=(u=(l=this.subscribeConnection)==null?void 0:l.selectedCandidatePair)==null?void 0:u.local)==null?void 0:p.candidate}; remote candidate - ${(g=(T=(h=this.subscribeConnection)==null?void 0:h.selectedCandidatePair)==null?void 0:T.remote)==null?void 0:g.candidate}`));else if(o==="disconnected")setTimeout(()=>{var P,v,R,$,ce,B,de;((P=this.subscribeConnection)==null?void 0:P.connectionState)==="disconnected"&&this.handleIceConnectionFailure(1,S.WebrtcErrors.ICEDisconnected("SUBSCRIBE",`local candidate - ${($=(R=(v=this.subscribeConnection)==null?void 0:v.selectedCandidatePair)==null?void 0:R.local)==null?void 0:$.candidate}; remote candidate - ${(de=(B=(ce=this.subscribeConnection)==null?void 0:ce.selectedCandidatePair)==null?void 0:B.remote)==null?void 0:de.candidate}`))},5e3);else if(o==="connected"){(f=this.subscribeConnection)==null||f.handleSelectedIceCandidatePairs();let P=this.callbacks.get(at);this.callbacks.delete(at),P&&P.promise.resolve(!0)}}),onIceCandidate:o=>{var l;(l=this.connectivityListener)==null||l.onICECandidate(o,!1)},onSelectedCandidatePairChange:o=>{var l;(l=this.connectivityListener)==null||l.onSelectedICECandidatePairChange(o,!1)}};this.publishConnection||(this.publishConnection=new di(this.signal,this.initConfig.rtcConfiguration,s)),this.subscribeConnection||(this.subscribeConnection=new ui(this.signal,this.initConfig.rtcConfiguration,this.isFlagEnabled.bind(this),n,this.eventBus))}(r=this.webrtcInternals)==null||r.setPeerConnections({publish:(t=this.publishConnection)==null?void 0:t.nativeConnection,subscribe:(i=this.subscribeConnection)==null?void 0:i.nativeConnection})}negotiateJoinWithRetry(s){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r=!0}){try{yield this.negotiateJoin({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r})}catch(n){d.e(A,"Join negotiation failed \u274C",n);let o=n instanceof k?n:S.WebsocketMethodErrors.ServerErrors(500,"JOIN",`Websocket join error - ${n.message}`),l=parseInt(`${o.code/100}`)===5||[E.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,429].includes(o.code);if(o.code===410&&(o.isTerminal=!0),l){this.joinRetryCount=0,o.isTerminal=!1;let u=()=>c(this,null,function*(){return this.joinRetryCount++,yield this.negotiateJoin({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r})});yield this.retryScheduler.schedule({category:2,error:o,task:u,originalState:"Joined",changeState:!1})}else throw n}})}negotiateJoin(s){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r=!0}){return r?yield this.negotiateJoinWebRTC({name:e,data:t,autoSubscribeVideo:i}):yield this.negotiateJoinNonWebRTC({name:e,data:t,autoSubscribeVideo:i})})}negotiateJoinWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){if(d.d(A,"\u23F3 join: Negotiating over PUBLISH connection"),!this.publishConnection)return d.e(A,"Publish peer connection not found, cannot negotiate"),!1;let s=yield this.publishConnection.createOffer();yield this.publishConnection.setLocalDescription(s);let n=this.isFlagEnabled("subscribeDegradation"),o=this.isFlagEnabled("simulcast"),l=this.isFlagEnabled("onDemandTracks"),u=yield this.signal.join(e,t,!i,n,o,l,s);this.setSFUNodeId(u==null?void 0:u.sfu_node_id),yield this.publishConnection.setRemoteDescription(u);for(let p of this.publishConnection.candidates)yield this.publishConnection.addIceCandidate(p);return this.publishConnection.initAfterJoin(),!!u})}negotiateJoinNonWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){d.d(A,"\u23F3 join: Negotiating Non-WebRTC");let s=this.isFlagEnabled("subscribeDegradation"),n=this.isFlagEnabled("simulcast"),o=this.isFlagEnabled("onDemandTracks"),l=yield this.signal.join(e,t,!i,s,n,o);return this.setSFUNodeId(l==null?void 0:l.sfu_node_id),!!l})}negotiateOnFirstPublish(){return c(this,null,function*(){if(d.d(A,"\u23F3 Negotiating offer over PUBLISH connection"),!this.publishConnection)return d.e(A,"Publish peer connection not found, cannot negotiate"),!1;try{let e=yield this.publishConnection.createOffer(this.trackStates);yield this.publishConnection.setLocalDescription(e);let t=yield this.signal.offer(e,this.trackStates);yield this.publishConnection.setRemoteDescription(t);for(let i of this.publishConnection.candidates)yield this.publishConnection.addIceCandidate(i);return this.publishConnection.initAfterJoin(),!!t}catch(e){if(e instanceof k&&e.code===421)return!0;throw e}})}applyPublishAnswer(e,t=!0){return c(this,null,function*(){if(!this.publishConnection)return;if(this.publishConnection.signalingState==="have-local-offer"){yield this.publishConnection.setRemoteDescription(e);return}let i=this.publishConnection.signalingState;if(d.w(A,`[role=PUBLISH] discarding stale answer, state=${i}`),!t||i!=="stable")return;d.d(A,"[role=PUBLISH] re-offering after stale answer");let r=yield this.publishConnection.createOffer(this.trackStates);yield this.publishConnection.setLocalDescription(r);let s=yield this.signal.offer(r,this.trackStates);yield this.applyPublishAnswer(s,!1)})}performPublishRenegotiation(e){return c(this,null,function*(){d.d(A,"\u23F3 [role=PUBLISH] onRenegotiationNeeded START",this.trackStates);let t=this.callbacks.get(st);if(!t){d.w(A,"no callback found for renegotiation");return}if(!this.publishConnection){d.e(A,"Publish peer connection not found, cannot renegotiate");return}try{let i=yield this.publishConnection.createOffer(this.trackStates,e);yield this.publishConnection.setLocalDescription(i),d.time("renegotiation-offer-exchange");let r=yield this.signal.offer(i,this.trackStates);this.callbacks.delete(st),d.timeEnd("renegotiation-offer-exchange"),yield this.applyPublishAnswer(r),t.promise.resolve(!0),d.d(A,"[role=PUBLISH] onRenegotiationNeeded DONE \u2705")}catch(i){let r;i instanceof k?r=i:r=S.GenericErrors.Unknown("PUBLISH",i.message),r.code===421?t.promise.resolve(!0):t.promise.reject(r),d.d(A,"[role=PUBLISH] onRenegotiationNeeded FAILED \u274C")}})}handleIceConnectionFailure(e,t){return c(this,null,function*(){this.retryScheduler.isTaskInProgress(e===0?3:4)||(e===0?this.retryScheduler.schedule({category:3,error:t,task:this.retryPublishIceFailedTask,originalState:"Joined"}):this.retryScheduler.schedule({category:4,error:t,task:this.retrySubscribeIceFailedTask,originalState:"Joined"}))})}internalConnect(e,t,i,r){return c(this,null,function*(){var n,o,l;d.d(A,"connect: started \u23F0");let s=new Date;try{this.analyticsTimer.start("init_response_time"),this.initConfig=yield pi.fetchInitConfig({token:e,peerId:i,userAgent:this.store.getUserAgent(),initEndpoint:t,iceServers:r}),(n=this.connectivityListener)==null||n.onInitSuccess(this.initConfig.endpoint);let u=this.store.getRoom();return u&&(u.effectsKey=(o=this.initConfig.config.vb)==null?void 0:o.effectsKey,u.isEffectsEnabled=this.isFlagEnabled("effectsSDKEnabled"),u.disableNoneLayerRequest=this.isFlagEnabled("disableNoneLayerRequest"),u.isVBEnabled=this.isFlagEnabled("vb"),u.isHipaaEnabled=this.isFlagEnabled("hipaa"),u.isNoiseCancellationEnabledFromInit=this.isFlagEnabled("noiseCancellation")),this.analyticsTimer.end("init_response_time"),Le.setWebsocketEndpoint(this.initConfig.endpoint),this.validateNotDisconnected("post init"),yield this.openSignal(e,i),this.observer.onConnected(),(l=this.connectivityListener)==null||l.onSignallingSuccess(),this.store.setSimulcastEnabled(this.isFlagEnabled("simulcast")),d.d(A,"Adding Analytics Transport: JsonRpcSignal"),this.analyticsEventsService.setTransport(this.analyticsSignalTransport),this.analyticsEventsService.flush(),this.initConfig}catch(u){throw this.state!=="Reconnecting"&&this.eventBus.analytics.publish(y.connect(u,this.getAdditionalAnalyticsProperties(),s,new Date,t)),d.e(A,"\u274C internal connect: failed",u),u}})}validateNotDisconnected(e){if(this.state==="Disconnected")throw d.w(A,"aborting join as transport state is disconnected"),S.GenericErrors.ValidationFailed(`leave called before join could complete - stage=${e}`)}openSignal(e,t){return c(this,null,function*(){if(!this.initConfig)throw S.APIErrors.InitConfigNotAvailable("INIT","Init Config not found");d.d(A,"\u23F3 internal connect: connecting to ws endpoint",this.initConfig.endpoint);let i=new URL(this.initConfig.endpoint);i.searchParams.set("peer",t),i.searchParams.set("token",e),i.searchParams.set("user_agent_v2",this.store.getUserAgent()),i.searchParams.set("protocol_version",Ca),i.searchParams.set("protocol_spec",La),this.endpoint=i.toString(),this.analyticsTimer.start("ws_connect_time"),yield this.signal.open(this.endpoint),this.analyticsTimer.end("ws_connect_time"),this.analyticsTimer.start("on_policy_change_time"),this.analyticsTimer.start("room_state_time"),d.d(A,"\u2705 internal connect: connected to ws endpoint")})}initStatsAnalytics(){var e,t;this.isFlagEnabled("publishStats")&&(this.publishStatsAnalytics=new ni(this.store,this.eventBus,this.getValueFromInitConfig("publishStats","maxSampleWindowSize",30),this.getValueFromInitConfig("publishStats","maxSamplePushInterval",300)),(e=this.getWebrtcInternals())==null||e.start()),this.isFlagEnabled("subscribeStats")&&(this.subscribeStatsAnalytics=new oi(this.store,this.eventBus,this.getValueFromInitConfig("subscribeStats","maxSampleWindowSize",10),this.getValueFromInitConfig("subscribeStats","maxSamplePushInterval",60)),(t=this.getWebrtcInternals())==null||t.start())}getValueFromInitConfig(e,t,i){var r,s;return((s=(r=this.initConfig)==null?void 0:r.config[e])==null?void 0:s[t])||i}doesRoleNeedWebRTC(e){var r,s;if(!this.isFlagEnabled("nonWebRTCDisableOffer"))return!0;let t=!!(e.publishParams.allowed&&((r=e.publishParams.allowed)==null?void 0:r.length)>0),i=!!(e.subscribeParams.subscribeToRoles&&((s=e.subscribeParams.subscribeToRoles)==null?void 0:s.length)>0);return t||i}doesLocalPeerNeedWebRTC(){var t;let e=(t=this.store.getLocalPeer())==null?void 0:t.role;return e?this.doesRoleNeedWebRTC(e):!0}setTransportStateForConnect(){if(this.state==="Failed"&&(this.state="Disconnected"),this.state!=="Disconnected"&&this.state!=="Reconnecting")throw S.WebsocketMethodErrors.AlreadyJoined("JOIN",`Cannot join a meeting in ${this.state} state`);this.state==="Disconnected"&&(this.state="Connecting",this.observer.onStateChange(this.state))}sendErrorAnalyticsEvent(e,t){let i=this.getAdditionalAnalyticsProperties(),r;switch(t){case 0:r=y.connect(e,i);break;case 1:r=y.disconnect(e,i);break;case 2:r=y.join({error:e,time:this.analyticsTimer.getTimeTaken("join_time"),init_response_time:this.analyticsTimer.getTimeTaken("init_response_time"),ws_connect_time:this.analyticsTimer.getTimeTaken("ws_connect_time"),on_policy_change_time:this.analyticsTimer.getTimeTaken("on_policy_change_time"),local_audio_track_time:this.analyticsTimer.getTimeTaken("local_audio_track_time"),local_video_track_time:this.analyticsTimer.getTimeTaken("local_video_track_time"),retries_join:this.joinRetryCount});break;case 3:r=y.publish({error:e});break;case 4:r=y.subscribeFail(e);break}this.eventBus.analytics.publish(r)}getSubscribeConnection(){return this.subscribeConnection}getAdditionalAnalyticsProperties(){var n,o,l,u,p,h,T,g;let e=zn(),t=typeof document!="undefined"&&document.hidden,i=this.store.getRemoteVideoTracks().filter(f=>f.degraded).length,r=(u=(l=(o=(n=this.getWebrtcInternals())==null?void 0:n.getCurrentStats())==null?void 0:o.getLocalPeerStats())==null?void 0:l.publish)==null?void 0:u.bitrate,s=(g=(T=(h=(p=this.getWebrtcInternals())==null?void 0:p.getCurrentStats())==null?void 0:h.getLocalPeerStats())==null?void 0:T.subscribe)==null?void 0:g.bitrate;return{network_info:e,document_hidden:t,num_degraded_tracks:i,bitrate:{publish:r,subscribe:s},max_sub_bitrate:this.maxSubscribeBitrate,recent_pong_response_times:this.signal.getPongResponseTimes(),transport_state:this.state}}};function Vr(a){if(!a||a.length===0)throw S.APIErrors.InvalidTokenFormat("INIT","Token cannot be an empty string or undefined or null");let e=a.split(".");if(e.length!==3)throw S.APIErrors.InvalidTokenFormat("INIT","Expected 3 '.' separate fields - header, payload and signature respectively");let t=atob(e[1]);try{let i=JSON.parse(t);return{roomId:i.room_id,userId:i.user_id,role:i.role}}catch(i){throw S.APIErrors.InvalidTokenFormat("INIT",`couldn't parse to json - ${i.message}`)}}var Xn={published:!1,isInitialised:!1,isReconnecting:!1,isPreviewInProgress:!1,isPreviewCalled:!1,isJoinInProgress:!1,deviceManagersInitialised:!1},Fr=class{constructor(){this.TAG="[HMSSdk]:";this.transportState="Disconnected";this.analyticsTimer=new Ii;this.sdkState=m({},Xn);this.isDiagnostics=!1;this.playlistSettings={video:{bitrate:is},audio:{bitrate:rs}};this.handleAutoplayError=e=>{var t,i;(i=(t=this.errorListener)==null?void 0:t.onError)==null||i.call(t,e)};this.observer={onNotification:e=>{var t;if(e.method==="on-peer-leave-request"){this.handlePeerLeaveRequest(e.params);return}switch(e.method){case"on-policy-change":this.analyticsTimer.end("on_policy_change_time");break;case"peer-list":this.analyticsTimer.end("peer_list_time"),this.sendJoinAnalyticsEvent(this.sdkState.isPreviewCalled);break;case"room-state":this.analyticsTimer.end("room_state_time");break;default:}(t=this.notificationManager)==null||t.handleNotification(e,this.sdkState.isReconnecting)},onConnected:()=>{this.initNotificationManager()},onTrackAdd:e=>{var t;(t=this.notificationManager)==null||t.handleTrackAdd(e)},onTrackRemove:e=>{var t;(t=this.notificationManager)==null||t.handleTrackRemove(e)},onFailure:e=>{var t;(t=this.errorListener)==null||t.onError(e)},onStateChange:(e,t)=>c(this,null,function*(){var r,s;let i=n=>c(this,null,function*(){var o,l;yield this.internalLeave(!0,n),!this.sdkState.isPreviewInProgress&&!this.sdkState.isJoinInProgress&&((l=(o=this.errorListener)==null?void 0:o.onError)==null||l.call(o,n)),this.sdkState.isReconnecting=!1});switch(e){case"Preview":case"Joined":this.initNotificationManager(),this.transportState==="Reconnecting"&&((r=this.listener)==null||r.onReconnected());break;case"Failed":yield i(t);break;case"Reconnecting":this.sdkState.isReconnecting=!0,(s=this.listener)==null||s.onReconnecting(t);break}this.transportState=e,d.d(this.TAG,"Transport State Change",this.transportState)})};this.handlePeerLeaveRequest=e=>{var r;let t=e.requested_by?this.store.getPeerById(e.requested_by):void 0,i={roomEnded:e.room_end,reason:e.reason,requestedBy:t};(r=this.listener)==null||r.onRemovedFromRoom(i),this.internalLeave(!1)};this.handlePreviewError=e=>{var t;this.analyticsTimer.end("preview_time"),e&&((t=this.errorListener)==null||t.onError(e)),this.sendPreviewAnalyticsEvent(e),this.sdkState.isPreviewInProgress=!1};this.handleTrackInterruption=e=>{var t,i;d.d(this.TAG,"Track interruption",`{
104
104
  started: ${e.started};
105
105
  type: ${e.type};
106
106
  reason: ${e.reason};