@100mslive/hms-video-store 0.12.29 → 0.12.30
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 +6 -6
- package/dist/index.cjs.js.map +3 -3
- package/dist/index.js +6 -6
- package/dist/index.js.map +3 -3
- package/package.json +2 -2
- package/src/sdk/index.ts +0 -4
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var $o=Object.create;var yt=Object.defineProperty,Ko=Object.defineProperties,qo=Object.getOwnPropertyDescriptor,jo=Object.getOwnPropertyDescriptors,Jo=Object.getOwnPropertyNames,hi=Object.getOwnPropertySymbols,Js=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty,Qs=Object.prototype.propertyIsEnumerable,Qo=Reflect.get;var js=(a,e,t)=>e in a?yt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,h=(a,e)=>{for(var t in e||(e={}))xr.call(e,t)&&js(a,t,e[t]);if(hi)for(var t of hi(e))Qs.call(e,t)&&js(a,t,e[t]);return a},M=(a,e)=>Ko(a,jo(e));var Ur=(a,e)=>{var t={};for(var i in a)xr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&hi)for(var i of hi(a))e.indexOf(i)<0&&Qs.call(a,i)&&(t[i]=a[i]);return t};var zo=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Yo=(a,e)=>{for(var t in e)yt(a,t,{get:e[t],enumerable:!0})},zs=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jo(e))!xr.call(a,r)&&r!==t&&yt(a,r,{get:()=>e[r],enumerable:!(i=qo(e,r))||i.enumerable});return a};var Ge=(a,e,t)=>(t=a!=null?$o(Js(a)):{},zs(e||!a||!a.__esModule?yt(t,"default",{value:a,enumerable:!0}):t,a)),Xo=a=>zs(yt({},"__esModule",{value:!0}),a);var de=(a,e,t)=>Qo(Js(a),t,e);var c=(a,e,t)=>new Promise((i,r)=>{var s=d=>{try{n(t.next(d))}catch(u){r(u)}},o=d=>{try{n(t.throw(d))}catch(u){r(u)}},n=d=>d.done?i(d.value):Promise.resolve(d.value).then(s,o);n((t=t.apply(a,e)).next())});var qr=zo((Ll,an)=>{an.exports={version:"0.12.29",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","src"],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":"^1.0.1",uuid:"^8.3.2","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.36","@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:"569b73a22e6e5001deb3ba5a80effbcf73f21c20"}});var Kd={};Yo(Kd,{ConnectivityState:()=>vo,DeviceType:()=>es,Diagnostics:()=>ht,DomainCategory:()=>Gr,EventBus:()=>mt,HLSPlaylistType:()=>zr,HLSStreamType:()=>Yr,HMSAudioDeviceCategory:()=>bi,HMSAudioMode:()=>Pi,HMSAudioPluginType:()=>Mi,HMSLogLevel:()=>Fr,HMSMessageType:()=>Ys,HMSNotificationSeverity:()=>Br,HMSNotificationTypes:()=>Si,HMSPeerType:()=>Ei,HMSPlaylistType:()=>Vr,HMSPluginUnsupportedTypes:()=>yi,HMSReactiveStore:()=>Xe,HMSRecordingState:()=>Qr,HMSRoomState:()=>mi,HMSStats:()=>vt,HMSTrackExceptionTrackType:()=>Wr,HMSTranscriptionMode:()=>Zr,HMSTranscriptionState:()=>Xr,HMSVideoPluginCanvasContextType:()=>Ci,HMSVideoPluginType:()=>Hi,createDefaultStatsStore:()=>Et,createDefaultStoreState:()=>kt,getAudioDeviceCategory:()=>Ai,parsedUserAgent:()=>he,selectAppData:()=>uc,selectAppDataByPath:()=>hc,selectAudioPlaylist:()=>Ps,selectAudioPlaylistTrackByPeerID:()=>Rc,selectAudioTrackByID:()=>gc,selectAudioTrackByPeerID:()=>io,selectAudioTrackVolume:()=>Ds,selectAudioVolumeByPeerID:()=>_c,selectAuxiliaryAudioByPeerID:()=>bc,selectAuxiliaryTracksByPeerID:()=>Mc,selectAvailableRoleNames:()=>Fn,selectBroadcastMessages:()=>oo,selectBroadcastMessagesUnreadCount:()=>Bc,selectCameraStreamByPeerID:()=>vc,selectConnectionQualities:()=>Mn,selectConnectionQualityByPeerID:()=>Pc,selectDegradedTracks:()=>Nn,selectDevices:()=>vn,selectDidIJoinWithin:()=>dd,selectDominantSpeaker:()=>Rn,selectEffectsKey:()=>Xn,selectErrors:()=>Fa,selectFullAppData:()=>Fi,selectHLSState:()=>Kn,selectHMSBroadcastMessages:()=>$a,selectHMSMessages:()=>ut,selectHMSMessagesCount:()=>On,selectHMSStats:()=>Wo,selectHandRaisedPeers:()=>ic,selectHasPeerHandRaised:()=>jc,selectIsAllowedToPreviewMedia:()=>td,selectIsAllowedToPublish:()=>ed,selectIsAllowedToSubscribe:()=>Gn,selectIsAudioLocallyMuted:()=>Ls,selectIsConnectedToRoom:()=>He,selectIsEffectsEnabled:()=>zn,selectIsInPreview:()=>fs,selectIsLargeRoom:()=>Qn,selectIsLocalAudioEnabled:()=>Hn,selectIsLocalAudioPluginPresent:()=>od,selectIsLocalScreenShared:()=>Wi,selectIsLocalVideoDisplayEnabled:()=>Ts,selectIsLocalVideoEnabled:()=>Gi,selectIsLocalVideoPluginPresent:()=>ad,selectIsLocallyMutedByPeerID:()=>Dc,selectIsPeerAudioEnabled:()=>Cc,selectIsPeerVideoEnabled:()=>Lc,selectIsRoleAllowedToPublish:()=>id,selectIsScreenShareLocallyMutedByPeerID:()=>wc,selectIsSomeoneScreenSharing:()=>Cn,selectIsTranscriptionAllowedByMode:()=>zc,selectIsTranscriptionEnabled:()=>Vn,selectIsVBEnabled:()=>Yn,selectLocalAudioTrackID:()=>oe,selectLocalMediaSettings:()=>Ss,selectLocalPeer:()=>ee,selectLocalPeerID:()=>Pe,selectLocalPeerName:()=>Pn,selectLocalPeerRole:()=>Je,selectLocalPeerRoleName:()=>bn,selectLocalTrackIDs:()=>gs,selectLocalVideoTrackID:()=>z,selectMessageByMessageID:()=>Qc,selectMessageIDsInOrder:()=>ms,selectMessagesByPeerID:()=>Vc,selectMessagesByRole:()=>Fc,selectMessagesMap:()=>Ft,selectMessagesUnreadCountByPeerID:()=>Wc,selectMessagesUnreadCountByRole:()=>Gc,selectPeerAudioByID:()=>Ec,selectPeerByCondition:()=>nd,selectPeerByID:()=>X,selectPeerCount:()=>yn,selectPeerMetadata:()=>qc,selectPeerName:()=>Jc,selectPeerNameByID:()=>mc,selectPeerScreenSharing:()=>Wa,selectPeerSharingAudio:()=>Ln,selectPeerSharingAudioPlaylist:()=>_n,selectPeerSharingVideoPlaylist:()=>wn,selectPeerTypeByID:()=>Sc,selectPeers:()=>Te,selectPeersByCondition:()=>cd,selectPeersByRole:()=>$c,selectPeersByRoles:()=>Kc,selectPeersMap:()=>J,selectPeersScreenSharing:()=>Dn,selectPeersWithAudioStatus:()=>Yc,selectPermissions:()=>Ms,selectPollByID:()=>ws,selectPolls:()=>tc,selectPollsMap:()=>ys,selectPreviewRole:()=>vs,selectPreviewRoleName:()=>Ka,selectRTMPState:()=>$n,selectRecentError:()=>Tn,selectRecordingState:()=>Wn,selectRemotePeers:()=>In,selectRoleByRoleName:()=>no,selectRoleChangeRequest:()=>Zc,selectRolesMap:()=>fe,selectRoom:()=>B,selectRoomID:()=>fn,selectRoomStartTime:()=>Jn,selectRoomStarted:()=>Bn,selectRoomState:()=>te,selectScreenAudioTrackByID:()=>Tc,selectScreenShareAudioByPeerID:()=>Cs,selectScreenShareByPeerID:()=>Hc,selectScreenSharesByPeerId:()=>Hs,selectScreenVideoTrackByID:()=>fc,selectScreenshareAudioVolumeByPeerID:()=>Nc,selectSessionId:()=>jn,selectSessionMetadata:()=>ec,selectSessionStore:()=>pc,selectSimulcastLayerByTrack:()=>Oc,selectSpeakers:()=>Ga,selectTemplateAppData:()=>Zn,selectTrackAudioByID:()=>yc,selectTrackByID:()=>$t,selectTracksMap:()=>_,selectTranscriptionsState:()=>qn,selectUnreadHMSBroadcastMessagesCount:()=>Un,selectUnreadHMSMessagesCount:()=>xn,selectVideoPlaylist:()=>bs,selectVideoPlaylistAudioTrackByPeerID:()=>Ic,selectVideoPlaylistVideoTrackByPeerID:()=>Ac,selectVideoTrackByID:()=>Rs,selectVideoTrackByPeerID:()=>to,selectWhiteboard:()=>rc,selectWhiteboards:()=>qa,simulcastMapping:()=>Ne});module.exports=Xo(Kd);var mi=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(mi||{});var kt=()=>({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}),Et=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var Ys=(e=>(e.CHAT="chat",e))(Ys||{});var Br=(t=>(t.INFO="info",t.ERROR="error",t))(Br||{}),Si=(w=>(w.PEER_JOINED="PEER_JOINED",w.PEER_LEFT="PEER_LEFT",w.PEER_LIST="PEER_LIST",w.NEW_MESSAGE="NEW_MESSAGE",w.ERROR="ERROR",w.RECONNECTING="RECONNECTING",w.RECONNECTED="RECONNECTED",w.TRACK_ADDED="TRACK_ADDED",w.TRACK_REMOVED="TRACK_REMOVED",w.TRACK_MUTED="TRACK_MUTED",w.TRACK_UNMUTED="TRACK_UNMUTED",w.TRACK_DEGRADED="TRACK_DEGRADED",w.TRACK_RESTORED="TRACK_RESTORED",w.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",w.ROLE_UPDATED="ROLE_UPDATED",w.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",w.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",w.ROOM_ENDED="ROOM_ENDED",w.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",w.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",w.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",w.NAME_UPDATED="NAME_UPDATED",w.METADATA_UPDATED="METADATA_UPDATED",w.POLL_CREATED="POLL_CREATED",w.POLL_STARTED="POLL_STARTED",w.POLL_STOPPED="POLL_STOPPED",w.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",w.POLLS_LIST="POLLS_LIST",w.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",w.TRANSCRIPTION_STATE_UPDATED="TRANSCRIPTION_STATE_UPDATED",w))(Si||{});var Vr=(t=>(t.audio="audio",t.video="video",t))(Vr||{});var A=require("reselect");function We(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];Zo(s)&&(i=Pt(s)?s:i,t=bt(s)?s:t)}return{video:t,audio:i}}function Pt(a){return a&&a.type==="audio"}function bt(a){return a&&a.type==="video"}function Zo(a){return a&&a.source==="screen"}function gi(a){return a&&a.source==="audioplaylist"}function At(a){return a&&a.source==="videoplaylist"}function Xs(a){return a?!!(a!=null&&a.degraded):!1}function Ze(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function Zs(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function It(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 Fr=(d=>(d[d.VERBOSE=0]="VERBOSE",d[d.DEBUG=1]="DEBUG",d[d.INFO=2]="INFO",d[d.WARN=3]="WARN",d[d.TIME=4]="TIME",d[d.TIMEEND=5]="TIMEEND",d[d.ERROR=6]="ERROR",d[d.NONE=7]="NONE",d))(Fr||{}),en=typeof window!="undefined"&&typeof window.expect!="undefined",l=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}}}};l.level=en?7:0;var et=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var aa=require("ua-parser-js"),he=new aa.UAParser,U=typeof window!="undefined",ea,$e=typeof window=="undefined"&&!((ea=he.getBrowser().name)!=null&&ea.toLowerCase().includes("electron"));var tn=()=>!$e,tl=tn(),Rt=()=>he.getDevice().type==="mobile",oa=()=>typeof document!="undefined"&&document.hidden,na=()=>{var a;return((a=he.getOS().name)==null?void 0:a.toLowerCase())==="ios"},ta,ia,ca=(ia=(ta=he.getBrowser())==null?void 0:ta.name)==null?void 0:ia.toLowerCase().includes("safari"),ra,sa,Ti=((sa=(ra=he.getBrowser())==null?void 0:ra.name)==null?void 0:sa.toLowerCase())==="firefox";var Sa=require("uuid");var Gr=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Gr||{});function rn(){if(U&&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 tt=rn();var la=require("uuid");var P={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,o,n=!1){super(s);this.code=t;this.name=i;this.message=s;this.description=o;this.isTerminal=n;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 $o=Object.create;var yt=Object.defineProperty,Ko=Object.defineProperties,qo=Object.getOwnPropertyDescriptor,jo=Object.getOwnPropertyDescriptors,Jo=Object.getOwnPropertyNames,hi=Object.getOwnPropertySymbols,Js=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty,Qs=Object.prototype.propertyIsEnumerable,Qo=Reflect.get;var js=(a,e,t)=>e in a?yt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,h=(a,e)=>{for(var t in e||(e={}))xr.call(e,t)&&js(a,t,e[t]);if(hi)for(var t of hi(e))Qs.call(e,t)&&js(a,t,e[t]);return a},M=(a,e)=>Ko(a,jo(e));var Ur=(a,e)=>{var t={};for(var i in a)xr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&hi)for(var i of hi(a))e.indexOf(i)<0&&Qs.call(a,i)&&(t[i]=a[i]);return t};var zo=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Yo=(a,e)=>{for(var t in e)yt(a,t,{get:e[t],enumerable:!0})},zs=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jo(e))!xr.call(a,r)&&r!==t&&yt(a,r,{get:()=>e[r],enumerable:!(i=qo(e,r))||i.enumerable});return a};var Ge=(a,e,t)=>(t=a!=null?$o(Js(a)):{},zs(e||!a||!a.__esModule?yt(t,"default",{value:a,enumerable:!0}):t,a)),Xo=a=>zs(yt({},"__esModule",{value:!0}),a);var ce=(a,e,t)=>Qo(Js(a),t,e);var c=(a,e,t)=>new Promise((i,r)=>{var s=d=>{try{n(t.next(d))}catch(u){r(u)}},o=d=>{try{n(t.throw(d))}catch(u){r(u)}},n=d=>d.done?i(d.value):Promise.resolve(d.value).then(s,o);n((t=t.apply(a,e)).next())});var qr=zo((Ll,an)=>{an.exports={version:"0.12.30",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","src"],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":"^1.0.1",uuid:"^8.3.2","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.36","@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:"e5484f287d0f1d888f15068e29226eab12095a3f"}});var Kd={};Yo(Kd,{ConnectivityState:()=>vo,DeviceType:()=>es,Diagnostics:()=>ht,DomainCategory:()=>Gr,EventBus:()=>mt,HLSPlaylistType:()=>zr,HLSStreamType:()=>Yr,HMSAudioDeviceCategory:()=>bi,HMSAudioMode:()=>Pi,HMSAudioPluginType:()=>Mi,HMSLogLevel:()=>Fr,HMSMessageType:()=>Ys,HMSNotificationSeverity:()=>Br,HMSNotificationTypes:()=>Si,HMSPeerType:()=>Ei,HMSPlaylistType:()=>Vr,HMSPluginUnsupportedTypes:()=>yi,HMSReactiveStore:()=>Xe,HMSRecordingState:()=>Qr,HMSRoomState:()=>mi,HMSStats:()=>vt,HMSTrackExceptionTrackType:()=>Wr,HMSTranscriptionMode:()=>Zr,HMSTranscriptionState:()=>Xr,HMSVideoPluginCanvasContextType:()=>Ci,HMSVideoPluginType:()=>Hi,createDefaultStatsStore:()=>Et,createDefaultStoreState:()=>kt,getAudioDeviceCategory:()=>Ai,parsedUserAgent:()=>he,selectAppData:()=>uc,selectAppDataByPath:()=>hc,selectAudioPlaylist:()=>Ps,selectAudioPlaylistTrackByPeerID:()=>Rc,selectAudioTrackByID:()=>gc,selectAudioTrackByPeerID:()=>io,selectAudioTrackVolume:()=>Ds,selectAudioVolumeByPeerID:()=>_c,selectAuxiliaryAudioByPeerID:()=>bc,selectAuxiliaryTracksByPeerID:()=>Mc,selectAvailableRoleNames:()=>Fn,selectBroadcastMessages:()=>oo,selectBroadcastMessagesUnreadCount:()=>Bc,selectCameraStreamByPeerID:()=>vc,selectConnectionQualities:()=>Mn,selectConnectionQualityByPeerID:()=>Pc,selectDegradedTracks:()=>Nn,selectDevices:()=>vn,selectDidIJoinWithin:()=>dd,selectDominantSpeaker:()=>Rn,selectEffectsKey:()=>Xn,selectErrors:()=>Fa,selectFullAppData:()=>Fi,selectHLSState:()=>Kn,selectHMSBroadcastMessages:()=>$a,selectHMSMessages:()=>ut,selectHMSMessagesCount:()=>On,selectHMSStats:()=>Wo,selectHandRaisedPeers:()=>ic,selectHasPeerHandRaised:()=>jc,selectIsAllowedToPreviewMedia:()=>td,selectIsAllowedToPublish:()=>ed,selectIsAllowedToSubscribe:()=>Gn,selectIsAudioLocallyMuted:()=>Ls,selectIsConnectedToRoom:()=>He,selectIsEffectsEnabled:()=>zn,selectIsInPreview:()=>fs,selectIsLargeRoom:()=>Qn,selectIsLocalAudioEnabled:()=>Hn,selectIsLocalAudioPluginPresent:()=>od,selectIsLocalScreenShared:()=>Wi,selectIsLocalVideoDisplayEnabled:()=>Ts,selectIsLocalVideoEnabled:()=>Gi,selectIsLocalVideoPluginPresent:()=>ad,selectIsLocallyMutedByPeerID:()=>Dc,selectIsPeerAudioEnabled:()=>Cc,selectIsPeerVideoEnabled:()=>Lc,selectIsRoleAllowedToPublish:()=>id,selectIsScreenShareLocallyMutedByPeerID:()=>wc,selectIsSomeoneScreenSharing:()=>Cn,selectIsTranscriptionAllowedByMode:()=>zc,selectIsTranscriptionEnabled:()=>Vn,selectIsVBEnabled:()=>Yn,selectLocalAudioTrackID:()=>ae,selectLocalMediaSettings:()=>Ss,selectLocalPeer:()=>ee,selectLocalPeerID:()=>Pe,selectLocalPeerName:()=>Pn,selectLocalPeerRole:()=>Je,selectLocalPeerRoleName:()=>bn,selectLocalTrackIDs:()=>gs,selectLocalVideoTrackID:()=>z,selectMessageByMessageID:()=>Qc,selectMessageIDsInOrder:()=>ms,selectMessagesByPeerID:()=>Vc,selectMessagesByRole:()=>Fc,selectMessagesMap:()=>Ft,selectMessagesUnreadCountByPeerID:()=>Wc,selectMessagesUnreadCountByRole:()=>Gc,selectPeerAudioByID:()=>Ec,selectPeerByCondition:()=>nd,selectPeerByID:()=>X,selectPeerCount:()=>yn,selectPeerMetadata:()=>qc,selectPeerName:()=>Jc,selectPeerNameByID:()=>mc,selectPeerScreenSharing:()=>Wa,selectPeerSharingAudio:()=>Ln,selectPeerSharingAudioPlaylist:()=>_n,selectPeerSharingVideoPlaylist:()=>wn,selectPeerTypeByID:()=>Sc,selectPeers:()=>Te,selectPeersByCondition:()=>cd,selectPeersByRole:()=>$c,selectPeersByRoles:()=>Kc,selectPeersMap:()=>J,selectPeersScreenSharing:()=>Dn,selectPeersWithAudioStatus:()=>Yc,selectPermissions:()=>Ms,selectPollByID:()=>ws,selectPolls:()=>tc,selectPollsMap:()=>ys,selectPreviewRole:()=>vs,selectPreviewRoleName:()=>Ka,selectRTMPState:()=>$n,selectRecentError:()=>Tn,selectRecordingState:()=>Wn,selectRemotePeers:()=>In,selectRoleByRoleName:()=>no,selectRoleChangeRequest:()=>Zc,selectRolesMap:()=>fe,selectRoom:()=>B,selectRoomID:()=>fn,selectRoomStartTime:()=>Jn,selectRoomStarted:()=>Bn,selectRoomState:()=>te,selectScreenAudioTrackByID:()=>Tc,selectScreenShareAudioByPeerID:()=>Cs,selectScreenShareByPeerID:()=>Hc,selectScreenSharesByPeerId:()=>Hs,selectScreenVideoTrackByID:()=>fc,selectScreenshareAudioVolumeByPeerID:()=>Nc,selectSessionId:()=>jn,selectSessionMetadata:()=>ec,selectSessionStore:()=>pc,selectSimulcastLayerByTrack:()=>Oc,selectSpeakers:()=>Ga,selectTemplateAppData:()=>Zn,selectTrackAudioByID:()=>yc,selectTrackByID:()=>$t,selectTracksMap:()=>_,selectTranscriptionsState:()=>qn,selectUnreadHMSBroadcastMessagesCount:()=>Un,selectUnreadHMSMessagesCount:()=>xn,selectVideoPlaylist:()=>bs,selectVideoPlaylistAudioTrackByPeerID:()=>Ic,selectVideoPlaylistVideoTrackByPeerID:()=>Ac,selectVideoTrackByID:()=>Rs,selectVideoTrackByPeerID:()=>to,selectWhiteboard:()=>rc,selectWhiteboards:()=>qa,simulcastMapping:()=>Ne});module.exports=Xo(Kd);var mi=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(mi||{});var kt=()=>({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}),Et=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var Ys=(e=>(e.CHAT="chat",e))(Ys||{});var Br=(t=>(t.INFO="info",t.ERROR="error",t))(Br||{}),Si=(w=>(w.PEER_JOINED="PEER_JOINED",w.PEER_LEFT="PEER_LEFT",w.PEER_LIST="PEER_LIST",w.NEW_MESSAGE="NEW_MESSAGE",w.ERROR="ERROR",w.RECONNECTING="RECONNECTING",w.RECONNECTED="RECONNECTED",w.TRACK_ADDED="TRACK_ADDED",w.TRACK_REMOVED="TRACK_REMOVED",w.TRACK_MUTED="TRACK_MUTED",w.TRACK_UNMUTED="TRACK_UNMUTED",w.TRACK_DEGRADED="TRACK_DEGRADED",w.TRACK_RESTORED="TRACK_RESTORED",w.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",w.ROLE_UPDATED="ROLE_UPDATED",w.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",w.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",w.ROOM_ENDED="ROOM_ENDED",w.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",w.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",w.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",w.NAME_UPDATED="NAME_UPDATED",w.METADATA_UPDATED="METADATA_UPDATED",w.POLL_CREATED="POLL_CREATED",w.POLL_STARTED="POLL_STARTED",w.POLL_STOPPED="POLL_STOPPED",w.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",w.POLLS_LIST="POLLS_LIST",w.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",w.TRANSCRIPTION_STATE_UPDATED="TRANSCRIPTION_STATE_UPDATED",w))(Si||{});var Vr=(t=>(t.audio="audio",t.video="video",t))(Vr||{});var A=require("reselect");function We(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];Zo(s)&&(i=Pt(s)?s:i,t=bt(s)?s:t)}return{video:t,audio:i}}function Pt(a){return a&&a.type==="audio"}function bt(a){return a&&a.type==="video"}function Zo(a){return a&&a.source==="screen"}function gi(a){return a&&a.source==="audioplaylist"}function At(a){return a&&a.source==="videoplaylist"}function Xs(a){return a?!!(a!=null&&a.degraded):!1}function Ze(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function Zs(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function It(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 Fr=(d=>(d[d.VERBOSE=0]="VERBOSE",d[d.DEBUG=1]="DEBUG",d[d.INFO=2]="INFO",d[d.WARN=3]="WARN",d[d.TIME=4]="TIME",d[d.TIMEEND=5]="TIMEEND",d[d.ERROR=6]="ERROR",d[d.NONE=7]="NONE",d))(Fr||{}),en=typeof window!="undefined"&&typeof window.expect!="undefined",l=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}}}};l.level=en?7:0;var et=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var aa=require("ua-parser-js"),he=new aa.UAParser,U=typeof window!="undefined",ea,$e=typeof window=="undefined"&&!((ea=he.getBrowser().name)!=null&&ea.toLowerCase().includes("electron"));var tn=()=>!$e,tl=tn(),Rt=()=>he.getDevice().type==="mobile",oa=()=>typeof document!="undefined"&&document.hidden,na=()=>{var a;return((a=he.getOS().name)==null?void 0:a.toLowerCase())==="ios"},ta,ia,ca=(ia=(ta=he.getBrowser())==null?void 0:ta.name)==null?void 0:ia.toLowerCase().includes("safari"),ra,sa,Ti=((sa=(ra=he.getBrowser())==null?void 0:ra.name)==null?void 0:sa.toLowerCase())==="firefox";var Sa=require("uuid");var Gr=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Gr||{});function rn(){if(U&&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 tt=rn();var la=require("uuid");var P={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,o,n=!1){super(s);this.code=t;this.name=i;this.message=s;this.description=o;this.isTerminal=n;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};
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
source: ${this.source};
|
|
31
31
|
enabled: ${this.enabled};
|
|
32
32
|
nativeTrack: ${vi(this.nativeTrack)};
|
|
33
|
-
}`}};var _e=class extends we{constructor(t,i,r){super(t,i,r);this.type="audio";this.audioElement=null;if(i.kind!=="audio")throw new Error("Expected 'track' kind = 'audio'")}getVolume(){return this.audioElement?Math.floor(this.audioElement.volume*100):null}setVolume(t){return c(this,null,function*(){if(t<0||t>100)throw Error("Please pass a valid number between 0-100");yield this.subscribeToAudio(t===0?!1:this.enabled),this.audioElement&&(this.audioElement.volume=t/100)})}setAudioElement(t){l.d("[HMSAudioTrack]",this.logIdentifier,"adding audio element",`${this}`,t),this.audioElement=t}getAudioElement(){return this.audioElement}getOutputDevice(){return this.outputDevice}cleanup(){super.cleanup(),this.audioElement&&(this.audioElement.srcObject=null,this.audioElement.remove(),this.audioElement=null)}setOutputDevice(t){return c(this,null,function*(){var i;if(!t){l.d("[HMSAudioTrack]",this.logIdentifier,"device is null",`${this}`);return}if(!this.audioElement){l.d("[HMSAudioTrack]",this.logIdentifier,"no audio element to set output",`${this}`),this.outputDevice=t;return}try{typeof this.audioElement.setSinkId=="function"&&(Ti||(yield(i=this.audioElement)==null?void 0:i.setSinkId(t.deviceId)),this.outputDevice=t)}catch(r){l.d("[HMSAudioTrack]","error in setSinkId",r)}})}subscribeToAudio(t){return c(this,null,function*(){this.stream instanceof Ae&&(yield this.stream.setAudio(t,this.trackId,this.logIdentifier))})}};var Ma=Ge(require("lodash.isequal"));var Jr=class{constructor(){this.storage=new Me("hms-device-selection");this.remember=!1;this.TAG="[HMSDeviceStorage]"}setDevices(e){this.devices=e}rememberDevices(e){this.remember=e}updateSelection(e,{deviceId:t,groupId:i}){if(!this.devices||!this.remember)return;let r=this.devices[e].find(o=>this.isSame({deviceId:t,groupId:i},o));if(!r){l.w(this.TAG,`Could not find device with deviceId: ${t}, groupId: ${i}`);return}let s=this.storage.get()||{};s[e]=r,this.storage.set(s)}getSelection(){if(this.remember)return this.storage.get()}cleanup(){this.remember=!1,this.devices=void 0}isSame(e,t){return e.deviceId===t.deviceId&&(e.groupId===t.groupId||!e.groupId)}},Z=new Jr;var Mi=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(Mi||{}),yi=(t=>(t.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",t.DEVICE_NOT_SUPPORTED="DEVICE_NOT_SUPPORTED",t))(yi||{});var Se=class{static failure(e,t){let i="mediaPlugin.failed",r=2,s=h({plugin_name:e},t.toAnalyticsProperties());return new C({name:i,level:r,properties:s})}static audioPluginFailure(e,t,i){let r="mediaPlugin.failed",s=2,o=h({plugin_name:e,sampleRate:t},i.toAnalyticsProperties());return new C({name:r,level:s,properties:o})}static audioPluginStats({pluginName:e,duration:t,loadTime:i,sampleRate:r}){let s="mediaPlugin.stats",o=1,n={plugin_name:e,duration:t,load_time:i,sampleRate:r};return new C({name:s,level:o,properties:n})}static added(e,t){let i="mediaPlugin.added",r=1,s={plugin_name:e,added_at:t};return new C({name:i,level:r,properties:s})}static stats({pluginName:e,duration:t,loadTime:i,avgPreProcessingTime:r,avgProcessingTime:s,inputFrameRate:o,pluginFrameRate:n}){let d="mediaPlugin.stats",u=1,p={plugin_name:e,duration:t,load_time:i,avg_preprocessing_time:r,avg_processing_time:s,input_frame_rate:o,plugin_frame_rate:n};return new C({name:d,level:u,properties:p})}};var ki=class{constructor(e){this.eventBus=e;this.TAG="[AudioPluginsAnalytics]";this.initTime={},this.addedTimestamps={},this.pluginAdded={},this.pluginSampleRate={}}added(e,t){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.pluginSampleRate[e]=t,this.eventBus.analytics.publish(Se.added(e,this.addedTimestamps[e]))}removed(e){if(this.pluginAdded[e]){let t={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],sampleRate:this.pluginSampleRate[e]};this.eventBus.analytics.publish(Se.audioPluginStats(t)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(Se.audioPluginFailure(e,this.pluginSampleRate[e],t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){l.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),l.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let s=S.MediaPluginErrors.InitFailed("AUDIO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw l.e(this.TAG,s),this.failure(e,s),s}i&&(this.initTime[e]=i)})}timeInMs(e){return c(this,null,function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)})}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.pluginAdded[e],delete this.pluginSampleRate[e]}};var Dt=[{echoCancellation:{exact:!0}},{highpassFilter:{exact:!0}},{audioMirroring:{exact:!0}}];var Ei=(t=>(t.SIP="sip",t.REGULAR="regular",t))(Ei||{});var Qr=(n=>(n.NONE="none",n.INITIALISED="initialised",n.STARTED="started",n.PAUSED="paused",n.RESUMED="resumed",n.STOPPED="stopped",n.FAILED="failed",n))(Qr||{});var zr=(t=>(t.DVR="dvr",t.NO_DVR="no-dvr",t))(zr||{}),Yr=(i=>(i.REGULAR="regular",i.SCREEN="screen",i.COMPOSITE="composite",i))(Yr||{}),Xr=(r=>(r.INITIALISED="initialised",r.STARTED="started",r.STOPPED="stopped",r.FAILED="failed",r))(Xr||{}),Zr=(e=>(e.CAPTION="caption",e))(Zr||{});var Ne={f:"high",h:"medium",q:"low"};var Pi=(t=>(t.VOICE="voice",t.MUSIC="music",t))(Pi||{});var es=(i=>(i.videoInput="videoInput",i.audioInput="audioInput",i.audioOutput="audioOutput",i))(es||{});var K=class{constructor(){this._volume=1;this._codec="opus";this._maxBitrate=32;this._deviceId="default";this._audioMode="voice";this._advanced=[...Dt,{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}}]}volume(e){if(!(0<=e&&e<=1))throw Error("volume can only be in range [0.0, 1.0]");return this._volume=e,this}codec(e){return this._codec=e,this}maxBitrate(e){if(e&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=this._audioMode==="music"?320:e,this}deviceId(e){return this._deviceId=e,this}audioMode(e="voice"){return this._audioMode=e,this._audioMode==="music"?this._maxBitrate=320:this._maxBitrate=32,this}advanced(e){return this._advanced=e,this}build(){return new Ke(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced,this._audioMode)}},Ke=class{constructor(e,t,i,r,s,o){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=s,this.audioMode=o,this.audioMode==="music"?this.maxBitrate=320:this.maxBitrate=32}toConstraints(){return{deviceId:this.deviceId,advanced:this.audioMode==="music"?[]:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}};var j=class{constructor(){this._width=320;this._height=180;this._codec="vp8";this._maxFramerate=30;this._maxBitrate=150;this._advanced=[]}setWidth(e){return this._width=e,this}setHeight(e){return this._height=e,this}codec(e){return this._codec=e,this}maxFramerate(e){if(e&&e<=0)throw Error("maxFramerate should be >= 1");return this._maxFramerate=e,this}maxBitrate(e,t=!0){if(typeof e=="number"&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,!this._maxBitrate&&t&&(this._maxBitrate=15e4),this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}facingMode(e){return this._facingMode=e,this}build(){return new qe(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate,this._facingMode)}},qe=class{constructor(e,t,i,r,s,o,n,d){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=n,this.deviceId=s,this.advanced=o,this.facingMode=d}toConstraints(e){let t="ideal";e&&(t="max");let i=this.improviseConstraintsAspect();return{width:{[t]:i.width},height:{[t]:i.height},frameRate:this.maxFramerate,deviceId:this.deviceId,facingMode:this.facingMode}}toAnalyticsProperties(){return{width:this.width,height:this.height,video_bitrate:this.maxBitrate,framerate:this.maxFramerate,video_codec:this.codec,facingMode:this.facingMode}}improviseConstraintsAspect(){return Rt()&&this.height&&this.width&&this.height>this.width?{width:this.height,height:this.width}:{width:this.width,height:this.height}}};var Oe=class{constructor(){this._video=new j().build();this._audio=new K().build();this._screen=new j().build();this._simulcast=!1}video(e){return this._video=e,this}audio(e){return this._audio=e,this}screen(e){return this._screen=e,this}simulcast(e){return this._simulcast=e,this}build(){if(this._audio===null&&this._video===null)throw S.TracksErrors.NothingToReturn("TRACK");if(this._video===null&&this._simulcast)throw S.TracksErrors.InvalidVideoSettings("TRACK","Cannot enable simulcast when no video settings are provided");return new it(this._video,this._audio,this._simulcast,this._screen||void 0)}},it=class{constructor(e,t,i,r=null){this.video=e,this.audio=t,this.simulcast=i,this.screen=r}toAnalyticsProperties(){let e={audio_enabled:this.audio!==null,video_enabled:this.video!==null};return this.audio&&(e=h(h({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=h(h({},this.video.toAnalyticsProperties()),e)),e}};var wt=class{constructor(e,t,i){this.eventBus=t;this.TAG="[AudioPluginsManager]";this.pluginAddInProgress=!1;this.hmsTrack=e,this.pluginsMap=new Map,this.analytics=new ki(t),this.audioContext=re.getAudioContext(),this.room=i}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e){return c(this,null,function*(){var i,r;let t=(i=e.getName)==null?void 0:i.call(e);if(!t){l.w("no name provided by the plugin");return}if(this.pluginAddInProgress){let s=S.MediaPluginErrors.AddAlreadyInProgress("AUDIO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.added(t,this.audioContext.sampleRate),this.analytics.failure(t,s),l.w("can't add another plugin when previous add is in progress"),s}switch(e.getName()){case"HMSKrispPlugin":{if(!((r=this.room)!=null&&r.isNoiseCancellationEnabled)){let n="Krisp Noise Cancellation is not enabled for this room";if(this.pluginsMap.size===0)throw Error(n);l.w(this.TAG,n);return}this.eventBus.analytics.publish(y.krispStart());let{settings:s}=this.hmsTrack,o=new K().codec(s.codec).maxBitrate(s.maxBitrate).deviceId(s.deviceId).advanced([...Dt,{autoGainControl:{exact:!1}},{noiseSuppression:{exact:!1}}]).audioMode(s.audioMode).build();yield this.hmsTrack.setSettings(o);break}default:}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e){return c(this,null,function*(){var i,r;let t=(i=e.getName)==null?void 0:i.call(e);if(this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} already added.`);return}yield this.validateAndThrow(t,e),(r=e.setEventBus)==null||r.call(e,this.eventBus);try{this.pluginsMap.size===0?yield this.initAudioNodes():this.prevAudioNode&&this.prevAudioNode.disconnect(),this.analytics.added(t,this.audioContext.sampleRate),yield this.analytics.initWithTime(t,()=>c(this,null,function*(){return e.init()})),this.pluginsMap.set(t,e),yield this.processPlugin(e),yield this.connectToDestination(),yield this.updateProcessedTrack()}catch(s){throw l.e(this.TAG,"failed to add plugin",s),s}})}validatePlugin(e){return e.checkSupport(this.audioContext)}validateAndThrow(e,t){return c(this,null,function*(){let i=this.validatePlugin(t);if(i.isSupported)l.i(this.TAG,`plugin is supported,- ${t.getName()}`);else if(this.analytics.added(e,this.audioContext.sampleRate),i.errType==="PLATFORM_NOT_SUPPORTED"){let r=S.MediaPluginErrors.PlatformNotSupported("AUDIO_PLUGINS","platform not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}else if(i.errType==="DEVICE_NOT_SUPPORTED"){let r=S.MediaPluginErrors.DeviceNotSupported("AUDIO_PLUGINS","audio device not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}})}removePlugin(e){return c(this,null,function*(){switch(e.getName()){case"HMSKrispPlugin":{this.eventBus.analytics.publish(y.krispStop());let{settings:t}=this.hmsTrack,i=new K().codec(t.codec).maxBitrate(t.maxBitrate).deviceId(t.deviceId).advanced([...Dt,{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}}]).audioMode(t.audioMode).build();yield this.hmsTrack.setSettings(i);break}default:break}yield this.removePluginInternal(e),this.pluginsMap.size===0?(yield this.cleanup(),l.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.hmsTrack.setProcessedTrack(void 0)):yield this.reprocessPlugins()})}cleanup(){return c(this,null,function*(){var e,t,i;for(let r of this.pluginsMap.values())yield this.removePluginInternal(r);yield this.hmsTrack.setProcessedTrack(void 0),(e=this.sourceNode)==null||e.disconnect(),(t=this.prevAudioNode)==null||t.disconnect(),(i=this.outputTrack)==null||i.stop(),this.sourceNode=void 0,this.destinationNode=void 0,this.prevAudioNode=void 0,this.outputTrack=void 0})}closeContext(){return c(this,null,function*(){this.audioContext=void 0})}reprocessPlugins(){return c(this,null,function*(){if(this.pluginsMap.size===0||!this.sourceNode)return;let e=Array.from(this.pluginsMap.values());yield this.cleanup(),yield this.initAudioNodes();for(let t of e)yield this.addPlugin(t);yield this.updateProcessedTrack()})}initAudioNodes(){return c(this,null,function*(){if(this.audioContext){let e=new MediaStream([this.hmsTrack.nativeTrack]);this.sourceNode=this.audioContext.createMediaStreamSource(e),this.destinationNode||(this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputTrack=this.destinationNode.stream.getAudioTracks()[0])}})}updateProcessedTrack(){return c(this,null,function*(){try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(e){throw l.e(this.TAG,"error in setting processed track",e),e}})}processPlugin(e){return c(this,null,function*(){try{let t=yield e.processAudioTrack(this.audioContext,this.prevAudioNode||this.sourceNode);this.prevAudioNode&&this.prevAudioNode.connect(t),this.prevAudioNode=t}catch(t){let i=e.getName();l.e(this.TAG,`error in processing plugin ${i}`,t),yield this.removePluginInternal(e)}})}connectToDestination(){return c(this,null,function*(){try{this.prevAudioNode&&this.destinationNode&&this.prevAudioNode.context===this.destinationNode.context&&this.prevAudioNode.connect(this.destinationNode)}catch(e){l.e(this.TAG,"error in connecting to destination node",e)}})}removePluginInternal(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(!this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} not found to remove.`);return}l.i(this.TAG,`removing plugin ${t}`),this.pluginsMap.delete(t),e.stop(),this.analytics.removed(t)})}};var ts=Ge(require("webrtc-adapter"));function on(a,e){let t=a.toLowerCase(),i=S.TracksErrors.GenericTrack("TRACK",a);return t.includes("device not found")?i=S.TracksErrors.DeviceNotAvailable("TRACK",e,a):t.includes("permission denied")&&(i=S.TracksErrors.CantAccessCaptureDevice("TRACK",e,a)),i}function nn(a,e=""){if(ts.default.browserDetails.browser==="chrome"&&a.name==="NotAllowedError"&&a.message.includes("denied by system"))return S.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);if(ts.default.browserDetails.browser==="firefox"&&a.name==="NotFoundError"){let i=S.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);return i.description=`Capture device is either blocked at Operating System level or not available - ${e}`,i}switch(a.name){case"OverconstrainedError":return S.TracksErrors.OverConstrained("TRACK",e,a.constraint);case"NotAllowedError":return S.TracksErrors.CantAccessCaptureDevice("TRACK",e,a.message);case"NotFoundError":return S.TracksErrors.DeviceNotAvailable("TRACK",e,a.message);case"NotReadableError":return S.TracksErrors.DeviceInUse("TRACK",e,a.message);case"TypeError":return S.TracksErrors.NothingToReturn("TRACK",a.message);default:return on(a.message,e)}}function xe(a,e){let t=nn(a,e);return t.addNativeError(a),t}function is(a){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({audio:a?a.toConstraints():!1})).getAudioTracks()[0]}catch(e){throw xe(e,"audio")}})}function rs(a){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({video:a?a.toConstraints():!1})).getVideoTracks()[0]}catch(e){throw xe(e,"video")}})}function ye(a){return"canvas"in a||a.label==="MediaStreamAudioDestinationNode"||a.label===""}var cn=32e3;var re={audioContext:null,getAudioContext(){return this.audioContext||(this.audioContext=Ti?new AudioContext:new AudioContext({sampleRate:cn})),this.audioContext},resumeContext(){return c(this,null,function*(){try{return yield this.getAudioContext().resume()}catch(a){l.e("AudioContext",a)}})}},bi=(r=>(r.SPEAKERPHONE="SPEAKERPHONE",r.WIRED="WIRED",r.BLUETOOTH="BLUETOOTH",r.EARPIECE="EARPIECE",r))(bi||{}),Ai=a=>{if(!a)return l.w("[DeviceManager]:","No device label provided"),"SPEAKERPHONE";let e=a.toLowerCase();return e.includes("speakerphone")?"SPEAKERPHONE":e.includes("wired")?"WIRED":/airpods|buds|wireless|bluetooth/gi.test(e)?"BLUETOOTH":e.includes("earpiece")?"EARPIECE":"SPEAKERPHONE"};var Ue=class{constructor(e=1/0){this.capacity=e;this.storage=[]}size(){return this.storage.length}toList(){return this.storage.slice(0)}enqueue(e){this.size()===this.capacity&&this.dequeue(),this.storage.push(e)}dequeue(){return this.storage.shift()}aggregate(e){return e(this.storage)}};var Ta=`(function workerSetup() {
|
|
33
|
+
}`}};var _e=class extends we{constructor(t,i,r){super(t,i,r);this.type="audio";this.audioElement=null;if(i.kind!=="audio")throw new Error("Expected 'track' kind = 'audio'")}getVolume(){return this.audioElement?Math.floor(this.audioElement.volume*100):null}setVolume(t){return c(this,null,function*(){if(t<0||t>100)throw Error("Please pass a valid number between 0-100");yield this.subscribeToAudio(t===0?!1:this.enabled),this.audioElement&&(this.audioElement.volume=t/100)})}setAudioElement(t){l.d("[HMSAudioTrack]",this.logIdentifier,"adding audio element",`${this}`,t),this.audioElement=t}getAudioElement(){return this.audioElement}getOutputDevice(){return this.outputDevice}cleanup(){super.cleanup(),this.audioElement&&(this.audioElement.srcObject=null,this.audioElement.remove(),this.audioElement=null)}setOutputDevice(t){return c(this,null,function*(){var i;if(!t){l.d("[HMSAudioTrack]",this.logIdentifier,"device is null",`${this}`);return}if(!this.audioElement){l.d("[HMSAudioTrack]",this.logIdentifier,"no audio element to set output",`${this}`),this.outputDevice=t;return}try{typeof this.audioElement.setSinkId=="function"&&(Ti||(yield(i=this.audioElement)==null?void 0:i.setSinkId(t.deviceId)),this.outputDevice=t)}catch(r){l.d("[HMSAudioTrack]","error in setSinkId",r)}})}subscribeToAudio(t){return c(this,null,function*(){this.stream instanceof Ae&&(yield this.stream.setAudio(t,this.trackId,this.logIdentifier))})}};var Ma=Ge(require("lodash.isequal"));var Jr=class{constructor(){this.storage=new Me("hms-device-selection");this.remember=!1;this.TAG="[HMSDeviceStorage]"}setDevices(e){this.devices=e}rememberDevices(e){this.remember=e}updateSelection(e,{deviceId:t,groupId:i}){if(!this.devices||!this.remember)return;let r=this.devices[e].find(o=>this.isSame({deviceId:t,groupId:i},o));if(!r){l.w(this.TAG,`Could not find device with deviceId: ${t}, groupId: ${i}`);return}let s=this.storage.get()||{};s[e]=r,this.storage.set(s)}getSelection(){if(this.remember)return this.storage.get()}cleanup(){this.remember=!1,this.devices=void 0}isSame(e,t){return e.deviceId===t.deviceId&&(e.groupId===t.groupId||!e.groupId)}},Z=new Jr;var Mi=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(Mi||{}),yi=(t=>(t.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",t.DEVICE_NOT_SUPPORTED="DEVICE_NOT_SUPPORTED",t))(yi||{});var Se=class{static failure(e,t){let i="mediaPlugin.failed",r=2,s=h({plugin_name:e},t.toAnalyticsProperties());return new C({name:i,level:r,properties:s})}static audioPluginFailure(e,t,i){let r="mediaPlugin.failed",s=2,o=h({plugin_name:e,sampleRate:t},i.toAnalyticsProperties());return new C({name:r,level:s,properties:o})}static audioPluginStats({pluginName:e,duration:t,loadTime:i,sampleRate:r}){let s="mediaPlugin.stats",o=1,n={plugin_name:e,duration:t,load_time:i,sampleRate:r};return new C({name:s,level:o,properties:n})}static added(e,t){let i="mediaPlugin.added",r=1,s={plugin_name:e,added_at:t};return new C({name:i,level:r,properties:s})}static stats({pluginName:e,duration:t,loadTime:i,avgPreProcessingTime:r,avgProcessingTime:s,inputFrameRate:o,pluginFrameRate:n}){let d="mediaPlugin.stats",u=1,p={plugin_name:e,duration:t,load_time:i,avg_preprocessing_time:r,avg_processing_time:s,input_frame_rate:o,plugin_frame_rate:n};return new C({name:d,level:u,properties:p})}};var ki=class{constructor(e){this.eventBus=e;this.TAG="[AudioPluginsAnalytics]";this.initTime={},this.addedTimestamps={},this.pluginAdded={},this.pluginSampleRate={}}added(e,t){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.pluginSampleRate[e]=t,this.eventBus.analytics.publish(Se.added(e,this.addedTimestamps[e]))}removed(e){if(this.pluginAdded[e]){let t={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],sampleRate:this.pluginSampleRate[e]};this.eventBus.analytics.publish(Se.audioPluginStats(t)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(Se.audioPluginFailure(e,this.pluginSampleRate[e],t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){l.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),l.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let s=S.MediaPluginErrors.InitFailed("AUDIO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw l.e(this.TAG,s),this.failure(e,s),s}i&&(this.initTime[e]=i)})}timeInMs(e){return c(this,null,function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)})}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.pluginAdded[e],delete this.pluginSampleRate[e]}};var Dt=[{echoCancellation:{exact:!0}},{highpassFilter:{exact:!0}},{audioMirroring:{exact:!0}}];var Ei=(t=>(t.SIP="sip",t.REGULAR="regular",t))(Ei||{});var Qr=(n=>(n.NONE="none",n.INITIALISED="initialised",n.STARTED="started",n.PAUSED="paused",n.RESUMED="resumed",n.STOPPED="stopped",n.FAILED="failed",n))(Qr||{});var zr=(t=>(t.DVR="dvr",t.NO_DVR="no-dvr",t))(zr||{}),Yr=(i=>(i.REGULAR="regular",i.SCREEN="screen",i.COMPOSITE="composite",i))(Yr||{}),Xr=(r=>(r.INITIALISED="initialised",r.STARTED="started",r.STOPPED="stopped",r.FAILED="failed",r))(Xr||{}),Zr=(e=>(e.CAPTION="caption",e))(Zr||{});var Ne={f:"high",h:"medium",q:"low"};var Pi=(t=>(t.VOICE="voice",t.MUSIC="music",t))(Pi||{});var es=(i=>(i.videoInput="videoInput",i.audioInput="audioInput",i.audioOutput="audioOutput",i))(es||{});var K=class{constructor(){this._volume=1;this._codec="opus";this._maxBitrate=32;this._deviceId="default";this._audioMode="voice";this._advanced=[...Dt,{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}}]}volume(e){if(!(0<=e&&e<=1))throw Error("volume can only be in range [0.0, 1.0]");return this._volume=e,this}codec(e){return this._codec=e,this}maxBitrate(e){if(e&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=this._audioMode==="music"?320:e,this}deviceId(e){return this._deviceId=e,this}audioMode(e="voice"){return this._audioMode=e,this._audioMode==="music"?this._maxBitrate=320:this._maxBitrate=32,this}advanced(e){return this._advanced=e,this}build(){return new Ke(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced,this._audioMode)}},Ke=class{constructor(e,t,i,r,s,o){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=s,this.audioMode=o,this.audioMode==="music"?this.maxBitrate=320:this.maxBitrate=32}toConstraints(){return{deviceId:this.deviceId,advanced:this.audioMode==="music"?[]:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}};var j=class{constructor(){this._width=320;this._height=180;this._codec="vp8";this._maxFramerate=30;this._maxBitrate=150;this._advanced=[]}setWidth(e){return this._width=e,this}setHeight(e){return this._height=e,this}codec(e){return this._codec=e,this}maxFramerate(e){if(e&&e<=0)throw Error("maxFramerate should be >= 1");return this._maxFramerate=e,this}maxBitrate(e,t=!0){if(typeof e=="number"&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,!this._maxBitrate&&t&&(this._maxBitrate=15e4),this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}facingMode(e){return this._facingMode=e,this}build(){return new qe(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate,this._facingMode)}},qe=class{constructor(e,t,i,r,s,o,n,d){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=n,this.deviceId=s,this.advanced=o,this.facingMode=d}toConstraints(e){let t="ideal";e&&(t="max");let i=this.improviseConstraintsAspect();return{width:{[t]:i.width},height:{[t]:i.height},frameRate:this.maxFramerate,deviceId:this.deviceId,facingMode:this.facingMode}}toAnalyticsProperties(){return{width:this.width,height:this.height,video_bitrate:this.maxBitrate,framerate:this.maxFramerate,video_codec:this.codec,facingMode:this.facingMode}}improviseConstraintsAspect(){return Rt()&&this.height&&this.width&&this.height>this.width?{width:this.height,height:this.width}:{width:this.width,height:this.height}}};var Oe=class{constructor(){this._video=new j().build();this._audio=new K().build();this._screen=new j().build();this._simulcast=!1}video(e){return this._video=e,this}audio(e){return this._audio=e,this}screen(e){return this._screen=e,this}simulcast(e){return this._simulcast=e,this}build(){if(this._audio===null&&this._video===null)throw S.TracksErrors.NothingToReturn("TRACK");if(this._video===null&&this._simulcast)throw S.TracksErrors.InvalidVideoSettings("TRACK","Cannot enable simulcast when no video settings are provided");return new it(this._video,this._audio,this._simulcast,this._screen||void 0)}},it=class{constructor(e,t,i,r=null){this.video=e,this.audio=t,this.simulcast=i,this.screen=r}toAnalyticsProperties(){let e={audio_enabled:this.audio!==null,video_enabled:this.video!==null};return this.audio&&(e=h(h({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=h(h({},this.video.toAnalyticsProperties()),e)),e}};var wt=class{constructor(e,t,i){this.eventBus=t;this.TAG="[AudioPluginsManager]";this.pluginAddInProgress=!1;this.hmsTrack=e,this.pluginsMap=new Map,this.analytics=new ki(t),this.audioContext=de.getAudioContext(),this.room=i}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e){return c(this,null,function*(){var i,r;let t=(i=e.getName)==null?void 0:i.call(e);if(!t){l.w("no name provided by the plugin");return}if(this.pluginAddInProgress){let s=S.MediaPluginErrors.AddAlreadyInProgress("AUDIO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.added(t,this.audioContext.sampleRate),this.analytics.failure(t,s),l.w("can't add another plugin when previous add is in progress"),s}switch(e.getName()){case"HMSKrispPlugin":{if(!((r=this.room)!=null&&r.isNoiseCancellationEnabled)){let n="Krisp Noise Cancellation is not enabled for this room";if(this.pluginsMap.size===0)throw Error(n);l.w(this.TAG,n);return}this.eventBus.analytics.publish(y.krispStart());let{settings:s}=this.hmsTrack,o=new K().codec(s.codec).maxBitrate(s.maxBitrate).deviceId(s.deviceId).advanced([...Dt,{autoGainControl:{exact:!1}},{noiseSuppression:{exact:!1}}]).audioMode(s.audioMode).build();yield this.hmsTrack.setSettings(o);break}default:}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e){return c(this,null,function*(){var i,r;let t=(i=e.getName)==null?void 0:i.call(e);if(this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} already added.`);return}yield this.validateAndThrow(t,e),(r=e.setEventBus)==null||r.call(e,this.eventBus);try{this.pluginsMap.size===0?yield this.initAudioNodes():this.prevAudioNode&&this.prevAudioNode.disconnect(),this.analytics.added(t,this.audioContext.sampleRate),yield this.analytics.initWithTime(t,()=>c(this,null,function*(){return e.init()})),this.pluginsMap.set(t,e),yield this.processPlugin(e),yield this.connectToDestination(),yield this.updateProcessedTrack()}catch(s){throw l.e(this.TAG,"failed to add plugin",s),s}})}validatePlugin(e){return e.checkSupport(this.audioContext)}validateAndThrow(e,t){return c(this,null,function*(){let i=this.validatePlugin(t);if(i.isSupported)l.i(this.TAG,`plugin is supported,- ${t.getName()}`);else if(this.analytics.added(e,this.audioContext.sampleRate),i.errType==="PLATFORM_NOT_SUPPORTED"){let r=S.MediaPluginErrors.PlatformNotSupported("AUDIO_PLUGINS","platform not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}else if(i.errType==="DEVICE_NOT_SUPPORTED"){let r=S.MediaPluginErrors.DeviceNotSupported("AUDIO_PLUGINS","audio device not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}})}removePlugin(e){return c(this,null,function*(){switch(e.getName()){case"HMSKrispPlugin":{this.eventBus.analytics.publish(y.krispStop());let{settings:t}=this.hmsTrack,i=new K().codec(t.codec).maxBitrate(t.maxBitrate).deviceId(t.deviceId).advanced([...Dt,{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}}]).audioMode(t.audioMode).build();yield this.hmsTrack.setSettings(i);break}default:break}yield this.removePluginInternal(e),this.pluginsMap.size===0?(yield this.cleanup(),l.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.hmsTrack.setProcessedTrack(void 0)):yield this.reprocessPlugins()})}cleanup(){return c(this,null,function*(){var e,t,i;for(let r of this.pluginsMap.values())yield this.removePluginInternal(r);yield this.hmsTrack.setProcessedTrack(void 0),(e=this.sourceNode)==null||e.disconnect(),(t=this.prevAudioNode)==null||t.disconnect(),(i=this.outputTrack)==null||i.stop(),this.sourceNode=void 0,this.destinationNode=void 0,this.prevAudioNode=void 0,this.outputTrack=void 0})}closeContext(){return c(this,null,function*(){this.audioContext=void 0})}reprocessPlugins(){return c(this,null,function*(){if(this.pluginsMap.size===0||!this.sourceNode)return;let e=Array.from(this.pluginsMap.values());yield this.cleanup(),yield this.initAudioNodes();for(let t of e)yield this.addPlugin(t);yield this.updateProcessedTrack()})}initAudioNodes(){return c(this,null,function*(){if(this.audioContext){let e=new MediaStream([this.hmsTrack.nativeTrack]);this.sourceNode=this.audioContext.createMediaStreamSource(e),this.destinationNode||(this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputTrack=this.destinationNode.stream.getAudioTracks()[0])}})}updateProcessedTrack(){return c(this,null,function*(){try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(e){throw l.e(this.TAG,"error in setting processed track",e),e}})}processPlugin(e){return c(this,null,function*(){try{let t=yield e.processAudioTrack(this.audioContext,this.prevAudioNode||this.sourceNode);this.prevAudioNode&&this.prevAudioNode.connect(t),this.prevAudioNode=t}catch(t){let i=e.getName();l.e(this.TAG,`error in processing plugin ${i}`,t),yield this.removePluginInternal(e)}})}connectToDestination(){return c(this,null,function*(){try{this.prevAudioNode&&this.destinationNode&&this.prevAudioNode.context===this.destinationNode.context&&this.prevAudioNode.connect(this.destinationNode)}catch(e){l.e(this.TAG,"error in connecting to destination node",e)}})}removePluginInternal(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(!this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} not found to remove.`);return}l.i(this.TAG,`removing plugin ${t}`),this.pluginsMap.delete(t),e.stop(),this.analytics.removed(t)})}};var ts=Ge(require("webrtc-adapter"));function on(a,e){let t=a.toLowerCase(),i=S.TracksErrors.GenericTrack("TRACK",a);return t.includes("device not found")?i=S.TracksErrors.DeviceNotAvailable("TRACK",e,a):t.includes("permission denied")&&(i=S.TracksErrors.CantAccessCaptureDevice("TRACK",e,a)),i}function nn(a,e=""){if(ts.default.browserDetails.browser==="chrome"&&a.name==="NotAllowedError"&&a.message.includes("denied by system"))return S.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);if(ts.default.browserDetails.browser==="firefox"&&a.name==="NotFoundError"){let i=S.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);return i.description=`Capture device is either blocked at Operating System level or not available - ${e}`,i}switch(a.name){case"OverconstrainedError":return S.TracksErrors.OverConstrained("TRACK",e,a.constraint);case"NotAllowedError":return S.TracksErrors.CantAccessCaptureDevice("TRACK",e,a.message);case"NotFoundError":return S.TracksErrors.DeviceNotAvailable("TRACK",e,a.message);case"NotReadableError":return S.TracksErrors.DeviceInUse("TRACK",e,a.message);case"TypeError":return S.TracksErrors.NothingToReturn("TRACK",a.message);default:return on(a.message,e)}}function xe(a,e){let t=nn(a,e);return t.addNativeError(a),t}function is(a){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({audio:a?a.toConstraints():!1})).getAudioTracks()[0]}catch(e){throw xe(e,"audio")}})}function rs(a){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({video:a?a.toConstraints():!1})).getVideoTracks()[0]}catch(e){throw xe(e,"video")}})}function ye(a){return"canvas"in a||a.label==="MediaStreamAudioDestinationNode"||a.label===""}var cn=32e3;var de={audioContext:null,getAudioContext(){return this.audioContext||(this.audioContext=Ti?new AudioContext:new AudioContext({sampleRate:cn})),this.audioContext},resumeContext(){return c(this,null,function*(){try{return yield this.getAudioContext().resume()}catch(a){l.e("AudioContext",a)}})}},bi=(r=>(r.SPEAKERPHONE="SPEAKERPHONE",r.WIRED="WIRED",r.BLUETOOTH="BLUETOOTH",r.EARPIECE="EARPIECE",r))(bi||{}),Ai=a=>{if(!a)return l.w("[DeviceManager]:","No device label provided"),"SPEAKERPHONE";let e=a.toLowerCase();return e.includes("speakerphone")?"SPEAKERPHONE":e.includes("wired")?"WIRED":/airpods|buds|wireless|bluetooth/gi.test(e)?"BLUETOOTH":e.includes("earpiece")?"EARPIECE":"SPEAKERPHONE"};var Ue=class{constructor(e=1/0){this.capacity=e;this.storage=[]}size(){return this.storage.length}toList(){return this.storage.slice(0)}enqueue(e){this.size()===this.capacity&&this.dequeue(),this.storage.push(e)}dequeue(){return this.storage.shift()}aggregate(e){return e(this.storage)}};var Ta=`(function workerSetup() {
|
|
34
34
|
function ticker() {
|
|
35
35
|
self.postMessage('tick');
|
|
36
36
|
}
|
|
@@ -44,11 +44,11 @@
|
|
|
44
44
|
break;
|
|
45
45
|
}
|
|
46
46
|
};
|
|
47
|
-
})()`;function se(a){if(a<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,a)})}function Be(a){if(a<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return se(a);let e=new Worker(URL.createObjectURL(new Blob([Ta],{type:"application/javascript"})));return e.postMessage(["start",a]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function fa(){if(typeof Worker=="undefined")return{sleep:e=>se(e)};let a=new Worker(URL.createObjectURL(new Blob([Ta],{type:"application/javascript"})));return{sleep:e=>(a.postMessage(["start",e]),new Promise(t=>{a.onmessage=i=>{i.data==="tick"&&t()}}))}}function Ii(a,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{a.apply(r,i)},e)}}var dn=35,ln=5,Ri=class{constructor(e,t,i){this.track=e;this.audioLevelEvent=t;this.silenceEvent=i;this.TAG="[TrackAudioLevelMonitor]";this.audioLevel=0;this.isMonitored=!1;this.interval=100;this.historyInterval=700;this.history=new Ue(this.historyInterval/this.interval);this.detectSilence=()=>c(this,null,function*(){let i=0;for(;this.isMonitored;){if(this.track.enabled)if(this.isSilentThisInstant()){if(i++,i>50){this.silenceEvent.publish({track:this.track});break}}else break;yield se(20)}});try{let r=new MediaStream([this.track.nativeTrack]);this.analyserNode=this.createAnalyserNodeForStream(r);let s=this.analyserNode.frequencyBinCount;this.dataArray=new Uint8Array(s)}catch(r){l.w(this.TAG,"Unable to initialize AudioContext",r)}}start(){this.stop(),this.isMonitored=!0,l.d(this.TAG,"Starting track Monitor",`${this.track}`),this.loop().then(()=>l.d(this.TAG,"Stopping track Monitor",`${this.track}`))}stop(){if(!this.analyserNode){l.d(this.TAG,"AudioContext not initialized");return}this.sendAudioLevel(0),this.isMonitored=!1}loop(){return c(this,null,function*(){for(;this.isMonitored;)this.sendAudioLevel(this.getMaxAudioLevelOverPeriod()),yield se(this.interval)})}sendAudioLevel(e=0){if(e=e>dn?e:0,Math.abs(this.audioLevel-e)>ln){this.audioLevel=e;let i={track:this.track,audioLevel:this.audioLevel};this.audioLevelEvent.publish(i)}}getMaxAudioLevelOverPeriod(){if(!this.analyserNode){l.d(this.TAG,"AudioContext not initialized");return}let e=this.calculateAudioLevel();return e!==void 0&&this.history.enqueue(e),this.history.aggregate(t=>Math.max(...t))}calculateAudioLevel(){if(!this.analyserNode||!this.dataArray){l.d(this.TAG,"AudioContext not initialized");return}this.analyserNode.getByteTimeDomainData(this.dataArray);let e=.009,t=e;for(let s of this.dataArray)t=Math.max(t,(s-128)/128);let i=(Math.log(e)-Math.log(t))/Math.log(e);return Math.ceil(Math.min(Math.max(i*100,0),100))}isSilentThisInstant(){if(!this.analyserNode||!this.dataArray){l.d(this.TAG,"AudioContext not initialized");return}return this.analyserNode.getByteTimeDomainData(this.dataArray),this.dataArray.every(e=>e===128||e===0)}createAnalyserNodeForStream(e){let t=re.getAudioContext(),i=t.createMediaStreamSource(e),r=t.createAnalyser();return r.fftSize=2048,i.connect(r),r}};function va(a,e){return function(i){return!(0,Ma.default)(a[i],e[i])}}var le=class a extends _e{constructor(t,i,r,s,o=new K().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this.TAG="[HMSLocalAudioTrack]";this.tracksCreated=new Set;this.isPublished=!1;this.handleVisibilityChange=()=>c(this,null,function*(){if(!this.shouldReacquireTrack()){l.d(this.TAG,`visibiltiy: ${document.visibilityState}`,`${this}`);return}if(document.visibilityState==="hidden")this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{l.d(this.TAG,"On visibile replacing track as it is not publishing");try{yield this.replaceTrackWith(this.settings)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.handleTrackMute=()=>{l.d(this.TAG,"muted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t}))};this.handleTrackUnmute=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t}));try{yield this.setEnabled(this.enabled),this.eventBus.localAudioUnmutedNatively.publish()}catch(i){this.eventBus.error.publish(i)}});this.replaceSenderTrack=()=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(this.processedTrack||this.nativeTrack)});this.shouldReacquireTrack=()=>ye(this.nativeTrack)||this.isTrackNotPublishing();this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=va(t,this.settings);(r("maxBitrate")||r("audioMode"))&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this,t)),(r("advanced")||r("audioMode"))&&(yield this.replaceTrackWith(t))});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(va(t,this.settings)("deviceId")){this.manuallySelectedDeviceId=i?this.manuallySelectedDeviceId:t.deviceId,l.d(this.TAG,"device change","manual selection:",this.manuallySelectedDeviceId,"new device:",t.deviceId),yield this.replaceTrackWith(t);let s=this.nativeTrack.getSettings().groupId;!i&&t.deviceId&&(Z.updateSelection("audioInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"audioInput",selection:{deviceId:t.deviceId,groupId:s}}))}});t.tracks.push(this),this.addTrackEventListeners(i),this.settings=o,o.deviceId!==i.getSettings().deviceId&&!ye(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new wt(this,s,n),this.setFirstTrackId(i.id),r==="regular"&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}clone(t){let i=this.nativeTrack.clone();t.nativeStream.addTrack(i);let r=new a(t,i,this.source,this.eventBus,this.settings,this.room);return r.peerId=this.peerId,this.pluginsManager.pluginsMap.size>0&&this.pluginsManager.pluginsMap.forEach(s=>{r.addPlugin(s).catch(o=>l.e(this.TAG,"Plugin add failed while migrating",s,o))}),r}getManuallySelectedDeviceId(){return this.manuallySelectedDeviceId}resetManuallySelectedDeviceId(){this.manuallySelectedDeviceId=void 0}updateTrack(t){return c(this,null,function*(){t.enabled=this.enabled,yield this.stream.replaceStreamTrack(this.nativeTrack,t),this.nativeTrack=t,yield this.replaceSenderTrack(),!!this.audioLevelMonitor&&this.initAudioLevelMonitor()})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop(),this.removeTrackEventListeners(i),this.tracksCreated.forEach(r=>r.stop()),this.tracksCreated.clear();try{let r=yield is(t);this.addTrackEventListeners(r),this.tracksCreated.add(r),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),yield this.updateTrack(r)}catch(r){let s=yield is(this.settings);throw this.addTrackEventListeners(s),this.tracksCreated.add(s),yield this.updateTrack(s),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}try{yield this.pluginsManager.reprocessPlugins()}catch(r){this.eventBus.audioPluginFailed.publish(r)}})}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(t&&this.shouldReacquireTrack()&&(yield this.replaceTrackWith(this.settings)),yield de(a.prototype,this,"setEnabled").call(this,t),t&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),this.eventBus.localAudioEnabled.publish({enabled:t,track:this}))})}isPublishedTrackId(t){return this.publishedTrackId===t}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(ye(this.nativeTrack)){this.settings=r;return}yield this.handleDeviceChange(r,i),yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.pluginsManager.getPlugins()}addPlugin(t){return c(this,null,function*(){return this.pluginsManager.addPlugin(t)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}setProcessedTrack(t){return c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack()})}initAudioLevelMonitor(){this.audioLevelMonitor&&this.destroyAudioLevelMonitor(),l.d(this.TAG,"Monitor Audio Level for",this,this.getMediaTrackSettings().deviceId),this.audioLevelMonitor=new Ri(this,this.eventBus.trackAudioLevelUpdate,this.eventBus.localAudioSilence),this.audioLevelMonitor.start(),this.audioLevelMonitor.detectSilence()}destroyAudioLevelMonitor(){var t;(t=this.audioLevelMonitor)==null||t.stop(),this.audioLevelMonitor=void 0}cleanup(){return c(this,null,function*(){var t;de(a.prototype,this,"cleanup").call(this),yield this.pluginsManager.cleanup(),yield this.pluginsManager.closeContext(),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.tracksCreated.forEach(i=>i.stop()),this.tracksCreated.clear(),this.isPublished=!1,this.destroyAudioLevelMonitor(),document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}getTrackIDBeingSent(){return this.processedTrack?this.processedTrack.id:this.nativeTrack.id}getTrackBeingSent(){return this.processedTrack||this.nativeTrack}addTrackEventListeners(t){t.addEventListener("mute",this.handleTrackMute),t.addEventListener("unmute",this.handleTrackUnmute)}removeTrackEventListeners(t){t.removeEventListener("mute",this.handleTrackMute),t.removeEventListener("unmute",this.handleTrackUnmute)}buildNewSettings(t){let{volume:i,codec:r,maxBitrate:s,deviceId:o,advanced:n,audioMode:d}=h(h({},this.settings),t);return new Ke(i,r,s,o,n,d)}};var ae=class a extends _e{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield de(a.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var rt=class extends we{constructor(t,i,r){super(t,i,r);this.type="video";this.sinkCount=0;this.handleTrackUnmute=()=>{this.getSinks().forEach(t=>this.reTriggerPlay({videoElement:t}))};this.reTriggerPlay=({videoElement:t})=>{setTimeout(()=>{t.play().catch(i=>{l.w("[HMSVideoTrack]","failed to play",i.message)})},0)};if(i.kind!=="video")throw new Error("Expected 'track' kind = 'video'")}setVideoHandler(t){this.videoHandler=t}hasSinks(){return this.sinkCount>0}getSinks(){return this.videoHandler.getVideoElements()||[]}attach(t){this.videoHandler.addVideoElement(t)}detach(t){this.videoHandler.removeVideoElement(t)}addSink(t){this.addSinkInternal(t,this.nativeTrack)}removeSink(t){t.srcObject!==null&&(t.srcObject=null,this.reduceSinkCount())}cleanup(){super.cleanup(),this.videoHandler.cleanup()}addSinkInternal(t,i){let r=t.srcObject;if(r!==null&&r instanceof MediaStream){let o=r.getVideoTracks()[0];if((o==null?void 0:o.id)===i.id){if(!o.muted&&o.readyState==="live")return;this.reduceSinkCount()}else this.reduceSinkCount()}this.addPropertiesToElement(t);let s=new MediaStream([i]);t.srcObject=s,this.reTriggerPlay({videoElement:t}),this.sinkCount++}reduceSinkCount(){this.sinkCount>0&&this.sinkCount--}addPropertiesToElement(t){ca||(t.autoplay=!0),t.playsInline=!0,t.muted=!0,t.controls=!1}};var Ra=Ge(require("lodash.isequal"));var Pa=require("uuid");var _t={none:-1,low:0,medium:1,high:2},un=.5,ya=(a,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...a].sort((o,n)=>_t[o.layer]-_t[n.layer]),s=e[i]*((window==null?void 0:window.devicePixelRatio)||1);for(let o=0;o<r.length;o++){let{resolution:n,layer:d}=r[o],u=n[i];if(s<=u){t=d;break}else{let p=r[o+1],m=p?p.resolution[i]:Number.POSITIVE_INFINITY;if((s-u)/(m-u)<un){t=d;break}}}return t};var ss=class{constructor(){this.TAG="[HMSIntersectionObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t)=>{var i;this.createObserver(),this.unobserve(e),(i=this.intersectionObserver)==null||i.observe(e),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.intersectionObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.intersectionObserver&&(this.intersectionObserver=new IntersectionObserver(this.handleIntersection))};this.handleIntersection=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.IntersectionObserver!="undefined";return e||l.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},ka=new ss;var as=class{constructor(){this.TAG="[HMSResizeObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t,i={box:"border-box"})=>{var r;this.createObserver(),this.unobserve(e),(r=this.resizeObserver)==null||r.observe(e,i),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.resizeObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.resizeObserver&&(this.resizeObserver=new ResizeObserver(Ii(this.handleResize,300)))};this.handleResize=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.ResizeObserver!="undefined";return e||l.w(this.TAG,"Resize Observer is not supported"),e}},Ea=new as;var st=class{constructor(e){this.track=e;this.TAG="[VideoElementManager]";this.videoElements=new Set;this.entries=new WeakMap;this.handleIntersection=e=>c(this,null,function*(){let t=getComputedStyle(e.target).visibility==="visible";this.track.enabled&&(e.isIntersecting&&t||!document.contains(e.target))?(l.d(this.TAG,"add sink intersection",`${this.track}`,this.id),this.entries.set(e.target,e.boundingClientRect),yield this.selectMaxLayer(),yield this.track.addSink(e.target)):(l.d(this.TAG,"remove sink intersection",`${this.track}`,this.id),yield this.track.removeSink(e.target))});this.handleResize=e=>c(this,null,function*(){!this.track.enabled||!(this.track instanceof O)||(this.entries.set(e.target,e.contentRect),yield this.selectMaxLayer())});this.cleanup=()=>{this.videoElements.forEach(e=>{var t,i;e.srcObject=null,(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e)}),this.videoElements.clear(),this.resizeObserver=void 0,this.intersectionObserver=void 0};this.init(),this.id=(0,Pa.v4)()}updateSinks(e=!1){for(let t of this.videoElements)this.track.enabled?this.track.addSink(t,e):this.track.removeSink(t,e)}addVideoElement(e){return c(this,null,function*(){var t;this.videoElements.has(e)||(this.init(),l.d(this.TAG,`Adding video element for ${this.track}`,this.id),this.videoElements.add(e),this.videoElements.size>=10&&l.w(this.TAG,`${this.track}`,`the track is added to ${this.videoElements.size} video elements, while this may be intentional, it's likely that there is a bug leading to unnecessary creation of video elements in the UI`),(t=this.intersectionObserver)!=null&&t.isSupported()?this.intersectionObserver.observe(e,this.handleIntersection):U&&(this.isElementInViewport(e)?this.track.addSink(e):this.track.removeSink(e)),this.resizeObserver?this.resizeObserver.observe(e,this.handleResize):this.track instanceof O&&(yield this.track.setPreferredLayer(this.track.getPreferredLayer())))})}removeVideoElement(e){var t,i;this.track.removeSink(e),this.videoElements.delete(e),this.entries.delete(e),(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e),l.d(this.TAG,`Removing video element for ${this.track}`)}getVideoElements(){return Array.from(this.videoElements)}init(){U&&(this.resizeObserver=Ea,this.intersectionObserver=ka)}isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft,r=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{opacity:n,display:d}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,t+=e.offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+s>window.pageYOffset&&i+r>window.pageXOffset&&!o&&(n!==""?parseFloat(n)>0:!0)&&d!=="none"}selectMaxLayer(){return c(this,null,function*(){if(!(this.track instanceof O)||this.videoElements.size===0)return;let e;for(let t of this.videoElements){let i=this.entries.get(t);if(!i)continue;let{width:r,height:s}=i;if(r===0||s===0)continue;let o=ya(this.track.getSimulcastDefinitions(),{width:r,height:s});e?e=_t[o]>_t[e]?o:e:e=o}e&&(l.d(this.TAG,`selecting max layer ${e} for the track`,`${this.track}`),yield this.track.setPreferredLayer(e))})}};var Hi=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(Hi||{}),Ci=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(Ci||{});var Nt=class{constructor(){this.total=0;this.count=0}add(e){this.count++,this.total+=e}getAvg(){return Math.floor(this.total/this.count)}reset(){this.total=0,this.count=0}};var at=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new Nt,this.addedTimestamps={},this.processingAvgs={},this.pluginAdded={},this.pluginInputFrameRate={},this.pluginFrameRate={}}added(e,t,i){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.processingAvgs[e]=new Nt,t&&(this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t),this.eventBus.analytics.publish(Se.added(e,this.addedTimestamps[e]))}removed(e){var t;if(this.pluginAdded[e]){let i={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],avgPreProcessingTime:this.preProcessingAvgs.getAvg(),avgProcessingTime:(t=this.processingAvgs[e])==null?void 0:t.getAvg(),inputFrameRate:this.pluginInputFrameRate[e],pluginFrameRate:this.pluginFrameRate[e]};this.eventBus.analytics.publish(Se.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(Se.failure(e,t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){l.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),l.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let s=S.MediaPluginErrors.InitFailed("VIDEO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw l.e(this.TAG,s),this.failure(e,s),s}i&&(this.initTime[e]=i)})}preProcessWithTime(e){return c(this,null,function*(){let t=yield this.timeInMs(e);this.preProcessingAvgs.add(t)})}processWithTime(e,t){return c(this,null,function*(){var r;let i;try{i=yield this.timeInMs(t)}catch(s){let o=S.MediaPluginErrors.ProcessingFailed("VIDEO_PLUGINS",`Failed during processing of plugin${s.message||s}`);throw l.e(this.TAG,o),this.failure(e,o),o}i&&((r=this.processingAvgs[e])==null||r.add(i))})}timeInMs(e){return c(this,null,function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)})}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.processingAvgs[e],delete this.pluginAdded[e],delete this.pluginInputFrameRate[e],delete this.pluginFrameRate[e]}};var ba=24,pn=320,hn=240,Ot=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.reusableWorker=fa();this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new at(t),this.canvases=new Array}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e,t){return c(this,null,function*(){var i;if(this.pluginAddInProgress){let r=(i=e.getName)==null?void 0:i.call(e);if(!r||r===""){l.w("no name provided by the plugin");return}let s=S.MediaPluginErrors.AddAlreadyInProgress("VIDEO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.failure(r,s),l.w("can't add another plugin when previous add is in progress"),s}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e,t)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e,t){return c(this,null,function*(){var o,n;let i=(o=e.getName)==null?void 0:o.call(e);if(!i||i===""){l.w("no name provided by the plugin");return}if(this.pluginsMap.has(i)){l.w(this.TAG,`plugin - ${e.getName()} already added.`);return}let r=this.hmsTrack.getMediaTrackSettings().frameRate||ba,s=0;t&&t>0?(l.i(this.TAG,`adding plugin ${e.getName()} with framerate ${t}`),t<r&&(s=Math.ceil(r/t)-1),this.analytics.added(i,r,t)):(l.i(this.TAG,`adding plugin ${e.getName()}`),this.analytics.added(i,r)),l.i(this.TAG,"numFrames to skip processing",s),this.pluginNumFramesToSkip[i]=s,this.pluginNumFramesSkipped[i]=s,this.validateAndThrow(i,e);try{if(yield this.analytics.initWithTime(i,()=>c(this,null,function*(){return yield e.init()})),this.pluginsMap.set(i,e),this.pluginsMap.size+1>this.canvases.length)for(let d=this.canvases.length;d<=this.pluginsMap.size;d++)this.canvases[d]=document.createElement("canvas");yield this.startPluginsLoop((n=e.getContextType)==null?void 0:n.call(e))}catch(d){throw l.e(this.TAG,"failed to add plugin",d),yield this.removePlugin(e),d}})}validatePlugin(e){return e.checkSupport()}validateAndThrow(e,t){let i=this.validatePlugin(t);if(i.isSupported)l.i(this.TAG,`plugin is supported,- ${t.getName()}`);else{let r;switch(i.errType){case"PLATFORM_NOT_SUPPORTED":throw r=S.MediaPluginErrors.PlatformNotSupported("VIDEO_PLUGINS","platform not supported, see docs"),this.analytics.failure(e,r),r;case"DEVICE_NOT_SUPPORTED":throw r=S.MediaPluginErrors.DeviceNotSupported("VIDEO_PLUGINS","video device not supported, see docs"),this.analytics.failure(e,r),r}}}removePlugin(e){return c(this,null,function*(){let t=e.getName();if(!this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} not found to remove.`);return}l.i(this.TAG,`removing plugin ${t}`),this.removePluginEntry(t),this.pluginsMap.size===0&&(l.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.stopPluginsLoop()),e.stop(),this.analytics.removed(t)})}removePluginEntry(e){this.pluginsMap.delete(e),this.pluginNumFramesToSkip[e]&&delete this.pluginNumFramesToSkip[e],this.pluginNumFramesSkipped[e]&&delete this.pluginNumFramesSkipped[e]}waitForRestart(){return c(this,null,function*(){if(!(!this.pluginsLoopRunning||this.pluginsLoopState==="running"))for(;this.pluginsLoopState==="paused";)yield Be(100)})}cleanup(){return c(this,null,function*(){var e;for(let t of this.pluginsMap.values())yield this.removePlugin(t);(e=this.outputTrack)==null||e.stop()})}initElementsAndStream(e){this.inputCanvas||(this.inputCanvas=document.createElement("canvas")),this.outputCanvas=document.createElement("canvas"),this.inputVideo||(this.inputVideo=document.createElement("video")),this.inputCanvas.getContext("2d"),this.outputCanvas.getContext(e||"2d");let t=this.outputCanvas.captureStream();this.outputTrack=t.getVideoTracks()[0]}startPluginsLoop(e){return c(this,null,function*(){if(!this.pluginsLoopRunning){this.initElementsAndStream(e),this.pluginsLoopRunning=!0;try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(t){throw this.pluginsLoopRunning=!1,l.e(this.TAG,"error in setting processed track",t),t}this.pluginsLoop().then(()=>{l.d(this.TAG,"processLoop stopped")})}})}stopPluginsLoop(){return c(this,null,function*(){var e;this.pluginsLoopRunning=!1,yield this.hmsTrack.setProcessedTrack(void 0),this.resetCanvases(),(e=this.outputTrack)==null||e.stop(),this.inputVideo&&(this.inputVideo.srcObject=null,this.inputVideo=void 0)})}pluginsLoop(){return c(this,null,function*(){for(;this.pluginsLoopRunning;){let e=this.hmsTrack.getMediaTrackSettings().frameRate||ba,t=Math.floor(1e3/e);if(!this.hmsTrack.enabled||this.hmsTrack.nativeTrack.readyState==="ended"){this.pluginsLoopState==="running"&&this.resetCanvases(),this.pluginsLoopState="paused",yield this.reusableWorker.sleep(t);continue}let i=0;try{yield this.analytics.preProcessWithTime(()=>c(this,null,function*(){return yield this.doPreProcessing()}));let r=Date.now();yield this.processFramesThroughPlugins(),i=Math.floor(Date.now()-r),i>t&&(i=t)}catch(r){l.e(this.TAG,"error in plugins loop",r)}this.pluginsLoopState="running",yield this.reusableWorker.sleep(t-i)}})}doPreProcessing(){return c(this,null,function*(){yield this.addTrackToVideo(),yield this.updateInputCanvas()})}processFramesThroughPlugins(){return c(this,null,function*(){this.canvases[0]=this.inputCanvas;let e=0;for(let t of this.pluginsMap.values()){let i=t.getName();if(t){try{let r=this.checkIfSkipRequired(i);if(t.getPluginType()==="TRANSFORM"){let s=(o,n)=>c(this,null,function*(){try{yield t.processVideoFrame(o,n,r)}catch(d){l.e(this.TAG,`error in processing plugin ${i}`,d)}});if(r)e===this.pluginsMap.size-1?yield s(this.canvases[e],this.outputCanvas):yield s(this.canvases[e],this.canvases[e+1]);else{let o=this.canvases[e],n=this.canvases[e+1];e===this.pluginsMap.size-1?yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return s(o,this.outputCanvas)})):yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return s(o,n)}))}}else t.getPluginType()==="ANALYZE"&&!r&&(yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return yield t.processVideoFrame(this.inputCanvas)})))}catch(r){l.e(this.TAG,`error in processing plugin ${i}`,r),yield this.removePlugin(t)}e++}}})}addTrackToVideo(){return c(this,null,function*(){var t;if(!this.inputVideo)return;let e=this.inputVideo.srcObject;e!==null&&e instanceof MediaStream&&((t=e.getVideoTracks()[0])==null?void 0:t.id)===this.hmsTrack.nativeTrack.id||(this.inputVideo.pause(),this.inputVideo.srcObject=new MediaStream([this.hmsTrack.nativeTrack]),this.inputVideo.muted=!0,this.inputVideo.playsInline=!0,yield this.inputVideo.play())})}updateInputCanvas(){return c(this,null,function*(){if(!this.inputCanvas||!this.inputVideo)return;let{width:e=pn,height:t=hn}=this.hmsTrack.getMediaTrackSettings();this.inputCanvas.height!==t&&(this.inputCanvas.height=t),this.inputCanvas.width!==e&&(this.inputCanvas.width=e),this.inputCanvas.getContext("2d").drawImage(this.inputVideo,0,0,e,t)})}resetCanvases(){if(!this.outputCanvas||!this.inputCanvas)return;let e=this.inputCanvas.getContext("2d");e&&(e.fillStyle="rgb(0, 0, 0)",e.fillRect(0,0,this.outputCanvas.width,this.outputCanvas.height)),this.canvases=[]}checkIfSkipRequired(e){let t=!1;return this.pluginNumFramesSkipped[e]<this.pluginNumFramesToSkip[e]?(this.pluginNumFramesSkipped[e]++,t=!0):(t=!1,this.pluginNumFramesSkipped[e]=0),t}};var Li=class{constructor(e,t){this.TAG="[MediaStreamPluginsManager]";this.plugins=new Set,this.analytics=new at(e),this.room=t}addPlugins(e){e.forEach(t=>{var i;switch(t.getName()){case"HMSEffectsPlugin":if(!((i=this.room)!=null&&i.isEffectsEnabled)){let r="Effects Virtual Background is not enabled for this room";if(this.plugins.size===0)throw Error(r);l.w(this.TAG,r);return}break;default:}this.plugins.add(t)})}removePlugins(e){e.forEach(t=>{t.stop(),this.analytics.removed(t.getName()),this.plugins.delete(t)})}applyPlugins(e){let t=e;for(let i of this.plugins){let r=i.getName();try{t=i.apply(t),this.analytics.added(r)}catch(s){this.analytics.failure(r,s),l.e("Could not apply plugin",s,r)}}return t}getPlugins(){return Array.from(this.plugins).map(e=>e.getName())}cleanup(){return c(this,null,function*(){this.removePlugins(Array.from(this.plugins))})}};var Aa=require("uuid");var mn=["init_response_time","ws_connect_time","on_policy_change_time","local_audio_track_time","local_video_track_time","peer_list_time","room_state_time","join_response_time"],Di=class{constructor(){this.eventPerformanceMeasures={}}start(e){performance.mark(e)}end(e){var t;try{this.eventPerformanceMeasures[e]=performance.measure(e,e),l.d("[HMSPerformanceTiming]",e,(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration)}catch(i){l.w("[AnalyticsTimer]",`Error in measuring performance for event ${e}`,{error:i})}}getTimeTaken(e){var t;return(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration}getTimes(...e){return[...mn,...e].reduce((t,i)=>M(h({},t),{[i]:this.getTimeTaken(i)}),{})}cleanup(){this.eventPerformanceMeasures={}}};var os={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default",audioMode:"voice"},ke,wi,Ie=class a{constructor(e,t,i,r,s){this.store=e;this.observer=t;this.deviceManager=i;this.eventBus=r;this.analyticsTimer=s;this.TAG="[LocalTrackManager]";this.setScreenCaptureHandleConfig()}getTracksToPublish(){return c(this,arguments,function*(e=os){let t=this.getAVTrackSettings(e);if(!t)return[];let i=!!t.audio,r=!!t.video,s=[],{videoTrack:o,audioTrack:n}=yield this.updateCurrentLocalTrackSettings(t),d=(o==null?void 0:o.stream)||(n==null?void 0:n.stream),u=!!(o&&this.store.getTrackById(o.trackId)),p=!!(n&&this.store.getTrackById(n.trackId));if(u&&p)return[];let m={audio:i&&!n&&(e.isAudioMuted?"empty":!0),video:r&&!o&&(e.isVideoMuted?"empty":!0)};m.audio&&this.analyticsTimer.start("local_audio_track_time"),m.video&&this.analyticsTimer.start("local_video_track_time");try{l.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:m}),s=yield this.getLocalTracks(m,t,d)}catch(T){s=yield this.retryGetLocalTracks(T,t,m,d)}return m.audio&&this.analyticsTimer.end("local_audio_track_time"),m.video&&this.analyticsTimer.end("local_video_track_time"),o&&r&&!u&&s.push(o),n&&i&&!p&&s.push(n),s})}getLocalTracks(){return c(this,arguments,function*(e={audio:!0,video:!0},t,i){try{let r=yield this.getNativeLocalTracks(e,t);return this.createHMSLocalTracks(r,t,i)}catch(r){throw this.eventBus.analytics.publish(y.publish({devices:this.deviceManager.getDevices(),error:r,settings:t})),r}})}getNativeLocalTracks(){return c(this,arguments,function*(e={audio:!1,video:!1},t){let i=new it(e.video===!0?t.video:null,e.audio===!0?t.audio:null,t.simulcast),r=[];return(i.audio||i.video)&&r.push(...yield this.getAVTracks(i)),r.push(...this.getEmptyTracks(e)),r})}optimizeScreenShareConstraint(e,t){return c(this,null,function*(){var s,o,n;if(typeof t.video=="boolean"||!((s=t.video)!=null&&s.width)||!((o=t.video)!=null&&o.height))return;let i=this.store.getPublishParams();if(!i||!((n=i.allowed)!=null&&n.includes("screen")))return;let r=document.createElement("video");r.srcObject=e,r.addEventListener("loadedmetadata",()=>c(this,null,function*(){let{videoWidth:d,videoHeight:u}=r,p=i.screen,m=p.width*p.height,T=d/u,g=p.width/p.height;if(T>g){let f=t.video,E=T/g,v=Math.sqrt(E);d*u>m?(f.width=d/v,f.height=u/v):(f.height=u*v,f.width=d*v),yield e.getVideoTracks()[0].applyConstraints(f)}}))})}getLocalScreen(e,t=!1){return c(this,null,function*(){var T;let i=yield this.getOrDefaultScreenshareConfig(e),r=this.getScreenshareSettings(i.videoOnly),s={video:M(h({},r==null?void 0:r.video.toConstraints(!0)),{displaySurface:i.displaySurface}),preferCurrentTab:i.preferCurrentTab,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio};if(r!=null&&r.audio){let g=(T=r==null?void 0:r.audio)==null?void 0:T.toConstraints();delete g.advanced,s.audio=M(h({},g),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})}else e!=null&&e.forceCurrentTab&&e.preferCurrentTab&&e.cropElement&&(s.audio={echoCancellation:!0,noiseSuppression:!0});let o;try{l.d("retrieving screenshare with ",{config:i},{constraints:s}),o=yield navigator.mediaDevices.getDisplayMedia(s),t&&(yield this.optimizeScreenShareConstraint(o,s))}catch(g){l.w(this.TAG,"error in getting screenshare - ",g);let f=xe(g,"screen");throw this.eventBus.analytics.publish(y.publish({error:f,devices:this.deviceManager.getDevices(),settings:new it(r==null?void 0:r.video,r==null?void 0:r.audio,!1)})),f}let n=[],d=new ge(o),u=o.getVideoTracks()[0],p=new G(d,u,"screen",this.eventBus,r==null?void 0:r.video,this.store.getRoom());p.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"screen"));try{let g=this.validateCurrentTabCapture(p,i.forceCurrentTab);p.isCurrentTab=g,yield p.cropTo(i.cropTarget)}catch(g){throw o.getTracks().forEach(f=>f.stop()),g}n.push(p);let m=o.getAudioTracks()[0];if(m){let g=new le(d,m,"screen",this.eventBus,r==null?void 0:r.audio,this.store.getRoom());n.push(g)}return l.v(this.TAG,"getLocalScreen",n),n})}setScreenCaptureHandleConfig(e){var t;!((t=navigator.mediaDevices)!=null&&t.setCaptureHandleConfig)||this.isInIframe()||(e=e||{},Object.assign(e,{handle:(0,Aa.v4)(),exposeOrigin:!1,permittedOrigins:[window.location.origin]}),l.d("setting capture handle - ",e.handle),navigator.mediaDevices.setCaptureHandleConfig(e),this.captureHandleIdentifier=e.handle)}validateCurrentTabCapture(e,t){let i=e.getCaptureHandle(),r=!!(this.captureHandleIdentifier&&(i==null?void 0:i.handle)===this.captureHandleIdentifier);if(t&&!r)throw l.e(this.TAG,"current tab was not shared with forceCurrentTab as true"),S.TracksErrors.CurrentTabNotShared();return r}requestPermissions(){return c(this,null,function*(){try{(yield navigator.mediaDevices.getUserMedia({audio:!0,video:!0})).getTracks().forEach(t=>t.stop())}catch(e){l.e(this.TAG,e)}})}static getEmptyVideoTrack(e){var n,d,u;let t=((n=e==null?void 0:e.getSettings())==null?void 0:n.width)||320,i=((d=e==null?void 0:e.getSettings())==null?void 0:d.height)||240,r=1;ke||(ke=document.createElement("canvas"),ke.width=t,ke.height=i,(u=ke.getContext("2d"))==null||u.fillRect(0,0,t,i)),wi||(wi=setInterval(()=>{let p=ke==null?void 0:ke.getContext("2d");p&&p.fillRect(0,0,1,1)},1e3/r));let o=ke.captureStream(r).getVideoTracks()[0];return o.enabled=!1,o}static getEmptyAudioTrack(){let e=re.getAudioContext(),t=e.createOscillator(),i=e.createMediaStreamDestination();t.connect(i),t.start();let r=i.stream.getAudioTracks()[0];return r.enabled=!1,r}static cleanup(){clearInterval(wi),wi=void 0,ke=void 0}getAVTracks(e){return c(this,null,function*(){try{let t=yield navigator.mediaDevices.getUserMedia({audio:e.audio?e.audio.toConstraints():!1,video:e.video?e.video.toConstraints():!1});return t.getVideoTracks().concat(t.getAudioTracks())}catch(t){yield this.deviceManager.init();let i=!!(!this.deviceManager.hasWebcamPermission&&e.video),r=!!(!this.deviceManager.hasMicrophonePermission&&e.audio),s=this.getErrorType(i,r);throw xe(t,s)}})}getAVTrackSettings(e){let t=this.getAudioSettings(e),i=this.getVideoSettings(e);return!t&&!i?null:new Oe().video(i).audio(t).build()}isInIframe(){try{return window.self!==window.top}catch(e){return!0}}retryGetLocalTracks(e,t,i,r){return c(this,null,function*(){if(e instanceof k&&e.action==="TRACK"){this.observer.onFailure(e);let s=e.code===P.TracksErrors.OVER_CONSTRAINED,o=e.message.includes("audio"),n=e.message.includes("video");if(s){let d=new Oe().video(new qe).audio(new Ke).build();l.w(this.TAG,"Fetch AV Tracks failed with overconstrained error",{fetchTrackOptions:i},{error:e});try{return yield this.getLocalTracks(i,d,r)}catch(u){let p=u instanceof k?u.nativeError:u,m=u;if((p==null?void 0:p.name)==="OverconstrainedError"){let T=S.TracksErrors.GenericTrack("TRACK","Overconstrained error after dropping all constraints");T.addNativeError(p),m=T}return yield this.retryGetLocalTracks(m,t,i,r)}}i.audio=o?"empty":i.audio,i.video=n?"empty":i.video,l.w(this.TAG,"Fetch AV Tracks failed",{fetchTrackOptions:i},e);try{return yield this.getLocalTracks(i,t,r)}catch(d){return l.w(this.TAG,"Fetch empty tacks failed",d),i.audio=i.audio&&"empty",i.video=i.video&&"empty",this.observer.onFailure(d),yield this.getLocalTracks(i,t,r)}}else return l.w(this.TAG,"Fetch AV Tracks failed - unknown exception",e),this.observer.onFailure(e),[]})}getErrorType(e,t){return e&&t?"audio, video":e?"video":t?"audio":"audio, video"}getEmptyTracks(e){let t=[];return e.audio==="empty"&&t.push(a.getEmptyAudioTrack()),e.video==="empty"&&t.push(a.getEmptyVideoTrack()),t}updateCurrentLocalTrackSettings(e){return c(this,null,function*(){let t=this.store.getLocalPeerTracks(),i=t.find(n=>n.type==="video"&&n.source==="regular"),r=t.find(n=>n.type==="audio"&&n.source==="regular"),s=t.find(n=>n.type==="video"&&n.source==="screen");e!=null&&e.video&&(yield i==null?void 0:i.setSettings(e.video)),e!=null&&e.audio&&(yield r==null?void 0:r.setSettings(e.audio));let o=this.getScreenshareSettings(!0);return o!=null&&o.video&&(yield s==null?void 0:s.setSettings(o==null?void 0:o.video)),{videoTrack:i,audioTrack:r}})}getAudioSettings(e){var o;let t=this.store.getPublishParams();if(!t||!((o=t.allowed)!=null&&o.includes("audio")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.audioTrack,s=(r==null?void 0:r.settings.deviceId)||e.audioInputDeviceId;return new K().codec(t.audio.codec).maxBitrate(t.audio.bitRate).deviceId(s||os.audioInputDeviceId).build()}getVideoSettings(e){var n;let t=this.store.getPublishParams();if(!t||!((n=t.allowed)!=null&&n.includes("video")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.videoTrack,s=(r==null?void 0:r.settings.deviceId)||e.videoDeviceId,o=t.video;return new j().codec(o.codec).maxBitrate(o.bitRate).maxFramerate(o.frameRate).setWidth(o.width).setHeight(o.height).deviceId(s||os.videoDeviceId).build()}getScreenshareSettings(e=!1){var r;let t=this.store.getPublishParams();if(!t||!((r=t.allowed)!=null&&r.includes("screen")))return null;let i=t.screen;return{video:new j().maxBitrate(i.bitRate,!1).codec(i.codec).maxFramerate(i.frameRate).setWidth(i.width).setHeight(i.height).build(),audio:e?void 0:new K().build()}}getOrDefaultScreenshareConfig(e){return c(this,null,function*(){var i;let t=Object.assign({videoOnly:!1,audioOnly:!1,forceCurrentTab:!1,preferCurrentTab:!1,selfBrowserSurface:"exclude",surfaceSwitching:"include",systemAudio:"exclude",displaySurface:"monitor"},e||{});return t.forceCurrentTab&&(t.videoOnly=!0,t.preferCurrentTab=!0,t.selfBrowserSurface="include",t.surfaceSwitching="exclude"),t.preferCurrentTab&&(t.selfBrowserSurface="include",t.displaySurface=void 0),t.cropElement&&((i=window.CropTarget)!=null&&i.fromElement)&&(t.cropTarget=yield window.CropTarget.fromElement(t.cropElement)),t})}createHMSLocalTracks(e,t,i){let r=e.find(n=>n.kind==="video"),s=e.find(n=>n.kind==="audio");i?e.forEach(n=>i==null?void 0:i.nativeStream.addTrack(n)):i=new ge(new MediaStream(e));let o=[];if(s&&(t!=null&&t.audio)){let n=new le(i,s,"regular",this.eventBus,t.audio,this.store.getRoom());o.push(n)}if(r&&(t!=null&&t.video)){let n=new G(i,r,"regular",this.eventBus,t.video,this.store.getRoom());n.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"regular")),o.push(n)}return o}};function Ia(a,e){return function(i){return!(0,Ra.default)(a[i],e[i])}}var G=class a extends rt{constructor(t,i,r,s,o=new j().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this._layerDefinitions=[];this.TAG="[HMSLocalVideoTrack]";this.enabledStateBeforeBackground=!1;this.isCurrentTab=!1;this.isPublished=!1;this.replaceSenderTrack=t=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(t)});this.buildNewSettings=t=>{let{width:i,height:r,codec:s,maxFramerate:o,maxBitrate:n,deviceId:d,advanced:u,facingMode:p}=h(h({},this.settings),t);return new qe(i,r,s,o,d,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Ia(t,this.settings);if(r("maxBitrate")&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this)),r("width")||r("height")||r("advanced"))if(this.source==="video"){let s=yield this.replaceTrackWith(t);yield this.replaceSender(s,this.enabled),this.nativeTrack=s,yield this.processPlugins(),this.videoHandler.updateSinks()}else yield this.nativeTrack.applyConstraints(t.toConstraints())});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(Ia(t,this.settings)("deviceId")&&this.source==="regular"){if(this.enabled){delete t.facingMode;let o=yield this.replaceTrackWith(t);yield this.replaceSender(o,this.enabled),this.nativeTrack=o,yield this.processPlugins(),this.videoHandler.updateSinks()}let s=this.nativeTrack.getSettings().groupId;!i&&t.deviceId&&(Z.updateSelection("videoInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"video",selection:{deviceId:t.deviceId,groupId:s}}))}});this.handleTrackMute=()=>{l.d(this.TAG,"muted natively",document.visibilityState);let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t})),this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmuteNatively=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t})),this.handleTrackUnmute(),this.eventBus.localVideoEnabled.publish({enabled:this.enabled,track:this}),this.eventBus.localVideoUnmutedNatively.publish(),yield this.setEnabled(this.enabled)});this.removeOrReplaceProcessedTrack=t=>c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack(this.processedTrack||this.nativeTrack)});this.handleVisibilityChange=()=>c(this,null,function*(){if(document.visibilityState==="hidden")this.enabledStateBeforeBackground=this.enabled,this.enabled&&(yield this.setEnabled(!1)),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{if(l.d(this.TAG,"visibility visible, restoring track state",this.enabledStateBeforeBackground),this.enabledStateBeforeBackground)try{yield this.setEnabled(!0)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.addTrackEventListeners(i),t.tracks.push(this),this.setVideoHandler(new st(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Ot(this,s),this.mediaStreamPluginsManager=new Li(s,n),this.setFirstTrackId(this.trackId),this.eventBus.localAudioUnmutedNatively.subscribe(this.handleTrackUnmute),U&&r==="regular"&&Rt()&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}clone(t){let i=this.nativeTrack.clone();t.nativeStream.addTrack(i);let r=new a(t,i,this.source,this.eventBus,this.settings,this.room);return r.peerId=this.peerId,this.pluginsManager.pluginsMap.size>0&&this.pluginsManager.pluginsMap.forEach(s=>{r.addPlugin(s).catch(o=>l.e(this.TAG,"Plugin add failed while migrating",s,o))}),this.mediaStreamPluginsManager.plugins.size>0&&r.addStreamPlugins(Array.from(this.mediaStreamPluginsManager.plugins)),r}setSimulcastDefinitons(t){this._layerDefinitions=t}getSimulcastDefinitions(){return this._layerDefinitions}setEnabled(t){return c(this,null,function*(){var i;if(t!==this.enabled){if(this.source==="regular"){let r;t?r=yield this.replaceTrackWith(this.settings):r=yield this.replaceTrackWithBlank(),yield this.replaceSender(r,t),(i=this.nativeTrack)==null||i.stop(),this.nativeTrack=r,yield de(a.prototype,this,"setEnabled").call(this,t),t&&(yield this.pluginsManager.waitForRestart(),yield this.processPlugins(),this.settings=this.buildNewSettings({deviceId:r.getSettings().deviceId})),this.videoHandler.updateSinks()}this.eventBus.localVideoEnabled.publish({enabled:t,track:this})}})}processPlugins(){return c(this,null,function*(){try{if(this.pluginsManager.getPlugins().length>0)return;if(this.mediaStreamPluginsManager.getPlugins().length>0){let r=this.mediaStreamPluginsManager.applyPlugins(new MediaStream([this.nativeTrack])).getVideoTracks()[0];yield this.setProcessedTrack(r)}else yield this.setProcessedTrack();this.videoHandler.updateSinks()}catch(t){console.error("error in processing plugin(s)",t)}})}addStreamPlugins(t){return c(this,null,function*(){if(this.pluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSMediaStreamPlugin and HMSVideoPlugin cannot be used together");this.mediaStreamPluginsManager.addPlugins(t),yield this.processPlugins()})}removeStreamPlugins(t){return c(this,null,function*(){this.mediaStreamPluginsManager.removePlugins(t),yield this.processPlugins()})}isPublishedTrackId(t){return this.publishedTrackId===t}addSink(t){this.addSinkInternal(t,this.processedTrack||this.nativeTrack)}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(yield this.handleDeviceChange(r,i),!this.enabled||ye(this.nativeTrack)){this.settings=r;return}else yield this.pluginsManager.waitForRestart();yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.mediaStreamPluginsManager.getPlugins().length>0?this.mediaStreamPluginsManager.getPlugins():this.pluginsManager.getPlugins()}addPlugin(t,i){return c(this,null,function*(){if(this.mediaStreamPluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSVideoPlugin and HMSMediaStreamPlugin cannot be used together");return this.pluginsManager.addPlugin(t,i)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}cleanup(){return c(this,null,function*(){var t;this.eventBus.localAudioUnmutedNatively.unsubscribe(this.handleTrackUnmute),this.removeTrackEventListeners(this.nativeTrack),yield this.mediaStreamPluginsManager.cleanup(),yield this.pluginsManager.cleanup(),de(a.prototype,this,"cleanup").call(this),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,U&&Rt()&&document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}cropTo(t){return c(this,null,function*(){if(t&&this.source==="screen")try{this.nativeTrack.cropTo&&(yield this.nativeTrack.cropTo(t))}catch(i){throw l.e(this.TAG,"failed to crop screenshare capture - ",i),S.TracksErrors.GenericTrack("TRACK","failed to crop screenshare capture")}})}getCaptureHandle(){if(this.nativeTrack.getCaptureHandle)return this.nativeTrack.getCaptureHandle()}setProcessedTrack(t){return c(this,null,function*(){if(!this.nativeTrack.enabled){this.processedTrack=t;return}yield this.removeOrReplaceProcessedTrack(t),this.videoHandler.updateSinks()})}getTrackIDBeingSent(){return this.getTrackBeingSent().id}getTrackBeingSent(){return this.enabled?this.processedTrack||this.nativeTrack:this.nativeTrack}switchCamera(){return c(this,null,function*(){var s;let t=this.getMediaTrackSettings().facingMode;if(!t||this.source!=="regular"){l.d(this.TAG,"facingMode not supported");return}let i=t==="environment"?"user":"environment";(s=this.nativeTrack)==null||s.stop();let r=yield this.replaceTrackWith(this.buildNewSettings({facingMode:i,deviceId:void 0}));yield this.replaceSender(r,this.enabled),this.nativeTrack=r,yield this.processPlugins(),this.videoHandler.updateSinks(),this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId,facingMode:i}),Z.updateSelection("videoInput",{deviceId:this.settings.deviceId,groupId:this.nativeTrack.getSettings().groupId})})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;this.removeTrackEventListeners(i),i==null||i.stop();try{let r=yield rs(t);return this.addTrackEventListeners(r),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),this.settings.deviceId==="default"&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),r}catch(r){let s=yield rs(this.settings);throw this.addTrackEventListeners(s),yield this.replaceSender(s,this.enabled),this.nativeTrack=s,yield this.processPlugins(),this.videoHandler.updateSinks(),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=Ie.getEmptyVideoTrack(t);return this.removeTrackEventListeners(t),this.addTrackEventListeners(i),t==null||t.stop(),l.d(this.TAG,"replaceTrackWithBlank, Previous track stopped",t,"newTrack",i),i})}replaceSender(t,i){return c(this,null,function*(){i?yield this.replaceSenderTrack(this.processedTrack||t):yield this.replaceSenderTrack(t),this.stream.replaceStreamTrack(this.nativeTrack,t)})}addTrackEventListeners(t){t.addEventListener("mute",this.handleTrackMute),t.addEventListener("unmute",this.handleTrackUnmuteNatively)}removeTrackEventListeners(t){t.removeEventListener("mute",this.handleTrackMute),t.removeEventListener("unmute",this.handleTrackUnmuteNatively)}};var ot="renegotiation-callback-id",_i="ion-sfu";var nt="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var Ha="https://event.100ms.live/v2/client/report",Ca="https://event-nonprod.100ms.live/v2/client/report";var xt=Math.pow(2,31)-1,F={DEVICE_CHANGE:"device-change",LOCAL_AUDIO_ENABLED:"local-audio-enabled",LOCAL_VIDEO_ENABLED:"local-video-enabled",LOCAL_VIDEO_UNMUTED_NATIVELY:"local-video-unmuted-natively",LOCAL_AUDIO_UNMUTED_NATIVELY:"local-audio-unmuted-natively",STATS_UPDATE:"stats-update",RTC_STATS_UPDATE:"rtc-stats-update",TRACK_DEGRADED:"track-degraded",TRACK_RESTORED:"track-restored",TRACK_AUDIO_LEVEL_UPDATE:"track-audio-level-update",LOCAL_AUDIO_SILENCE:"local-audio-silence",ANALYTICS:"analytics",AUDIO_PLUGIN_FAILED:"audio-plugin-failed",POLICY_CHANGE:"policy-change",LOCAL_ROLE_UPDATE:"local-role-update",AUDIO_TRACK_UPDATE:"audio-track-update",AUDIO_TRACK_ADDED:"audio-track-added",AUDIO_TRACK_REMOVED:"audio-track-removed",AUTOPLAY_ERROR:"autoplay-error",LEAVE:"leave",ERROR:"error"},La="2.5",Da="20250115",Re="_handraise",cs=1e3,ds=64,wa="https://whiteboard.100ms.live",_a="https://whiteboard-qa.100ms.live";var O=class a extends rt{constructor(t,i,r,s){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new ls;this.preferredLayer="high";this.disableNoneLayerRequest=!1;this.disableNoneLayerRequest=!!s,this.setVideoHandler(new st(this))}setTrackId(t){this.bizTrackId=t}get trackId(){return this.bizTrackId||super.trackId}get degraded(){return this._degraded}get degradedAt(){return this._degradedAt}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(de(a.prototype,this,"setEnabled").call(this,t),this.videoHandler.updateSinks(!0))})}setPreferredLayer(t){return c(this,null,function*(){if(t==="none"){l.w("layer none will be ignored");return}if(this.preferredLayer=t,!!this.shouldSendVideoLayer(t,"preferLayer")){if(!this.hasSinks()){l.d(`[Remote Track] ${this.logIdentifier}
|
|
47
|
+
})()`;function re(a){if(a<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,a)})}function Be(a){if(a<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return re(a);let e=new Worker(URL.createObjectURL(new Blob([Ta],{type:"application/javascript"})));return e.postMessage(["start",a]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function fa(){if(typeof Worker=="undefined")return{sleep:e=>re(e)};let a=new Worker(URL.createObjectURL(new Blob([Ta],{type:"application/javascript"})));return{sleep:e=>(a.postMessage(["start",e]),new Promise(t=>{a.onmessage=i=>{i.data==="tick"&&t()}}))}}function Ii(a,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{a.apply(r,i)},e)}}var dn=35,ln=5,Ri=class{constructor(e,t,i){this.track=e;this.audioLevelEvent=t;this.silenceEvent=i;this.TAG="[TrackAudioLevelMonitor]";this.audioLevel=0;this.isMonitored=!1;this.interval=100;this.historyInterval=700;this.history=new Ue(this.historyInterval/this.interval);this.detectSilence=()=>c(this,null,function*(){let i=0;for(;this.isMonitored;){if(this.track.enabled)if(this.isSilentThisInstant()){if(i++,i>50){this.silenceEvent.publish({track:this.track});break}}else break;yield re(20)}});try{let r=new MediaStream([this.track.nativeTrack]);this.analyserNode=this.createAnalyserNodeForStream(r);let s=this.analyserNode.frequencyBinCount;this.dataArray=new Uint8Array(s)}catch(r){l.w(this.TAG,"Unable to initialize AudioContext",r)}}start(){this.stop(),this.isMonitored=!0,l.d(this.TAG,"Starting track Monitor",`${this.track}`),this.loop().then(()=>l.d(this.TAG,"Stopping track Monitor",`${this.track}`))}stop(){if(!this.analyserNode){l.d(this.TAG,"AudioContext not initialized");return}this.sendAudioLevel(0),this.isMonitored=!1}loop(){return c(this,null,function*(){for(;this.isMonitored;)this.sendAudioLevel(this.getMaxAudioLevelOverPeriod()),yield re(this.interval)})}sendAudioLevel(e=0){if(e=e>dn?e:0,Math.abs(this.audioLevel-e)>ln){this.audioLevel=e;let i={track:this.track,audioLevel:this.audioLevel};this.audioLevelEvent.publish(i)}}getMaxAudioLevelOverPeriod(){if(!this.analyserNode){l.d(this.TAG,"AudioContext not initialized");return}let e=this.calculateAudioLevel();return e!==void 0&&this.history.enqueue(e),this.history.aggregate(t=>Math.max(...t))}calculateAudioLevel(){if(!this.analyserNode||!this.dataArray){l.d(this.TAG,"AudioContext not initialized");return}this.analyserNode.getByteTimeDomainData(this.dataArray);let e=.009,t=e;for(let s of this.dataArray)t=Math.max(t,(s-128)/128);let i=(Math.log(e)-Math.log(t))/Math.log(e);return Math.ceil(Math.min(Math.max(i*100,0),100))}isSilentThisInstant(){if(!this.analyserNode||!this.dataArray){l.d(this.TAG,"AudioContext not initialized");return}return this.analyserNode.getByteTimeDomainData(this.dataArray),this.dataArray.every(e=>e===128||e===0)}createAnalyserNodeForStream(e){let t=de.getAudioContext(),i=t.createMediaStreamSource(e),r=t.createAnalyser();return r.fftSize=2048,i.connect(r),r}};function va(a,e){return function(i){return!(0,Ma.default)(a[i],e[i])}}var le=class a extends _e{constructor(t,i,r,s,o=new K().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this.TAG="[HMSLocalAudioTrack]";this.tracksCreated=new Set;this.isPublished=!1;this.handleVisibilityChange=()=>c(this,null,function*(){if(!this.shouldReacquireTrack()){l.d(this.TAG,`visibiltiy: ${document.visibilityState}`,`${this}`);return}if(document.visibilityState==="hidden")this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{l.d(this.TAG,"On visibile replacing track as it is not publishing");try{yield this.replaceTrackWith(this.settings)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.handleTrackMute=()=>{l.d(this.TAG,"muted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t}))};this.handleTrackUnmute=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t}));try{yield this.setEnabled(this.enabled),this.eventBus.localAudioUnmutedNatively.publish()}catch(i){this.eventBus.error.publish(i)}});this.replaceSenderTrack=()=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(this.processedTrack||this.nativeTrack)});this.shouldReacquireTrack=()=>ye(this.nativeTrack)||this.isTrackNotPublishing();this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=va(t,this.settings);(r("maxBitrate")||r("audioMode"))&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this,t)),(r("advanced")||r("audioMode"))&&(yield this.replaceTrackWith(t))});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(va(t,this.settings)("deviceId")){this.manuallySelectedDeviceId=i?this.manuallySelectedDeviceId:t.deviceId,l.d(this.TAG,"device change","manual selection:",this.manuallySelectedDeviceId,"new device:",t.deviceId),yield this.replaceTrackWith(t);let s=this.nativeTrack.getSettings().groupId;!i&&t.deviceId&&(Z.updateSelection("audioInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"audioInput",selection:{deviceId:t.deviceId,groupId:s}}))}});t.tracks.push(this),this.addTrackEventListeners(i),this.settings=o,o.deviceId!==i.getSettings().deviceId&&!ye(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new wt(this,s,n),this.setFirstTrackId(i.id),r==="regular"&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}clone(t){let i=this.nativeTrack.clone();t.nativeStream.addTrack(i);let r=new a(t,i,this.source,this.eventBus,this.settings,this.room);return r.peerId=this.peerId,this.pluginsManager.pluginsMap.size>0&&this.pluginsManager.pluginsMap.forEach(s=>{r.addPlugin(s).catch(o=>l.e(this.TAG,"Plugin add failed while migrating",s,o))}),r}getManuallySelectedDeviceId(){return this.manuallySelectedDeviceId}resetManuallySelectedDeviceId(){this.manuallySelectedDeviceId=void 0}updateTrack(t){return c(this,null,function*(){t.enabled=this.enabled,yield this.stream.replaceStreamTrack(this.nativeTrack,t),this.nativeTrack=t,yield this.replaceSenderTrack(),!!this.audioLevelMonitor&&this.initAudioLevelMonitor()})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop(),this.removeTrackEventListeners(i),this.tracksCreated.forEach(r=>r.stop()),this.tracksCreated.clear();try{let r=yield is(t);this.addTrackEventListeners(r),this.tracksCreated.add(r),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),yield this.updateTrack(r)}catch(r){let s=yield is(this.settings);throw this.addTrackEventListeners(s),this.tracksCreated.add(s),yield this.updateTrack(s),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}try{yield this.pluginsManager.reprocessPlugins()}catch(r){this.eventBus.audioPluginFailed.publish(r)}})}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(t&&this.shouldReacquireTrack()&&(yield this.replaceTrackWith(this.settings)),yield ce(a.prototype,this,"setEnabled").call(this,t),t&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),this.eventBus.localAudioEnabled.publish({enabled:t,track:this}))})}isPublishedTrackId(t){return this.publishedTrackId===t}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(ye(this.nativeTrack)){this.settings=r;return}yield this.handleDeviceChange(r,i),yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.pluginsManager.getPlugins()}addPlugin(t){return c(this,null,function*(){return this.pluginsManager.addPlugin(t)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}setProcessedTrack(t){return c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack()})}initAudioLevelMonitor(){this.audioLevelMonitor&&this.destroyAudioLevelMonitor(),l.d(this.TAG,"Monitor Audio Level for",this,this.getMediaTrackSettings().deviceId),this.audioLevelMonitor=new Ri(this,this.eventBus.trackAudioLevelUpdate,this.eventBus.localAudioSilence),this.audioLevelMonitor.start(),this.audioLevelMonitor.detectSilence()}destroyAudioLevelMonitor(){var t;(t=this.audioLevelMonitor)==null||t.stop(),this.audioLevelMonitor=void 0}cleanup(){return c(this,null,function*(){var t;ce(a.prototype,this,"cleanup").call(this),yield this.pluginsManager.cleanup(),yield this.pluginsManager.closeContext(),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.tracksCreated.forEach(i=>i.stop()),this.tracksCreated.clear(),this.isPublished=!1,this.destroyAudioLevelMonitor(),document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}getTrackIDBeingSent(){return this.processedTrack?this.processedTrack.id:this.nativeTrack.id}getTrackBeingSent(){return this.processedTrack||this.nativeTrack}addTrackEventListeners(t){t.addEventListener("mute",this.handleTrackMute),t.addEventListener("unmute",this.handleTrackUnmute)}removeTrackEventListeners(t){t.removeEventListener("mute",this.handleTrackMute),t.removeEventListener("unmute",this.handleTrackUnmute)}buildNewSettings(t){let{volume:i,codec:r,maxBitrate:s,deviceId:o,advanced:n,audioMode:d}=h(h({},this.settings),t);return new Ke(i,r,s,o,n,d)}};var se=class a extends _e{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield ce(a.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var rt=class extends we{constructor(t,i,r){super(t,i,r);this.type="video";this.sinkCount=0;this.handleTrackUnmute=()=>{this.getSinks().forEach(t=>this.reTriggerPlay({videoElement:t}))};this.reTriggerPlay=({videoElement:t})=>{setTimeout(()=>{t.play().catch(i=>{l.w("[HMSVideoTrack]","failed to play",i.message)})},0)};if(i.kind!=="video")throw new Error("Expected 'track' kind = 'video'")}setVideoHandler(t){this.videoHandler=t}hasSinks(){return this.sinkCount>0}getSinks(){return this.videoHandler.getVideoElements()||[]}attach(t){this.videoHandler.addVideoElement(t)}detach(t){this.videoHandler.removeVideoElement(t)}addSink(t){this.addSinkInternal(t,this.nativeTrack)}removeSink(t){t.srcObject!==null&&(t.srcObject=null,this.reduceSinkCount())}cleanup(){super.cleanup(),this.videoHandler.cleanup()}addSinkInternal(t,i){let r=t.srcObject;if(r!==null&&r instanceof MediaStream){let o=r.getVideoTracks()[0];if((o==null?void 0:o.id)===i.id){if(!o.muted&&o.readyState==="live")return;this.reduceSinkCount()}else this.reduceSinkCount()}this.addPropertiesToElement(t);let s=new MediaStream([i]);t.srcObject=s,this.reTriggerPlay({videoElement:t}),this.sinkCount++}reduceSinkCount(){this.sinkCount>0&&this.sinkCount--}addPropertiesToElement(t){ca||(t.autoplay=!0),t.playsInline=!0,t.muted=!0,t.controls=!1}};var Ra=Ge(require("lodash.isequal"));var Pa=require("uuid");var _t={none:-1,low:0,medium:1,high:2},un=.5,ya=(a,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...a].sort((o,n)=>_t[o.layer]-_t[n.layer]),s=e[i]*((window==null?void 0:window.devicePixelRatio)||1);for(let o=0;o<r.length;o++){let{resolution:n,layer:d}=r[o],u=n[i];if(s<=u){t=d;break}else{let p=r[o+1],m=p?p.resolution[i]:Number.POSITIVE_INFINITY;if((s-u)/(m-u)<un){t=d;break}}}return t};var ss=class{constructor(){this.TAG="[HMSIntersectionObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t)=>{var i;this.createObserver(),this.unobserve(e),(i=this.intersectionObserver)==null||i.observe(e),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.intersectionObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.intersectionObserver&&(this.intersectionObserver=new IntersectionObserver(this.handleIntersection))};this.handleIntersection=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.IntersectionObserver!="undefined";return e||l.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},ka=new ss;var as=class{constructor(){this.TAG="[HMSResizeObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t,i={box:"border-box"})=>{var r;this.createObserver(),this.unobserve(e),(r=this.resizeObserver)==null||r.observe(e,i),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.resizeObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.resizeObserver&&(this.resizeObserver=new ResizeObserver(Ii(this.handleResize,300)))};this.handleResize=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.ResizeObserver!="undefined";return e||l.w(this.TAG,"Resize Observer is not supported"),e}},Ea=new as;var st=class{constructor(e){this.track=e;this.TAG="[VideoElementManager]";this.videoElements=new Set;this.entries=new WeakMap;this.handleIntersection=e=>c(this,null,function*(){let t=getComputedStyle(e.target).visibility==="visible";this.track.enabled&&(e.isIntersecting&&t||!document.contains(e.target))?(l.d(this.TAG,"add sink intersection",`${this.track}`,this.id),this.entries.set(e.target,e.boundingClientRect),yield this.selectMaxLayer(),yield this.track.addSink(e.target)):(l.d(this.TAG,"remove sink intersection",`${this.track}`,this.id),yield this.track.removeSink(e.target))});this.handleResize=e=>c(this,null,function*(){!this.track.enabled||!(this.track instanceof O)||(this.entries.set(e.target,e.contentRect),yield this.selectMaxLayer())});this.cleanup=()=>{this.videoElements.forEach(e=>{var t,i;e.srcObject=null,(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e)}),this.videoElements.clear(),this.resizeObserver=void 0,this.intersectionObserver=void 0};this.init(),this.id=(0,Pa.v4)()}updateSinks(e=!1){for(let t of this.videoElements)this.track.enabled?this.track.addSink(t,e):this.track.removeSink(t,e)}addVideoElement(e){return c(this,null,function*(){var t;this.videoElements.has(e)||(this.init(),l.d(this.TAG,`Adding video element for ${this.track}`,this.id),this.videoElements.add(e),this.videoElements.size>=10&&l.w(this.TAG,`${this.track}`,`the track is added to ${this.videoElements.size} video elements, while this may be intentional, it's likely that there is a bug leading to unnecessary creation of video elements in the UI`),(t=this.intersectionObserver)!=null&&t.isSupported()?this.intersectionObserver.observe(e,this.handleIntersection):U&&(this.isElementInViewport(e)?this.track.addSink(e):this.track.removeSink(e)),this.resizeObserver?this.resizeObserver.observe(e,this.handleResize):this.track instanceof O&&(yield this.track.setPreferredLayer(this.track.getPreferredLayer())))})}removeVideoElement(e){var t,i;this.track.removeSink(e),this.videoElements.delete(e),this.entries.delete(e),(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e),l.d(this.TAG,`Removing video element for ${this.track}`)}getVideoElements(){return Array.from(this.videoElements)}init(){U&&(this.resizeObserver=Ea,this.intersectionObserver=ka)}isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft,r=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{opacity:n,display:d}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,t+=e.offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+s>window.pageYOffset&&i+r>window.pageXOffset&&!o&&(n!==""?parseFloat(n)>0:!0)&&d!=="none"}selectMaxLayer(){return c(this,null,function*(){if(!(this.track instanceof O)||this.videoElements.size===0)return;let e;for(let t of this.videoElements){let i=this.entries.get(t);if(!i)continue;let{width:r,height:s}=i;if(r===0||s===0)continue;let o=ya(this.track.getSimulcastDefinitions(),{width:r,height:s});e?e=_t[o]>_t[e]?o:e:e=o}e&&(l.d(this.TAG,`selecting max layer ${e} for the track`,`${this.track}`),yield this.track.setPreferredLayer(e))})}};var Hi=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(Hi||{}),Ci=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(Ci||{});var Nt=class{constructor(){this.total=0;this.count=0}add(e){this.count++,this.total+=e}getAvg(){return Math.floor(this.total/this.count)}reset(){this.total=0,this.count=0}};var at=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new Nt,this.addedTimestamps={},this.processingAvgs={},this.pluginAdded={},this.pluginInputFrameRate={},this.pluginFrameRate={}}added(e,t,i){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.processingAvgs[e]=new Nt,t&&(this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t),this.eventBus.analytics.publish(Se.added(e,this.addedTimestamps[e]))}removed(e){var t;if(this.pluginAdded[e]){let i={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],avgPreProcessingTime:this.preProcessingAvgs.getAvg(),avgProcessingTime:(t=this.processingAvgs[e])==null?void 0:t.getAvg(),inputFrameRate:this.pluginInputFrameRate[e],pluginFrameRate:this.pluginFrameRate[e]};this.eventBus.analytics.publish(Se.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(Se.failure(e,t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){l.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),l.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let s=S.MediaPluginErrors.InitFailed("VIDEO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw l.e(this.TAG,s),this.failure(e,s),s}i&&(this.initTime[e]=i)})}preProcessWithTime(e){return c(this,null,function*(){let t=yield this.timeInMs(e);this.preProcessingAvgs.add(t)})}processWithTime(e,t){return c(this,null,function*(){var r;let i;try{i=yield this.timeInMs(t)}catch(s){let o=S.MediaPluginErrors.ProcessingFailed("VIDEO_PLUGINS",`Failed during processing of plugin${s.message||s}`);throw l.e(this.TAG,o),this.failure(e,o),o}i&&((r=this.processingAvgs[e])==null||r.add(i))})}timeInMs(e){return c(this,null,function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)})}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.processingAvgs[e],delete this.pluginAdded[e],delete this.pluginInputFrameRate[e],delete this.pluginFrameRate[e]}};var ba=24,pn=320,hn=240,Ot=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.reusableWorker=fa();this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new at(t),this.canvases=new Array}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e,t){return c(this,null,function*(){var i;if(this.pluginAddInProgress){let r=(i=e.getName)==null?void 0:i.call(e);if(!r||r===""){l.w("no name provided by the plugin");return}let s=S.MediaPluginErrors.AddAlreadyInProgress("VIDEO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.failure(r,s),l.w("can't add another plugin when previous add is in progress"),s}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e,t)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e,t){return c(this,null,function*(){var o,n;let i=(o=e.getName)==null?void 0:o.call(e);if(!i||i===""){l.w("no name provided by the plugin");return}if(this.pluginsMap.has(i)){l.w(this.TAG,`plugin - ${e.getName()} already added.`);return}let r=this.hmsTrack.getMediaTrackSettings().frameRate||ba,s=0;t&&t>0?(l.i(this.TAG,`adding plugin ${e.getName()} with framerate ${t}`),t<r&&(s=Math.ceil(r/t)-1),this.analytics.added(i,r,t)):(l.i(this.TAG,`adding plugin ${e.getName()}`),this.analytics.added(i,r)),l.i(this.TAG,"numFrames to skip processing",s),this.pluginNumFramesToSkip[i]=s,this.pluginNumFramesSkipped[i]=s,this.validateAndThrow(i,e);try{if(yield this.analytics.initWithTime(i,()=>c(this,null,function*(){return yield e.init()})),this.pluginsMap.set(i,e),this.pluginsMap.size+1>this.canvases.length)for(let d=this.canvases.length;d<=this.pluginsMap.size;d++)this.canvases[d]=document.createElement("canvas");yield this.startPluginsLoop((n=e.getContextType)==null?void 0:n.call(e))}catch(d){throw l.e(this.TAG,"failed to add plugin",d),yield this.removePlugin(e),d}})}validatePlugin(e){return e.checkSupport()}validateAndThrow(e,t){let i=this.validatePlugin(t);if(i.isSupported)l.i(this.TAG,`plugin is supported,- ${t.getName()}`);else{let r;switch(i.errType){case"PLATFORM_NOT_SUPPORTED":throw r=S.MediaPluginErrors.PlatformNotSupported("VIDEO_PLUGINS","platform not supported, see docs"),this.analytics.failure(e,r),r;case"DEVICE_NOT_SUPPORTED":throw r=S.MediaPluginErrors.DeviceNotSupported("VIDEO_PLUGINS","video device not supported, see docs"),this.analytics.failure(e,r),r}}}removePlugin(e){return c(this,null,function*(){let t=e.getName();if(!this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} not found to remove.`);return}l.i(this.TAG,`removing plugin ${t}`),this.removePluginEntry(t),this.pluginsMap.size===0&&(l.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.stopPluginsLoop()),e.stop(),this.analytics.removed(t)})}removePluginEntry(e){this.pluginsMap.delete(e),this.pluginNumFramesToSkip[e]&&delete this.pluginNumFramesToSkip[e],this.pluginNumFramesSkipped[e]&&delete this.pluginNumFramesSkipped[e]}waitForRestart(){return c(this,null,function*(){if(!(!this.pluginsLoopRunning||this.pluginsLoopState==="running"))for(;this.pluginsLoopState==="paused";)yield Be(100)})}cleanup(){return c(this,null,function*(){var e;for(let t of this.pluginsMap.values())yield this.removePlugin(t);(e=this.outputTrack)==null||e.stop()})}initElementsAndStream(e){this.inputCanvas||(this.inputCanvas=document.createElement("canvas")),this.outputCanvas=document.createElement("canvas"),this.inputVideo||(this.inputVideo=document.createElement("video")),this.inputCanvas.getContext("2d"),this.outputCanvas.getContext(e||"2d");let t=this.outputCanvas.captureStream();this.outputTrack=t.getVideoTracks()[0]}startPluginsLoop(e){return c(this,null,function*(){if(!this.pluginsLoopRunning){this.initElementsAndStream(e),this.pluginsLoopRunning=!0;try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(t){throw this.pluginsLoopRunning=!1,l.e(this.TAG,"error in setting processed track",t),t}this.pluginsLoop().then(()=>{l.d(this.TAG,"processLoop stopped")})}})}stopPluginsLoop(){return c(this,null,function*(){var e;this.pluginsLoopRunning=!1,yield this.hmsTrack.setProcessedTrack(void 0),this.resetCanvases(),(e=this.outputTrack)==null||e.stop(),this.inputVideo&&(this.inputVideo.srcObject=null,this.inputVideo=void 0)})}pluginsLoop(){return c(this,null,function*(){for(;this.pluginsLoopRunning;){let e=this.hmsTrack.getMediaTrackSettings().frameRate||ba,t=Math.floor(1e3/e);if(!this.hmsTrack.enabled||this.hmsTrack.nativeTrack.readyState==="ended"){this.pluginsLoopState==="running"&&this.resetCanvases(),this.pluginsLoopState="paused",yield this.reusableWorker.sleep(t);continue}let i=0;try{yield this.analytics.preProcessWithTime(()=>c(this,null,function*(){return yield this.doPreProcessing()}));let r=Date.now();yield this.processFramesThroughPlugins(),i=Math.floor(Date.now()-r),i>t&&(i=t)}catch(r){l.e(this.TAG,"error in plugins loop",r)}this.pluginsLoopState="running",yield this.reusableWorker.sleep(t-i)}})}doPreProcessing(){return c(this,null,function*(){yield this.addTrackToVideo(),yield this.updateInputCanvas()})}processFramesThroughPlugins(){return c(this,null,function*(){this.canvases[0]=this.inputCanvas;let e=0;for(let t of this.pluginsMap.values()){let i=t.getName();if(t){try{let r=this.checkIfSkipRequired(i);if(t.getPluginType()==="TRANSFORM"){let s=(o,n)=>c(this,null,function*(){try{yield t.processVideoFrame(o,n,r)}catch(d){l.e(this.TAG,`error in processing plugin ${i}`,d)}});if(r)e===this.pluginsMap.size-1?yield s(this.canvases[e],this.outputCanvas):yield s(this.canvases[e],this.canvases[e+1]);else{let o=this.canvases[e],n=this.canvases[e+1];e===this.pluginsMap.size-1?yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return s(o,this.outputCanvas)})):yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return s(o,n)}))}}else t.getPluginType()==="ANALYZE"&&!r&&(yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return yield t.processVideoFrame(this.inputCanvas)})))}catch(r){l.e(this.TAG,`error in processing plugin ${i}`,r),yield this.removePlugin(t)}e++}}})}addTrackToVideo(){return c(this,null,function*(){var t;if(!this.inputVideo)return;let e=this.inputVideo.srcObject;e!==null&&e instanceof MediaStream&&((t=e.getVideoTracks()[0])==null?void 0:t.id)===this.hmsTrack.nativeTrack.id||(this.inputVideo.pause(),this.inputVideo.srcObject=new MediaStream([this.hmsTrack.nativeTrack]),this.inputVideo.muted=!0,this.inputVideo.playsInline=!0,yield this.inputVideo.play())})}updateInputCanvas(){return c(this,null,function*(){if(!this.inputCanvas||!this.inputVideo)return;let{width:e=pn,height:t=hn}=this.hmsTrack.getMediaTrackSettings();this.inputCanvas.height!==t&&(this.inputCanvas.height=t),this.inputCanvas.width!==e&&(this.inputCanvas.width=e),this.inputCanvas.getContext("2d").drawImage(this.inputVideo,0,0,e,t)})}resetCanvases(){if(!this.outputCanvas||!this.inputCanvas)return;let e=this.inputCanvas.getContext("2d");e&&(e.fillStyle="rgb(0, 0, 0)",e.fillRect(0,0,this.outputCanvas.width,this.outputCanvas.height)),this.canvases=[]}checkIfSkipRequired(e){let t=!1;return this.pluginNumFramesSkipped[e]<this.pluginNumFramesToSkip[e]?(this.pluginNumFramesSkipped[e]++,t=!0):(t=!1,this.pluginNumFramesSkipped[e]=0),t}};var Li=class{constructor(e,t){this.TAG="[MediaStreamPluginsManager]";this.plugins=new Set,this.analytics=new at(e),this.room=t}addPlugins(e){e.forEach(t=>{var i;switch(t.getName()){case"HMSEffectsPlugin":if(!((i=this.room)!=null&&i.isEffectsEnabled)){let r="Effects Virtual Background is not enabled for this room";if(this.plugins.size===0)throw Error(r);l.w(this.TAG,r);return}break;default:}this.plugins.add(t)})}removePlugins(e){e.forEach(t=>{t.stop(),this.analytics.removed(t.getName()),this.plugins.delete(t)})}applyPlugins(e){let t=e;for(let i of this.plugins){let r=i.getName();try{t=i.apply(t),this.analytics.added(r)}catch(s){this.analytics.failure(r,s),l.e("Could not apply plugin",s,r)}}return t}getPlugins(){return Array.from(this.plugins).map(e=>e.getName())}cleanup(){return c(this,null,function*(){this.removePlugins(Array.from(this.plugins))})}};var Aa=require("uuid");var mn=["init_response_time","ws_connect_time","on_policy_change_time","local_audio_track_time","local_video_track_time","peer_list_time","room_state_time","join_response_time"],Di=class{constructor(){this.eventPerformanceMeasures={}}start(e){performance.mark(e)}end(e){var t;try{this.eventPerformanceMeasures[e]=performance.measure(e,e),l.d("[HMSPerformanceTiming]",e,(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration)}catch(i){l.w("[AnalyticsTimer]",`Error in measuring performance for event ${e}`,{error:i})}}getTimeTaken(e){var t;return(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration}getTimes(...e){return[...mn,...e].reduce((t,i)=>M(h({},t),{[i]:this.getTimeTaken(i)}),{})}cleanup(){this.eventPerformanceMeasures={}}};var os={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default",audioMode:"voice"},ke,wi,Ie=class a{constructor(e,t,i,r,s){this.store=e;this.observer=t;this.deviceManager=i;this.eventBus=r;this.analyticsTimer=s;this.TAG="[LocalTrackManager]";this.setScreenCaptureHandleConfig()}getTracksToPublish(){return c(this,arguments,function*(e=os){let t=this.getAVTrackSettings(e);if(!t)return[];let i=!!t.audio,r=!!t.video,s=[],{videoTrack:o,audioTrack:n}=yield this.updateCurrentLocalTrackSettings(t),d=(o==null?void 0:o.stream)||(n==null?void 0:n.stream),u=!!(o&&this.store.getTrackById(o.trackId)),p=!!(n&&this.store.getTrackById(n.trackId));if(u&&p)return[];let m={audio:i&&!n&&(e.isAudioMuted?"empty":!0),video:r&&!o&&(e.isVideoMuted?"empty":!0)};m.audio&&this.analyticsTimer.start("local_audio_track_time"),m.video&&this.analyticsTimer.start("local_video_track_time");try{l.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:m}),s=yield this.getLocalTracks(m,t,d)}catch(T){s=yield this.retryGetLocalTracks(T,t,m,d)}return m.audio&&this.analyticsTimer.end("local_audio_track_time"),m.video&&this.analyticsTimer.end("local_video_track_time"),o&&r&&!u&&s.push(o),n&&i&&!p&&s.push(n),s})}getLocalTracks(){return c(this,arguments,function*(e={audio:!0,video:!0},t,i){try{let r=yield this.getNativeLocalTracks(e,t);return this.createHMSLocalTracks(r,t,i)}catch(r){throw this.eventBus.analytics.publish(y.publish({devices:this.deviceManager.getDevices(),error:r,settings:t})),r}})}getNativeLocalTracks(){return c(this,arguments,function*(e={audio:!1,video:!1},t){let i=new it(e.video===!0?t.video:null,e.audio===!0?t.audio:null,t.simulcast),r=[];return(i.audio||i.video)&&r.push(...yield this.getAVTracks(i)),r.push(...this.getEmptyTracks(e)),r})}optimizeScreenShareConstraint(e,t){return c(this,null,function*(){var s,o,n;if(typeof t.video=="boolean"||!((s=t.video)!=null&&s.width)||!((o=t.video)!=null&&o.height))return;let i=this.store.getPublishParams();if(!i||!((n=i.allowed)!=null&&n.includes("screen")))return;let r=document.createElement("video");r.srcObject=e,r.addEventListener("loadedmetadata",()=>c(this,null,function*(){let{videoWidth:d,videoHeight:u}=r,p=i.screen,m=p.width*p.height,T=d/u,g=p.width/p.height;if(T>g){let f=t.video,E=T/g,v=Math.sqrt(E);d*u>m?(f.width=d/v,f.height=u/v):(f.height=u*v,f.width=d*v),yield e.getVideoTracks()[0].applyConstraints(f)}}))})}getLocalScreen(e,t=!1){return c(this,null,function*(){var T;let i=yield this.getOrDefaultScreenshareConfig(e),r=this.getScreenshareSettings(i.videoOnly),s={video:M(h({},r==null?void 0:r.video.toConstraints(!0)),{displaySurface:i.displaySurface}),preferCurrentTab:i.preferCurrentTab,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio};if(r!=null&&r.audio){let g=(T=r==null?void 0:r.audio)==null?void 0:T.toConstraints();delete g.advanced,s.audio=M(h({},g),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})}else e!=null&&e.forceCurrentTab&&e.preferCurrentTab&&e.cropElement&&(s.audio={echoCancellation:!0,noiseSuppression:!0});let o;try{l.d("retrieving screenshare with ",{config:i},{constraints:s}),o=yield navigator.mediaDevices.getDisplayMedia(s),t&&(yield this.optimizeScreenShareConstraint(o,s))}catch(g){l.w(this.TAG,"error in getting screenshare - ",g);let f=xe(g,"screen");throw this.eventBus.analytics.publish(y.publish({error:f,devices:this.deviceManager.getDevices(),settings:new it(r==null?void 0:r.video,r==null?void 0:r.audio,!1)})),f}let n=[],d=new ge(o),u=o.getVideoTracks()[0],p=new G(d,u,"screen",this.eventBus,r==null?void 0:r.video,this.store.getRoom());p.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"screen"));try{let g=this.validateCurrentTabCapture(p,i.forceCurrentTab);p.isCurrentTab=g,yield p.cropTo(i.cropTarget)}catch(g){throw o.getTracks().forEach(f=>f.stop()),g}n.push(p);let m=o.getAudioTracks()[0];if(m){let g=new le(d,m,"screen",this.eventBus,r==null?void 0:r.audio,this.store.getRoom());n.push(g)}return l.v(this.TAG,"getLocalScreen",n),n})}setScreenCaptureHandleConfig(e){var t;!((t=navigator.mediaDevices)!=null&&t.setCaptureHandleConfig)||this.isInIframe()||(e=e||{},Object.assign(e,{handle:(0,Aa.v4)(),exposeOrigin:!1,permittedOrigins:[window.location.origin]}),l.d("setting capture handle - ",e.handle),navigator.mediaDevices.setCaptureHandleConfig(e),this.captureHandleIdentifier=e.handle)}validateCurrentTabCapture(e,t){let i=e.getCaptureHandle(),r=!!(this.captureHandleIdentifier&&(i==null?void 0:i.handle)===this.captureHandleIdentifier);if(t&&!r)throw l.e(this.TAG,"current tab was not shared with forceCurrentTab as true"),S.TracksErrors.CurrentTabNotShared();return r}requestPermissions(){return c(this,null,function*(){try{(yield navigator.mediaDevices.getUserMedia({audio:!0,video:!0})).getTracks().forEach(t=>t.stop())}catch(e){l.e(this.TAG,e)}})}static getEmptyVideoTrack(e){var n,d,u;let t=((n=e==null?void 0:e.getSettings())==null?void 0:n.width)||320,i=((d=e==null?void 0:e.getSettings())==null?void 0:d.height)||240,r=1;ke||(ke=document.createElement("canvas"),ke.width=t,ke.height=i,(u=ke.getContext("2d"))==null||u.fillRect(0,0,t,i)),wi||(wi=setInterval(()=>{let p=ke==null?void 0:ke.getContext("2d");p&&p.fillRect(0,0,1,1)},1e3/r));let o=ke.captureStream(r).getVideoTracks()[0];return o.enabled=!1,o}static getEmptyAudioTrack(){let e=de.getAudioContext(),t=e.createOscillator(),i=e.createMediaStreamDestination();t.connect(i),t.start();let r=i.stream.getAudioTracks()[0];return r.enabled=!1,r}static cleanup(){clearInterval(wi),wi=void 0,ke=void 0}getAVTracks(e){return c(this,null,function*(){try{let t=yield navigator.mediaDevices.getUserMedia({audio:e.audio?e.audio.toConstraints():!1,video:e.video?e.video.toConstraints():!1});return t.getVideoTracks().concat(t.getAudioTracks())}catch(t){yield this.deviceManager.init();let i=!!(!this.deviceManager.hasWebcamPermission&&e.video),r=!!(!this.deviceManager.hasMicrophonePermission&&e.audio),s=this.getErrorType(i,r);throw xe(t,s)}})}getAVTrackSettings(e){let t=this.getAudioSettings(e),i=this.getVideoSettings(e);return!t&&!i?null:new Oe().video(i).audio(t).build()}isInIframe(){try{return window.self!==window.top}catch(e){return!0}}retryGetLocalTracks(e,t,i,r){return c(this,null,function*(){if(e instanceof k&&e.action==="TRACK"){this.observer.onFailure(e);let s=e.code===P.TracksErrors.OVER_CONSTRAINED,o=e.message.includes("audio"),n=e.message.includes("video");if(s){let d=new Oe().video(new qe).audio(new Ke).build();l.w(this.TAG,"Fetch AV Tracks failed with overconstrained error",{fetchTrackOptions:i},{error:e});try{return yield this.getLocalTracks(i,d,r)}catch(u){let p=u instanceof k?u.nativeError:u,m=u;if((p==null?void 0:p.name)==="OverconstrainedError"){let T=S.TracksErrors.GenericTrack("TRACK","Overconstrained error after dropping all constraints");T.addNativeError(p),m=T}return yield this.retryGetLocalTracks(m,t,i,r)}}i.audio=o?"empty":i.audio,i.video=n?"empty":i.video,l.w(this.TAG,"Fetch AV Tracks failed",{fetchTrackOptions:i},e);try{return yield this.getLocalTracks(i,t,r)}catch(d){return l.w(this.TAG,"Fetch empty tacks failed",d),i.audio=i.audio&&"empty",i.video=i.video&&"empty",this.observer.onFailure(d),yield this.getLocalTracks(i,t,r)}}else return l.w(this.TAG,"Fetch AV Tracks failed - unknown exception",e),this.observer.onFailure(e),[]})}getErrorType(e,t){return e&&t?"audio, video":e?"video":t?"audio":"audio, video"}getEmptyTracks(e){let t=[];return e.audio==="empty"&&t.push(a.getEmptyAudioTrack()),e.video==="empty"&&t.push(a.getEmptyVideoTrack()),t}updateCurrentLocalTrackSettings(e){return c(this,null,function*(){let t=this.store.getLocalPeerTracks(),i=t.find(n=>n.type==="video"&&n.source==="regular"),r=t.find(n=>n.type==="audio"&&n.source==="regular"),s=t.find(n=>n.type==="video"&&n.source==="screen");e!=null&&e.video&&(yield i==null?void 0:i.setSettings(e.video)),e!=null&&e.audio&&(yield r==null?void 0:r.setSettings(e.audio));let o=this.getScreenshareSettings(!0);return o!=null&&o.video&&(yield s==null?void 0:s.setSettings(o==null?void 0:o.video)),{videoTrack:i,audioTrack:r}})}getAudioSettings(e){var o;let t=this.store.getPublishParams();if(!t||!((o=t.allowed)!=null&&o.includes("audio")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.audioTrack,s=(r==null?void 0:r.settings.deviceId)||e.audioInputDeviceId;return new K().codec(t.audio.codec).maxBitrate(t.audio.bitRate).deviceId(s||os.audioInputDeviceId).build()}getVideoSettings(e){var n;let t=this.store.getPublishParams();if(!t||!((n=t.allowed)!=null&&n.includes("video")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.videoTrack,s=(r==null?void 0:r.settings.deviceId)||e.videoDeviceId,o=t.video;return new j().codec(o.codec).maxBitrate(o.bitRate).maxFramerate(o.frameRate).setWidth(o.width).setHeight(o.height).deviceId(s||os.videoDeviceId).build()}getScreenshareSettings(e=!1){var r;let t=this.store.getPublishParams();if(!t||!((r=t.allowed)!=null&&r.includes("screen")))return null;let i=t.screen;return{video:new j().maxBitrate(i.bitRate,!1).codec(i.codec).maxFramerate(i.frameRate).setWidth(i.width).setHeight(i.height).build(),audio:e?void 0:new K().build()}}getOrDefaultScreenshareConfig(e){return c(this,null,function*(){var i;let t=Object.assign({videoOnly:!1,audioOnly:!1,forceCurrentTab:!1,preferCurrentTab:!1,selfBrowserSurface:"exclude",surfaceSwitching:"include",systemAudio:"exclude",displaySurface:"monitor"},e||{});return t.forceCurrentTab&&(t.videoOnly=!0,t.preferCurrentTab=!0,t.selfBrowserSurface="include",t.surfaceSwitching="exclude"),t.preferCurrentTab&&(t.selfBrowserSurface="include",t.displaySurface=void 0),t.cropElement&&((i=window.CropTarget)!=null&&i.fromElement)&&(t.cropTarget=yield window.CropTarget.fromElement(t.cropElement)),t})}createHMSLocalTracks(e,t,i){let r=e.find(n=>n.kind==="video"),s=e.find(n=>n.kind==="audio");i?e.forEach(n=>i==null?void 0:i.nativeStream.addTrack(n)):i=new ge(new MediaStream(e));let o=[];if(s&&(t!=null&&t.audio)){let n=new le(i,s,"regular",this.eventBus,t.audio,this.store.getRoom());o.push(n)}if(r&&(t!=null&&t.video)){let n=new G(i,r,"regular",this.eventBus,t.video,this.store.getRoom());n.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"regular")),o.push(n)}return o}};function Ia(a,e){return function(i){return!(0,Ra.default)(a[i],e[i])}}var G=class a extends rt{constructor(t,i,r,s,o=new j().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this._layerDefinitions=[];this.TAG="[HMSLocalVideoTrack]";this.enabledStateBeforeBackground=!1;this.isCurrentTab=!1;this.isPublished=!1;this.replaceSenderTrack=t=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(t)});this.buildNewSettings=t=>{let{width:i,height:r,codec:s,maxFramerate:o,maxBitrate:n,deviceId:d,advanced:u,facingMode:p}=h(h({},this.settings),t);return new qe(i,r,s,o,d,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Ia(t,this.settings);if(r("maxBitrate")&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this)),r("width")||r("height")||r("advanced"))if(this.source==="video"){let s=yield this.replaceTrackWith(t);yield this.replaceSender(s,this.enabled),this.nativeTrack=s,yield this.processPlugins(),this.videoHandler.updateSinks()}else yield this.nativeTrack.applyConstraints(t.toConstraints())});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(Ia(t,this.settings)("deviceId")&&this.source==="regular"){if(this.enabled){delete t.facingMode;let o=yield this.replaceTrackWith(t);yield this.replaceSender(o,this.enabled),this.nativeTrack=o,yield this.processPlugins(),this.videoHandler.updateSinks()}let s=this.nativeTrack.getSettings().groupId;!i&&t.deviceId&&(Z.updateSelection("videoInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"video",selection:{deviceId:t.deviceId,groupId:s}}))}});this.handleTrackMute=()=>{l.d(this.TAG,"muted natively",document.visibilityState);let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t})),this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmuteNatively=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t})),this.handleTrackUnmute(),this.eventBus.localVideoEnabled.publish({enabled:this.enabled,track:this}),this.eventBus.localVideoUnmutedNatively.publish(),yield this.setEnabled(this.enabled)});this.removeOrReplaceProcessedTrack=t=>c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack(this.processedTrack||this.nativeTrack)});this.handleVisibilityChange=()=>c(this,null,function*(){if(document.visibilityState==="hidden")this.enabledStateBeforeBackground=this.enabled,this.enabled&&(yield this.setEnabled(!1)),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{if(l.d(this.TAG,"visibility visible, restoring track state",this.enabledStateBeforeBackground),this.enabledStateBeforeBackground)try{yield this.setEnabled(!0)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.addTrackEventListeners(i),t.tracks.push(this),this.setVideoHandler(new st(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Ot(this,s),this.mediaStreamPluginsManager=new Li(s,n),this.setFirstTrackId(this.trackId),this.eventBus.localAudioUnmutedNatively.subscribe(this.handleTrackUnmute),U&&r==="regular"&&Rt()&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}clone(t){let i=this.nativeTrack.clone();t.nativeStream.addTrack(i);let r=new a(t,i,this.source,this.eventBus,this.settings,this.room);return r.peerId=this.peerId,this.pluginsManager.pluginsMap.size>0&&this.pluginsManager.pluginsMap.forEach(s=>{r.addPlugin(s).catch(o=>l.e(this.TAG,"Plugin add failed while migrating",s,o))}),this.mediaStreamPluginsManager.plugins.size>0&&r.addStreamPlugins(Array.from(this.mediaStreamPluginsManager.plugins)),r}setSimulcastDefinitons(t){this._layerDefinitions=t}getSimulcastDefinitions(){return this._layerDefinitions}setEnabled(t){return c(this,null,function*(){var i;if(t!==this.enabled){if(this.source==="regular"){let r;t?r=yield this.replaceTrackWith(this.settings):r=yield this.replaceTrackWithBlank(),yield this.replaceSender(r,t),(i=this.nativeTrack)==null||i.stop(),this.nativeTrack=r,yield ce(a.prototype,this,"setEnabled").call(this,t),t&&(yield this.pluginsManager.waitForRestart(),yield this.processPlugins(),this.settings=this.buildNewSettings({deviceId:r.getSettings().deviceId})),this.videoHandler.updateSinks()}this.eventBus.localVideoEnabled.publish({enabled:t,track:this})}})}processPlugins(){return c(this,null,function*(){try{if(this.pluginsManager.getPlugins().length>0)return;if(this.mediaStreamPluginsManager.getPlugins().length>0){let r=this.mediaStreamPluginsManager.applyPlugins(new MediaStream([this.nativeTrack])).getVideoTracks()[0];yield this.setProcessedTrack(r)}else yield this.setProcessedTrack();this.videoHandler.updateSinks()}catch(t){console.error("error in processing plugin(s)",t)}})}addStreamPlugins(t){return c(this,null,function*(){if(this.pluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSMediaStreamPlugin and HMSVideoPlugin cannot be used together");this.mediaStreamPluginsManager.addPlugins(t),yield this.processPlugins()})}removeStreamPlugins(t){return c(this,null,function*(){this.mediaStreamPluginsManager.removePlugins(t),yield this.processPlugins()})}isPublishedTrackId(t){return this.publishedTrackId===t}addSink(t){this.addSinkInternal(t,this.processedTrack||this.nativeTrack)}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(yield this.handleDeviceChange(r,i),!this.enabled||ye(this.nativeTrack)){this.settings=r;return}else yield this.pluginsManager.waitForRestart();yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.mediaStreamPluginsManager.getPlugins().length>0?this.mediaStreamPluginsManager.getPlugins():this.pluginsManager.getPlugins()}addPlugin(t,i){return c(this,null,function*(){if(this.mediaStreamPluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSVideoPlugin and HMSMediaStreamPlugin cannot be used together");return this.pluginsManager.addPlugin(t,i)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}cleanup(){return c(this,null,function*(){var t;this.eventBus.localAudioUnmutedNatively.unsubscribe(this.handleTrackUnmute),this.removeTrackEventListeners(this.nativeTrack),yield this.mediaStreamPluginsManager.cleanup(),yield this.pluginsManager.cleanup(),ce(a.prototype,this,"cleanup").call(this),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,U&&Rt()&&document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}cropTo(t){return c(this,null,function*(){if(t&&this.source==="screen")try{this.nativeTrack.cropTo&&(yield this.nativeTrack.cropTo(t))}catch(i){throw l.e(this.TAG,"failed to crop screenshare capture - ",i),S.TracksErrors.GenericTrack("TRACK","failed to crop screenshare capture")}})}getCaptureHandle(){if(this.nativeTrack.getCaptureHandle)return this.nativeTrack.getCaptureHandle()}setProcessedTrack(t){return c(this,null,function*(){if(!this.nativeTrack.enabled){this.processedTrack=t;return}yield this.removeOrReplaceProcessedTrack(t),this.videoHandler.updateSinks()})}getTrackIDBeingSent(){return this.getTrackBeingSent().id}getTrackBeingSent(){return this.enabled?this.processedTrack||this.nativeTrack:this.nativeTrack}switchCamera(){return c(this,null,function*(){var s;let t=this.getMediaTrackSettings().facingMode;if(!t||this.source!=="regular"){l.d(this.TAG,"facingMode not supported");return}let i=t==="environment"?"user":"environment";(s=this.nativeTrack)==null||s.stop();let r=yield this.replaceTrackWith(this.buildNewSettings({facingMode:i,deviceId:void 0}));yield this.replaceSender(r,this.enabled),this.nativeTrack=r,yield this.processPlugins(),this.videoHandler.updateSinks(),this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId,facingMode:i}),Z.updateSelection("videoInput",{deviceId:this.settings.deviceId,groupId:this.nativeTrack.getSettings().groupId})})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;this.removeTrackEventListeners(i),i==null||i.stop();try{let r=yield rs(t);return this.addTrackEventListeners(r),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),this.settings.deviceId==="default"&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),r}catch(r){let s=yield rs(this.settings);throw this.addTrackEventListeners(s),yield this.replaceSender(s,this.enabled),this.nativeTrack=s,yield this.processPlugins(),this.videoHandler.updateSinks(),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=Ie.getEmptyVideoTrack(t);return this.removeTrackEventListeners(t),this.addTrackEventListeners(i),t==null||t.stop(),l.d(this.TAG,"replaceTrackWithBlank, Previous track stopped",t,"newTrack",i),i})}replaceSender(t,i){return c(this,null,function*(){i?yield this.replaceSenderTrack(this.processedTrack||t):yield this.replaceSenderTrack(t),this.stream.replaceStreamTrack(this.nativeTrack,t)})}addTrackEventListeners(t){t.addEventListener("mute",this.handleTrackMute),t.addEventListener("unmute",this.handleTrackUnmuteNatively)}removeTrackEventListeners(t){t.removeEventListener("mute",this.handleTrackMute),t.removeEventListener("unmute",this.handleTrackUnmuteNatively)}};var ot="renegotiation-callback-id",_i="ion-sfu";var nt="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var Ha="https://event.100ms.live/v2/client/report",Ca="https://event-nonprod.100ms.live/v2/client/report";var xt=Math.pow(2,31)-1,F={DEVICE_CHANGE:"device-change",LOCAL_AUDIO_ENABLED:"local-audio-enabled",LOCAL_VIDEO_ENABLED:"local-video-enabled",LOCAL_VIDEO_UNMUTED_NATIVELY:"local-video-unmuted-natively",LOCAL_AUDIO_UNMUTED_NATIVELY:"local-audio-unmuted-natively",STATS_UPDATE:"stats-update",RTC_STATS_UPDATE:"rtc-stats-update",TRACK_DEGRADED:"track-degraded",TRACK_RESTORED:"track-restored",TRACK_AUDIO_LEVEL_UPDATE:"track-audio-level-update",LOCAL_AUDIO_SILENCE:"local-audio-silence",ANALYTICS:"analytics",AUDIO_PLUGIN_FAILED:"audio-plugin-failed",POLICY_CHANGE:"policy-change",LOCAL_ROLE_UPDATE:"local-role-update",AUDIO_TRACK_UPDATE:"audio-track-update",AUDIO_TRACK_ADDED:"audio-track-added",AUDIO_TRACK_REMOVED:"audio-track-removed",AUTOPLAY_ERROR:"autoplay-error",LEAVE:"leave",ERROR:"error"},La="2.5",Da="20250115",Re="_handraise",cs=1e3,ds=64,wa="https://whiteboard.100ms.live",_a="https://whiteboard-qa.100ms.live";var O=class a extends rt{constructor(t,i,r,s){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new ls;this.preferredLayer="high";this.disableNoneLayerRequest=!1;this.disableNoneLayerRequest=!!s,this.setVideoHandler(new st(this))}setTrackId(t){this.bizTrackId=t}get trackId(){return this.bizTrackId||super.trackId}get degraded(){return this._degraded}get degradedAt(){return this._degradedAt}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(ce(a.prototype,this,"setEnabled").call(this,t),this.videoHandler.updateSinks(!0))})}setPreferredLayer(t){return c(this,null,function*(){if(t==="none"){l.w("layer none will be ignored");return}if(this.preferredLayer=t,!!this.shouldSendVideoLayer(t,"preferLayer")){if(!this.hasSinks()){l.d(`[Remote Track] ${this.logIdentifier}
|
|
48
48
|
streamId=${this.stream.id}
|
|
49
49
|
trackId=${this.trackId}
|
|
50
50
|
saving ${t}, source=${this.source}
|
|
51
|
-
Track does not have any sink`);return}yield this.requestLayer(t,"preferLayer"),this.pushInHistory(`uiPreferLayer-${t}`)}})}getSimulcastLayer(){return this.stream.getSimulcastLayer()}getLayer(){return this.stream.getVideoLayer()}getPreferredLayer(){return this.preferredLayer}getPreferredLayerDefinition(){return this._layerDefinitions.find(t=>t.layer===this.preferredLayer)}replaceTrack(t){this.nativeTrack=t.nativeTrack,t.transceiver&&(this.transceiver=t.transceiver,this.stream.updateId(t.stream.id)),this.videoHandler.updateSinks()}addSink(t,i=!0){return c(this,null,function*(){ye(this.nativeTrack)?yield this.requestLayer(this.preferredLayer,"addSink"):(
|
|
51
|
+
Track does not have any sink`);return}yield this.requestLayer(t,"preferLayer"),this.pushInHistory(`uiPreferLayer-${t}`)}})}getSimulcastLayer(){return this.stream.getSimulcastLayer()}getLayer(){return this.stream.getVideoLayer()}getPreferredLayer(){return this.preferredLayer}getPreferredLayerDefinition(){return this._layerDefinitions.find(t=>t.layer===this.preferredLayer)}replaceTrack(t){this.nativeTrack=t.nativeTrack,t.transceiver&&(this.transceiver=t.transceiver,this.stream.updateId(t.stream.id)),this.videoHandler.updateSinks()}addSink(t,i=!0){return c(this,null,function*(){ye(this.nativeTrack)?yield this.requestLayer(this.preferredLayer,"addSink"):(ce(a.prototype,this,"addSink").call(this,t),i&&(yield this.updateLayer("addSink"))),this.pushInHistory("uiSetLayer-high")})}removeSink(t,i=!0){return c(this,null,function*(){ce(a.prototype,this,"removeSink").call(this,t),i&&(yield this.updateLayer("removeSink")),this._degraded=!1,this.pushInHistory("uiSetLayer-none")})}getSimulcastDefinitions(){return[...this._layerDefinitions]}setSimulcastDefinitons(t){this._layerDefinitions=t}setLayerFromServer(t){this._degraded=this.getDegradationValue(t),this._degradedAt=this._degraded?new Date:this._degradedAt;let i=t.current_layer;return l.d(`[Remote Track] ${this.logIdentifier}
|
|
52
52
|
streamId=${this.stream.id}
|
|
53
53
|
trackId=${this.trackId}
|
|
54
54
|
layer update from sfu
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
Setting layer field to=${t}`)}setVideoLayer(t,i,r,s){return l.d(`[Remote stream] ${r}
|
|
73
73
|
streamId=${this.id}
|
|
74
74
|
trackId=${i}
|
|
75
|
-
source: ${s} request ${t} layer`),this.setVideoLayerLocally(t,r,s),this.connection.sendOverApiDataChannelWithResponse({params:{max_spatial_layer:this.video,track_id:i},method:"prefer-video-track-state"})}getSimulcastLayer(){return this.video}getVideoLayer(){return this.video}isAudioSubscribed(){return this.audio}};var Na=(a,e,t,i)=>c(void 0,null,function*(){var o;let r,s={};if((o=e.transceiver)!=null&&o.sender.track){try{r=yield e.transceiver.sender.getStats();let n={},d={},u={};r==null||r.forEach(p=>{switch(p.type){case"outbound-rtp":d[p.id]=p;break;case"remote-inbound-rtp":u[p.ssrc]=p;break;case"codec":n[p.id]=p.mimeType;break;default:break}}),Object.keys(h({},d)).forEach(p=>{var v,
|
|
75
|
+
source: ${s} request ${t} layer`),this.setVideoLayerLocally(t,r,s),this.connection.sendOverApiDataChannelWithResponse({params:{max_spatial_layer:this.video,track_id:i},method:"prefer-video-track-state"})}getSimulcastLayer(){return this.video}getVideoLayer(){return this.video}isAudioSubscribed(){return this.audio}};var Na=(a,e,t,i)=>c(void 0,null,function*(){var o;let r,s={};if((o=e.transceiver)!=null&&o.sender.track){try{r=yield e.transceiver.sender.getStats();let n={},d={},u={};r==null||r.forEach(p=>{switch(p.type){case"outbound-rtp":d[p.id]=p;break;case"remote-inbound-rtp":u[p.ssrc]=p;break;case"codec":n[p.id]=p.mimeType;break;default:break}}),Object.keys(h({},d)).forEach(p=>{var v,R;let m=(v=d[p])==null?void 0:v.codecId,T=m?n[m]:void 0,g;T&&(g=T.substring(T.indexOf("/")+1));let f=M(h({},d[p]),{rid:(R=d[p])==null?void 0:R.rid}),E=u[f.ssrc];s[p]=M(h({},f),{bitrate:Ut("bytesSent",f,i==null?void 0:i[p]),packetsLost:E==null?void 0:E.packetsLost,jitter:E==null?void 0:E.jitter,roundTripTime:E==null?void 0:E.roundTripTime,totalRoundTripTime:E==null?void 0:E.totalRoundTripTime,peerName:t,peerID:e.peerId,enabled:e.enabled,codec:g})})}catch(n){a.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("TRACK",`Error getting local track stats ${e.trackId} - ${n.message}`))),l.w("[HMSWebrtcStats]","Error in getting local track stats",e,n,n.name)}return s}}),Oa=(a,e,t,i)=>c(void 0,null,function*(){var d;let r;try{r=yield(d=e.transceiver)==null?void 0:d.receiver.getStats()}catch(u){a.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("TRACK",`Error getting remote track stats ${e.trackId} - ${u.message}`))),l.w("[HMSWebrtcStats]","Error in getting remote track stats",e,u)}let s=Sn(r),o=Ut("bytesReceived",s,i),n=us("packetsLost",s,i);return s!=null&&s.remote&&Object.assign(s.remote,{packetsLostRate:us("packetsLost",s.remote,i==null?void 0:i.remote)}),s&&M(h({},s),{bitrate:o,packetsLostRate:n,peerID:e.peerId,enabled:e.enabled,peerName:t,codec:s.codec})}),Sn=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;return r&&(s=r.substring(r.indexOf("/")+1)),e&&Object.assign(e,{remote:t,codec:s})},ps=(a,e,t)=>{let i=gn(e),r=Ut(a==="publish"?"bytesSent":"bytesReceived",i,t&&t[a]);return i&&Object.assign(i,{bitrate:r})},gn=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},xa=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},Ua=(a,e)=>Array.from(new Set(a.concat(e))),Ut=(a,e,t)=>us(a,e,t)*8,us=(a,e,t)=>{let i=e&&e[a],r=t?t[a]:null;return[e,t,me(i),me(r)].every(o=>!!o)?hs(i,r,e==null?void 0:e.timestamp,t==null?void 0:t.timestamp)*1e3:0},hs=(a,e,t,i)=>me(a)&&me(e)&&t&&i?(a-e)/(t-i):0;var Ni=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,m,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))),l.w(this.TAG,"Error in getting publish stats",f)}let i=t&&ps("publish",t,e),r;try{r=yield(m=this.subscribeConnection)==null?void 0:m.getStats()}catch(f){this.eventBus.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("SUBSCRIBE",f.message))),l.w(this.TAG,"Error in getting subscribe stats",f)}let s=r&&ps("subscribe",r,e),{packetsLost:o,jitter:n}=xa(r),d=hs(o,(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:d,jitter:n,packetsLost:o});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 O||r instanceof se),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),o=this.getRemoteTrackStats(r.trackId),n=yield Oa(this.eventBus,r,s,o);n&&(this.remoteTrackStats[r.trackId]=n)}});this.updateLocalTrackStats=()=>c(this,null,function*(){var i;let e=this.store.getLocalPeerTracks().reduce((r,s)=>(r[s.getTrackIDBeingSent()]=s,r),{}),t=Ua(Object.keys(this.localTrackStats),Object.keys(e));for(let r of t){let s=e[r];if(s){let o=(i=this.store.getLocalPeer())==null?void 0:i.name,n=yield Na(this.eventBus,s,o,this.localTrackStats[r]);n&&(this.localTrackStats[r]=n)}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 Oi=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 Ni(this.store,this.eventBus,e,t)}start(){return c(this,null,function*(){if(this.isMonitored){l.d(this.TAG,"Already started");return}this.stop(),this.isMonitored=!0,l.d(this.TAG,"Starting Webrtc Stats Monitor"),this.startLoop().then(()=>l.d(this.TAG,"Stopping Webrtc Stats Monitor")).catch(e=>{this.eventBus.analytics.publish(y.rtcStatsFailed(S.WebrtcErrors.StatsFailed("PUBLISH",e.message))),l.e(this.TAG,e.message)})})}stop(){this.isMonitored=!1}startLoop(){return c(this,null,function*(){for(;this.isMonitored;)yield this.handleStatsUpdate(),yield re(this.interval)})}cleanup(){this.stop(),this.eventBus.statsUpdate.removeAllListeners()}};var ct=class{constructor({peerId:e,name:t,isLocal:i,customerUserId:r,metadata:s,role:o,joinedAt:n,groups:d,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=n,this.groups=d,this.realtime=u,this.type=p,o&&(this.role=o)}get isHandRaised(){var e;return!!((e=this.groups)!=null&&e.includes(Re))}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`{
|
|
76
76
|
name: ${this.name};
|
|
77
77
|
role: ${(e=this.role)==null?void 0:e.name};
|
|
78
78
|
peerId: ${this.peerId};
|
|
@@ -88,5 +88,5 @@
|
|
|
88
88
|
${this.asRole?`asRole: ${this.asRole.name};`:""}
|
|
89
89
|
${this.audioTrack?`audioTrack: ${(i=this.audioTrack)==null?void 0:i.trackId};`:""}
|
|
90
90
|
${this.videoTrack?`videoTrack: ${(r=this.videoTrack)==null?void 0:r.trackId};`:""}
|
|
91
|
-
}`}};var Bt=class extends ct{constructor(t){super(M(h({},t),{isLocal:!1}));this.isLocal=!1;this.auxiliaryTracks=[];this.fromRoomState=!1;this.fromRoomState=!!t.fromRoomState}};var Ee=(a,e)=>new Bt({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 xi=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(h({},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=Ee(i,this.store);t.push(r)}),t}updateState(e){this.isEnd=e.eof,this.total=e.total,e.iterator&&(this.iterator=e.iterator)}};var lt=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*(){this.audioContext.state==="suspended"&&(yield this.audioContext.resume(),l.d(this.TAG,"AudioContext is resumed"))})}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=>{l.d(this.TAG,"AudioContext close error",e.message)})}};var Va=require("eventemitter2"),Ve=class extends Va.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 Ui=class extends Ve{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}`;l.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){l.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 lt(t),t}};var Bi=class extends Ve{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}`;l.e(this.TAG,s),this.stop(),r(s)},this.videoElement.oncanplaythrough=()=>c(this,null,function*(){var s,o,n;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 d=this.canvas.captureStream();if(!d){l.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();d.addTrack(u),d.getTracks().forEach(p=>{this.tracks.push(p)}),i(this.tracks)}else this.seeked?(this.seeked=!1,(n=this.canvasContext)==null||n.drawImage(this.videoElement,0,0,(s=this.canvas)==null?void 0:s.width,(o=this.canvas)==null?void 0:o.height)):(yield this.videoElement.play(),i(this.tracks))}catch(d){l.e(this.TAG,"Error playing video",t,d.message),r(d)}}),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 lt(t),t}createCanvas(){this.canvas||(this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"))}};var Vi={audio:{list:[],currentIndex:-1,isAutoplayOn:!0},video:{list:[],currentIndex:-1,isAutoplayOn:!0}},Vt=class extends Ve{constructor(t,i){super();this.sdk=t;this.eventBus=i;this.state={audio:h({},Vi.audio),video:h({},Vi.video)};this.TAG="[PlaylistManager]";this.handlePausePlaylist=r=>c(this,[r],function*({enabled:t,track:i}){var o;if(t)return;let s;i.source==="audioplaylist"&&(s="audio"),i.source==="videoplaylist"&&(s="video"),s&&((o=this.getElement(s))==null||o.pause())});this.addTrack=(t,i)=>c(this,null,function*(){yield this.sdk.addTrack(t,i),l.d(this.TAG,"Playlist track added",vi(t))});this.removeTrack=t=>c(this,null,function*(){yield this.sdk.removeTrack(t,!0),l.d(this.TAG,"Playlist track removed",t)});this.audioManager=new Ui,this.videoManager=new Bi,this.addListeners()}getList(t="audio"){return this.state[t].list}setList(t){if(!t||t.length===0){l.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],o=r.findIndex(n=>t===n.id);return o>-1?(s===o&&this.isPlaying(i)&&(yield this.stop(i)),r.splice(o,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 o=Math.max(s.currentTime+t,0);s.currentTime=Math.min(o,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 n;let{list:i,currentIndex:r}=this.state[t],s=(n=i[r])==null?void 0:n.url,o=this.getElement(t);return!s||!o?0:Math.floor(100*(o.currentTime/o.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,o){return c(this,arguments,function*(t,{id:i,type:r="audio"}){let d=this.state[r].list.findIndex(p=>p.id===i);if(!i||d===-1){l.w(this.TAG,"Pass a valid id");return}let u=this.state[r].list[d].url;t?yield this.play(u,r):yield this.pause(u,r),this.state[r].currentIndex=d,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:h({},Vi.audio),video:h({},Vi.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){l.e(this.TAG,"Error in onProgress callback")}}),this.audioManager.on("progress",()=>{try{t({type:"audio",progress:this.getCurrentProgress("audio")})}catch(i){l.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,o=s.getElement();if(this.isItemCurrentlyPlaying(t,i)){l.w(this.TAG,`The ${i} is currently playing`);return}if(o!=null&&o.src.includes(t))yield o.play();else{o==null||o.pause();let n=yield s.play(t);for(let d of n)yield this.addTrack(d,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(),l.d(this.TAG,"paused url",t)):l.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 B=a=>a.room,Fa=a=>a.errors,Tn=(0,A.createSelector)(Fa,a=>a.length===0?null:a.at(-1)),fn=(0,A.createSelector)(B,a=>a.id),J=a=>a.peers,Ft=a=>a.messages.byID,ms=a=>a.messages.allIDs,_=a=>a.tracks,Ss=a=>a.settings,Fi=a=>a.appData,vn=a=>a.devices,Ga=a=>a.speakers,Mn=a=>a.connectionQualities,He=(0,A.createSelector)([B],a=>a&&a.isConnected),yn=(0,A.createSelector)([He,B],(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)),kn=a=>a.hideLocalPeer,Te=(0,A.createSelector)([B,J,kn],(a,e,t)=>t?a.peers.filter(i=>a.localPeer!==i).map(i=>e[i]):a.peers.map(i=>e[i])),En=(0,A.createSelector)(_,a=>Object.values(a)),ee=(0,A.createSelector)(B,J,(a,e)=>e[a.localPeer]),Pe=(0,A.createSelector)(B,a=>a.localPeer),Pn=(0,A.createSelector)(ee,a=>a==null?void 0:a.name),bn=(0,A.createSelector)(ee,a=>a==null?void 0:a.roleName),oe=(0,A.createSelector)(ee,a=>a==null?void 0:a.audioTrack),z=(0,A.createSelector)(ee,a=>a==null?void 0:a.videoTrack),An=(0,A.createSelector)(ee,a=>a==null?void 0:a.auxiliaryTracks),gs=(0,A.createSelector)([oe,z,An],(a,e,t)=>{let i=t?[...t]:[];return a&&i.unshift(a),e&&i.unshift(e),i}),In=(0,A.createSelector)(Te,a=>a.filter(e=>!e.isLocal)),Rn=(0,A.createSelector)(J,Ga,(a,e)=>{let t=Object.entries(e).sort((i,r)=>{var n,d;let s=((n=i[1])==null?void 0:n.audioLevel)||0;return(((d=r[1])==null?void 0:d.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}),Hn=a=>{let e=ee(a);return Ze(a,e==null?void 0:e.audioTrack)},Gi=a=>{let e=ee(a);return Ze(a,e==null?void 0:e.videoTrack)},Ts=a=>{let e=ee(a);return Zs(a,e==null?void 0:e.videoTrack)},Wi=(0,A.createSelector)(ee,_,(a,e)=>{let{video:t,audio:i}=We(e,a);return!!(t||i)}),Wa=(0,A.createSelector)(J,_,(a,e)=>{let t;for(let i in a){let r=a[i],{video:s,audio:o}=We(e,r);if(s)return r;o&&!t&&(t=r)}return t}),Cn=(0,A.createSelector)(Wa,a=>!!a),Ln=(0,A.createSelector)(J,_,(a,e)=>{for(let t in a){let i=a[t],{audio:r,video:s}=We(e,i);if(!s&&r)return i}}),Dn=(0,A.createSelector)(J,_,(a,e)=>{let t=[],i=[];for(let r in a){let s=a[r],{video:o,audio:n}=We(e,s);o?t.push(s):n&&i.push(s)}return t.concat(i)}),wn=(0,A.createSelector)(J,_,(a,e)=>{for(let t in e){let i=e[t];if(At(i)&&bt(i)&&i.peerId)return a[i.peerId]}}),_n=(0,A.createSelector)(J,_,(a,e)=>{for(let t in e){let i=e[t];if(gi(i)&&i.peerId)return a[i.peerId]}}),Nn=(0,A.createSelector)(En,a=>a.filter(Xs)),On=(0,A.createSelector)(ms,a=>a.length),xn=(0,A.createSelector)(Ft,a=>Object.values(a).filter(e=>!e.read).length),ut=(0,A.createSelector)(ms,Ft,(a,e)=>{let t=[];return a.forEach(i=>{t.push(e[i])}),t}),$a=(0,A.createSelector)(ut,a=>a.filter(e=>{var t;return!e.recipientPeer&&!(e.recipientRoles&&((t=e.recipientRoles)==null?void 0:t.length)>0)})),Un=(0,A.createSelector)($a,a=>a.filter(e=>!e.read).length),te=(0,A.createSelector)([B],a=>a&&a.roomState),fs=(0,A.createSelector)(te,a=>a==="Preview"),Bn=(0,A.createSelector)(B,a=>a.roomState!=="Disconnected"),Vn=(0,A.createSelector)(B,a=>!a.transcriptions||a.transcriptions.length<=0?!1:a.transcriptions.some(e=>e.mode==="caption"&&e.state==="started")),fe=a=>a.roles,Fn=(0,A.createSelector)([fe],a=>Object.keys(a)),Je=(0,A.createSelector)([ee,fe],(a,e)=>a!=null&&a.roleName?e[a.roleName]:null),Ka=a=>{var e;return(e=a.preview)==null?void 0:e.asRole},vs=(0,A.createSelector)([Ka,fe],(a,e)=>a?e[a]:null),Gn=(0,A.createSelector)([Je],a=>{var e;return(e=a==null?void 0:a.subscribeParams)!=null&&e.subscribeToRoles?a.subscribeParams.subscribeToRoles.length>0:!1}),Ms=(0,A.createSelector)(Je,a=>a==null?void 0:a.permissions),Wn=(0,A.createSelector)(B,a=>a.recording),$n=(0,A.createSelector)(B,a=>a.rtmp),Kn=(0,A.createSelector)(B,a=>a.hls),qn=(0,A.createSelector)(B,a=>a.transcriptions),jn=(0,A.createSelector)(B,a=>a.sessionId),Jn=(0,A.createSelector)(B,a=>a.startedAt),Qn=(0,A.createSelector)(B,a=>!!a.isLargeRoom),zn=(0,A.createSelector)(B,a=>!!a.isEffectsEnabled),Yn=(0,A.createSelector)(B,a=>!!a.isVBEnabled),Xn=(0,A.createSelector)(B,a=>a.effectsKey),Zn=a=>a.templateAppData,ec=a=>a.sessionMetadata,ys=a=>a.polls,tc=a=>Object.values(a.polls),ic=(0,A.createSelector)(Te,a=>a.filter(e=>e.isHandRaised)),qa=a=>a.whiteboards,rc=(0,A.createSelector)(qa,a=>Object.values(a)[0]);var ks=require("reselect");var ja=(a="audio")=>e=>e.playlist[a].list,Es=(a="audio")=>e=>e.playlist[a].selection,Ja=(a="audio")=>e=>e.playlist[a].progress,Qa=(a="audio")=>e=>e.playlist[a].currentTime,za=(a="audio")=>e=>e.playlist[a].playbackRate,Ya=(a="audio")=>e=>e.playlist[a].volume,Xa=(a="audio")=>(0,ks.createSelector)(ja(a),e=>Object.values(e)),Za=(a="audio")=>(0,ks.createSelector)(ja(a),Es(a),(e,t)=>{if(t.id)return e[t.id]}),Ps={selection:Es("audio"),progress:Ja("audio"),currentTime:Qa("audio"),playbackRate:za("audio"),volume:Ya("audio"),list:Xa("audio"),selectedItem:Za("audio")},bs={selection:Es("video"),progress:Ja("video"),currentTime:Qa("video"),playbackRate:za("video"),volume:Ya("video"),list:Xa("video"),selectedItem:Za("video")};var D=require("reselect");function H(a){return e=>t=>a(t,e)}var Gt="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(Gt,...t);break}case 1:{console.debug(Gt,...t);break}case 2:{console.info(Gt,...t);break}case 3:{console.warn(Gt,...t);break}case 6:{console.error(Gt,...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 As=(a,e)=>e,Wt=(a,e)=>e,eo=(a,e)=>e,sc=(a,e)=>e,ac=(a,e)=>e,Y=(0,D.createSelector)([J,As],(a,e)=>e?a[e]:null),Is=(0,D.createSelector)([_,Wt],(a,e)=>e?a[e]:null),oc=(0,D.createSelector)([_,Wt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="video"?t:null}),nc=(0,D.createSelector)([_,Wt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="audio"?t:null}),cc=(0,D.createSelector)([_,Wt],(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}),dc=(0,D.createSelector)([_,Wt],(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}),lc=(0,D.createSelector)([ys,ac],(a,e)=>e?a[e]:null),X=H(Y),uc=H((0,D.createSelector)([Fi,sc],(a,e)=>{if(a)return e?a[e]:a}));function pc(a){return e=>{if(e.sessionStore)return a?e.sessionStore[a]:e.sessionStore}}var hc=(...a)=>(0,D.createSelector)([Fi],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}}),mc=H((0,D.createSelector)(Y,a=>a==null?void 0:a.name)),Sc=H((0,D.createSelector)(Y,a=>a==null?void 0:a.type)),$t=H(Is),Rs=H(oc),gc=H(nc),Tc=H(cc),fc=H(dc),to=H((a,e)=>{let t=Y(a,e);if(t&&t.videoTrack&&t.videoTrack!=="")return a.tracks[t.videoTrack]}),io=H((a,e)=>{let t=Y(a,e);if(t&&t.audioTrack&&t.audioTrack!=="")return a.tracks[t.audioTrack]}),vc=to,Mc=H((a,e)=>{let t=Y(a,e);return(t==null?void 0:t.auxiliaryTracks.map(i=>a.tracks[i]))||[]}),ro=(a,e)=>e?a.speakers[e]:null,yc=H((0,D.createSelector)(ro,a=>(a==null?void 0:a.audioLevel)||0)),kc=(a,e)=>{let t=io(e)(a);return ro(a,t==null?void 0:t.id)},Ec=H((0,D.createSelector)(kc,a=>(a==null?void 0:a.audioLevel)||0)),Pc=H((a,e)=>{if(e)return a.connectionQualities[e]}),bc=H((a,e)=>{let t=Y(a,e);if(t){let i=t==null?void 0:t.auxiliaryTracks.find(r=>Pt(a.tracks[r]));return i?a.tracks[i]:void 0}}),Ac=H((0,D.createSelector)(_,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return At(r)&&bt(r)});return t?a[t]:void 0})),Ic=H((0,D.createSelector)(_,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return At(r)&&Pt(r)});return t?a[t]:void 0})),Rc=H((0,D.createSelector)(_,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return gi(r)&&Pt(r)});return t?a[t]:void 0})),Hs=H((0,D.createSelector)(_,Y,(a,e)=>We(a,e))),Hc=a=>(0,D.createSelector)(Hs(a),e=>e.video),Cs=a=>(0,D.createSelector)(Hs(a),e=>e.audio),Cc=H((a,e)=>{let t=Y(a,e);return Ze(a,t==null?void 0:t.audioTrack)}),Lc=H((a,e)=>{let t=Y(a,e);return Ze(a,t==null?void 0:t.videoTrack)}),Ls=H((a,e)=>{if(e&&a.tracks[e])return a.tracks[e].volume===0}),Dc=H((a,e)=>{let t=Y(a,e);return Ls(t==null?void 0:t.audioTrack)(a)}),wc=H((a,e)=>{let t=Cs(e)(a);return Ls(t==null?void 0:t.id)(a)}),Ds=H((a,e)=>{let t=Is(a,e);if(t){if(t.type!=="audio"){b.w("Please pass audio track here");return}return t.volume}}),_c=H((a,e)=>{let t=Y(a,e);return Ds(t==null?void 0:t.audioTrack)(a)}),Nc=H((a,e)=>{let t=Cs(e)(a);return Ds(t==null?void 0:t.id)(a)}),Oc=H((a,e)=>{let t=Is(a,e);if(t){if(t.type!=="video"){b.w("Please pass video track here");return}return t.layer}}),so=(0,D.createSelector)([ut,Pe,As],(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)})}),ao=(0,D.createSelector)([ut,eo],(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})}),oo=(0,D.createSelector)(ut,a=>a.filter(e=>{var t;return!e.recipientPeer&&!((t=e.recipientRoles)!=null&&t.length)})),xc=(0,D.createSelector)([ao,eo],a=>a?a.filter(e=>!e.read).length:0),Uc=(0,D.createSelector)([so,As],a=>a?a.filter(e=>!e.read).length:0),Bc=(0,D.createSelector)(oo,a=>a.filter(e=>!e.read).length),Vc=H(so),Fc=H(ao),Gc=H(xc),Wc=H(Uc),$c=a=>(0,D.createSelector)([Te],e=>e.filter(t=>t.roleName===a)),Kc=a=>(0,D.createSelector)([Te],e=>e.filter(t=>t.roleName?a.includes(t.roleName):!1)),qc=a=>(0,D.createSelector)(X(a),e=>{try{return e!=null&&e.metadata&&e.metadata!==""?JSON.parse(e.metadata):{}}catch(t){return console.error("cannot parse peer metadata",t),{}}}),jc=a=>(0,D.createSelector)(X(a),e=>!!(e!=null&&e.isHandRaised)),Jc=a=>(0,D.createSelector)(X(a),e=>e==null?void 0:e.name),ws=H(lc),Qc=a=>(0,D.createSelector)(Ft,e=>e[a]),zc=a=>(0,D.createSelector)(Je,e=>e!=null&&e.permissions.transcriptions?e.permissions.transcriptions[a].length>0:!1);var Kt=require("reselect");var Yc=(0,Kt.createSelector)([J,_],(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}})),Xc=a=>a.roleChangeRequests[0]||null,Zc=(0,Kt.createSelector)([Xc,J,fe],(a,e,t)=>a?{requestedBy:a.requestedBy?e[a.requestedBy]:void 0,role:t[a.roleName],token:a.token}:null),ed=(0,Kt.createSelector)([Je],a=>It(a)),td=(0,Kt.createSelector)([vs],a=>It(a));var be=require("reselect");var no=a=>(0,be.createSelector)([fe],e=>e[a]),id=a=>(0,be.createSelector)(no(a),e=>It(e)),rd=(0,be.createSelector)([z,_],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),sd=(0,be.createSelector)([oe,_],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),ad=a=>(0,be.createSelector)([rd],e=>e.includes(a)),od=a=>(0,be.createSelector)([sd],e=>e.includes(a)),nd=a=>(0,be.createSelector)(Te,e=>e.find(a)),cd=a=>(0,be.createSelector)(Te,e=>e.filter(a)),dd=a=>(0,be.createSelector)(B,e=>e.joinedAt&&Date.now()-e.joinedAt.getTime()<=a);var Oo=require("immer"),xo=Ge(require("zustand/shallow")),Uo=Ge(require("zustand/vanilla"));var lo=require("eventemitter2");var $i={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"},Ki={0:"POLL_CREATED",1:"POLL_STARTED",2:"POLL_STOPPED",4:"POLL_VOTES_UPDATED",3:"POLLS_LIST"},co={TRANSCRIPTION_STATE_UPDATED:"TRANSCRIPTION_STATE_UPDATED"};var _s="hmsNotification",qi=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(_s,i),()=>{this.eventEmitter.removeListener(_s,i)}};this.store=e,this.eventEmitter=new lo.EventEmitter2({maxListeners:Object.keys(Si).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(X(t==null?void 0:t.id))||t,r=$i[e];if(r&&i){let s=this.createNotification(r,i,"info");this.emitEvent(s)}}sendTrackUpdate(e,t){let i=this.store.getState($t(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=Ki[e],r=this.store.getState(ws(t));if(i){let s=this.createNotification(i,r,"info");this.emitEvent(s)}}sendTranscriptionUpdate(e){let t=this.createNotification(co.TRANSCRIPTION_STATE_UPDATED,e,"info");this.emitEvent(t)}emitEvent(e){this.eventEmitter.emit(_s,e)}createNotification(e,t,i,r=""){return this.id++,{id:this.id,type:e,message:r,data:t,severity:i}}};var ji=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(o){b.w("failed to update store",o)}})};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 uo(a){return a instanceof ae||a instanceof O}var po=(a,e)=>{let t=jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Qe(r,s)?(ne(r.auxiliaryTracks,s.auxiliaryTracks)&&(s.auxiliaryTracks=r.auxiliaryTracks),r.groups&&ne(r.groups,s.groups)&&(s.groups=r.groups),Object.assign(r,s)):xs(r,s)?delete a[i]:Ji(r,s)&&(a[i]=s)}},ho=(a,e)=>{let t=jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Qe(r,s)?(Os(r,s),Object.assign(r,s)):xs(r,s)?delete a[i]:Ji(r,s)&&(a[i]=s)}},mo=(a,e)=>{let t=jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Qe(r,s)?(r.questions&&ne(r.questions,s.questions)&&(s.questions=r.questions),Object.assign(r,s)):Ji(r,s)&&(a[i]=s)}},Ns=(a,e)=>{let t=jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Qe(r,s)?Object.assign(r,s):xs(r,s)?delete a[i]:Ji(r,s)&&(a[i]=s)}},So=(a,e,t)=>{let i=t.reduce((s,o)=>(s[o.firstTrackId]=Object.values(e[o.getTrackIDBeingSent()]||{}).sort((n,d)=>!n.rid||!d.rid?0:n.rid<d.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]}},Os=(a,e)=>{a.plugins&&ne(a.plugins,e.plugins)&&(e.plugins=a.plugins),a.type==="video"&&a.layerDefinitions&&ne(a.layerDefinitions,e.layerDefinitions)&&(e.layerDefinitions=a.layerDefinitions)},Qe=(a,e)=>a&&e,xs=(a,e)=>a&&!e,Ji=(a,e)=>!a&&e,ne=(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 ae&&(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 G||t instanceof le)&&(e.isPublished=t.isPublished)}static updateDeviceID(e,t){var i;t instanceof G||t instanceof le?e.deviceID=t.settings.deviceId:e.deviceID=(i=t.getMediaTrackSettings())==null?void 0:i.deviceId}static enrichVideoTrack(e,t){t instanceof O&&(e.layer=t.getLayer(),e.preferredLayer=t.getPreferredLayer(),e.degraded=t.degraded),(t instanceof O||t instanceof G)&&(ne(t.getSimulcastDefinitions(),e.layerDefinitions)||(e.layerDefinitions=t.getSimulcastDefinitions()))}static enrichScreenTrack(e,t){var i,r;if(t instanceof G){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 G||t instanceof le)&&(ne(t.getPlugins(),e.plugins)||(e.plugins=t.getPlugins()))}static convertRoom(e,t){let{recording:i,rtmp:r,hls:s,transcriptions:o}=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:o,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,o;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:(o=e.peer)==null?void 0:o.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),o=t.url===(r==null?void 0:r.url);return M(h({},t),{type:t.type,selected:o,playing:o&&s})}static getConvertedPlaylistType(e,t){let i={},r=e.getCurrentSelection(t),s=e.getCurrentProgress(t),o=e.getVolume(t),n=e.getList(t),d=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:d>0,hasNext:d<n.length-1},progress:s,volume:o,currentTime:e.getCurrentTime(t),playbackRate:e.getPlaybackRate(t)}}static convertRecordingStreamingState(e,t,i,r){var s;return{recording:{browser:h({running:!1},e==null?void 0:e.browser),server:h({running:!1},e==null?void 0:e.server),hls:h({running:!1},e==null?void 0:e.hls)},rtmp:h({running:!1},t),hls:{variants:((s=i==null?void 0:i.variants)==null?void 0:s.map(o=>o))||[],running:!!(i!=null&&i.running),error:i==null?void 0:i.error},transcriptions:r||[]}}};var Jt=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"?Ps:bs,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 Qi=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 zi=class{constructor(e,t){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(He);b.d("starting audio levels is connected to room",e),e&&(yield this.monitorAudioLevels());let t=this.store.subscribe(this.monitorAudioLevels.bind(this),He);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(He)){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 t=this.store.getState(Te).filter(s=>!!s.audioTrack),i=[];for(let s of t){let o=this.actions.getTrackById(s.audioTrack||""),n=(r=o==null?void 0:o.stream)==null?void 0:r.nativeStream;if(s.joinedAt&&n){let d=yield this.getAudioLevel(s,n);d.level>0&&i.push(d)}}if(i.length>0){let s={event:"app-audio-level",data:i};b.d("logging audio levels",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,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 n of t)r=Math.max(r,(n-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 go=2e4,To=1e4,pt={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}},fo="https://100ms.live/test-audio.wav";var Yi=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 ld=a=>!!a&&!isNaN(a),ce=a=>a[a.length-1],Fe=(a,e)=>{let t=a.filter(i=>ld(e(i)));return t.reduce((i,r)=>i+(e(r)||0),0)/t.length},Xi=class{constructor(e){this.sdk=e;this.peerStatsList=[];this.localAudioTrackStatsList=[];this.localVideoTrackStatsList=[];this.remoteAudioTrackStatsList=[];this.remoteVideoTrackStatsList=[]}handleStatsUpdate(e){return c(this,null,function*(){var n,d,u,p,m,T,g,f;let t=e.getLocalPeerStats();t&&this.peerStatsList.push(t);let i=(u=(d=(n=this.sdk.getLocalPeer())==null?void 0:n.audioTrack)==null?void 0:d.nativeTrack)==null?void 0:u.id,r=(T=(m=(p=this.sdk.getLocalPeer())==null?void 0:p.videoTrack)==null?void 0:m.nativeTrack)==null?void 0:T.id,s=e.getLocalTrackStats();s&&(i&&this.localAudioTrackStatsList.push(s[i]),r&&this.localVideoTrackStatsList.push(s[r]));let o=yield(f=(g=this.sdk.getWebrtcInternals())==null?void 0:g.getSubscribePeerConnection())==null?void 0:f.getStats();o==null||o.forEach(E=>{if(E.type==="inbound-rtp"){let v=E.kind==="audio"?this.remoteAudioTrackStatsList:this.remoteVideoTrackStatsList,I=Ut("bytesReceived",E,ce(v));v.push(M(h({},E),{bitrate:I}))}})})}buildReport(){var E,v,I,$,ue,ve,pe,Mt,Ks,qs;let e=(E=ce(this.peerStatsList))==null?void 0:E.publish,t=(v=ce(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)),o=((I=ce(this.remoteAudioTrackStatsList))==null?void 0:I.packetsReceived)||0,n=(($=ce(this.remoteVideoTrackStatsList))==null?void 0:$.packetsReceived)||0,d=this.localAudioTrackStatsList.map(V=>V?Fe(Object.values(V),ie=>ie.bitrate):0),u=this.localVideoTrackStatsList.map(V=>V?Fe(Object.values(V),ie=>ie.bitrate):0),p=((ue=ce(this.remoteAudioTrackStatsList))==null?void 0:ue.jitter)||0,m=((ve=ce(this.remoteVideoTrackStatsList))==null?void 0:ve.jitter)||0,T=Math.max(p,m),g=ce(this.localAudioTrackStatsList),f=ce(this.localVideoTrackStatsList);return{combined:{roundTripTime:s,packetsReceived:o+n,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:Fe(this.peerStatsList,V=>{var ie;return(ie=V.publish)==null?void 0:ie.bitrate}),bitrateReceived:Fe(this.peerStatsList,V=>{var ie;return(ie=V.subscribe)==null?void 0:ie.bitrate}),jitter:T},audio:{roundTripTime:s,packetsReceived:o,packetsLost:((pe=ce(this.remoteAudioTrackStatsList))==null?void 0:pe.packetsLost)||0,bytesReceived:((Mt=ce(this.remoteAudioTrackStatsList))==null?void 0:Mt.bytesReceived)||0,bitrateSent:Fe(d,V=>V),bitrateReceived:Fe(this.remoteAudioTrackStatsList,V=>V.bitrate),bytesSent:g?Object.values(g).reduce((V,ie)=>V+(ie.bytesSent||0),0):0,jitter:p},video:{roundTripTime:s,packetsLost:((Ks=ce(this.remoteVideoTrackStatsList))==null?void 0:Ks.packetsLost)||0,bytesReceived:((qs=ce(this.remoteVideoTrackStatsList))==null?void 0:qs.bytesReceived)||0,packetsReceived:n,bitrateSent:Fe(u,V=>V),bitrateReceived:Fe(this.remoteVideoTrackStatsList,V=>V.bitrate),bytesSent:f?Object.values(f).reduce((V,ie)=>V+(ie.bytesSent||0),0):0,jitter:m}}}};var vo=(n=>(n[n.STARTING=0]="STARTING",n[n.INIT_FETCHED=1]="INIT_FETCHED",n[n.SIGNAL_CONNECTED=2]="SIGNAL_CONNECTED",n[n.ICE_ESTABLISHED=3]="ICE_ESTABLISHED",n[n.MEDIA_CAPTURED=4]="MEDIA_CAPTURED",n[n.MEDIA_PUBLISHED=5]="MEDIA_PUBLISHED",n[n.COMPLETED=6]="COMPLETED",n))(vo||{});var Mo,yo,Zi=class{constructor(e,t,i,r){this.sdk=e;this.sdkListener=t;this.progressCallback=i;this.completionCallback=r;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 Yi;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=(Mo=this.sdkListener.onNetworkQuality)==null?void 0:Mo.bind(this.sdkListener);this.onPreview=this.sdkListener.onPreview.bind(this.sdkListener);this.onDeviceChange=(yo=this.sdkListener.onDeviceChange)==null?void 0:yo.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 Xi(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()},go)}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 ze=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.id=e}};var er=(a,e,t)=>c(void 0,null,function*(){let r=Error("something went wrong during fetch");for(let s=0;s<4;s++)try{let o=yield fetch(a,e),n=yield o.clone().json();if(t&&t.length&&!o.ok&&t.includes(n.code))throw S.APIErrors.ServerErrors(n.code,"GET_TOKEN",n.message,!1);return o}catch(o){r=o}throw["Failed to fetch","NetworkError"].some(s=>r.message.includes(s))?S.APIErrors.EndpointUnreachable("GET_TOKEN",r.message):r});var ht=class{constructor(e,t){this.sdk=e;this.sdkListener=t;this.recordedAudio=fo;this.sdk.setIsDiagnostics(!0),this.initSdkWithLocalPeer()}get localPeer(){var e;return(e=this.sdk)==null?void 0:e.store.getLocalPeer()}checkBrowserSupport(){Ct(),Ht()}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,o,n,d;if(this.initSdkWithLocalPeer(),!this.localPeer)throw new Error("Local peer not found");this.sdk.store.setSimulcastEnabled(!1),this.localPeer.role=M(h({},pt),{publishParams:M(h({},pt.publishParams),{allowed:["video"]})});let t=new Oe().video(new j().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");(o=this.sdk)==null||o.deviceManager.init(!0),this.localPeer.videoTrack=r,(d=(n=this.sdk)==null?void 0:n.listener)==null||d.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=To}){var u,p,m,T;this.initSdkWithLocalPeer(g=>{this.stopMicCheck(),t==null||t(g)});let o=yield this.getLocalAudioTrack(e);if((u=this.sdk)==null||u.deviceManager.init(!0),!this.localPeer)throw new Error("Local peer not found");if(!o)throw new Error("No audio track found");this.localPeer.audioTrack=o,(p=this.sdk)==null||p.initPreviewTrackAudioLevelMonitor(),(T=(m=this.sdk)==null?void 0:m.listener)==null||T.onPeerUpdate(9,[this.localPeer]),this.mediaRecorder=new MediaRecorder(o.stream.nativeStream);let n=[];this.mediaRecorder.ondataavailable=function(g){n.push(g.data)},this.mediaRecorder.onstop=()=>{var f,E;let g=new Blob(n,{type:(f=this.mediaRecorder)==null?void 0:f.mimeType});this.recordedAudio=URL.createObjectURL(g),(E=this.onStopMicCheck)==null||E.call(this)},this.mediaRecorder.start();let d=setTimeout(()=>{this.stopMicCheck()},r);this.onStopMicCheck=()=>{clearTimeout(d),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){return c(this,null,function*(){if(!this.sdk)throw new Error("SDK not found");this.connectivityCheck=new Zi(this.sdk,this.sdkListener,e,t);let r=yield this.getAuthToken(i);yield this.sdk.leave(),yield this.sdk.join({authToken:r,userName:"diagnostics-test"},this.connectivityCheck),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:s=>{var o;(o=this.connectivityCheck)==null||o.handleConnectionQualityUpdate(s)}})})}stopConnectivityCheck(){return c(this,null,function*(){var e;return(e=this.connectivityCheck)==null?void 0:e.cleanupAndReport()})}initSdkWithLocalPeer(e){var r,s,o;this.sdkListener&&((r=this.sdk)==null||r.initStoreAndManagers(M(h({},this.sdkListener),{onError:n=>{e==null||e(n),this.sdkListener.onError(n)}})));let t=new je({name:"diagnostics-peer",role:pt,type:"regular"});(s=this.sdk)==null||s.store.addPeer(t);let i=new ze("diagnostics-room");this.sdk.store.setRoom(i),this.sdkListener.onRoomUpdate("ROOM_PEER_COUNT_UPDATED",i),(o=this.sdk)==null||o.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 er(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(h({},pt),{publishParams:M(h({},pt.publishParams),{allowed:["audio"]})});let t=new Oe().audio(new K().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 tr=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(X(t.peerId)),r=$i[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(X(t.peerId)));else if([12,13,14].includes(e))this.syncRoomState(r),i||(i=this.store.getState(X(t.peerId)));else{let s=N.convertPeer(t);this.setState(o=>{let n=o.peers[s.id];Qe(n,s)&&(ne(n.auxiliaryTracks,s.auxiliaryTracks)&&(n.auxiliaryTracks=s.auxiliaryTracks),Object.assign(n,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 Qi(this.sdk,this.setSessionStoreValueLocally.bind(this)),this.actionBatcher=new ji(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 O){if(t==="none"){b.d("layer none will be ignored");return}if(((r=this.store.getState(Rs(e)))==null?void 0:r.preferredLayer)===t){b.d(`preferred layer is already ${t}`);return}this.setState(o=>{let n=o.tracks[e];n&&(n.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(te);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(He),t=!0;e||(t=!1,this.logPossibleInconsistency("room leave is called when no room is connected"));let i=this.store.getState(te);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(oe);t&&(yield this.setEnabledTrack(t,e))})}setLocalVideoEnabled(e){return c(this,null,function*(){let t=this.store.getState(z);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(o=>{o.tracks[e]?o.tracks[e].displayEnabled=t:this.logPossibleInconsistency("track id not found for setEnabled")},"displayEnabled");try{yield this.setEnabledSDKTrack(e,t),this.syncRoomState("setEnabled")}catch(o){throw this.setState(n=>{n.tracks[e].displayEnabled=!t},"rollbackDisplayEnabled"),this.hmsNotifications.sendError(N.convertException(o)),o}let r=t?3:2;this.hmsNotifications.sendTrackUpdate(r,e)})}setAudioSettings(e){return c(this,null,function*(){let t=this.store.getState(oe);t&&(yield this.setSDKLocalAudioTrackSettings(t,e),this.syncRoomState("setAudioSettings"))})}setVideoSettings(e){return c(this,null,function*(){let t=this.store.getState(z);t&&(yield this.setSDKLocalVideoTrackSettings(t,e),this.syncRoomState("setVideoSettings"))})}switchCamera(){return c(this,null,function*(){let e=this.store.getState(z);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(fe),s=t.map(d=>r[d]),{message_id:o,timestamp:n}=yield this.sdk.sendGroupMessage(e,s,i);this.updateMessageInStore({message:e,recipientRoles:t,type:i,id:o,time:n})})}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(o=>{o.messages.byID[r.id]=r,o.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())}),Gi)});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(z);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(oe);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 o={[e]:t};s.appData=o}},`setAppData-${e}`)}rejectChangeRole(e){this.removeRoleChangeRequest(e)}endRoom(e,t){return c(this,null,function*(){let i=this.store.getState(Ms);if(!(i!=null&&i.endRoom)){b.w("You are not allowed to perform this action - endRoom");return}let r=this.store.getState(te);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(o=>{o.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)})}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&&uo(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(fe);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 zi(this.store,this),yield this.beamSpeakerLabelsLogger.start())})}initDiagnostics(){let e=new ht(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),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,kt())},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),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(X((r=e.requestedBy)==null?void 0:r.peerId));this.hmsNotifications.sendLeaveRoom(M(h({},e),{requestedBy:t||void 0}));let i=e.roomEnded||!t?"roomEnded":"removedFromRoom";b.i(`resetting state after peer removed ${i}`,e),this.resetState(i)}onDeviceChange(e){let t=e.devices;if(!t)return;let i=this.store.getState(ee);if(this.setState(r=>{ne(r.devices.audioInput,t.audioInput)||(r.devices.audioInput=t.audioInput),ne(r.devices.videoInput,t.videoInput)||(r.devices.videoInput=t.videoInput),ne(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){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),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=Ki[e];this.setState(r=>{let s=t.reduce((o,n)=>{var d;return o[n.id]=M(h({},n),{questions:(d=n.questions)==null?void 0:d.map(u=>{var p,m;return M(h({},u),{answer:u.answer?h({},u.answer):void 0,options:(p=u.options)==null?void 0:p.map(T=>h({},T)),responses:(m=u.responses)==null?void 0:m.map(T=>h({},T))})})}),o},{});mo(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(Wi)?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(Wi)?(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={},o={},n,d=this.sdk.getPeers();for(let g of d){let f=N.convertPeer(g);t[f.id]=f,i.push(f.id),o[f.id]={peerID:f.id,downlinkQuality:g.networkQuality||-1};let E=[g.audioTrack,g.videoTrack,...g.auxiliaryTracks];for(let v of E){if(!v)continue;let I=N.convertTrack(v);r[I.id]=I}if(g.isLocal){let v=g;n=this.getPreviewFields(v),Object.assign(s,this.getMediaSettings(v))}}let u=this.sdk.getRecordingState(),p=this.sdk.getRTMPState(),m=this.sdk.getHLSState(),T=this.sdk.getTranscriptionState();this.setState(g=>{var v;g.room.peers=i;let f=g.peers,E=g.tracks;po(f,t),ho(E,r),Object.assign(g.settings,s),g.room.isConnected&&Object.assign(g.connectionQualities,o),(v=g.preview)!=null&&v.localPeer&&(n!=null&&n.localPeer)?Object.assign(g.preview,n):g.preview=n,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,m,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 Jt(t,"audio",this.syncPlaylistState.bind(this),this.store),this.videoPlaylist=new Jt(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(J),r=t.filter(o=>!i[o.peerId]);if(this.syncRoomState("peersJoined"),this.store.getState(He)){let o=[];for(let n of t){let d=this.store.getState(X(n.peerId));d&&o.push(d)}this.hmsNotifications.sendPeerList(o)}else r.forEach(o=>{let n=this.store.getState(X(o.peerId));n&&this.hmsNotifications.sendPeerUpdate(0,n)});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(o=>{let n=o.tracks[s.id];Qe(n,s)&&(Os(n,s),Object.assign(n,s))},r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}}onMessageReceived(e){let t=N.convertMessage(e,this.store.getState(Pe));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 o=s.track.trackId;i[o]=s.audioLevel,t.speakers[o]||(t.speakers[o]={audioLevel:s.audioLevel,peerID:s.peer.peerId,trackID:o})});let r=Object.entries(t.speakers);for(let[s,o]of r)o.audioLevel=i[s]||0,o.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(X((s=e.requestedBy)==null?void 0:s.peerId)),i=this.getStoreLocalTrackIDfromSDKTrack(e.track),r=this.store.getState($t(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(X((s=e.requestedBy)==null?void 0:s.peerId));e.enabled||this.syncRoomState("changeMultiTrackStateRequest");let i=[],r=this.store.getState(_);for(let o of e.tracks){let n=this.getStoreLocalTrackIDfromSDKTrack(o);n&&r[n]&&i.push(r[n])}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,o=e.trackId;if(r)if(o===r.audioTrack)delete r.audioTrack;else if(o===r.videoTrack)delete r.videoTrack;else{let n=r.auxiliaryTracks.indexOf(o);n>-1&&r.auxiliaryTracks.splice(n,1)}delete s[o]},"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(Ss),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 _e?(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(ee);if((t==null?void 0:t.videoTrack)!==e)return!1;let i=this.store.getState(Ts),r=this.store.getState(Gi);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(z);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(z);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(oe);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(gs).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(fs)&&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(o=>o&&typeof o.bitrate=="number"&&o.bitrate>0))}};var ir=a=>U?`${a} ${document.title}`:a;var rr=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,o=Date.now(),n=0,d=se(i).then(()=>{this.controller.abort()});try{let m=(u=(yield fetch(`${t}?${Date.now()}`,{signal:s})).body)==null?void 0:u.getReader();if(!m)throw Error("unable to process request");let T=()=>c(this,null,function*(){if(m)try{let g=!1;for(;!g;){let{value:f,done:E}=yield m.read();g=E,f&&(n+=f.byteLength,this.sendScore({scoreMap:r,downloadedSize:n,startTime:o}))}}catch(g){g.name!=="AbortError"&&l.d(this.TAG,g)}});return Promise.race([T(),d]).then(()=>{this.sendScore({scoreMap:r,downloadedSize:n,startTime:o,finished:!0})}).catch(g=>{l.d(this.TAG,g),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:g.message}))})}catch(p){p.name!=="AbortError"?(l.d(this.TAG,p),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:p.message}))):l.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,n=t/1024/s*8,d=-1;for(let u in e){let p=e[u];n>=p.low&&(!p.high||n<=p.high)&&(d=Number(u))}this.updateScoreToListener(d),r&&this.eventBus.analytics.publish(y.previewNetworkQuality({score:d,downLink:n.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 Qt=class{constructor(e,t,i,r,s,o){this.store=e;this.transport=t;this.deviceManager=i;this.publish=r;this.removeAuxiliaryTrack=s;this.listener=o;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,E,v,I,$;let r=new Set(e.publishParams.allowed),s=new Set(t.publishParams.allowed),o=this.removeTrack(r,s,"video"),n=this.removeTrack(r,s,"audio"),d=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((E=e.publishParams.simulcast)==null?void 0:E.screen,(v=t.publishParams.simulcast)==null?void 0:v.screen),m=($=(I=this.store.getLocalPeer())==null?void 0:I.videoTrack)==null?void 0:$.enabled;yield this.removeAudioTrack(n),yield this.removeVideoTracks(o||u),yield this.removeScreenTracks(d||p);let T=this.getSettings();u&&(T.isVideoMuted=!m),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(o=>{var d;let n=(d=t==null?void 0:t.layers)==null?void 0:d.find(u=>u.rid===o.rid);return(n==null?void 0:n.maxBitrate)!==o.maxBitrate||(n==null?void 0:n.maxFramerate)!==o.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,o;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=((o=this.deviceManager.currentSelection.audioOutput)==null?void 0:o.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 Us=class{constructor(){this.TAG="[HTTPAnalyticsTransport]";this.failedEvents=new Me("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"?Ha:Ca;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=>{l.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))}},Ce=new Us;var zt=class{constructor(e){this.type=e.type,this.source=e.source||"regular",this.description="",e instanceof we?(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 Yt=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=Lt(this.env);this.polls=new Map;this.whiteboards=new Map;this.addPermissionToRole=(e,t,i,r)=>{var o;if(!this.knownRoles[e]){l.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(h({},s[t]),{[r]:[i]}):t==="whiteboard"&&(s[t]||(s[t]=[]),(o=s[t])==null||o.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(o=>this.addPermissionToRole(o,"whiteboard","admin")),(r=t==null?void 0:t.reader)==null||r.forEach(o=>this.addPermissionToRole(o,"whiteboard","read")),(s=t==null?void 0:t.writer)==null||s.forEach(o=>this.addPermissionToRole(o,"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))};this.handleNoiseCancellationPlugin=e=>{this.room&&(this.room.isNoiseCancellationEnabled=!!(e!=null&&e.enabled)&&!!this.room.isNoiseCancellationEnabled)}}getConfig(){return this.config}setSimulcastEnabled(e){this.simulcastEnabled=e}removeRemoteTracks(){this.tracks.forEach(e=>{(e instanceof ae||e instanceof O)&&(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 O)}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(o=>o.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=Lt(this.env,e)}setRoom(e){this.room=e}setKnownRoles(e){var i,r;if(this.knownRoles=e.known_roles,this.addPluginsToRoles(e.plugins),this.roleDetailsArrived=!0,this.templateAppData=e.app_data,!this.simulcastEnabled)return;let t=(i=this.knownRoles[e.name])==null?void 0:i.publishParams;this.videoLayers=this.convertSimulcastLayers((r=t.simulcast)==null?void 0:r.video),this.updatePeersPolicy()}hasRoleDetailsArrived(){return this.roleDetailsArrived}setConfig(e){var t,i,r;if(Z.rememberDevices(!!e.rememberDeviceSelection),e.rememberDeviceSelection){let s=Z.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*(){for(let t of this.getAudioTracks())yield t.setVolume(e)})}updateAudioOutputDevice(e){return c(this,null,function*(){let t=[];this.getAudioTracks().forEach(i=>{i instanceof ae&&t.push(i.setOutputDevice(e))}),yield Promise.all(t)})}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(h({},e),{layers:(e.layers||[]).map(t=>M(h({},t),{maxBitrate:t.maxBitrate*1e3}))})}getSimulcastDefinitionsForPeer(e,t){var n,d,u;if([!e||!e.role,t==="screen",!this.simulcastEnabled].some(p=>!!p))return[];let i=this.getPolicyForRole(e.role.name).publishParams,r,s,o;return t==="regular"?(r=(n=i.simulcast)==null?void 0:n.video,s=i.video.width,o=i.video.height):t==="screen"&&(r=(d=i.simulcast)==null?void 0:d.screen,s=i.screen.width,o=i.screen.height),((u=r==null?void 0:r.layers)==null?void 0:u.map(p=>{let m=Ne[p.rid],T={width:Math.floor(s/p.scaleResolutionDownBy),height:Math.floor(o/p.scaleResolutionDownBy)};return{layer:m,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}case"noiseCancellation":{this.handleNoiseCancellationPlugin(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,Ce.setEnv(i)}};var sr=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(),l.d(this.TAG,"Wake lock released")}catch(e){let t=e;l.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)&&(l.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)){l.d(this.TAG,"Wake lock feature not supported");return}this.wakeLock=yield navigator.wakeLock.request("screen"),l.d(this.TAG,"Wake lock acquired")}catch(e){let t=e;l.w(this.TAG,"Error acquiring wake lock",`name=${t.name}, message=${t.message}`)}})}};var ar=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();l.d(this.TAG,"Max buffer size reached","Removed event to accommodate new events",t)}return this}flushFailedClientEvents(){Ce.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){l.w(this.TAG,"Flush Failed",t)}}sendClientEventOnHTTP(e){var r,s,o,n;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:(o=t==null?void 0:t.startedAt)==null?void 0:o.getTime(),role:(n=i==null?void 0:i.role)==null?void 0:n.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},Ce.sendEvent(e)}};var Eo=require("uuid");var ko={autoplayFailed:void 0,initialized:!1,autoplayCheckPromise:void 0},Xt=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=h({},ko);this.handleAudioPaused=e=>c(this,null,function*(){l.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})=>{l.d(this.TAG,"Track updated",`${e}`)};this.handleTrackAdd=r=>c(this,[r],function*({track:e,peer:t,callListener:i=!0}){var o,n;let s=document.createElement("audio");s.style.display="none",s.id=e.trackId,s.addEventListener("pause",this.handleAudioPaused),s.onerror=()=>c(this,null,function*(){var u,p;l.e(this.TAG,"error on audio element",s.error);let d=S.TracksErrors.AudioPlaybackError(`Audio playback error for track - ${e.trackId} code - ${(u=s==null?void 0:s.error)==null?void 0:u.code}`);this.eventBus.analytics.publish(y.audioPlaybackError(d)),((p=s==null?void 0:s.error)==null?void 0:p.code)===MediaError.MEDIA_ERR_DECODE&&(this.removeAudioElement(s,e),yield se(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),yield e.setVolume(this.volume),l.d(this.TAG,"Audio track added",`${e}`),this.init(),(o=this.audioSink)==null||o.append(s),this.outputDevice&&(yield e.setOutputDevice(this.outputDevice)),s.srcObject=new MediaStream([e.nativeTrack]),i&&((n=this.listener)==null||n.onTrackUpdate(0,e,t)),yield this.handleAutoplayError(e)});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),l.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&&(l.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*(){yield this.store.updateAudioOutputVolume(e),this.volume=e})}unblockAutoplay(){return c(this,null,function*(){this.autoPausedTracks.size>0&&(yield this.unpauseAudioTracks()),yield re.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,Eo.v4)()}`,(e&&document.getElementById(e)||document.body).append(t),this.audioSink=t,l.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=h({},ko)}playAudioFor(e){return c(this,null,function*(){let t=e.getAudioElement();if(!t){l.w(this.TAG,"No audio element found on track",e.trackId);return}try{yield t.play(),this.state.autoplayFailed=!1,this.autoPausedTracks.delete(e),l.d(this.TAG,"Played track",`${e}`)}catch(i){this.autoPausedTracks.add(e),l.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 or=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.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 Zt=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);return i&&(this.outputDevice=i,yield this.store.updateAudioOutputDevice(i),this.eventBus.analytics.publish(y.deviceChange({isUserSelection:t,selection:{audioOutput:i},devices:this.getDevices(),type:"audioOutput"})),Z.updateSelection("audioOutput",{deviceId:i.deviceId,groupId:i.groupId})),i});this.getCurrentSelection=()=>{var o,n;let e=this.store.getLocalPeer(),t=this.createIdentifier((o=e==null?void 0:e.audioTrack)==null?void 0:o.getMediaTrackSettings()),i=this.createIdentifier((n=e==null?void 0:e.videoTrack)==null?void 0:n.getMediaTrackSettings()),r=this.audioInput.find(d=>this.createIdentifier(d)===t),s=this.videoInput.find(d=>this.createIdentifier(d)===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),Z.setDevices({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput]}),this.logDevices("Enumerate Devices")}catch(e){l.e(this.TAG,"Failed enumerating devices",e)}});this.updateToActualDefaultDevice=()=>c(this,null,function*(){var r,s,o,n,d;let e=this.store.getLocalPeer();if(!((s=(r=this.store.getConfig())==null?void 0:r.settings)==null?void 0:s.videoDeviceId)&&(e!=null&&e.videoTrack)&&(yield e.videoTrack.setSettings({deviceId:(o=this.videoInput[0])==null?void 0:o.deviceId},!0)),!((d=(n=this.store.getConfig())==null?void 0:n.settings)==null?void 0:d.audioInputDeviceId)&&(e!=null&&e.audioTrack)){let u=()=>{var T;let m=this.audioInput.find(g=>!g.label.toLowerCase().includes("iphone"));return na()&&m?m==null?void 0:m.deviceId:(T=this.getNewAudioInputDevice())==null?void 0:T.deviceId};u()&&(yield e.audioTrack.setSettings({deviceId:u()},!0))}});this.handleDeviceChange=Ii(()=>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){l.d(this.TAG,"No Audio track on local peer");return}if(!this.audioInputChanged){l.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"})),l.e(this.TAG,"Audio device not found");return}let{settings:i}=e,r=new K().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){l.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){l.d(this.TAG,"No video track on local peer");return}if(!this.videoInputChanged){l.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"})),l.e(this.TAG,"Video device not found");return}let{settings:i}=e,r=new j().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){l.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=()=>{"ondevicechange"in navigator.mediaDevices||(this.timer=setTimeout(()=>{c(this,null,function*(){yield this.enumerateDevices(),yield this.autoSelectAudioOutput(),this.startPollingForDevices()})},5e3))};this.autoSelectAudioOutput=()=>c(this,null,function*(){var d,u;if("ondevicechange"in navigator.mediaDevices||!((d=this.store.getLocalPeer())!=null&&d.joinedAt))return;let{bluetoothDevice:e,earpiece:t,speakerPhone:i,wired:r}=this.categorizeAudioInputDevices(),s=(u=this.store.getLocalPeer())==null?void 0:u.audioTrack;if(!s||!t)return;let o=this.getManuallySelectedAudioDevice(),n=(o==null?void 0:o.deviceId)||(e==null?void 0:e.deviceId)||(r==null?void 0:r.deviceId)||(i==null?void 0:i.deviceId);if(l.d(this.TAG,"externalDeviceID",n),!(s.settings.deviceId===n&&this.earpieceSelected))try{if(!this.earpieceSelected){if((e==null?void 0:e.deviceId)===n){this.earpieceSelected=!0;return}yield s.setSettings({deviceId:t==null?void 0:t.deviceId},!0),this.earpieceSelected=!0}yield s.setSettings({deviceId:n},!0)}catch(p){this.eventBus.error.publish(p)}});let i=({enabled:r,track:s})=>r&&s.source==="regular";this.eventBus.localVideoEnabled.waitFor(i).then(()=>c(this,null,function*(){yield this.enumerateDevices(),this.videoInputChanged&&this.eventBus.deviceChange.publish({devices:this.getDevices()})})),this.eventBus.localAudioEnabled.waitFor(i).then(()=>c(this,null,function*(){yield this.enumerateDevices(),this.audioInputChanged&&this.eventBus.deviceChange.publish({devices:this.getDevices()})})),this.eventBus.deviceChange.subscribe(({type:r,isUserSelection:s,selection:o})=>{if(s){let n=r==="video"?"videoInput":r,d=this[n].find(u=>this.createIdentifier(u)===this.createIdentifier(o));this.eventBus.analytics.publish(y.deviceChange({selection:{[n]:d},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()),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(o=>o.deviceId!=="default"&&t.label.includes(o.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 o=Ai(s.label);o==="SPEAKERPHONE"?t=s:o==="WIRED"?i=s:o==="BLUETOOTH"?e=s:o==="EARPIECE"&&(r=s)}return{bluetoothDevice:e,speakerPhone:t,wired:i,earpiece:r}}getAudioOutputDeviceMatchingInput(e){var o,n;let t=((n=(o=this.store.getConfig())==null?void 0:o.settings)==null?void 0:n.speakerAutoSelectionBlacklist)||[];if(t==="all"||!e)return;let i=e.label.toLowerCase()||"";if(t.some(d=>i.includes(d.toLowerCase())))return;let r=this.audioOutput.find(d=>e.deviceId!=="default"&&d.label===e.label);if(r)return r;let s=this.audioOutput.find(d=>d.groupId===e.groupId);if(s&&this.audioOutput[0].deviceId==="default"&&s.groupId===this.audioOutput[0].groupId)return s}logDevices(e=""){l.d(this.TAG,e,JSON.stringify({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput],selected:this.getCurrentSelection()},null,4))}};var nr=class{constructor(e,t){this.deviceManager=e;this.audioSinkManager=t}getVolume(){return this.audioSinkManager.getVolume()}setVolume(e){if(e<0||e>100)throw Error("Please pass a valid number between 0-100");this.audioSinkManager.setVolume(e)}getDevice(){return this.deviceManager.outputDevice}setDevice(e){return this.deviceManager.updateOutputDevice(e,!0)}unblockAutoplay(){return c(this,null,function*(){yield this.audioSinkManager.unblockAutoplay(),yield re.resumeContext()})}};var ei=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}){l.d(this.TAG,`sendFeedback: feedbackEndpoint=${t} peerId=${i.peer.peer_id} session=${i.peer.session_id} `);let o=new URL("v2/client/feedback",t),n=M(h({},i),{payload:r});try{let d=yield fetch(o,{headers:{Authorization:`Bearer ${e}`},body:JSON.stringify(n),method:"POST"});try{this.handleError(d);return}catch(u){throw l.e(this.TAG,"error",u.message,d.status),u instanceof k?u:S.APIErrors.ServerErrors(d.status,"FEEDBACK",u.message)}}catch(d){let u=d;throw["Failed to fetch","NetworkError","ECONNRESET"].some(p=>u.message.includes(p))?S.APIErrors.EndpointUnreachable("FEEDBACK",u.message):u}})}};ei.TAG="[FeedbackService]";var Po=require("eventemitter2");var x=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 mt=class{constructor(){this.eventEmitter=new Po.EventEmitter2;this.analytics=new x(F.ANALYTICS,this.eventEmitter);this.deviceChange=new x(F.DEVICE_CHANGE,this.eventEmitter);this.localAudioEnabled=new x(F.LOCAL_AUDIO_ENABLED,this.eventEmitter);this.localVideoEnabled=new x(F.LOCAL_VIDEO_ENABLED,this.eventEmitter);this.localVideoUnmutedNatively=new x(F.LOCAL_VIDEO_UNMUTED_NATIVELY,this.eventEmitter);this.localAudioUnmutedNatively=new x(F.LOCAL_AUDIO_UNMUTED_NATIVELY,this.eventEmitter);this.statsUpdate=new x(F.STATS_UPDATE,this.eventEmitter);this.trackDegraded=new x(F.TRACK_DEGRADED,this.eventEmitter);this.trackRestored=new x(F.TRACK_RESTORED,this.eventEmitter);this.trackAudioLevelUpdate=new x(F.TRACK_AUDIO_LEVEL_UPDATE,this.eventEmitter);this.audioPluginFailed=new x(F.AUDIO_PLUGIN_FAILED,this.eventEmitter);this.localAudioSilence=new x(F.LOCAL_AUDIO_SILENCE,this.eventEmitter);this.policyChange=new x(F.POLICY_CHANGE,this.eventEmitter);this.localRoleUpdate=new x(F.LOCAL_ROLE_UPDATE,this.eventEmitter);this.audioTrackUpdate=new x(F.AUDIO_TRACK_UPDATE,this.eventEmitter);this.audioTrackAdded=new x(F.AUDIO_TRACK_ADDED,this.eventEmitter);this.audioTrackRemoved=new x(F.AUDIO_TRACK_REMOVED,this.eventEmitter);this.autoplayError=new x(F.AUTOPLAY_ERROR,this.eventEmitter);this.leave=new x(F.LEAVE,this.eventEmitter);this.error=new x(F.ERROR,this.eventEmitter)}};var cr=class{constructor(e,t,i){this.store=e;this.listener=t;this.audioListener=i}handleActiveSpeakers(e){var s,o,n;let t=e["speaker-list"],i=t.map(d=>({audioLevel:d.level,peer:this.store.getPeerById(d.peer_id),track:this.store.getTrackById(d.track_id)}));(s=this.audioListener)==null||s.onAudioLevelUpdate(i),this.store.updateSpeakers(i);let r=t[0];if(r){let d=this.store.getPeerById(r.peer_id);(o=this.listener)==null||o.onPeerUpdate(4,d)}else(n=this.listener)==null||n.onPeerUpdate(5,null)}};var dr=class{constructor(e){this.listener=e;this.TAG="[BroadcastManager]"}handleNotification(e,t){e==="on-broadcast"&&this.handleBroadcast(t)}handleBroadcast(e){var t,i;l.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 lr=class{constructor(e,t){this.store=e;this.listener=t}handleQualityUpdate(e){var r;let i=e.peers.map(s=>{let o=this.store.getPeerById(s.peer_id);return o&&o.updateNetworkQuality(s.downlink_score),{peerID:s.peer_id,downlinkQuality:s.downlink_score}});(r=this.listener)==null||r.onConnectionQualityUpdate(i)}};var St=class{constructor(e,t,i){this.store=e;this.eventBus=t;this.listener=i;this.TAG="[TrackManager]";this.tracksToProcess=new Map;this.handleTrackAdd=e=>{l.d(this.TAG,"ONTRACKADD",`${e}`),this.tracksToProcess.set(e.trackId,e),this.processPendingTracks()};this.handleTrackRemovedPermanently=e=>{l.d(this.TAG,"ONTRACKREMOVE permanently",e),Object.keys(e.tracks).forEach(i=>{var n;let r=this.store.getTrackState(i);if(!r)return;let s=this.store.getTrackById(i);if(!s){l.d(this.TAG,"Track not found in store");return}s.type==="audio"&&this.eventBus.audioTrackRemoved.publish(s),this.store.removeTrack(s);let o=this.store.getPeerById(r.peerId);o&&(this.removePeerTracks(o,s),(n=this.listener)==null||n.onTrackUpdate(1,s,o))})};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 O&&this.setLayer(r,i)}};this.handleTrackUpdate=(e,t=!0)=>{var s,o;let i=this.store.getPeerById(e.peer.peer_id),r=e.peer;if(!i&&!r){l.d(this.TAG,"Track Update ignored - Peer not added to store");return}i||(i=Ee(r,this.store),this.store.addPeer(i));for(let n in e.tracks){let d=Object.assign({},(s=this.store.getTrackState(n))==null?void 0:s.trackInfo),u=e.tracks[n],p=this.store.getTrackById(n);if(this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:h(h({},d),u)}),!p||this.tracksToProcess.has(n))this.processTrackInfo(u,e.peer.peer_id,t),this.processPendingTracks();else{p.setEnabled(!u.mute);let m=this.processTrackUpdate(p,d,u);m&&((o=this.listener)==null||o.onTrackUpdate(m,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){l.d(this.TAG,"TrackState not added to store",`peerId - ${t.peerId}`,`trackId -${t.trackId}`);return}let r=this.store.getPeerById(i.peerId);if(!r){l.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,t.setEnabled(!i.trackInfo.mute),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)})}}handleTrackMetadataAdd(e){l.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;l.d(this.TAG,"ONTRACKREMOVE",`${e}`);let i=this.store.getTrackState(e.trackId);if(!i)return;if(!this.store.hasTrack(e)){l.d(this.TAG,"Track not found in store");return}if(t){this.store.removeTrack(e);let o=this.store.getPeerById(i.peerId);if(!o)return;this.removePeerTracks(o,e),(s=this.listener)==null||s.onTrackUpdate(1,e,o),e.type==="audio"&&this.eventBus.audioTrackRemoved.publish(e)}}setLayer(e,t){var s,o;let i=this.store.getPeerByTrackId(e.trackId);if(!i)return;e.setLayerFromServer(t)?(s=this.listener)==null||s.onTrackUpdate(5,e,i):(o=this.listener)==null||o.onTrackUpdate(6,e,i)}removePeerTracks(e,t){let i=e.auxiliaryTracks.indexOf(t);i>-1?(e.auxiliaryTracks.splice(i,1),l.d(this.TAG,"auxiliary track removed",`${t}`)):t.type==="audio"&&e.audioTrack===t?(e.audioTrack=void 0,l.d(this.TAG,"audio track removed",`${t}`)):t.type==="video"&&e.videoTrack===t&&(e.videoTrack=void 0,l.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),l.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(o=>o.trackId===i.trackId);s===-1?(e.auxiliaryTracks.push(i),this.store.addTrack(i)):(e.auxiliaryTracks[s].replaceTrack(i),this.store.addTrack(e.auxiliaryTracks[s]))}l.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 ur=class extends St{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)){l.d(this.TAG,`no peer in store for peerId: ${i}`);return}let o=new Ae(new MediaStream,this.transport.getSubscribeConnection()),n=Ie.getEmptyVideoTrack();n.enabled=!t.mute;let d=new O(o,n,t.source,(u=this.store.getRoom())==null?void 0:u.disableNoneLayerRequest);d.setTrackId(t.track_id),d.peerId=s.peerId,d.logIdentifier=s.name,this.addVideoTrack(s,d),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&&ye(t.videoTrack.nativeTrack)}isPeerRoleSubscribed(t){var s,o,n,d;if(!t)return!0;let i=this.store.getLocalPeer(),r=this.store.getPeerById(t);return r&&((d=(o=(s=i==null?void 0:i.role)==null?void 0:s.subscribeParams)==null?void 0:o.subscribeToRoles)==null?void 0:d.includes((n=r.role)==null?void 0:n.name))}};var pr=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(o=>!e[o.peerId]);r.length>0&&l.d(this.TAG,`${r}`),r.forEach(o=>{var d;let n={peer_id:o.peerId,role:((d=o.role)==null?void 0:d.name)||"",info:{name:o.name,data:o.metadata||"",user_id:o.customerUserId||"",type:o.type},tracks:{},groups:[],realtime:o.realtime};this.peerManager.handlePeerLeave(n)});let s=[];i.forEach(o=>{let n=this.store.getPeerById(o.peer_id),d=Object.values(o.tracks);n&&(this.store.getPeerTracks(n.peerId).forEach(p=>{var m;o.tracks[p.trackId]||(this.removePeerTrack(n,p.trackId),(m=this.listener)==null||m.onTrackUpdate(1,p,n))}),d.forEach(p=>{this.store.getTrackById(p.track_id)||this.store.setTrackState({peerId:n.peerId,trackInfo:p})}),this.trackManager.handleTrackUpdate({peer:o,tracks:o.tracks},!1),this.peerManager.handlePeerUpdate(o)),s.push(o)}),s.length>0&&this.peerManager.handlePeerList(s)}}handleNotification(e,t,i){if(e==="peer-list"){let r=t;i?(l.d(this.TAG,"RECONNECT_PEER_LIST event",JSON.stringify(r,null,2)),this.handleReconnectPeerList(r)):(l.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(l.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(o=>o.trackId===t);s>=0&&e.auxiliaryTracks.splice(s,1)}}};var L=a=>a?new Date(a):void 0;var hr=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(o=>o.peer_id));this.store.getRemotePeers().forEach(({peerId:o,fromRoomState:n})=>{!i.has(o)&&n&&this.store.removePeer(o)});for(let o of e)t.push(this.makePeer(o));(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,o;let t=this.store.getPeerById(e.peer_id);this.store.removePeer(e.peer_id),l.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(n=>{var d;(d=this.listener)==null||d.onTrackUpdate(1,n,t)}),(o=this.listener)==null||o.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,o,n,d,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),(o=this.listener)==null||o.onPeerUpdate(13,t);return}if(!t){l.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),(n=this.listener)==null||n.onPeerUpdate(8,t)}let i=t.isHandRaised;t.updateGroups(e.groups);let r=(d=e.groups)==null?void 0:d.includes(Re);i!==r&&((u=this.listener)==null||u.onPeerUpdate(12,t)),this.handlePeerInfoUpdate(h({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=Ee(e,this.store),t.realtime=e.realtime,t.joinedAt=L(e.joined_at),t.fromRoomState=!!e.is_from_room_state,this.store.addPeer(t),l.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 mr=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:l.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 Bs=(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))(Bs||{});var ti=(a,e,t)=>{let i=t==="qa"?_a:wa,r=new URL(i);return r.searchParams.set("endpoint",`https://${e}`),r.searchParams.set("token",a),r.toString()};var Sr=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 o;if(!this.isEnabled)return l.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(h({},t),{title:e==null?void 0:e.title,attributes:e==null?void 0:e.attributes,id:r.id,url:ti(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),(o=this.listener)==null||o.onWhiteboardUpdate(s)})}close(e){return c(this,null,function*(){var r;if(!this.isEnabled)return l.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 o=yield this.transport.signal.getWhiteboard({id:s.id}),n=this.store.getLocalPeer(),u=(n==null?void 0:n.customerUserId)===o.owner?(i=(t=n.role)==null?void 0:t.permissions.whiteboard)==null?void 0:i.includes("admin"):o.permissions.length>0,p=M(h({},s),{id:o.id,url:ti(o.token,o.addr,this.store.getEnv()),token:o.token,addr:o.addr,owner:o.owner,permissions:o.permissions,open:u});this.store.setWhiteboard(p),(r=this.listener)==null||r.onWhiteboardUpdate(p)}})}getCreateOptionsWithDefaults(e){var o;let t=Object.values(this.store.getKnownRoles()),i=[],r=[],s=[];return t.forEach(n=>{var d,u,p;(d=n.permissions.whiteboard)!=null&&d.includes("read")&&i.push(n.name),(u=n.permissions.whiteboard)!=null&&u.includes("write")&&r.push(n.name),(p=n.permissions.whiteboard)!=null&&p.includes("admin")&&s.push(n.name)}),{title:(e==null?void 0:e.title)||`${(o=this.store.getRoom())==null?void 0:o.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 ii=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.whiteboard=new Sr(e,t,i)}setListener(e){this.listener=e,this.whiteboard.setListener(e)}createPoll(e){return c(this,null,function*(){var o,n;let t={customerID:"userid",peerID:"peerid",userName:"username"},{poll_id:i}=yield this.transport.signal.setPollInfo(M(h({},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=gr(M(h({},e),{poll_id:e.id,state:"created",created_by:(o=this.store.getLocalPeer())==null?void 0:o.peerId}));s.questions=r.questions.map(({question:d,options:u,answer:p})=>M(h({},d),{options:u,answer:p})),(n=this.listener)==null||n.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 n,d;let o=this.getQuestionInPoll(i,s.questionIndex);return o.type==="single-choice"?(s.option=s.option||((n=s.options)==null?void 0:n[0])||-1,delete s.text,delete s.options):o.type==="multiple-choice"?((d=s.options)==null||d.sort(),delete s.text,delete s.option):(delete s.option,delete s.options),s.skipped&&(delete s.option,delete s.options,delete s.text),h({duration:0,type:o.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,m;let r=this.store.getPoll(e);if(!r)throw new Error("Invalid poll ID - Poll not found");let s=(m=(p=this.store.getLocalPeer())==null?void 0:p.role)==null?void 0:m.permissions,o=!!(s!=null&&s.pollRead||s!=null&&s.pollWrite);if(r.anonymous||r.state!=="stopped"||!o)return{entries:[],hasNext:!1};let n=yield this.transport.signal.fetchPollLeaderboard({poll_id:r.id,count:i,offset:t}),d={avgScore:n.avg_score,avgTime:n.avg_time,votedUsers:n.voted_users,totalUsers:n.total_users,correctUsers:n.correct_users};return{entries:n.questions.map(T=>({position:T.position,totalResponses:T.total_responses,correctResponses:T.correct_responses,duration:T.duration,peer:T.peer,score:T.score})),hasNext:!n.last,summary:d}})}getPollResponses(e,t){return c(this,null,function*(){var s,o;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:n,peer:d,final:u})=>{var m,T;let p=(m=e==null?void 0:e.questions)==null?void 0:m.find(g=>g.index===n.question);if(p){let g={id:n.response_id,questionIndex:n.question,option:n.option,options:n.options,text:n.text,responseFinal:u,peer:{peerid:d.peerid,userHash:d.hash,userid:d.userid,username:d.username},skipped:n.skipped,type:n.type,update:n.update},f=p.responses&&!t?[...p.responses]:[];(T=r.questions)!=null&&T[n.question-1]&&(r.questions[n.question-1].responses=[...f,g])}}),this.store.setPoll(r),(o=this.listener)==null||o.onPollsUpdate(4,[r])})}getPolls(){return c(this,null,function*(){var s,o,n;let e=yield this.transport.signal.getPollsList({count:50,state:"started"}),t=[],i=(o=(s=this.store.getLocalPeer())==null?void 0:s.role)==null?void 0:o.permissions.pollWrite,r=[...e.polls];if(i){let d=yield this.transport.signal.getPollsList({count:50,state:"created"}),u=yield this.transport.signal.getPollsList({count:50,state:"stopped"});r=[...d.polls,...r,...u.polls]}for(let d of r){let u=yield this.transport.signal.getPollQuestions({poll_id:d.poll_id,index:0,count:50}),p=gr(d),m=this.store.getPoll(d.poll_id);p.questions=u.questions.map(({question:T,options:g,answer:f},E)=>{var v,I;return M(h({},T),{options:g,answer:f,responses:(I=(v=m==null?void 0:m.questions)==null?void 0:v[E])==null?void 0:I.responses})}),t.push(p),this.store.setPoll(p)}return(n=this.listener)==null||n.onPollsUpdate(3,t),t})}createQuestionSetParams(e,t){var o,n;if(e.index){let d=(o=e.options)==null?void 0:o.map((u,p)=>M(h({},u),{index:p+1}));return{question:M(h({},e),{index:t+1}),options:d,answer:e.answer}}let i=M(h({},e),{index:t+1}),r,s=e.answer||{hidden:!1};return Array.isArray(e.options)&&["single-choice","multiple-choice"].includes(e.type)?(r=(n=e.options)==null?void 0:n.map((d,u)=>({index:u+1,text:d.text,weight:d.weight})),e.type==="single-choice"?s.option=e.options.findIndex(d=>d.isCorrectAnswer)+1||void 0:s.options=e.options.map((d,u)=>d.isCorrectAnswer?u+1:void 0).filter(d=>!!d)):(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}},gr=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 Tr=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 o=this.store.getPoll(s.poll_id);if(o&&o.state==="started"){(i=this.listener)==null||i.onPollsUpdate(1,[o]);return}let n=yield this.transport.signal.getPollQuestions({poll_id:s.poll_id,index:0,count:50}),d=gr(s);d.questions=n.questions.map(({question:u,options:p,answer:m})=>M(h({},u),{options:p,answer:m})),yield this.updatePollResponses(d,!0),t.push(d),this.store.setPoll(d)}(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 o=yield this.transport.signal.getPollResult({poll_id:r.poll_id});this.updatePollResult(s,o),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=h({},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 o,n;let s=(o=e.questions)==null?void 0:o.find(d=>d.index===r.question);s&&(s.result=h({},s.result),s.result.correctResponses=r.correct,s.result.skippedCount=r.skipped,s.result.totalResponses=r.total,(n=r.options)==null||n.forEach((d,u)=>{var m;let p=(m=s.options)==null?void 0:m[u];p&&p.voteCount!==d&&(p.voteCount=d)}))})}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:o,final:n})=>{var p;let d=(p=e==null?void 0:e.questions)==null?void 0:p.find(m=>m.index===s.question);if(!d)return;let u={id:s.response_id,questionIndex:s.question,option:s.option,options:s.options,text:s.text,responseFinal:n,peer:{peerid:o.peerid,userHash:o.hash,userid:o.userid,username:o.username},skipped:s.skipped,type:s.type,update:s.update};Array.isArray(d.responses)&&d.responses.length>0?d.responses.find(({id:m})=>m===u.id)||d.responses.push(u):d.responses=[u]})})}};var fr=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,o=this.store.getLocalPeerTracks().find(d=>d.publishedTrackId===i);if(!o)return;let n=()=>{var d;(d=this.listener)==null||d.onChangeTrackStateRequest({requestedBy:s,track:o,enabled:!r})};if(r){if(o.enabled===!r)return;o.setEnabled(!r).then(n)}else n()}handleChangeTrackStateRequest(e){var u;let{type:t,source:i,value:r,requested_by:s}=e,o=s?this.store.getPeerById(s):void 0,n=!r,d=this.getTracksToBeUpdated({type:t,source:i,enabled:n});if(d.length!==0)if(n)(u=this.listener)==null||u.onChangeMultiTrackStateRequest({requestedBy:o,tracks:d,type:t,source:i,enabled:!0});else{let p=[];for(let m of d)p.push(m.setEnabled(!1));Promise.all(p).then(()=>{var m;(m=this.listener)==null||m.onChangeMultiTrackStateRequest({requestedBy:o,tracks:d,enabled:!1})})}}getTracksToBeUpdated({type:e,source:t,enabled:i}){let s=this.store.getLocalPeerTracks();return e&&(s=s.filter(o=>o.type===e)),t&&(s=s.filter(o=>o.source===t)),s.filter(o=>o.enabled!==i)}};var vr=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){l.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){l.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,m,T;let{recording:t,streaming:i,transcriptions:r,session_id:s,started_at:o,name:n}=e,d=this.store.getRoom();if(!d){l.w(this.TAG,"on room state - room not present");return}d.name=n,d.rtmp.running=this.isStreamingRunning((u=i==null?void 0:i.rtmp)==null?void 0:u.state),d.rtmp.startedAt=L((p=i==null?void 0:i.rtmp)==null?void 0:p.started_at),d.rtmp.state=(m=i==null?void 0:i.rtmp)==null?void 0:m.state,d.recording.server=this.getPeerListSFURecording(t),d.recording.browser=this.getPeerListBrowserRecording(t),d.recording.hls=this.getPeerListHLSRecording(t),d.hls=this.convertHls(i==null?void 0:i.hls),d.transcriptions=this.addTranscriptionDetail(r),d.sessionId=s,d.startedAt=L(o),(T=this.listener)==null||T.onRoomUpdate("RECORDING_STATE_UPDATED",d)}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)})):[]}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 o,n,d;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((o=e==null?void 0:e.variants)==null?void 0:o[s].started_at),initialisedAt:L((n=e==null?void 0:e.variants)==null?void 0:n[s].initialised_at),state:r.state,stream_type:r==null?void 0:r.stream_type}):i.variants.push({initialisedAt:L((d=e==null?void 0:e.variants)==null?void 0:d[s].initialised_at),url:""})}),i):(l.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){l.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){l.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){l.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){l.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 l.e(this.TAG,"error in streaming/recording",i),i}};var Mr=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 yr=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){switch(e){case"on-whiteboard-update":{this.handleWhiteboardUpdate(t);break}default:break}}handleWhiteboardUpdate(e){return c(this,null,function*(){var n;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",o={id:e.id,title:e.title,attributes:e.attributes};if(o.open=r?i==null?void 0:i.open:s,o.owner=o.open?e.owner:void 0,o.open)if(r)o.url=i==null?void 0:i.url,o.token=i==null?void 0:i.token,o.addr=i==null?void 0:i.addr,o.permissions=i==null?void 0:i.permissions;else{let d=yield this.transport.signal.getWhiteboard({id:e.id});o.url=ti(d.token,d.addr,this.store.getEnv()),o.token=d.token,o.addr=d.addr,o.permissions=d.permissions,o.open=d.permissions.length>0}this.store.setWhiteboard(o),(n=this.listener)==null||n.onWhiteboardUpdate(o)})}};var kr=class{constructor(e,t,i,r,s,o){this.store=e;this.transport=i;this.listener=r;this.audioListener=s;this.connectionQualityListener=o;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 n=this.transport.isFlagEnabled("onDemandTracks");this.trackManager=n?new ur(this.store,t,this.transport,this.listener):new St(this.store,t,this.listener),this.peerManager=new hr(this.store,this.trackManager,this.listener),this.peerListManager=new pr(this.store,this.peerManager,this.trackManager,this.listener),this.broadcastManager=new dr(this.listener),this.policyChangeManager=new mr(this.store,t),this.requestManager=new fr(this.store,this.listener),this.activeSpeakerManager=new cr(this.store,this.listener,this.audioListener),this.connectionQualityManager=new lr(this.store,this.connectionQualityListener),this.roomUpdateManager=new vr(this.store,this.listener),this.sessionMetadataManager=new Mr(this.store,this.listener),this.pollsManager=new Tr(this.store,this.transport,this.listener),this.whiteboardManager=new yr(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,o;let i=e.method,r=e.params;["active-speakers","sfu-stats","on-connection-quality-update",void 0].includes(i)||l.d(this.TAG,`Received notification - ${i}`,{notification:r}),i==="sfu-stats"&&(s=window.HMS)!=null&&s.ON_SFU_STATS&&typeof((o=window.HMS)==null?void 0:o.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){l.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 Er=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 Pr=class{constructor(e,t,i="",r="",s="https://prod-init.100ms.live/init",o=!1,n){this.authToken=e;this.peerId=t;this.peerName=i;this.data=r;this.endpoint=s;this.autoSubscribeVideo=o;this.iceServers=n}};var Q=(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))(Q||{}),bo={0:[],1:[],2:[1],3:[1],4:[1]};var br=(n=>(n.Disconnected="Disconnected",n.Connecting="Connecting",n.Joined="Joined",n.Preview="Preview",n.Failed="Failed",n.Reconnecting="Reconnecting",n.Leaving="Leaving",n))(br||{});var Ar=class{constructor(e){this.promise=new Promise((t,i)=>{this.resolve=t,this.reject=i,e(t,i)})}};var Ir=class{constructor(e,t){this.onStateChange=e;this.sendEvent=t;this.TAG="[RetryScheduler]";this.inProgress=new Map;this.retryTaskIds=[]}schedule(n){return c(this,arguments,function*({category:e,error:t,task:i,originalState:r,maxRetryTime:s=6e4,changeState:o=!0}){yield this.scheduleTask({category:e,error:t,changeState:o,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:o,maxRetryTime:n=6e4,failedRetryCount:d=0}){if(l.d(this.TAG,"schedule: ",{category:Q[e],error:t}),d===0){let v=this.inProgress.get(e);if(v){l.d(this.TAG,`schedule: Already a task for ${Q[e]} scheduled, waiting for its completion`),yield v.promise;return}let I=new Ar(($,ue)=>{});this.inProgress.set(e,I),this.sendEvent(t,e)}let p=!1,m=bo[e];for(let v in m){let I=m[parseInt(v)];try{let $=this.inProgress.get(I);$&&(l.d(this.TAG,`schedule: Suspending retry task of ${Q[e]}, waiting for ${Q[I]} to recover`),yield $.promise,l.d(this.TAG,`schedule: Resuming retry task ${Q[e]} as it's dependency ${Q[I]} is recovered`))}catch($){l.d(this.TAG,`schedule: Stopping retry task of ${Q[e]} as it's dependency ${Q[I]} 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()-o;if(g>=n||p)return t.description+=`. [${Q[e]}] Could not recover after ${g} milliseconds`,p&&(t.description+=` Could not recover all of it's required dependencies - [${m.map(v=>Q[v]).toString()}]`),t.isTerminal=!0,T(t);i&&this.onStateChange("Reconnecting",t);let f=this.getDelayForRetryCount(e);l.d(this.TAG,`schedule: [${Q[e]}] [failedRetryCount=${d}] Scheduling retry task in ${f}ms`);let E;try{E=yield this.setTimeoutPromise(r,f)}catch(v){E=!1;let I=v;if(I.isTerminal)return l.e(this.TAG,`[${Q[e]}] Un-caught terminal exception ${I.name} in retry-task`,v),T(I);l.w(this.TAG,`[${Q[e]}] Un-caught exception ${I.name} in retry-task, initiating retry`,v)}if(E){let v=this.inProgress.get(e);this.inProgress.delete(e),v==null||v.resolve(d),i&&this.inProgress.size===0&&this.onStateChange(s),l.d(this.TAG,`schedule: [${Q[e]}] [failedRetryCount=${d}] Recovered \u267B\uFE0F after ${g}ms`)}else yield this.scheduleTask({category:e,error:t,changeState:i,task:r,originalState:s,maxRetryTime:n,failedAt:o,failedRetryCount:d+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 o=yield e();o&&this.retryTaskIds.splice(this.retryTaskIds.indexOf(s),1),i(o)}catch(o){r(o)}}),t);this.retryTaskIds.push(s)})})}};var Rr=class extends Ue{constructor(){super(100);this.localStorage=new Me("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 Hr=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 l.w(this.TAG,"Rate limit exceeded",t),t}try{this.sendSingleEvent(e),this.flushFailedEvents()}catch(t){l.w(this.TAG,"sendEvent failed",t)}}flushFailedEvents(e){var t;try{for(l.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):Ce.sendEvent(i))}}catch(i){l.w(this.TAG,"flushFailedEvents failed",i)}}sendSingleEvent(e){try{this.transportProvider.sendEvent(e),l.d(this.TAG,"Sent event",e.name,e)}catch(t){throw l.w(this.TAG,`${this.transportProvider.TAG}.sendEvent failed, adding to local storage events`,{event:e,error:t}),this.failedEvents.enqueue(e),t}}};var Cr=class extends Hr{constructor(t){super();this.transportProvider=t;this.failedEvents=new Rr}};var gt=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.stop=()=>{this.shouldSendEvent&&this.sendEvent(),this.eventBus.statsUpdate.unsubscribe(this.handleStatsUpdate.bind(this)),this.shouldSendEvent=!1};this.start()}start(){this.shouldSendEvent||(this.stop(),this.shouldSendEvent=!0,this.eventBus.statsUpdate.subscribe(this.handleStatsUpdate.bind(this)),this.startLoop().catch(e=>l.e("[StatsAnalytics]",e.message)))}startLoop(){return c(this,null,function*(){for(;this.shouldSendEvent;)yield se(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()})}},Tt=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?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)}},Lr=(a,e)=>a&&e&&(a.frameWidth!==e.frameWidth||a.frameHeight!==e.frameHeight),Dr=(a,e)=>a&&e&&a.enabled!==e.enabled,ri=a=>Object.entries(a).filter(([,e])=>e!==void 0).reduce((e,[t,i])=>(e[t]=i,e),{});var si=class extends gt{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(o=>{o.track.type==="audio"?t.push(o.toAnalytics()):o.track.type==="video"&&i.push(o.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()}handleStatsUpdate(t){let i=!1,r=t.getLocalTrackStats();Object.keys(r).forEach(s=>{let o=r[s],n=this.store.getLocalPeerTracks().find(d=>d.getTrackIDBeingSent()===s);Object.keys(o).forEach(d=>{var g,f,E;let u=o[d];if(!n)return;let p=this.getTrackIdentifier(n.trackId,u),m=M(h({},u),{availableOutgoingBitrate:(f=(g=t.getLocalPeerStats())==null?void 0:g.publish)==null?void 0:f.availableOutgoingBitrate});if(p&&this.trackAnalytics.has(p))(E=this.trackAnalytics.get(p))==null||E.pushTempStat(m);else if(n){let v=new Vs({track:n,sampleWindowSize:this.sampleWindowSize,rid:u.rid,ssrc:u.ssrc.toString(),kind:u.kind});v.pushTempStat(m),this.trackAnalytics.set(this.getTrackIdentifier(n.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}},Vs=class extends Tt{constructor(){super(...arguments);this.samples=[];this.collateSample=()=>{let t=this.getLatestStat(),i=t.qualityLimitationDurations,r=i&&{bandwidth_sec:i.bandwidth,cpu_sec:i.cpu,other_sec:i.other},s=t.frameHeight?{height_px:this.getLatestStat().frameHeight,width_px:this.getLatestStat().frameWidth}:void 0,o=this.calculateAverage("jitter",!1),n=o?Math.round(o*1e3):void 0,d=this.calculateAverage("roundTripTime",!1),u=d?Math.round(d*1e3):void 0;return ri({timestamp:Date.now(),avg_available_outgoing_bitrate_bps:this.calculateAverage("availableOutgoingBitrate"),avg_bitrate_bps:this.calculateAverage("bitrate"),avg_fps:this.calculateAverage("framesPerSecond"),total_packets_lost:this.getLatestStat().packetsLost,total_packets_sent:this.getLatestStat().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:n,avg_round_trip_time_ms:u,total_quality_limitation:r,resolution:s})};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===30||Dr(i,r)||i.kind==="video"&&Lr(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}};var ai=class extends gt{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(o=>{o.track.type==="audio"?t.push(o.toAnalytics()):o.track.type==="video"&&i.push(o.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,E;let o=this.store.getTrackById(s),n=i[s],d=(f=this.trackAnalytics.get(s))==null?void 0:f.getLatestStat(),p=((v,I)=>{let $=(I==null?void 0:I.jitterBufferDelay)||0,ue=(I==null?void 0:I.jitterBufferEmittedCount)||0,ve=((v==null?void 0:v.jitterBufferDelay)||0)-$,pe=((v==null?void 0:v.jitterBufferEmittedCount)||0)-ue;return pe>0?ve*1e3/pe:(I==null?void 0:I.calculatedJitterBufferDelay)||0})(n,d),m=this.calculateAvSyncForStat(n,t),T=M(h({},n),{calculatedJitterBufferDelay:p,avSync:m});if(n.kind==="video"){let v=o.getPreferredLayerDefinition();T.expectedFrameHeight=v==null?void 0:v.resolution.height,T.expectedFrameWidth=v==null?void 0:v.resolution.width}if(this.trackAnalytics.has(s))(E=this.trackAnalytics.get(s))==null||E.pushTempStat(T);else if(o){let v=new Gs({track:o,sampleWindowSize:this.sampleWindowSize,ssrc:n.ssrc.toString(),kind:n.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,o=r==null?void 0:r.videoTrack;if(!(s&&o&&s.enabled&&o.enabled))return xt;let d=i.getRemoteTrackStats(s.trackId);if(!d)return xt;if(d.estimatedPlayoutTimestamp)return d.estimatedPlayoutTimestamp-t.estimatedPlayoutTimestamp}},Gs=class extends Tt{constructor(){super(...arguments);this.samples=[];this.collateSample=()=>{let t=this.getLatestStat(),i=this.getFirstStat(),r={timestamp:Date.now(),total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount"),avg_jitter_buffer_delay:this.calculateAverage("calculatedJitterBufferDelay",!1)};if(t.kind==="video")return ri(M(h({},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 ri(M(h({},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||Dr(i,r)||i.kind==="video"&&Lr(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!==xt);return i.length===0?xt:i.reduce((r,s)=>r+s,0)/i.length}};var ft=(t=>(t[t.Publish=0]="Publish",t[t.Subscribe=1]="Subscribe",t))(ft||{});var oi=Ge(require("sdp-transform"));function Ao(a,e){var r;let t=oi.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 d,u,p;let o=(d=s.msid)==null?void 0:d.split(" ")[0],n=(u=i.find(m=>m.type===s.type&&m.stream_id===o))==null?void 0:u.track_id;n&&(s.msid=(p=s.msid)==null?void 0:p.replace(/\s(.+)/,` ${n}`))}),{type:a.type,sdp:oi.write(t)}}function Io(a,e){var s;if(!(a!=null&&a.sdp)||!e)return;let i=oi.parse(a.sdp).media.find(o=>me(o.mid)&&parseInt(o.mid)===parseInt(e));return(s=i==null?void 0:i.msid)==null?void 0:s.split(" ")[1]}function Ro(a){return a.sdp.includes("usedtx=1")?a:{type:a.type,sdp:a.sdp.replace("useinbandfec=1","useinbandfec=1;usedtx=1")}}var Le="[HMSConnection]",Ye=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 l.d(Le,`[role=${this.role}] createOffer offer=${JSON.stringify(i,null,1)}`),Ro(Ao(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 l.d(Le,`[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{l.d(Le,`[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{l.d(Le,`[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"){l.d(Le,`[role=${this.role}] addIceCandidate signalling state closed`);return}l.d(Le,`[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,o=()=>{typeof s.getSelectedCandidatePair=="function"&&(this.selectedCandidatePair=s.getSelectedCandidatePair(),this.selectedCandidatePair&&(this.observer.onSelectedCandidatePairChange(this.selectedCandidatePair),l.d(Le,`${ft[this.role]} connection`,`selected ${i||"unknown"} candidate pair`,JSON.stringify(this.selectedCandidatePair,null,2))))};typeof s.onselectedcandidatepairchange=="function"&&(s.onselectedcandidatepairchange=o),o()}})}catch(e){l.w(Le,`Error in logging selected ice candidate pair for ${ft[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 G&&e.settings.maxFramerate,s=this.getSenders().find(o=>{var n;return((n=o==null?void 0:o.track)==null?void 0:n.id)===e.getTrackIDBeingSent()});if(s){let o=s.getParameters();o.encodings.length===1&&(i&&(o.encodings[0].maxBitrate=i*1e3),r&&(o.encodings[0].maxFramerate=r)),yield s.setParameters(o)}else l.w(Le,`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 ni=class extends Ye{constructor(t,i,r){super(0,t);this.TAG="[HMSPublishConnection]";this.observer=r,this.nativeConnection=new RTCPeerConnection(i),this.channel=this.nativeConnection.createDataChannel(_i,{protocol:"SCTP"}),this.channel.onerror=s=>l.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 o;this.observer.onDTLSTransportError(new Error((o=s==null?void 0:s.error)==null?void 0:o.errorDetail)||"DTLS Transport failed")})}}close(){super.close(),this.channel.close()}initAfterJoin(){this.nativeConnection.onnegotiationneeded=()=>c(this,null,function*(){l.d(this.TAG,"onnegotiationneeded"),yield this.observer.onRenegotiationNeeded()})}};var Ho=Ge(require("eventemitter2")),Co=require("uuid");var ci=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){l.d(this.TAG,`[${this.metadata}] Sending [size=${e.length}] message=${e}`),this.nativeChannel.send(e)}close(){this.nativeChannel.close()}};var di=class extends Ye{constructor(t,i,r,s){super(1,t);this.isFlagEnabled=r;this.TAG="[HMSSubscribeConnection]";this.remoteStreams=new Map;this.MAX_RETRIES=3;this.pendingMessageQueue=[];this.eventEmitter=new Ho.default({maxListeners:60});this.handlePendingApiMessages=()=>{this.eventEmitter.emit("open",!0),this.pendingMessageQueue.length>0&&(l.d(this.TAG,"Found pending message queue, sending messages"),this.pendingMessageQueue.forEach(t=>this.sendOverApiDataChannel(t)),this.pendingMessageQueue.length=0)};this.sendMessage=(t,i)=>c(this,null,function*(){var s;((s=this.apiChannel)==null?void 0:s.readyState)!=="open"&&(yield this.eventEmitter.waitFor("open"));let r;for(let o=0;o<this.MAX_RETRIES;o++){this.apiChannel.send(t),r=yield this.waitForResponse(i);let n=r.error;if(n){if(n.code===404){l.d(this.TAG,`Track not found ${i}`,{request:t,try:o+1,error:n});break}if(l.d(this.TAG,`Failed sending ${i}`,{request:t,try:o+1,error:n}),!(n.code/100===5||n.code===429))throw Error(`code=${n.code}, message=${n.message}`);let u=(2+Math.random()*2)*1e3;yield Be(u)}else break}return r});this.waitForResponse=t=>c(this,null,function*(){let i=yield this.eventEmitter.waitFor("message",function(s){return s.includes(t)}),r=JSON.parse(i[0]);return l.d(this.TAG,`response for ${t} -`,JSON.stringify(r,null,2)),r});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===_i&&(this.apiChannel=new ci(t.channel,{onMessage:i=>{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 m=new Ae(i,this);this.remoteStreams.set(r,m)}i.addEventListener("removetrack",m=>{if(m.track.id!==t.track.id)return;let T=s.tracks.findIndex(g=>{var f;return g.nativeTrack.id===m.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),o=t.track.kind==="audio",n=o?ae:O,d=o?new n(s,t.track):new n(s,t.track,void 0,this.isFlagEnabled("disableNoneLayerRequest"));t.track.kind==="video"&&s.setVideoLayerLocally("none","addTrack","subscribeConnection"),d.transceiver=t.transceiver;let u=Io(this.remoteDescription,(p=t.transceiver)==null?void 0:p.mid);u&&d.setSdpTrackId(u),s.tracks.push(d),this.observer.onTrackAdd(d)}}sendOverApiDataChannel(t){this.apiChannel&&this.apiChannel.readyState==="open"?this.apiChannel.send(t):(l.w(this.TAG,`API Data channel not ${this.apiChannel?"open":"present"}, queueing`,t),this.pendingMessageQueue.push(t))}sendOverApiDataChannelWithResponse(t,i){return c(this,null,function*(){let r=(0,Co.v4)();if(t.method==="prefer-video-track-state"&&this.isFlagEnabled("disableVideoTrackAutoUnsubscribe")&&t.params.max_spatial_layer==="none")return l.d(this.TAG,"video auto unsubscribe is disabled, request is ignored"),{id:r};let s=JSON.stringify(h({id:i||r,jsonrpc:"2.0"},t));return this.sendMessage(s,r)})}close(){var t;super.close(),(t=this.apiChannel)==null||t.close()}};var Lo=(a,e)=>!e||e.length===0?a:e.map(i=>({urls:i.urls,credentialType:"password",credential:i.password,username:i.userName}));var _r="[InitService]",li=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(n){return c(this,arguments,function*({token:e,peerId:t,userAgent:i,initEndpoint:r="https://prod-init.100ms.live",region:s="",iceServers:o}){l.d(_r,`fetchInitConfig: initEndpoint=${r} token=${e} peerId=${t} region=${s} `);let d=md(r,t,i,s);try{let u=yield fetch(d,{headers:{Authorization:`Bearer ${e}`}});try{let p=yield u.clone().json();return this.handleError(u,p),l.d(_r,`config is ${JSON.stringify(p,null,2)}`),Sd(p,o)}catch(p){let m=yield u.text();throw l.e(_r,"json error",p.message,m),p instanceof k?p:S.APIErrors.ServerErrors(u.status,"INIT",p.message)}}catch(u){let p=u;throw["Failed to fetch","NetworkError","ECONNRESET"].some(m=>p.message.includes(m))?S.APIErrors.EndpointUnreachable("INIT",p.message):p}})}};function md(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 l.e(_r,s.name,s.message),s}}function Sd(a,e){var t;return M(h({},a),{rtcConfiguration:M(h({},a.rtcConfiguration),{iceServers:Lo((t=a.rtcConfiguration)==null?void 0:t.ice_servers,e)})})}var Do=require("uuid");var ui=class{constructor(e){this.TAG="[SIGNAL]: ";this.pongResponseTimes=new Ue(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=()=>{l.d(this.TAG,"Window network offline"),this.setIsConnected(!1,"Window network offline")};this.onlineListener=()=>{l.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=""){l.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,Do.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((n,d)=>{this.callbacks.set(i,{resolve:n,reject:d,metadata:{method:e}})})}catch(o){if(o instanceof k)throw o;let n=o;throw S.WebsocketMethodErrors.ServerErrors(Number(n.code),$r(e),n.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=()=>{l.e(this.TAG,"Error from websocket"),r=!0,i(S.WebSocketConnectionErrors.FailedToConnect("JOIN","Error opening websocket connection"))};this.onCloseHandler=n=>{l.w(`Websocket closed code=${n.code}`),r?this.setIsConnected(!1,`code: ${n.code}${n.code!==1e3?", unexpected websocket close":""}`):(r=!0,i(S.WebSocketConnectionErrors.AbnormalClose("JOIN",`Error opening websocket connection - websocket closed unexpectedly with code=${n.code}`)))},this.socket.addEventListener("error",s);let o=()=>{var n,d;r=!0,t(),this.setIsConnected(!0),this.id++,(n=this.socket)==null||n.removeEventListener("open",o),(d=this.socket)==null||d.removeEventListener("error",s),this.pingPongLoop(this.id)};this.socket.addEventListener("open",o),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,o,n){return c(this,null,function*(){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("JOIN","Failed to send join over WS connection");let d={name:e,disableVidAutoSub:i,data:t,offer:n,server_sub_degrade:r,simulcast:s,onDemandTracks:o},u=yield this.internalCall("join",d);return this.isJoinCompleted=!0,this.pendingTrickle.forEach(({target:p,candidate:m})=>this.trickle(p,m)),this.pendingTrickle.length=0,l.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",h({},e))})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.call("rtmp-stop",{})})}startHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-start",h({},e))})}stopHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-stop",h({},e))})}startTranscription(e){return c(this,null,function*(){yield this.call("transcription-start",h({},e))})}stopTranscription(e){return c(this,null,function*(){yield this.call("transcription-stop",h({},e))})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.call("hls-timed-metadata",h({},e))})}updatePeer(e){return c(this,null,function*(){yield this.call("peer-update",h({},e))})}getPeer(e){return c(this,null,function*(){return yield this.call("get-peer",h({},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",h({},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",h({},e))}getPollInfo(e){return this.call("poll-info-get",h({},e))}setPollQuestions(e){return this.call("poll-questions-set",h({},e))}startPoll(e){return this.call("poll-start",h({},e))}stopPoll(e){return this.call("poll-stop",h({},e))}getPollQuestions(e){return this.call("poll-questions-get",h({},e))}setPollResponses(e){return this.call("poll-response",h({},e))}getPollResponses(e){return this.call("poll-responses",h({},e))}getPollsList(e){return this.call("poll-list",h({},e))}getPollResult(e){return this.call("poll-result",h({},e))}createWhiteboard(e){return this.validateConnection(),this.call("whiteboard-create",h({},e))}getWhiteboard(e){return this.validateConnection(),this.call("whiteboard-get",h({},e))}fetchPollLeaderboard(e){return this.call("poll-leaderboard",h({},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":l.w(this.TAG,e.params);break;default:this.observer.onNotification(e);break}}rejectPendingCalls(e=""){this.callbacks.forEach((t,i)=>{var r,s,o,n;((r=t.metadata)==null?void 0:r.method)!=="ping"&&(l.e(this.TAG,`rejecting pending callback ${(s=t.metadata)==null?void 0:s.method}, id=${i}`),t.reject(S.WebSocketConnectionErrors.WebSocketConnectionLost((o=t.metadata)!=null&&o.method?$r((n=t.metadata)==null?void 0:n.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?(l.d(this.TAG,`Pong timeout ${e}, pageHidden=${oa()}`),this.id===e&&this.setIsConnected(!1,"ping pong failure")):setTimeout(()=>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(),l.d(this.TAG,`Try number ${s} sending ${e}`,t),yield this.internalCall(e,t)}catch(o){if(r=o,l.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 d=(2+Math.random()*2)*1e3;yield Be(d)}throw l.e(`Sending ${e} over WS failed after ${Math.min(s,3)} retries`,{method:e,params:t,error:r}),r})}};var wo=()=>{if(!U||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]:",pi=class{constructor(e,t,i,r,s,o,n){this.observer=e;this.deviceManager=t;this.store=i;this.eventBus=r;this.analyticsEventsService=s;this.analyticsTimer=o;this.pluginUsageTracker=n;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){l.d(R,"ignoring old offer");return}yield this.subscribeConnection.setRemoteDescription(e),l.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),l.d(R,"[role=SUBSCRIBE] onOffer renegotiation DONE \u2705")}catch(t){l.d(R,"[role=SUBSCRIBE] onOffer renegotiation FAILED \u274C",t),this.state="Failed";let i;t instanceof k?i=t:i=S.GenericErrors.Unknown("SUBSCRIBE",t.message),this.observer.onFailure(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*(){l.d(R,"socket offline",br[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;l.d(R,"socket online",br[this.state]),this.analyticsSignalTransport.flushFailedEvents((e=this.store.getLocalPeer())==null?void 0:e.peerId)},onNetworkOnline:()=>{this.analyticsEventsService.flushFailedClientEvents()}};this.signal=new ui(this.signalObserver);this.analyticsSignalTransport=new Cr(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)&&(l.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(ot,{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(nt,{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;l.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 Oi(this.store,this.eventBus);let d=(u,p)=>c(this,null,function*(){u!==this.state&&(this.state=u,yield this.observer.onStateChange(this.state,p))});this.retryScheduler=new Ir(d,this.sendErrorAnalyticsEvent.bind(this)),this.eventBus.statsUpdate.subscribe(u=>{var m,T;let p=((T=(m=u.getLocalPeerStats())==null?void 0:m.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,o){return c(this,null,function*(){let n=yield this.connect(e,t,i,r,s,o);return this.state="Preview",this.observer.onStateChange(this.state),n})}join(e,t,i,r,s=!1,o){return c(this,null,function*(){l.d(R,"join: started \u23F0");try{(!this.signal.isConnected||!this.initConfig)&&(yield this.connect(e,r,t,i,s,o)),this.validateNotDisconnected("connect"),this.initConfig&&(yield this.waitForLocalRoleAvailability(),yield this.createConnectionsAndNegotiateJoin(i,s),this.initStatsAnalytics(),l.d(R,"\u2705 join: Negotiated over PUBLISH connection"))}catch(n){l.e(R,`join: failed \u274C [token=${e}]`,n),this.state="Failed";let d=n;throw d.isTerminal=d.isTerminal||d.code===500,yield this.observer.onStateChange(this.state,d),d}l.d(R,"\u2705 join: successful"),this.state="Joined",this.observer.onStateChange(this.state)})}connect(e,t,i,r,s=!1,o){return c(this,null,function*(){this.setTransportStateForConnect(),this.joinParameters=new Pr(e,i,r.name,r.metaData,t,s,o);try{return yield this.internalConnect(e,t,i,o)}catch(n){if(n instanceof k&&([P.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,P.WebSocketConnectionErrors.FAILED_TO_CONNECT,P.WebSocketConnectionErrors.ABNORMAL_CLOSE,P.APIErrors.ENDPOINT_UNREACHABLE].includes(n.code)||n.code.toString().startsWith("5")||n.code.toString().startsWith("429"))){let u=()=>c(this,null,function*(){return yield this.internalConnect(e,t,i,o),!!(this.initConfig&&this.initConfig.endpoint)});yield this.retryScheduler.schedule({category:0,error:n,task:u,originalState:this.state,changeState:!1})}else throw n}})}leave(i){return c(this,arguments,function*(e,t="user request"){var r,s,o;this.retryScheduler.reset(),this.joinParameters=void 0,l.d(R,"leaving in transport");try{let n=this.pluginUsageTracker.getPluginUsage("HMSKrispPlugin");if(n&&this.eventBus.analytics.publish(y.getKrispUsage(n)),this.state="Leaving",(r=this.publishStatsAnalytics)==null||r.stop(),(s=this.subscribeStatsAnalytics)==null||s.stop(),(o=this.webrtcInternals)==null||o.cleanup(),this.clearPeerConnections(),e)try{this.signal.leave(t),l.d(R,"signal leave done")}catch(d){l.w(R,"failed to send leave on websocket to server",d)}this.analyticsEventsService.flushFailedClientEvents(),this.analyticsEventsService.reset(),yield this.signal.close()}catch(n){this.eventBus.analytics.publish(y.disconnect(n)),l.e(R,"leave: FAILED \u274C",n)}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,o;l.time("sfu migration"),this.clearPeerConnections();let e=this.store.getPeerMap();this.store.removeRemoteTracks();for(let n in e){let d=e[n];d.isLocal||(d.audioTrack=void 0,d.videoTrack=void 0,d.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 n=t.audioTrack.stream;i.get(n.id)||i.set(n.id,new ge(new MediaStream));let d=t.audioTrack.clone(i.get(n.id));this.store.removeTrack(t.audioTrack),t.audioTrack.cleanup(),yield this.publishTrack(d),t.audioTrack=d}if(t.videoTrack){let n=t.videoTrack.stream;i.get(n.id)||i.set(n.id,new ge(new MediaStream)),this.store.removeTrack(t.videoTrack);let d=t.videoTrack.clone(i.get(n.id));t.videoTrack.cleanup(),yield this.publishTrack(d),t.videoTrack=d}let r=[];for(;t.auxiliaryTracks.length>0;){let n=t.auxiliaryTracks.shift();if(n){let d=n.stream;i.get(d.id)||i.set(d.id,new ge(n.source==="screen"?d.nativeStream.clone():new MediaStream)),this.store.removeTrack(n);let u=n.clone(i.get(d.id));u.type==="video"&&u.source==="screen"&&(this.screenStream.add(d.nativeStream),this.screenStream.add(u.stream.nativeStream),u.nativeTrack.addEventListener("ended",this.onScreenshareStop)),n.cleanup(),yield this.publishTrack(u),r.push(u)}}t.auxiliaryTracks=r,i.clear(),(o=(s=this.listener)==null?void 0:s.onSFUMigration)==null||o.call(s),l.timeEnd("sfu migration")})}trackUpdate(e,t){var s;let r=Array.from(this.trackStates.values()).find(o=>e.type===o.type&&e.source===o.source);if(r){let o=new zt(M(h({},r),{mute:!t}));this.trackStates.set(r.track_id,o),l.d(R,"Track Update",this.trackStates,e),this.signal.trackUpdate(new Map([[r.track_id,o]]));let n=this.store.getLocalPeer();n&&t===e.enabled&&((s=this.listener)==null||s.onTrackUpdate(t?3:2,e,n))}}publishTrack(e){return c(this,null,function*(){e.publishedTrackId=e.getTrackIDBeingSent(),l.d(R,`\u23F3 publishTrack: trackId=${e.trackId}, toPublishTrackId=${e.publishedTrackId}`,`${e}`),this.trackStates.set(e.publishedTrackId,new zt(e));let t=new Promise((s,o)=>{this.callbacks.set(ot,{promise:{resolve:s,reject:o},action:"PUBLISH",extra:{}})}),i=e.stream;i.setConnection(this.publishConnection);let r=this.store.getSimulcastLayers(e.source);i.addTransceiver(e,r),l.time(`publish-${e.trackId}-${e.type}`),yield t,l.timeEnd(`publish-${e.trackId}-${e.type}`),this.store.addTrack(e),yield i.setMaxBitrateAndFramerate(e).then(()=>{l.d(R,`Setting maxBitrate=${e.settings.maxBitrate} kpbs${e instanceof G?` and maxFramerate=${e.settings.maxFramerate}`:""} for ${e.source} ${e.type} ${e.trackId}`)}).catch(s=>l.w(R,"Failed setting maxBitrate and maxFramerate",s)),e.isPublished=!0,l.d(R,`\u2705 publishTrack: trackId=${e.trackId}`,`${e}`,this.callbacks)})}unpublishTrack(e){return c(this,null,function*(){if(l.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(o=>e.type===o.type&&e.source===o.source);s&&this.trackStates.delete(s.track_id)}let t=new Promise((r,s)=>{this.callbacks.set(ot,{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),l.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,o,n=!1)=>{(["disconnected","failed"].includes(o)?l.w.bind(l):l.d.bind(l))(R,`${ft[s]} ${n?"ice":""} connection state change: ${o}`)};if(this.initConfig){let s={onRenegotiationNeeded:()=>c(this,null,function*(){yield this.performPublishRenegotiation()}),onDTLSTransportStateChange:n=>{var p,m,T;if((n==="failed"?l.w.bind(l):l.d.bind(l))(R,`Publisher on dtls transport state change: ${n}`),!n||this.lastPublishDtlsState===n||(this.lastPublishDtlsState=n,this.publishDtlsStateTimer!==0&&(clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0),n!=="connecting"&&n!=="failed"))return;let u=(T=(m=(p=this.initConfig)==null?void 0:p.config)==null?void 0:m.dtlsStateTimeouts)==null?void 0:T[n];!u||u<=0||(this.publishDtlsStateTimer=window.setTimeout(()=>{var f;let g=(f=this.publishConnection)==null?void 0:f.nativeConnection.connectionState;if(g&&n&&g===n){let E=S.WebrtcErrors.ICEFailure("PUBLISH",`DTLS transport state ${n} timeout:${u}ms`,!0);this.eventBus.analytics.publish(y.disconnect(E)),this.observer.onFailure(E)}},u))},onDTLSTransportError:n=>{l.e(R,`onDTLSTransportError ${n.name} ${n.message}`,n),this.eventBus.analytics.publish(y.disconnect(n))},onIceConnectionChange:n=>c(this,null,function*(){e(0,n,!0)}),onConnectionStateChange:n=>c(this,null,function*(){var d,u,p,m,T,g,f,E;e(0,n,!1),n!=="new"&&(n==="connected"?((d=this.connectivityListener)==null||d.onICESuccess(!0),(u=this.publishConnection)==null||u.handleSelectedIceCandidatePairs()):n==="failed"?yield this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEFailure("PUBLISH",`local candidate - ${(T=(m=(p=this.publishConnection)==null?void 0:p.selectedCandidatePair)==null?void 0:m.local)==null?void 0:T.candidate}; remote candidate - ${(E=(f=(g=this.publishConnection)==null?void 0:g.selectedCandidatePair)==null?void 0:f.remote)==null?void 0:E.candidate}`)):this.publishDisconnectTimer=window.setTimeout(()=>{var v,I,$,ue,ve,pe,Mt;((v=this.publishConnection)==null?void 0:v.connectionState)!=="connected"&&this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEDisconnected("PUBLISH",`local candidate - ${(ue=($=(I=this.publishConnection)==null?void 0:I.selectedCandidatePair)==null?void 0:$.local)==null?void 0:ue.candidate}; remote candidate - ${(Mt=(pe=(ve=this.publishConnection)==null?void 0:ve.selectedCandidatePair)==null?void 0:pe.remote)==null?void 0:Mt.candidate}`))},5e3))}),onIceCandidate:n=>{var d;(d=this.connectivityListener)==null||d.onICECandidate(n,!0)},onSelectedCandidatePairChange:n=>{var d;(d=this.connectivityListener)==null||d.onSelectedICECandidatePairChange(n,!0)}},o={onApiChannelMessage:n=>{this.observer.onNotification(JSON.parse(n))},onTrackAdd:n=>{l.d(R,"[Subscribe] onTrackAdd",`${n}`),this.observer.onTrackAdd(n)},onTrackRemove:n=>{l.d(R,"[Subscribe] onTrackRemove",`${n}`),this.observer.onTrackRemove(n)},onIceConnectionChange:n=>c(this,null,function*(){var d;if(e(1,n,!0),n==="connected"){let u=this.callbacks.get(nt);this.callbacks.delete(nt),(d=this.connectivityListener)==null||d.onICESuccess(!1),u&&u.promise.resolve(!0)}}),onConnectionStateChange:n=>c(this,null,function*(){var d,u,p,m,T,g,f;if(e(1,n,!1),n==="failed")yield this.handleIceConnectionFailure(1,S.WebrtcErrors.ICEFailure("SUBSCRIBE",`local candidate - ${(p=(u=(d=this.subscribeConnection)==null?void 0:d.selectedCandidatePair)==null?void 0:u.local)==null?void 0:p.candidate}; remote candidate - ${(g=(T=(m=this.subscribeConnection)==null?void 0:m.selectedCandidatePair)==null?void 0:T.remote)==null?void 0:g.candidate}`));else if(n==="disconnected")setTimeout(()=>{var E,v,I,$,ue,ve,pe;((E=this.subscribeConnection)==null?void 0:E.connectionState)==="disconnected"&&this.handleIceConnectionFailure(1,S.WebrtcErrors.ICEDisconnected("SUBSCRIBE",`local candidate - ${($=(I=(v=this.subscribeConnection)==null?void 0:v.selectedCandidatePair)==null?void 0:I.local)==null?void 0:$.candidate}; remote candidate - ${(pe=(ve=(ue=this.subscribeConnection)==null?void 0:ue.selectedCandidatePair)==null?void 0:ve.remote)==null?void 0:pe.candidate}`))},5e3);else if(n==="connected"){(f=this.subscribeConnection)==null||f.handleSelectedIceCandidatePairs();let E=this.callbacks.get(nt);this.callbacks.delete(nt),E&&E.promise.resolve(!0)}}),onIceCandidate:n=>{var d;(d=this.connectivityListener)==null||d.onICECandidate(n,!1)},onSelectedCandidatePairChange:n=>{var d;(d=this.connectivityListener)==null||d.onSelectedICECandidatePairChange(n,!1)}};this.publishConnection||(this.publishConnection=new ni(this.signal,this.initConfig.rtcConfiguration,s)),this.subscribeConnection||(this.subscribeConnection=new di(this.signal,this.initConfig.rtcConfiguration,this.isFlagEnabled.bind(this),o))}(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(o){l.e(R,"Join negotiation failed \u274C",o);let n=o instanceof k?o:S.WebsocketMethodErrors.ServerErrors(500,"JOIN",`Websocket join error - ${o.message}`),d=parseInt(`${n.code/100}`)===5||[P.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,429].includes(n.code);if(n.code===410&&(n.isTerminal=!0),d){this.joinRetryCount=0,n.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:n,task:u,originalState:"Joined",changeState:!1})}else throw o}})}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(l.d(R,"\u23F3 join: Negotiating over PUBLISH connection"),!this.publishConnection)return l.e(R,"Publish peer connection not found, cannot negotiate"),!1;let s=yield this.publishConnection.createOffer();yield this.publishConnection.setLocalDescription(s);let o=this.isFlagEnabled("subscribeDegradation"),n=this.isFlagEnabled("simulcast"),d=this.isFlagEnabled("onDemandTracks"),u=yield this.signal.join(e,t,!i,o,n,d,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}){l.d(R,"\u23F3 join: Negotiating Non-WebRTC");let s=this.isFlagEnabled("subscribeDegradation"),o=this.isFlagEnabled("simulcast"),n=this.isFlagEnabled("onDemandTracks"),d=yield this.signal.join(e,t,!i,s,o,n);return this.setSFUNodeId(d==null?void 0:d.sfu_node_id),!!d})}negotiateOnFirstPublish(){return c(this,null,function*(){if(l.d(R,"\u23F3 Negotiating offer over PUBLISH connection"),!this.publishConnection)return l.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*(){l.d(R,"\u23F3 [role=PUBLISH] onRenegotiationNeeded START",this.trackStates);let t=this.callbacks.get(ot);if(!t){l.w(R,"no callback found for renegotiation");return}if(!this.publishConnection){l.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),l.time("renegotiation-offer-exchange");let r=yield this.signal.offer(i,this.trackStates);this.callbacks.delete(ot),l.timeEnd("renegotiation-offer-exchange"),yield this.publishConnection.setRemoteDescription(r),t.promise.resolve(!0),l.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),l.d(R,"[role=PUBLISH] onRenegotiationNeeded FAILED \u274C")}})}handleIceConnectionFailure(e,t){return c(this,null,function*(){this.retryScheduler.isTaskInProgress(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 o,n,d;l.d(R,"connect: started \u23F0");let s=new Date;try{this.analyticsTimer.start("init_response_time"),this.initConfig=yield li.fetchInitConfig({token:e,peerId:i,userAgent:this.store.getUserAgent(),initEndpoint:t,iceServers:r}),(o=this.connectivityListener)==null||o.onInitSuccess(this.initConfig.endpoint);let u=this.store.getRoom();return u&&(u.effectsKey=(n=this.initConfig.config.vb)==null?void 0:n.effectsKey,u.isEffectsEnabled=this.isFlagEnabled("effectsSDKEnabled"),u.disableNoneLayerRequest=this.isFlagEnabled("disableNoneLayerRequest"),u.isVBEnabled=this.isFlagEnabled("vb"),u.isHipaaEnabled=this.isFlagEnabled("hipaa"),u.isNoiseCancellationEnabled=this.isFlagEnabled("noiseCancellation")),this.analyticsTimer.end("init_response_time"),Ce.setWebsocketEndpoint(this.initConfig.endpoint),this.validateNotDisconnected("post init"),yield this.openSignal(e,i),this.observer.onConnected(),(d=this.connectivityListener)==null||d.onSignallingSuccess(),this.store.setSimulcastEnabled(this.isFlagEnabled("simulcast")),l.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)),l.e(R,"\u274C internal connect: failed",u),u}})}validateNotDisconnected(e){if(this.state==="Disconnected")throw l.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");l.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",La),i.searchParams.set("protocol_spec",Da),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"),l.d(R,"\u2705 internal connect: connected to ws endpoint")})}initStatsAnalytics(){var e,t;this.isFlagEnabled("publishStats")&&(this.publishStatsAnalytics=new si(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 ai(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 o,n,d,u,p,m,T,g;let e=wo(),t=typeof document!="undefined"&&document.hidden,i=this.store.getRemoteVideoTracks().filter(f=>f.degraded).length,r=(u=(d=(n=(o=this.getWebrtcInternals())==null?void 0:o.getCurrentStats())==null?void 0:n.getLocalPeerStats())==null?void 0:d.publish)==null?void 0:u.bitrate,s=(g=(T=(m=(p=this.getWebrtcInternals())==null?void 0:p.getCurrentStats())==null?void 0:m.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 Nr(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 No={published:!1,isInitialised:!1,isReconnecting:!1,isPreviewInProgress:!1,isPreviewCalled:!1,isJoinInProgress:!1,deviceManagersInitialised:!1},Or=class{constructor(){this.TAG="[HMSSdk]:";this.transportState="Disconnected";this.analyticsTimer=new Di;this.sdkState=h({},No);this.isDiagnostics=!1;this.playlistSettings={video:{bitrate:cs},audio:{bitrate:ds}};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=o=>c(this,null,function*(){var n,d;yield this.internalLeave(!0,o),!this.sdkState.isPreviewInProgress&&!this.sdkState.isJoinInProgress&&((d=(n=this.errorListener)==null?void 0:n.onError)==null||d.call(n,o)),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,l.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.handleDeviceChange=e=>{var i,r;if(e.isUserSelection)return;l.d(this.TAG,"Device Change event",e),(r=(i=this.deviceChangeListener)==null?void 0:i.onDeviceChange)==null||r.call(i,e),(()=>{var s,o,n,d;if(e.error&&e.type){let u=e.type.includes("audio")?(s=this.localPeer)==null?void 0:s.audioTrack:(o=this.localPeer)==null?void 0:o.videoTrack;(n=this.errorListener)==null||n.onError(e.error),[P.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,P.TracksErrors.DEVICE_IN_USE,P.TracksErrors.DEVICE_NOT_AVAILABLE].includes(e.error.code)&&u&&(u.setEnabled(!1),(d=this.listener)==null||d.onTrackUpdate(2,u,this.localPeer))}})()};this.handleAudioPluginError=e=>{var t;l.e(this.TAG,"Audio Plugin Error event",e),(t=this.errorListener)==null||t.onError(e)};this.handleError=e=>{var t;l.e(this.TAG,e),(t=this.errorListener)==null||t.onError(e)};this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){var r;this.deviceManager.currentSelection=this.deviceManager.getCurrentSelection(),yield this.transport.handleLocalRoleUpdate({oldRole:e,newRole:t}),yield(r=this.roleChangeManager)==null?void 0:r.handleLocalPeerRoleUpdate({oldRole:e,newRole:t}),yield this.interactivityCenter.whiteboard.handleLocalRoleUpdate()});this.unpauseRemoteVideoTracks=()=>{this.store.getRemoteVideoTracks().forEach(e=>e.handleTrackUnmute())};this.sendAudioPresenceFailed=()=>{var t;let e=S.TracksErrors.NoAudioDetected("PREVIEW");l.w(this.TAG,"Audio Presence Failure",this.transportState,e),this.isDiagnostics&&((t=this.listener)==null||t.onError(e))};this.sendJoinAnalyticsEvent=(e=!1,t)=>{this.eventBus.analytics.publish(y.join(M(h({error:t},this.analyticsTimer.getTimes()),{time:this.analyticsTimer.getTimeTaken("join_time"),is_preview_called:e,retries_join:this.transport.joinRetryCount})))};this.sendPreviewAnalyticsEvent=e=>{this.eventBus.analytics.publish(y.preview(M(h({error:e},this.analyticsTimer.getTimes()),{time:this.analyticsTimer.getTimeTaken("preview_time")})))};this.sendAnalyticsEvent=e=>{this.isDiagnostics||this.analyticsEventsService.queue(e).flush()}}setSessionPeerInfo(e,t){var r,s,o,n;let i=this.store.getRoom();if(!t||!i){l.e(this.TAG,"setSessionPeerInfo> Local peer or room is undefined");return}this.sessionPeerInfo={peer:{peer_id:t.peerId,role:(r=t.role)==null?void 0:r.name,joined_at:((s=t.joinedAt)==null?void 0:s.valueOf())||0,room_name:i.name,session_started_at:((o=i.startedAt)==null?void 0:o.valueOf())||0,user_data:t.customerUserId,user_name:t.name,template_id:i.templateId,session_id:i.sessionId,token:(n=this.store.getConfig())==null?void 0:n.authToken},agent:this.store.getUserAgent(),device_id:fi(),cluster:{websocket_url:e},timestamp:Date.now()}}initNotificationManager(){this.notificationManager||(this.notificationManager=new kr(this.store,this.eventBus,this.transport,this.listener,this.audioListener))}initStoreAndManagers(e){var t,i;if(this.listener=e,this.errorListener=e,this.deviceChangeListener=e,(t=this.store)==null||t.setErrorListener(this.errorListener),this.sdkState.isInitialised){(i=this.notificationManager)==null||i.setListener(this.listener),this.audioSinkManager.setListener(this.listener),this.interactivityCenter.setListener(this.listener),this.transport.setListener(this.listener);return}this.sdkState.isInitialised=!0,this.store=new Yt,this.store.setErrorListener(this.errorListener),this.eventBus=new mt,this.pluginUsageTracker=new or(this.eventBus),this.wakeLockManager=new sr,this.networkTestManager=new rr(this.eventBus,this.listener),this.playlistManager=new Vt(this,this.eventBus),this.deviceManager=new Zt(this.store,this.eventBus),this.audioSinkManager=new Xt(this.store,this.deviceManager,this.eventBus),this.audioOutput=new nr(this.deviceManager,this.audioSinkManager),this.audioSinkManager.setListener(this.listener),this.eventBus.autoplayError.subscribe(this.handleAutoplayError),this.localTrackManager=new Ie(this.store,this.observer,this.deviceManager,this.eventBus,this.analyticsTimer),this.analyticsEventsService=new ar(this.store),this.transport=new pi(this.observer,this.deviceManager,this.store,this.eventBus,this.analyticsEventsService,this.analyticsTimer,this.pluginUsageTracker),"onInitSuccess"in e&&this.transport.setConnectivityListener(e),this.sessionStore=new Er(this.transport),this.interactivityCenter=new ii(this.transport,this.store,this.listener),this.eventBus.analytics.subscribe(this.sendAnalyticsEvent),this.eventBus.deviceChange.subscribe(this.handleDeviceChange),this.eventBus.localVideoUnmutedNatively.subscribe(this.unpauseRemoteVideoTracks),this.eventBus.localAudioUnmutedNatively.subscribe(this.unpauseRemoteVideoTracks),this.eventBus.audioPluginFailed.subscribe(this.handleAudioPluginError),this.eventBus.error.subscribe(this.handleError)}validateJoined(e){if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION",`Not connected - ${e}`)}sendHLSAnalytics(e){this.sendAnalyticsEvent(y.hlsPlayerError(e))}refreshDevices(){return c(this,null,function*(){this.validateJoined("refreshDevices"),yield this.deviceManager.init(!0)})}getWebrtcInternals(){var e;return(e=this.transport)==null?void 0:e.getWebrtcInternals()}getDebugInfo(){var r;if(!this.transport)throw l.e(this.TAG,"Transport is not defined"),new Error("getDebugInfo can only be called after join");let e=this.transport.getWebsocketEndpoint(),t=Object.values(Bs).filter(s=>this.transport.isFlagEnabled(s)),i=(r=this.store.getConfig())==null?void 0:r.initEndpoint;return{websocketURL:e,enabledFlags:t,initEndpoint:i}}getSessionStore(){return this.sessionStore}getPlaylistManager(){return this.playlistManager}getRecordingState(){var e;return(e=this.store.getRoom())==null?void 0:e.recording}getRTMPState(){var e;return(e=this.store.getRoom())==null?void 0:e.rtmp}getHLSState(){var e;return(e=this.store.getRoom())==null?void 0:e.hls}getTranscriptionState(){var e;return(e=this.store.getRoom())==null?void 0:e.transcriptions}getTemplateAppData(){return this.store.getTemplateAppData()}getInteractivityCenter(){return this.interactivityCenter}getPeerListIterator(e){return new xi(this.transport,this.store,e)}updatePlaylistSettings(e){e.video&&Object.assign(this.playlistSettings.video,e.video),e.audio&&Object.assign(this.playlistSettings.audio,e.audio)}get localPeer(){var e;return(e=this.store)==null?void 0:e.getLocalPeer()}preview(e,t){return c(this,null,function*(){if(Ct(),Ht(),this.sdkState.isPreviewInProgress)return Promise.reject(S.GenericErrors.PreviewAlreadyInProgress("PREVIEW","Preview already called"));if(["Joined","Reconnecting"].includes(this.transportState))return this.midCallPreview(e.asRole,e.settings);this.analyticsTimer.start("preview_time"),this.setUpPreview(e,t);let i=!1,r=!1,s=setTimeout(()=>{var o,n;(!i||!r)&&((n=(o=this.listener)==null?void 0:o.onNetworkQuality)==null||n.call(o,-1))},3e3);return new Promise((o,n)=>{let d=()=>c(this,null,function*(){var m;if(this.localPeer){let T=e.asRole&&this.store.getPolicyForRole(e.asRole);this.localPeer.asRole=T||this.localPeer.role}let u=yield this.localTrackManager.getTracksToPublish(e.settings);u.forEach(T=>{var g;if(this.setLocalPeerTrack(T),T.isTrackNotPublishing()){let f=S.TracksErrors.NoDataInTrack(`${T.type} track has no data. muted: ${T.nativeTrack.muted}, readyState: ${T.nativeTrack.readyState}`);l.e(this.TAG,f),this.sendAnalyticsEvent(y.publish({devices:this.deviceManager.getDevices(),error:f})),(g=this.listener)==null||g.onError(f)}}),(m=this.localPeer)!=null&&m.audioTrack&&this.initPreviewTrackAudioLevelMonitor(),yield this.initDeviceManagers(),this.sdkState.isPreviewInProgress=!1,this.analyticsTimer.end("preview_time");let p=this.store.getRoom();p&&t.onPreview(p,u),this.sendPreviewAnalyticsEvent(),o()});this.eventBus.policyChange.subscribeOnce(d),this.eventBus.leave.subscribeOnce(this.handlePreviewError),this.eventBus.leave.subscribeOnce(u=>n(u)),this.transport.preview(e.authToken,e.initEndpoint,this.localPeer.peerId,{name:e.userName,metaData:e.metaData||""},e.autoVideoSubscribe,e.iceServers).then(u=>{var p;i=!0,clearTimeout(s),u&&e.captureNetworkQualityInPreview&&this.networkTestManager.start((p=u.config)==null?void 0:p.networkHealth).then(()=>{r=!0})}).catch(u=>{this.handlePreviewError(u),n(u)})})})}midCallPreview(e,t){return c(this,null,function*(){var s,o;if(!this.localPeer||this.transportState!=="Joined")throw S.GenericErrors.NotConnected("VALIDATION","Not connected - midCallPreview");let i=e&&this.store.getPolicyForRole(e);if(!i)throw S.GenericErrors.InvalidRole("PREVIEW",`role ${e} does not exist in policy`);this.localPeer.asRole=i;let r=yield this.localTrackManager.getTracksToPublish(t);r.forEach(n=>this.setLocalPeerTrack(n)),(s=this.localPeer)!=null&&s.audioTrack&&this.initPreviewTrackAudioLevelMonitor(),yield this.initDeviceManagers(),(o=this.listener)==null||o.onPreview(this.store.getRoom(),r)})}cancelMidCallPreview(){return c(this,null,function*(){var e,t,i;if((!this.localPeer||!this.localPeer.isInPreview())&&l.w(this.TAG,"Cannot cancel mid call preview as preview is not in progress"),(e=this.localPeer)!=null&&e.asRole&&this.localPeer.role){let r=this.localPeer.asRole,s=this.localPeer.role;delete this.localPeer.asRole,yield(t=this.roleChangeManager)==null?void 0:t.diffRolesAndPublishTracks({oldRole:r,newRole:s}),(i=this.listener)==null||i.onPeerUpdate(8,this.localPeer)}})}join(e,t){return c(this,null,function*(){var d,u,p,m,T,g,f,E,v;if(Ct(),Ht(),this.sdkState.isPreviewInProgress)throw S.GenericErrors.NotReady("JOIN","Preview is in progress, can't join");(u=(d=this.eventBus)==null?void 0:d.leave)==null||u.unsubscribe(this.handlePreviewError),this.analyticsTimer.start("join_time"),this.sdkState.isJoinInProgress=!0;let{roomId:i,userId:r,role:s}=Nr(e.authToken),o=((m=(p=this.localPeer)==null?void 0:p.asRole)==null?void 0:m.name)||((g=(T=this.localPeer)==null?void 0:T.role)==null?void 0:g.name);(f=this.networkTestManager)==null||f.stop(),this.commonSetup(e,i,t),this.removeDevicesFromConfig(e),this.store.setConfig(e),this.store.createAndSetUserAgent(this.frameworkInfo),re.resumeContext();let n=this.store.getConfig();n!=null&&n.autoManageWakeLock&&this.wakeLockManager.acquireLock(),this.localPeer?(this.localPeer.name=e.userName,this.localPeer.role=this.store.getPolicyForRole(s),this.localPeer.customerUserId=r,this.localPeer.metadata=e.metaData,delete this.localPeer.asRole):this.createAndAddLocalPeerToStore(e,s,r),this.roleChangeManager=new Qt(this.store,this.transport,this.deviceManager,this.getAndPublishTracks.bind(this),this.removeTrack.bind(this),this.listener),this.eventBus.localRoleUpdate.subscribe(this.handleLocalRoleUpdate),l.d(this.TAG,`\u23F3 Joining room ${i}`),l.time(`join-room-${i}`);try{yield this.transport.join(e.authToken,this.localPeer.peerId,{name:e.userName,metaData:e.metaData},e.initEndpoint,e.autoVideoSubscribe,e.iceServers),l.d(this.TAG,`\u2705 Joined room ${i}`),this.analyticsTimer.start("peer_list_time"),yield this.notifyJoin(),this.sdkState.isJoinInProgress=!1,yield this.publish(e.settings,o),yield this.deviceManager.autoSelectAudioOutput(),re.getAudioContext().state==="suspended"&&((E=this.listener)==null||E.onError(S.TracksErrors.AutoplayBlocked("JOIN")))}catch(I){throw this.analyticsTimer.end("join_time"),this.sdkState.isJoinInProgress=!1,(v=this.listener)==null||v.onError(I),this.sendJoinAnalyticsEvent(this.sdkState.isPreviewCalled,I),l.e(this.TAG,"Unable to join room",I),I}l.timeEnd(`join-room-${i}`)})}stringifyMetadata(e){e.metaData&&typeof e.metaData!="string"?e.metaData=JSON.stringify(e.metaData):e.metaData||(e.metaData="")}cleanup(){var e,t,i;this.cleanDeviceManagers(),this.eventBus.analytics.unsubscribe(this.sendAnalyticsEvent),this.eventBus.localVideoUnmutedNatively.unsubscribe(this.unpauseRemoteVideoTracks),this.eventBus.localAudioUnmutedNatively.unsubscribe(this.unpauseRemoteVideoTracks),this.eventBus.error.unsubscribe(this.handleError),this.analyticsTimer.cleanup(),Z.cleanup(),this.playlistManager.cleanup(),(e=this.wakeLockManager)==null||e.cleanup(),Ie.cleanup(),this.notificationManager=void 0,l.cleanup(),this.sdkState=h({},No),this.localPeer&&((t=this.localPeer.audioTrack)==null||t.cleanup(),this.localPeer.audioTrack=void 0,(i=this.localPeer.videoTrack)==null||i.cleanup(),this.localPeer.videoTrack=void 0),this.store.cleanup(),this.listener=void 0,this.roleChangeManager&&this.eventBus.localRoleUpdate.unsubscribe(this.handleLocalRoleUpdate)}leave(e){return this.internalLeave(e)}internalLeave(e=!0,t){return c(this,null,function*(){var r,s,o,n;let i=(r=this.store)==null?void 0:r.getRoom();if(i){for(;(this.sdkState.isPreviewInProgress||this.sdkState.isJoinInProgress)&&!(t!=null&&t.isTerminal);)yield Be(100);let d=i.id;this.setSessionPeerInfo(this.transport.getWebsocketEndpoint()||"",this.localPeer),(s=this.networkTestManager)==null||s.stop(),this.eventBus.leave.publish(t);let u=(o=this.localPeer)==null?void 0:o.peerId;l.d(this.TAG,`\u23F3 Leaving room ${d}, peerId=${u}`),yield(n=this.transport)==null?void 0:n.leave(e,t?"sdk request":"user request"),this.cleanup(),l.d(this.TAG,`\u2705 Left room ${d}, peerId=${u}`)}})}getAuthTokenByRoomCode(e,t){return c(this,null,function*(){let i=(t||{}).endpoint||"https://auth.100ms.live/v2/token";this.analyticsTimer.start("GET_TOKEN");let r=yield er(i,{method:"POST",body:JSON.stringify({code:e.roomCode,user_id:e.userId})},[429,500,501,502,503,504,505,506,507,508,509,510,511]),s=yield r.json();if(this.analyticsTimer.end("GET_TOKEN"),!r.ok)throw S.APIErrors.ServerErrors(s.code,"GET_TOKEN",s.message,!1);let{token:o}=s;if(!o)throw Error(s.message);return o})}getLocalPeer(){return this.store.getLocalPeer()}getPeers(){return this.store.getPeers()}getPeerMap(){return this.store.getPeerMap()}getAudioOutput(){return this.audioOutput}sendMessage(e,t){this.sendMessageInternal({message:t,type:e})}sendBroadcastMessage(e,t){return c(this,null,function*(){return yield this.sendMessageInternal({message:e,type:t})})}sendGroupMessage(e,t,i){return c(this,null,function*(){let r=this.store.getKnownRoles();if((t.filter(o=>r[o.name])||[]).length===0)throw S.GenericErrors.ValidationFailed("No valid role is present",t);return yield this.sendMessageInternal({message:e,recipientRoles:t,type:i})})}sendDirectMessage(e,t,i){return c(this,null,function*(){var o,n;if(((o=this.localPeer)==null?void 0:o.peerId)===t)throw S.GenericErrors.ValidationFailed("Cannot send message to self");let r=!!((n=this.store.getRoom())!=null&&n.large_room_optimization),s=this.store.getPeerById(t);if(!s)if(r){let d=yield this.transport.signal.getPeer({peer_id:t});if(!d)throw S.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);s=Ee(d,this.store)}else throw S.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);return yield this.sendMessageInternal({message:e,recipientPeer:s,type:i})})}submitSessionFeedback(e,t){return c(this,null,function*(){if(!this.sessionPeerInfo)throw l.e(this.TAG,"submitSessionFeedback> session is undefined"),new Error("session is undefined");let i=this.sessionPeerInfo.peer.token;if(!i)throw l.e(this.TAG,"submitSessionFeedback> token is undefined"),new Error("Internal error, token is not present");try{yield ei.sendFeedback({token:i,info:this.sessionPeerInfo,feedback:e,eventEndpoint:t}),l.i(this.TAG,"submitSessionFeedback> submitted feedback"),this.sessionPeerInfo=void 0}catch(r){throw l.e(this.TAG,"submitSessionFeedback> error occured ",r),new Error("Unable to submit feedback")}})}getPeer(e){return c(this,null,function*(){let t=yield this.transport.signal.getPeer({peer_id:e});if(t)return Ee(t,this.store)})}findPeerByName(r){return c(this,arguments,function*({query:e,limit:t=10,offset:i}){let{peers:s,offset:o,eof:n}=yield this.transport.signal.findPeerByName({query:e==null?void 0:e.toLowerCase(),limit:t,offset:i});return s.length>0?{offset:o,eof:n,peers:s.map(d=>Ee({peer_id:d.peer_id,role:d.role,groups:[],info:{name:d.name,data:"",user_id:"",type:d.type}},this.store))}:{offset:o,peers:[]}})}sendMessageInternal(s){return c(this,arguments,function*({recipientRoles:e,recipientPeer:t,type:i="chat",message:r}){if(r.replace(/\u200b/g," ").trim()==="")throw l.w(this.TAG,"sendMessage","Ignoring empty message send"),S.GenericErrors.ValidationFailed("Empty message not allowed");let o={info:{message:r,type:i}};return e!=null&&e.length&&(o.roles=e.map(n=>n.name)),t!=null&&t.peerId&&(o.peer_id=t.peerId),l.d(this.TAG,"Sending Message: ",o),yield this.transport.signal.broadcast(o)})}startScreenShare(e,t){return c(this,null,function*(){var n,d,u;let i=this.store.getPublishParams();if(!i)return;let{allowed:r}=i;if(!(r&&r.includes("screen"))){l.e(this.TAG,`Role ${(n=this.localPeer)==null?void 0:n.role} cannot share screen`);return}if((u=(d=this.localPeer)==null?void 0:d.auxiliaryTracks)!=null&&u.find(p=>p.source==="screen"))throw Error("Cannot share multiple screens");let o=yield this.getScreenshareTracks(e,t);if(!this.localPeer){l.d(this.TAG,"Screenshared when not connected"),o.forEach(p=>{p.cleanup()});return}this.transport.setOnScreenshareStop(()=>{this.stopEndedScreenshare(e)}),yield this.transport.publish(o),o.forEach(p=>{var m,T,g;p.peerId=(m=this.localPeer)==null?void 0:m.peerId,(T=this.localPeer)==null||T.auxiliaryTracks.push(p),(g=this.listener)==null||g.onTrackUpdate(0,p,this.localPeer)})})}stopEndedScreenshare(e){return c(this,null,function*(){l.d(this.TAG,"\u2705 Screenshare ended natively"),yield this.stopScreenShare(),e()})}stopScreenShare(){return c(this,null,function*(){var t;l.d(this.TAG,"\u2705 Screenshare ended from app");let e=(t=this.localPeer)==null?void 0:t.auxiliaryTracks.filter(i=>i.source==="screen");if(e)for(let i of e)yield this.removeTrack(i.trackId)})}addTrack(e,t="regular"){return c(this,null,function*(){var u,p,m,T;if(!e){l.w(this.TAG,"Please pass a valid MediaStreamTrack");return}if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot addTrack");if(this.localPeer.auxiliaryTracks.find(g=>g.trackId===e.id))return;let r=e.kind,s=new MediaStream([e]),o=new ge(s),n=r==="audio"?le:G,d=new n(o,e,t,this.eventBus);yield this.applySettings(d),yield this.setPlaylistSettings({track:e,hmsTrack:d,source:t}),yield(u=this.transport)==null?void 0:u.publish([d]),d.peerId=(p=this.localPeer)==null?void 0:p.peerId,(m=this.localPeer)==null||m.auxiliaryTracks.push(d),(T=this.listener)==null||T.onTrackUpdate(0,d,this.localPeer)})}removeTrack(e,t=!1){return c(this,null,function*(){var r;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot removeTrack");let i=this.localPeer.auxiliaryTracks.findIndex(s=>s.trackId===e);if(i>-1){let s=this.localPeer.auxiliaryTracks[i];s.isPublished?yield this.transport.unpublish([s]):yield s.cleanup(),t||this.stopPlaylist(s),this.localPeer.auxiliaryTracks.splice(i,1),(r=this.listener)==null||r.onTrackUpdate(1,s,this.localPeer)}else l.w(this.TAG,`No track found for ${e}`)})}setAnalyticsLevel(e){this.analyticsEventsService.level=e}setLogLevel(e){l.level=e}addAudioListener(e){var t;this.audioListener=e,(t=this.notificationManager)==null||t.setAudioListener(e)}addConnectionQualityListener(e){var t;(t=this.notificationManager)==null||t.setConnectionQualityListener(e)}setIsDiagnostics(e){this.isDiagnostics=e}changeRole(e,t,i=!1){return c(this,null,function*(){var r;yield(r=this.transport)==null?void 0:r.signal.requestRoleChange({requested_for:e,role:t,force:i})})}changeRoleOfPeer(e,t,i=!1){return c(this,null,function*(){var r;yield(r=this.transport)==null?void 0:r.signal.requestRoleChange({requested_for:e,role:t,force:i})})}changeRoleOfPeersWithRoles(e,t){return c(this,null,function*(){var i;e.length<=0||!t||(yield(i=this.transport)==null?void 0:i.signal.requestBulkRoleChange({roles:e.map(r=>r.name),role:t,force:!0}))})}acceptChangeRole(e){return c(this,null,function*(){var t,i;yield(i=this.transport)==null?void 0:i.signal.acceptRoleChangeRequest({requested_by:(t=e.requestedBy)==null?void 0:t.peerId,role:e.role.name,token:e.token})})}endRoom(e,t){return c(this,null,function*(){var i;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot end room");yield(i=this.transport)==null?void 0:i.signal.endRoom(e,t),yield this.leave()})}removePeer(e,t){return c(this,null,function*(){var i;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot remove peer");yield(i=this.transport)==null?void 0:i.signal.removePeer({requested_for:e,reason:t})})}startRTMPOrRecording(e){return c(this,null,function*(){var i,r;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot start streaming or recording");let t={meeting_url:e.meetingURL,record:e.record};(i=e.rtmpURLs)!=null&&i.length&&(t.rtmp_urls=e.rtmpURLs),e.resolution&&(t.resolution=e.resolution),yield(r=this.transport)==null?void 0:r.signal.startRTMPOrRecording(t)})}stopRTMPAndRecording(){return c(this,null,function*(){var e;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot stop streaming or recording");yield(e=this.transport)==null?void 0:e.signal.stopRTMPAndRecording()})}startHLSStreaming(e){return c(this,null,function*(){var i;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot start HLS streaming");let t={};e&&e.variants&&e.variants.length>0&&(t.variants=e.variants.map(r=>{let s={meeting_url:r.meetingURL};return r.metadata&&(s.metadata=r.metadata),s})),e!=null&&e.recording&&(t.hls_recording={single_file_per_layer:e.recording.singleFilePerLayer,hls_vod:e.recording.hlsVod}),yield(i=this.transport)==null?void 0:i.signal.startHLSStreaming(t)})}stopHLSStreaming(e){return c(this,null,function*(){var t,i,r;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot stop HLS streaming");if(e){let s={variants:(t=e==null?void 0:e.variants)==null?void 0:t.map(o=>{let n={meeting_url:o.meetingURL};return o.metadata&&(n.metadata=o.metadata),n})};yield(i=this.transport)==null?void 0:i.signal.stopHLSStreaming(s)}yield(r=this.transport)==null?void 0:r.signal.stopHLSStreaming()})}startTranscription(e){return c(this,null,function*(){var i;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot start transcriptions");let t={mode:e.mode};yield(i=this.transport)==null?void 0:i.signal.startTranscription(t)})}stopTranscription(e){return c(this,null,function*(){var i;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot stop transcriptions");if(!e)throw S.GenericErrors.Signalling("VALIDATION","No mode is passed to stop the transcription");let t={mode:e.mode};yield(i=this.transport)==null?void 0:i.signal.stopTranscription(t)})}sendHLSTimedMetadata(e){return c(this,null,function*(){var t;if(this.validateJoined("sendHLSTimedMetadata"),e.length>0){let i={metadata_objs:e};yield(t=this.transport)==null?void 0:t.signal.sendHLSTimedMetadata(i)}})}changeName(e){return c(this,null,function*(){var i,r;this.validateJoined("changeName");let t=this.store.getLocalPeer();t&&t.name!==e&&(yield(i=this.transport)==null?void 0:i.signal.updatePeer({name:e}),(r=this.notificationManager)==null||r.updateLocalPeer({name:e}))})}changeMetadata(e){return c(this,null,function*(){var t,i;this.validateJoined("changeMetadata"),yield(t=this.transport)==null?void 0:t.signal.updatePeer({data:e}),(i=this.notificationManager)==null||i.updateLocalPeer({metadata:e})})}setSessionMetadata(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.setSessionMetadata({key:"default",data:e})})}getSessionMetadata(){return c(this,null,function*(){var t;return(yield(t=this.transport)==null?void 0:t.signal.getSessionMetadata("default")).data})}getRoles(){return Object.values(this.store.getKnownRoles())}changeTrackState(e,t){return c(this,null,function*(){var r;if(e.type==="video"&&e.source!=="regular"){l.w(this.TAG,"Muting non-regular video tracks is currently not supported");return}if(e.enabled===t){l.w(this.TAG,`Aborting change track state, track already has enabled - ${t}`,e);return}if(!this.store.getTrackById(e.trackId))throw S.GenericErrors.ValidationFailed("No track found for change track state",e);let i=this.store.getPeerByTrackId(e.trackId);if(!i)throw S.GenericErrors.ValidationFailed("No peer found for change track state",e);yield(r=this.transport)==null?void 0:r.signal.requestTrackStateChange({requested_for:i.peerId,track_id:e.trackId,stream_id:e.stream.id,mute:!t})})}changeMultiTrackState(e){return c(this,null,function*(){var o;if(typeof e.enabled!="boolean")throw S.GenericErrors.ValidationFailed("Pass a boolean for enabled");let{enabled:t,roles:i,type:r,source:s}=e;yield(o=this.transport)==null?void 0:o.signal.requestMultiTrackStateChange({value:!t,type:r,source:s,roles:i==null?void 0:i.map(n=>n==null?void 0:n.name)})})}raiseLocalPeerHand(){return c(this,null,function*(){var e;this.validateJoined("raiseLocalPeerHand"),yield(e=this.transport)==null?void 0:e.signal.joinGroup(Re)})}lowerLocalPeerHand(){return c(this,null,function*(){var e;this.validateJoined("lowerLocalPeerHand"),yield(e=this.transport)==null?void 0:e.signal.leaveGroup(Re)})}raiseRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.addToGroup(e,Re)})}lowerRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.removeFromGroup(e,Re)})}setFrameworkInfo(e){this.frameworkInfo=h(h({},this.frameworkInfo),e)}attachVideo(e,t){return c(this,null,function*(){let i=this.store.getConfig();i!=null&&i.autoManageVideo?e.attach(t):yield e.addSink(t)})}detachVideo(e,t){return c(this,null,function*(){let i=this.store.getConfig();i!=null&&i.autoManageVideo?e.detach(t):yield e.removeSink(t)})}publish(e,t){return c(this,null,function*(){var i,r,s;if([this.store.getPublishParams(),!this.sdkState.published,!$e].every(o=>!!o)){let o=t&&t!==((r=(i=this.localPeer)==null?void 0:i.role)==null?void 0:r.name)?()=>{var n;return(n=this.roleChangeManager)==null?void 0:n.diffRolesAndPublishTracks({oldRole:this.store.getPolicyForRole(t),newRole:this.localPeer.role})}:()=>this.getAndPublishTracks(e);yield(s=o==null?void 0:o())==null?void 0:s.catch(n=>{var d;l.e(this.TAG,"Error in publish",n),(d=this.listener)==null||d.onError(n)})}})}getAndPublishTracks(e){return c(this,null,function*(){var i,r;let t=yield this.localTrackManager.getTracksToPublish(e);yield this.setAndPublishTracks(t),(r=(i=this.localPeer)==null?void 0:i.audioTrack)==null||r.initAudioLevelMonitor(),this.sdkState.published=!0})}setAndPublishTracks(e){return c(this,null,function*(){var t,i;for(let r of e){if(yield this.transport.publish([r]),r.isTrackNotPublishing()){let s=S.TracksErrors.NoDataInTrack(`${r.type} track has no data. muted: ${r.nativeTrack.muted}, readyState: ${r.nativeTrack.readyState}`);l.e(this.TAG,s),this.sendAnalyticsEvent(y.publish({devices:this.deviceManager.getDevices(),error:s})),(t=this.listener)==null||t.onError(s)}this.setLocalPeerTrack(r),(i=this.listener)==null||i.onTrackUpdate(0,r,this.localPeer)}yield this.initDeviceManagers()})}setLocalPeerTrack(e){var t;switch(e.peerId=(t=this.localPeer)==null?void 0:t.peerId,e.type){case"audio":this.localPeer.audioTrack=e;break;case"video":this.localPeer.videoTrack=e;break}}initDeviceManagers(){return c(this,null,function*(){var e,t,i,r,s;this.sdkState.deviceManagersInitialised||(this.sdkState.deviceManagersInitialised=!0,yield this.deviceManager.init(),(yield this.deviceManager.updateOutputDevice((t=(e=this.store.getConfig())==null?void 0:e.settings)==null?void 0:t.audioOutputDeviceId))||(yield this.deviceManager.updateOutputDevice((r=(i=Z.getSelection())==null?void 0:i.audioOutput)==null?void 0:r.deviceId)),this.audioSinkManager.init((s=this.store.getConfig())==null?void 0:s.audioSinkElementId))})}cleanDeviceManagers(){this.eventBus.deviceChange.unsubscribe(this.handleDeviceChange),this.eventBus.audioPluginFailed.unsubscribe(this.handleAudioPluginError),this.eventBus.autoplayError.unsubscribe(this.handleAutoplayError),this.deviceManager.cleanup(),this.audioSinkManager.cleanup()}initPreviewTrackAudioLevelMonitor(){var t;let e=(t=this.localPeer)==null?void 0:t.audioTrack;e==null||e.initAudioLevelMonitor(),this.eventBus.trackAudioLevelUpdate.subscribe(i=>{var s;let r=i&&i.track.trackId===(e==null?void 0:e.trackId)?[{audioLevel:i.audioLevel,peer:this.localPeer,track:e}]:[];this.store.updateSpeakers(r),(s=this.audioListener)==null||s.onAudioLevelUpdate(r)}),this.eventBus.localAudioSilence.subscribe(this.sendAudioPresenceFailed)}notifyJoin(){var i;let e=this.store.getLocalPeer(),t=this.store.getRoom();if(!t){l.w(this.TAG,"notify join - room not present");return}if(t.joinedAt=new Date,e&&(e.joinedAt=t.joinedAt),e!=null&&e.role){this.analyticsTimer.end("join_time"),(i=this.listener)==null||i.onJoin(t);return}return new Promise((r,s)=>{this.eventBus.policyChange.subscribeOnce(()=>{var o;this.analyticsTimer.end("join_time"),(o=this.listener)==null||o.onJoin(t),r()}),this.eventBus.leave.subscribeOnce(o=>{s(o)})})}setUpPreview(e,t){this.sdkState.isPreviewCalled=!0,this.sdkState.isPreviewInProgress=!0;let{roomId:i,userId:r,role:s}=Nr(e.authToken);this.commonSetup(e,i,t),this.store.setConfig(e),this.store.createAndSetUserAgent(this.frameworkInfo),this.createAndAddLocalPeerToStore(e,s,r,e.asRole)}setPlaylistSettings(r){return c(this,arguments,function*({track:e,hmsTrack:t,source:i}){var s,o;if(i==="videoplaylist"){let n={};if(e.kind==="audio")n.maxBitrate=((s=this.playlistSettings.audio)==null?void 0:s.bitrate)||ds;else{n.maxBitrate=((o=this.playlistSettings.video)==null?void 0:o.bitrate)||cs;let{width:d,height:u}=e.getSettings();n.width=d,n.height=u}yield t.setSettings(n)}else i==="audioplaylist"&&(yield t.setSettings({maxBitrate:64}))})}createAndAddLocalPeerToStore(e,t,i,r){let s=this.store.getPolicyForRole(t),o=r?this.store.getPolicyForRole(r):void 0,n=new je({name:e.userName||"",customerUserId:i,metadata:e.metaData||"",role:s,asRole:o||s,type:"regular"});this.store.addPeer(n)}commonSetup(e,t,i){this.stringifyMetadata(e),e.initEndpoint||(e.initEndpoint="https://prod-init.100ms.live"),this.initStoreAndManagers(i),this.store.getRoom()||this.store.setRoom(new ze(t))}removeDevicesFromConfig(e){this.store.getConfig()&&e.settings&&(delete e.settings.audioOutputDeviceId,delete e.settings.videoDeviceId,delete e.settings.audioInputDeviceId)}getScreenshareTracks(e,t){return c(this,null,function*(){let i=this.transport.isFlagEnabled("scaleScreenshareBasedOnPixels"),[r,s]=yield this.localTrackManager.getLocalScreen(t,i),o=()=>{this.stopEndedScreenshare(e)},n=[];if(t!=null&&t.audioOnly){if(r.nativeTrack.stop(),!s)throw S.TracksErrors.NothingToReturn("TRACK","Select share audio when sharing screen","No audio found");n.push(s),s.nativeTrack.addEventListener("ended",o)}else n.push(r),r.nativeTrack.addEventListener("ended",o),s&&n.push(s);return n})}stopPlaylist(e){e.source==="audioplaylist"?this.playlistManager.stop("audio"):e.source==="videoplaylist"&&this.playlistManager.stop("video")}applySettings(e){return c(this,null,function*(){pa(this.store);let t=this.store.getPublishParams();if(t){if(e instanceof G){let i=e.source==="regular"?"video":e.source==="screen"?"screen":"";if(!i||!t.allowed.includes(i))return;let r=t[i];if(!r)return;let s=new j().codec(r.codec).maxBitrate(r.bitRate).maxFramerate(r.frameRate).setWidth(r.width).setHeight(r.height).build();yield e.setSettings(s)}else if(e instanceof le){if(!t.allowed.includes("audio"))return;let i=new K().codec(t.audio.codec).maxBitrate(t.audio.bitRate).build();yield e.setSettings(i)}}})}};var Xe=class a{constructor(e,t,i){this.getStats=()=>(this.stats||(this.stats=new vt(this.store,this.sdk)),this.stats);this.getDiagnosticsSDK=()=>(this.diagnostics||(this.diagnostics=this.actions.initDiagnostics()),this.diagnostics);e?this.store=e:this.store=a.createNewHMSStore(ir("HMSStore"),kt),i?this.notifications=i:this.notifications=new qi(this.store),t?this.actions=t:(this.sdk=new Or,this.actions=new tr(this.store,this.sdk,this.notifications)),this.actions.setFrameworkInfo({type:"js",sdkVersion:qr().version}),this.initialTriggerOnSubscribe=!1,U&&(window.__hms=this)}triggerOnSubscribe(){this.initialTriggerOnSubscribe||(a.makeStoreTriggerOnSubscribe(this.store),this.initialTriggerOnSubscribe=!0)}getStore(){return this.store}getHMSActions(){return this.actions}getActions(){return this.actions}getNotifications(){return{onNotification:this.notifications.onNotification}}static createNewHMSStore(e,t){let i=(0,Uo.default)(()=>t()),r=i.setState;i.setState=n=>{let d=typeof n=="function"?(0,Oo.produce)(n):n;r(d)};let s=i.getState;i.getState=n=>n?n(s()):s(),a.compareWithShallowCheckInSubscribe(i);let o=a.setUpDevtools(i,e);return M(h({},i),{namedSetState:o})}static makeStoreTriggerOnSubscribe(e){let t=e.subscribe;e.subscribe=(i,r,s)=>(i(e.getState(r),void 0),t(i,r,s))}static compareWithShallowCheckInSubscribe(e){let t=e.subscribe;e.subscribe=(i,r,s)=>(r||(r=o=>o),s=s||xo.default,t(i,r,s))}static setUpDevtools(e,t){let i;try{i=window.__REDUX_DEVTOOLS_EXTENSION__||window.top.__REDUX_DEVTOOLS_EXTENSION__}catch(o){}if(!i)return o=>{e.setState(o)};let r=i.connect(a.devtoolsOptions(t));r.prefix=t?`${t} > `:"";let s=e.setState;return e.setState=o=>{s(o),r.send(`${r.prefix}setState`,e.getState())},r.subscribe(a.devtoolsSubscribe(r,e,s)),r.send("setUpStore",e.getState()),(o,n)=>{s(o);let d=n||`${r.prefix}action`;r.send(d,e.getState())}}static devtoolsOptions(e){return{name:e,actionsBlacklist:["audioLevel","playlistProgress","connectionQuality"]}}static devtoolsSubscribe(e,t,i){return r=>{var s,o,n,d;if(r.type==="DISPATCH"&&r.state)["JUMP_TO_ACTION","JUMP_TO_STATE"].includes(r.payload.type)?i(JSON.parse(r.state)):t.setState(JSON.parse(r.state));else if(r.type==="DISPATCH"&&((s=r.payload)==null?void 0:s.type)==="COMMIT")e.init(t.getState());else if(r.type==="DISPATCH"&&((o=r.payload)==null?void 0:o.type)==="IMPORT_STATE"){let u=(n=r.payload.nextLiftedState)==null?void 0:n.actionsById;(((d=r.payload.nextLiftedState)==null?void 0:d.computedStates)||[]).forEach(({state:m},T)=>{let g=u[T]||`${e.prefix}setState`;T===0?e.init(m):(i(m),e.send(g,t.getState()))})}}}};var Vo=(a,e,t)=>{let i;t.getState(te)==="Connected"&&(i=Bo(a,e,t)),t.subscribe(r=>{["Connected","Reconnecting"].includes(r)?i||(i=Bo(a,e,t)):["Disconnected","Failed"].includes(r)&&i&&(kd(e,r),i(),i=void 0)},te)},Bo=(a,e,t)=>{var s,o;let i=Md(t,e);(s=a.getWebrtcInternals())==null||s.start();let r=(o=a.getWebrtcInternals())==null?void 0:o.onStatsChange(n=>yd(e,n,t,a));return()=>{i(),r&&r()}},Md=(a,e)=>{let t,i,r;return a.getState(Pe)?e.namedSetState(s=>{s.localPeer.id=a.getState(Pe)},"localpeer-id"):t=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.id=s},"localpeer-id")},Pe),a.getState(z)?e.namedSetState(s=>{s.localPeer.videoTrack=a.getState(z)},"localpeer-videotrack-id"):i=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.videoTrack=s},"localpeer-videotrack-id")},z),a.getState(oe)?e.namedSetState(s=>{s.localPeer.audioTrack=a.getState(oe)},"localpeer-audiotrack-id"):r=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.audioTrack=s},"localpeer-audiotrack-id")},oe),()=>{t==null||t(),i==null||i(),r==null||r()}},yd=(a,e,t,i)=>{let r=t.getState(_);a.namedSetState(s=>{let o=t.getState(Pe),n={},d=Object.keys(r).filter(p=>r[p].peerId!==o);for(let p of d){let m=e.getRemoteTrackStats(p);m&&(n[p]=m)}Ns(s.remoteTrackStats,n);let u={[o]:e.getLocalPeerStats()};Ns(s.peerStats,u),So(s.localTrackStats,e.getLocalTrackStats(),i.store.getLocalPeerTracks())},"webrtc-stats")},kd=(a,e="resetState")=>{a.namedSetState(t=>{Object.assign(t,Et())},e)};var vt=class{constructor(e,t){this.hmsStore=e;this.sdk=t;this.store=Xe.createNewHMSStore(ir("HMSStatsStore"),Et),this.getState=this.store.getState,this.subscribe=this.store.subscribe,this.getPublishPeerConnection=()=>new Promise(i=>{var r,s;this.hmsStore.getState(te)==="Connected"?i((s=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:s.getPublishPeerConnection()):this.hmsStore.subscribe(o=>{var n,d;o==="Connected"&&i((d=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:d.getPublishPeerConnection())},te)}),this.getSubscribePeerConnection=()=>new Promise(i=>{var r,s;this.hmsStore.getState(te)==="Connected"?i((s=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:s.getSubscribePeerConnection()):this.hmsStore.subscribe(o=>{var n,d;o==="Connected"&&i((d=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:d.getSubscribePeerConnection())},te)}),this.sdk&&Vo(this.sdk,this.store,this.hmsStore)}};var q=require("reselect");var Ed=a=>a.localPeer.id,Pd=a=>a.localPeer.audioTrack,bd=a=>a.localPeer.videoTrack,Ad=(a,e)=>e,Fo=(a,e)=>e,Id=a=>a.remoteTrackStats,Go=a=>a.peerStats,Ws=a=>a.localTrackStats,De=(0,q.createSelector)([Go,Ed],(a,e)=>a[e]),Rd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.packetsLost}),Hd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.jitter}),Cd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.bitrate}),Ld=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.bitrate}),Dd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.availableOutgoingBitrate}),wd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.availableIncomingBitrate}),_d=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.bytesSent}),Nd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.bytesReceived}),Od=(0,q.createSelector)([Go,Ad],(a,e)=>e?a[e]:void 0),xd=(0,q.createSelector)([Id,Fo],(a,e)=>e?a[e]:void 0),$s=(0,q.createSelector)([Ws,Fo],(a,e)=>e?a[e]:void 0),Ud=H(Od),Bd=H(xd),Vd=(0,q.createSelector)([Ws,Pd],(a,e)=>{var t;return e?(t=a[e])==null?void 0:t[0]:void 0}),Fd=H((0,q.createSelector)($s,a=>a==null?void 0:a[0])),Gd=(0,q.createSelector)([Ws,bd],(a,e)=>{var t;return e?(t=a[e])==null?void 0:t[0]:void 0}),Wd=H((0,q.createSelector)($s,a=>a)),$d=a=>H((0,q.createSelector)($s,e=>{let t=Object.keys(Ne).find(i=>Ne[i]===a);return a&&(e==null?void 0:e.find(i=>i.rid===t))||(e==null?void 0:e[0])})),Wo={localPeerStats:De,packetsLost:Rd,jitter:Hd,publishBitrate:Cd,subscribeBitrate:Ld,availablePublishBitrate:Dd,availableSubscribeBitrate:wd,totalBytesSent:_d,totalBytesReceived:Nd,peerStatsByID:Ud,trackStatsByID:Bd,localAudioTrackStatsByID:Fd,localVideoTrackStatsByID:Wd,localVideoTrackStatsByLayer:$d,localAudioTrackStats:Vd,localVideoTrackStats:Gd};
|
|
91
|
+
}`}};var Bt=class extends ct{constructor(t){super(M(h({},t),{isLocal:!1}));this.isLocal=!1;this.auxiliaryTracks=[];this.fromRoomState=!1;this.fromRoomState=!!t.fromRoomState}};var Ee=(a,e)=>new Bt({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 xi=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(h({},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=Ee(i,this.store);t.push(r)}),t}updateState(e){this.isEnd=e.eof,this.total=e.total,e.iterator&&(this.iterator=e.iterator)}};var lt=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*(){this.audioContext.state==="suspended"&&(yield this.audioContext.resume(),l.d(this.TAG,"AudioContext is resumed"))})}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=>{l.d(this.TAG,"AudioContext close error",e.message)})}};var Va=require("eventemitter2"),Ve=class extends Va.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 Ui=class extends Ve{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}`;l.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){l.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 lt(t),t}};var Bi=class extends Ve{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}`;l.e(this.TAG,s),this.stop(),r(s)},this.videoElement.oncanplaythrough=()=>c(this,null,function*(){var s,o,n;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 d=this.canvas.captureStream();if(!d){l.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();d.addTrack(u),d.getTracks().forEach(p=>{this.tracks.push(p)}),i(this.tracks)}else this.seeked?(this.seeked=!1,(n=this.canvasContext)==null||n.drawImage(this.videoElement,0,0,(s=this.canvas)==null?void 0:s.width,(o=this.canvas)==null?void 0:o.height)):(yield this.videoElement.play(),i(this.tracks))}catch(d){l.e(this.TAG,"Error playing video",t,d.message),r(d)}}),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 lt(t),t}createCanvas(){this.canvas||(this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"))}};var Vi={audio:{list:[],currentIndex:-1,isAutoplayOn:!0},video:{list:[],currentIndex:-1,isAutoplayOn:!0}},Vt=class extends Ve{constructor(t,i){super();this.sdk=t;this.eventBus=i;this.state={audio:h({},Vi.audio),video:h({},Vi.video)};this.TAG="[PlaylistManager]";this.handlePausePlaylist=r=>c(this,[r],function*({enabled:t,track:i}){var o;if(t)return;let s;i.source==="audioplaylist"&&(s="audio"),i.source==="videoplaylist"&&(s="video"),s&&((o=this.getElement(s))==null||o.pause())});this.addTrack=(t,i)=>c(this,null,function*(){yield this.sdk.addTrack(t,i),l.d(this.TAG,"Playlist track added",vi(t))});this.removeTrack=t=>c(this,null,function*(){yield this.sdk.removeTrack(t,!0),l.d(this.TAG,"Playlist track removed",t)});this.audioManager=new Ui,this.videoManager=new Bi,this.addListeners()}getList(t="audio"){return this.state[t].list}setList(t){if(!t||t.length===0){l.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],o=r.findIndex(n=>t===n.id);return o>-1?(s===o&&this.isPlaying(i)&&(yield this.stop(i)),r.splice(o,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 o=Math.max(s.currentTime+t,0);s.currentTime=Math.min(o,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 n;let{list:i,currentIndex:r}=this.state[t],s=(n=i[r])==null?void 0:n.url,o=this.getElement(t);return!s||!o?0:Math.floor(100*(o.currentTime/o.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,o){return c(this,arguments,function*(t,{id:i,type:r="audio"}){let d=this.state[r].list.findIndex(p=>p.id===i);if(!i||d===-1){l.w(this.TAG,"Pass a valid id");return}let u=this.state[r].list[d].url;t?yield this.play(u,r):yield this.pause(u,r),this.state[r].currentIndex=d,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:h({},Vi.audio),video:h({},Vi.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){l.e(this.TAG,"Error in onProgress callback")}}),this.audioManager.on("progress",()=>{try{t({type:"audio",progress:this.getCurrentProgress("audio")})}catch(i){l.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,o=s.getElement();if(this.isItemCurrentlyPlaying(t,i)){l.w(this.TAG,`The ${i} is currently playing`);return}if(o!=null&&o.src.includes(t))yield o.play();else{o==null||o.pause();let n=yield s.play(t);for(let d of n)yield this.addTrack(d,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(),l.d(this.TAG,"paused url",t)):l.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 B=a=>a.room,Fa=a=>a.errors,Tn=(0,A.createSelector)(Fa,a=>a.length===0?null:a.at(-1)),fn=(0,A.createSelector)(B,a=>a.id),J=a=>a.peers,Ft=a=>a.messages.byID,ms=a=>a.messages.allIDs,_=a=>a.tracks,Ss=a=>a.settings,Fi=a=>a.appData,vn=a=>a.devices,Ga=a=>a.speakers,Mn=a=>a.connectionQualities,He=(0,A.createSelector)([B],a=>a&&a.isConnected),yn=(0,A.createSelector)([He,B],(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)),kn=a=>a.hideLocalPeer,Te=(0,A.createSelector)([B,J,kn],(a,e,t)=>t?a.peers.filter(i=>a.localPeer!==i).map(i=>e[i]):a.peers.map(i=>e[i])),En=(0,A.createSelector)(_,a=>Object.values(a)),ee=(0,A.createSelector)(B,J,(a,e)=>e[a.localPeer]),Pe=(0,A.createSelector)(B,a=>a.localPeer),Pn=(0,A.createSelector)(ee,a=>a==null?void 0:a.name),bn=(0,A.createSelector)(ee,a=>a==null?void 0:a.roleName),ae=(0,A.createSelector)(ee,a=>a==null?void 0:a.audioTrack),z=(0,A.createSelector)(ee,a=>a==null?void 0:a.videoTrack),An=(0,A.createSelector)(ee,a=>a==null?void 0:a.auxiliaryTracks),gs=(0,A.createSelector)([ae,z,An],(a,e,t)=>{let i=t?[...t]:[];return a&&i.unshift(a),e&&i.unshift(e),i}),In=(0,A.createSelector)(Te,a=>a.filter(e=>!e.isLocal)),Rn=(0,A.createSelector)(J,Ga,(a,e)=>{let t=Object.entries(e).sort((i,r)=>{var n,d;let s=((n=i[1])==null?void 0:n.audioLevel)||0;return(((d=r[1])==null?void 0:d.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}),Hn=a=>{let e=ee(a);return Ze(a,e==null?void 0:e.audioTrack)},Gi=a=>{let e=ee(a);return Ze(a,e==null?void 0:e.videoTrack)},Ts=a=>{let e=ee(a);return Zs(a,e==null?void 0:e.videoTrack)},Wi=(0,A.createSelector)(ee,_,(a,e)=>{let{video:t,audio:i}=We(e,a);return!!(t||i)}),Wa=(0,A.createSelector)(J,_,(a,e)=>{let t;for(let i in a){let r=a[i],{video:s,audio:o}=We(e,r);if(s)return r;o&&!t&&(t=r)}return t}),Cn=(0,A.createSelector)(Wa,a=>!!a),Ln=(0,A.createSelector)(J,_,(a,e)=>{for(let t in a){let i=a[t],{audio:r,video:s}=We(e,i);if(!s&&r)return i}}),Dn=(0,A.createSelector)(J,_,(a,e)=>{let t=[],i=[];for(let r in a){let s=a[r],{video:o,audio:n}=We(e,s);o?t.push(s):n&&i.push(s)}return t.concat(i)}),wn=(0,A.createSelector)(J,_,(a,e)=>{for(let t in e){let i=e[t];if(At(i)&&bt(i)&&i.peerId)return a[i.peerId]}}),_n=(0,A.createSelector)(J,_,(a,e)=>{for(let t in e){let i=e[t];if(gi(i)&&i.peerId)return a[i.peerId]}}),Nn=(0,A.createSelector)(En,a=>a.filter(Xs)),On=(0,A.createSelector)(ms,a=>a.length),xn=(0,A.createSelector)(Ft,a=>Object.values(a).filter(e=>!e.read).length),ut=(0,A.createSelector)(ms,Ft,(a,e)=>{let t=[];return a.forEach(i=>{t.push(e[i])}),t}),$a=(0,A.createSelector)(ut,a=>a.filter(e=>{var t;return!e.recipientPeer&&!(e.recipientRoles&&((t=e.recipientRoles)==null?void 0:t.length)>0)})),Un=(0,A.createSelector)($a,a=>a.filter(e=>!e.read).length),te=(0,A.createSelector)([B],a=>a&&a.roomState),fs=(0,A.createSelector)(te,a=>a==="Preview"),Bn=(0,A.createSelector)(B,a=>a.roomState!=="Disconnected"),Vn=(0,A.createSelector)(B,a=>!a.transcriptions||a.transcriptions.length<=0?!1:a.transcriptions.some(e=>e.mode==="caption"&&e.state==="started")),fe=a=>a.roles,Fn=(0,A.createSelector)([fe],a=>Object.keys(a)),Je=(0,A.createSelector)([ee,fe],(a,e)=>a!=null&&a.roleName?e[a.roleName]:null),Ka=a=>{var e;return(e=a.preview)==null?void 0:e.asRole},vs=(0,A.createSelector)([Ka,fe],(a,e)=>a?e[a]:null),Gn=(0,A.createSelector)([Je],a=>{var e;return(e=a==null?void 0:a.subscribeParams)!=null&&e.subscribeToRoles?a.subscribeParams.subscribeToRoles.length>0:!1}),Ms=(0,A.createSelector)(Je,a=>a==null?void 0:a.permissions),Wn=(0,A.createSelector)(B,a=>a.recording),$n=(0,A.createSelector)(B,a=>a.rtmp),Kn=(0,A.createSelector)(B,a=>a.hls),qn=(0,A.createSelector)(B,a=>a.transcriptions),jn=(0,A.createSelector)(B,a=>a.sessionId),Jn=(0,A.createSelector)(B,a=>a.startedAt),Qn=(0,A.createSelector)(B,a=>!!a.isLargeRoom),zn=(0,A.createSelector)(B,a=>!!a.isEffectsEnabled),Yn=(0,A.createSelector)(B,a=>!!a.isVBEnabled),Xn=(0,A.createSelector)(B,a=>a.effectsKey),Zn=a=>a.templateAppData,ec=a=>a.sessionMetadata,ys=a=>a.polls,tc=a=>Object.values(a.polls),ic=(0,A.createSelector)(Te,a=>a.filter(e=>e.isHandRaised)),qa=a=>a.whiteboards,rc=(0,A.createSelector)(qa,a=>Object.values(a)[0]);var ks=require("reselect");var ja=(a="audio")=>e=>e.playlist[a].list,Es=(a="audio")=>e=>e.playlist[a].selection,Ja=(a="audio")=>e=>e.playlist[a].progress,Qa=(a="audio")=>e=>e.playlist[a].currentTime,za=(a="audio")=>e=>e.playlist[a].playbackRate,Ya=(a="audio")=>e=>e.playlist[a].volume,Xa=(a="audio")=>(0,ks.createSelector)(ja(a),e=>Object.values(e)),Za=(a="audio")=>(0,ks.createSelector)(ja(a),Es(a),(e,t)=>{if(t.id)return e[t.id]}),Ps={selection:Es("audio"),progress:Ja("audio"),currentTime:Qa("audio"),playbackRate:za("audio"),volume:Ya("audio"),list:Xa("audio"),selectedItem:Za("audio")},bs={selection:Es("video"),progress:Ja("video"),currentTime:Qa("video"),playbackRate:za("video"),volume:Ya("video"),list:Xa("video"),selectedItem:Za("video")};var D=require("reselect");function H(a){return e=>t=>a(t,e)}var Gt="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(Gt,...t);break}case 1:{console.debug(Gt,...t);break}case 2:{console.info(Gt,...t);break}case 3:{console.warn(Gt,...t);break}case 6:{console.error(Gt,...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 As=(a,e)=>e,Wt=(a,e)=>e,eo=(a,e)=>e,sc=(a,e)=>e,ac=(a,e)=>e,Y=(0,D.createSelector)([J,As],(a,e)=>e?a[e]:null),Is=(0,D.createSelector)([_,Wt],(a,e)=>e?a[e]:null),oc=(0,D.createSelector)([_,Wt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="video"?t:null}),nc=(0,D.createSelector)([_,Wt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="audio"?t:null}),cc=(0,D.createSelector)([_,Wt],(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}),dc=(0,D.createSelector)([_,Wt],(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}),lc=(0,D.createSelector)([ys,ac],(a,e)=>e?a[e]:null),X=H(Y),uc=H((0,D.createSelector)([Fi,sc],(a,e)=>{if(a)return e?a[e]:a}));function pc(a){return e=>{if(e.sessionStore)return a?e.sessionStore[a]:e.sessionStore}}var hc=(...a)=>(0,D.createSelector)([Fi],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}}),mc=H((0,D.createSelector)(Y,a=>a==null?void 0:a.name)),Sc=H((0,D.createSelector)(Y,a=>a==null?void 0:a.type)),$t=H(Is),Rs=H(oc),gc=H(nc),Tc=H(cc),fc=H(dc),to=H((a,e)=>{let t=Y(a,e);if(t&&t.videoTrack&&t.videoTrack!=="")return a.tracks[t.videoTrack]}),io=H((a,e)=>{let t=Y(a,e);if(t&&t.audioTrack&&t.audioTrack!=="")return a.tracks[t.audioTrack]}),vc=to,Mc=H((a,e)=>{let t=Y(a,e);return(t==null?void 0:t.auxiliaryTracks.map(i=>a.tracks[i]))||[]}),ro=(a,e)=>e?a.speakers[e]:null,yc=H((0,D.createSelector)(ro,a=>(a==null?void 0:a.audioLevel)||0)),kc=(a,e)=>{let t=io(e)(a);return ro(a,t==null?void 0:t.id)},Ec=H((0,D.createSelector)(kc,a=>(a==null?void 0:a.audioLevel)||0)),Pc=H((a,e)=>{if(e)return a.connectionQualities[e]}),bc=H((a,e)=>{let t=Y(a,e);if(t){let i=t==null?void 0:t.auxiliaryTracks.find(r=>Pt(a.tracks[r]));return i?a.tracks[i]:void 0}}),Ac=H((0,D.createSelector)(_,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return At(r)&&bt(r)});return t?a[t]:void 0})),Ic=H((0,D.createSelector)(_,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return At(r)&&Pt(r)});return t?a[t]:void 0})),Rc=H((0,D.createSelector)(_,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return gi(r)&&Pt(r)});return t?a[t]:void 0})),Hs=H((0,D.createSelector)(_,Y,(a,e)=>We(a,e))),Hc=a=>(0,D.createSelector)(Hs(a),e=>e.video),Cs=a=>(0,D.createSelector)(Hs(a),e=>e.audio),Cc=H((a,e)=>{let t=Y(a,e);return Ze(a,t==null?void 0:t.audioTrack)}),Lc=H((a,e)=>{let t=Y(a,e);return Ze(a,t==null?void 0:t.videoTrack)}),Ls=H((a,e)=>{if(e&&a.tracks[e])return a.tracks[e].volume===0}),Dc=H((a,e)=>{let t=Y(a,e);return Ls(t==null?void 0:t.audioTrack)(a)}),wc=H((a,e)=>{let t=Cs(e)(a);return Ls(t==null?void 0:t.id)(a)}),Ds=H((a,e)=>{let t=Is(a,e);if(t){if(t.type!=="audio"){b.w("Please pass audio track here");return}return t.volume}}),_c=H((a,e)=>{let t=Y(a,e);return Ds(t==null?void 0:t.audioTrack)(a)}),Nc=H((a,e)=>{let t=Cs(e)(a);return Ds(t==null?void 0:t.id)(a)}),Oc=H((a,e)=>{let t=Is(a,e);if(t){if(t.type!=="video"){b.w("Please pass video track here");return}return t.layer}}),so=(0,D.createSelector)([ut,Pe,As],(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)})}),ao=(0,D.createSelector)([ut,eo],(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})}),oo=(0,D.createSelector)(ut,a=>a.filter(e=>{var t;return!e.recipientPeer&&!((t=e.recipientRoles)!=null&&t.length)})),xc=(0,D.createSelector)([ao,eo],a=>a?a.filter(e=>!e.read).length:0),Uc=(0,D.createSelector)([so,As],a=>a?a.filter(e=>!e.read).length:0),Bc=(0,D.createSelector)(oo,a=>a.filter(e=>!e.read).length),Vc=H(so),Fc=H(ao),Gc=H(xc),Wc=H(Uc),$c=a=>(0,D.createSelector)([Te],e=>e.filter(t=>t.roleName===a)),Kc=a=>(0,D.createSelector)([Te],e=>e.filter(t=>t.roleName?a.includes(t.roleName):!1)),qc=a=>(0,D.createSelector)(X(a),e=>{try{return e!=null&&e.metadata&&e.metadata!==""?JSON.parse(e.metadata):{}}catch(t){return console.error("cannot parse peer metadata",t),{}}}),jc=a=>(0,D.createSelector)(X(a),e=>!!(e!=null&&e.isHandRaised)),Jc=a=>(0,D.createSelector)(X(a),e=>e==null?void 0:e.name),ws=H(lc),Qc=a=>(0,D.createSelector)(Ft,e=>e[a]),zc=a=>(0,D.createSelector)(Je,e=>e!=null&&e.permissions.transcriptions?e.permissions.transcriptions[a].length>0:!1);var Kt=require("reselect");var Yc=(0,Kt.createSelector)([J,_],(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}})),Xc=a=>a.roleChangeRequests[0]||null,Zc=(0,Kt.createSelector)([Xc,J,fe],(a,e,t)=>a?{requestedBy:a.requestedBy?e[a.requestedBy]:void 0,role:t[a.roleName],token:a.token}:null),ed=(0,Kt.createSelector)([Je],a=>It(a)),td=(0,Kt.createSelector)([vs],a=>It(a));var be=require("reselect");var no=a=>(0,be.createSelector)([fe],e=>e[a]),id=a=>(0,be.createSelector)(no(a),e=>It(e)),rd=(0,be.createSelector)([z,_],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),sd=(0,be.createSelector)([ae,_],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),ad=a=>(0,be.createSelector)([rd],e=>e.includes(a)),od=a=>(0,be.createSelector)([sd],e=>e.includes(a)),nd=a=>(0,be.createSelector)(Te,e=>e.find(a)),cd=a=>(0,be.createSelector)(Te,e=>e.filter(a)),dd=a=>(0,be.createSelector)(B,e=>e.joinedAt&&Date.now()-e.joinedAt.getTime()<=a);var Oo=require("immer"),xo=Ge(require("zustand/shallow")),Uo=Ge(require("zustand/vanilla"));var lo=require("eventemitter2");var $i={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"},Ki={0:"POLL_CREATED",1:"POLL_STARTED",2:"POLL_STOPPED",4:"POLL_VOTES_UPDATED",3:"POLLS_LIST"},co={TRANSCRIPTION_STATE_UPDATED:"TRANSCRIPTION_STATE_UPDATED"};var _s="hmsNotification",qi=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(_s,i),()=>{this.eventEmitter.removeListener(_s,i)}};this.store=e,this.eventEmitter=new lo.EventEmitter2({maxListeners:Object.keys(Si).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(X(t==null?void 0:t.id))||t,r=$i[e];if(r&&i){let s=this.createNotification(r,i,"info");this.emitEvent(s)}}sendTrackUpdate(e,t){let i=this.store.getState($t(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=Ki[e],r=this.store.getState(ws(t));if(i){let s=this.createNotification(i,r,"info");this.emitEvent(s)}}sendTranscriptionUpdate(e){let t=this.createNotification(co.TRANSCRIPTION_STATE_UPDATED,e,"info");this.emitEvent(t)}emitEvent(e){this.eventEmitter.emit(_s,e)}createNotification(e,t,i,r=""){return this.id++,{id:this.id,type:e,message:r,data:t,severity:i}}};var ji=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(o){b.w("failed to update store",o)}})};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 uo(a){return a instanceof se||a instanceof O}var po=(a,e)=>{let t=jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Qe(r,s)?(oe(r.auxiliaryTracks,s.auxiliaryTracks)&&(s.auxiliaryTracks=r.auxiliaryTracks),r.groups&&oe(r.groups,s.groups)&&(s.groups=r.groups),Object.assign(r,s)):xs(r,s)?delete a[i]:Ji(r,s)&&(a[i]=s)}},ho=(a,e)=>{let t=jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Qe(r,s)?(Os(r,s),Object.assign(r,s)):xs(r,s)?delete a[i]:Ji(r,s)&&(a[i]=s)}},mo=(a,e)=>{let t=jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Qe(r,s)?(r.questions&&oe(r.questions,s.questions)&&(s.questions=r.questions),Object.assign(r,s)):Ji(r,s)&&(a[i]=s)}},Ns=(a,e)=>{let t=jt(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];Qe(r,s)?Object.assign(r,s):xs(r,s)?delete a[i]:Ji(r,s)&&(a[i]=s)}},So=(a,e,t)=>{let i=t.reduce((s,o)=>(s[o.firstTrackId]=Object.values(e[o.getTrackIDBeingSent()]||{}).sort((n,d)=>!n.rid||!d.rid?0:n.rid<d.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]}},Os=(a,e)=>{a.plugins&&oe(a.plugins,e.plugins)&&(e.plugins=a.plugins),a.type==="video"&&a.layerDefinitions&&oe(a.layerDefinitions,e.layerDefinitions)&&(e.layerDefinitions=a.layerDefinitions)},Qe=(a,e)=>a&&e,xs=(a,e)=>a&&!e,Ji=(a,e)=>!a&&e,oe=(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 se&&(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 G||t instanceof le)&&(e.isPublished=t.isPublished)}static updateDeviceID(e,t){var i;t instanceof G||t instanceof le?e.deviceID=t.settings.deviceId:e.deviceID=(i=t.getMediaTrackSettings())==null?void 0:i.deviceId}static enrichVideoTrack(e,t){t instanceof O&&(e.layer=t.getLayer(),e.preferredLayer=t.getPreferredLayer(),e.degraded=t.degraded),(t instanceof O||t instanceof G)&&(oe(t.getSimulcastDefinitions(),e.layerDefinitions)||(e.layerDefinitions=t.getSimulcastDefinitions()))}static enrichScreenTrack(e,t){var i,r;if(t instanceof G){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 G||t instanceof le)&&(oe(t.getPlugins(),e.plugins)||(e.plugins=t.getPlugins()))}static convertRoom(e,t){let{recording:i,rtmp:r,hls:s,transcriptions:o}=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:o,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,o;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:(o=e.peer)==null?void 0:o.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),o=t.url===(r==null?void 0:r.url);return M(h({},t),{type:t.type,selected:o,playing:o&&s})}static getConvertedPlaylistType(e,t){let i={},r=e.getCurrentSelection(t),s=e.getCurrentProgress(t),o=e.getVolume(t),n=e.getList(t),d=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:d>0,hasNext:d<n.length-1},progress:s,volume:o,currentTime:e.getCurrentTime(t),playbackRate:e.getPlaybackRate(t)}}static convertRecordingStreamingState(e,t,i,r){var s;return{recording:{browser:h({running:!1},e==null?void 0:e.browser),server:h({running:!1},e==null?void 0:e.server),hls:h({running:!1},e==null?void 0:e.hls)},rtmp:h({running:!1},t),hls:{variants:((s=i==null?void 0:i.variants)==null?void 0:s.map(o=>o))||[],running:!!(i!=null&&i.running),error:i==null?void 0:i.error},transcriptions:r||[]}}};var Jt=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"?Ps:bs,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 Qi=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 zi=class{constructor(e,t){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(He);b.d("starting audio levels is connected to room",e),e&&(yield this.monitorAudioLevels());let t=this.store.subscribe(this.monitorAudioLevels.bind(this),He);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(He)){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 t=this.store.getState(Te).filter(s=>!!s.audioTrack),i=[];for(let s of t){let o=this.actions.getTrackById(s.audioTrack||""),n=(r=o==null?void 0:o.stream)==null?void 0:r.nativeStream;if(s.joinedAt&&n){let d=yield this.getAudioLevel(s,n);d.level>0&&i.push(d)}}if(i.length>0){let s={event:"app-audio-level",data:i};b.d("logging audio levels",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,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 n of t)r=Math.max(r,(n-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 go=2e4,To=1e4,pt={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}},fo="https://100ms.live/test-audio.wav";var Yi=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 ld=a=>!!a&&!isNaN(a),ne=a=>a[a.length-1],Fe=(a,e)=>{let t=a.filter(i=>ld(e(i)));return t.reduce((i,r)=>i+(e(r)||0),0)/t.length},Xi=class{constructor(e){this.sdk=e;this.peerStatsList=[];this.localAudioTrackStatsList=[];this.localVideoTrackStatsList=[];this.remoteAudioTrackStatsList=[];this.remoteVideoTrackStatsList=[]}handleStatsUpdate(e){return c(this,null,function*(){var n,d,u,p,m,T,g,f;let t=e.getLocalPeerStats();t&&this.peerStatsList.push(t);let i=(u=(d=(n=this.sdk.getLocalPeer())==null?void 0:n.audioTrack)==null?void 0:d.nativeTrack)==null?void 0:u.id,r=(T=(m=(p=this.sdk.getLocalPeer())==null?void 0:p.videoTrack)==null?void 0:m.nativeTrack)==null?void 0:T.id,s=e.getLocalTrackStats();s&&(i&&this.localAudioTrackStatsList.push(s[i]),r&&this.localVideoTrackStatsList.push(s[r]));let o=yield(f=(g=this.sdk.getWebrtcInternals())==null?void 0:g.getSubscribePeerConnection())==null?void 0:f.getStats();o==null||o.forEach(E=>{if(E.type==="inbound-rtp"){let v=E.kind==="audio"?this.remoteAudioTrackStatsList:this.remoteVideoTrackStatsList,R=Ut("bytesReceived",E,ne(v));v.push(M(h({},E),{bitrate:R}))}})})}buildReport(){var E,v,R,$,ue,ve,pe,Mt,Ks,qs;let e=(E=ne(this.peerStatsList))==null?void 0:E.publish,t=(v=ne(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)),o=((R=ne(this.remoteAudioTrackStatsList))==null?void 0:R.packetsReceived)||0,n=(($=ne(this.remoteVideoTrackStatsList))==null?void 0:$.packetsReceived)||0,d=this.localAudioTrackStatsList.map(V=>V?Fe(Object.values(V),ie=>ie.bitrate):0),u=this.localVideoTrackStatsList.map(V=>V?Fe(Object.values(V),ie=>ie.bitrate):0),p=((ue=ne(this.remoteAudioTrackStatsList))==null?void 0:ue.jitter)||0,m=((ve=ne(this.remoteVideoTrackStatsList))==null?void 0:ve.jitter)||0,T=Math.max(p,m),g=ne(this.localAudioTrackStatsList),f=ne(this.localVideoTrackStatsList);return{combined:{roundTripTime:s,packetsReceived:o+n,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:Fe(this.peerStatsList,V=>{var ie;return(ie=V.publish)==null?void 0:ie.bitrate}),bitrateReceived:Fe(this.peerStatsList,V=>{var ie;return(ie=V.subscribe)==null?void 0:ie.bitrate}),jitter:T},audio:{roundTripTime:s,packetsReceived:o,packetsLost:((pe=ne(this.remoteAudioTrackStatsList))==null?void 0:pe.packetsLost)||0,bytesReceived:((Mt=ne(this.remoteAudioTrackStatsList))==null?void 0:Mt.bytesReceived)||0,bitrateSent:Fe(d,V=>V),bitrateReceived:Fe(this.remoteAudioTrackStatsList,V=>V.bitrate),bytesSent:g?Object.values(g).reduce((V,ie)=>V+(ie.bytesSent||0),0):0,jitter:p},video:{roundTripTime:s,packetsLost:((Ks=ne(this.remoteVideoTrackStatsList))==null?void 0:Ks.packetsLost)||0,bytesReceived:((qs=ne(this.remoteVideoTrackStatsList))==null?void 0:qs.bytesReceived)||0,packetsReceived:n,bitrateSent:Fe(u,V=>V),bitrateReceived:Fe(this.remoteVideoTrackStatsList,V=>V.bitrate),bytesSent:f?Object.values(f).reduce((V,ie)=>V+(ie.bytesSent||0),0):0,jitter:m}}}};var vo=(n=>(n[n.STARTING=0]="STARTING",n[n.INIT_FETCHED=1]="INIT_FETCHED",n[n.SIGNAL_CONNECTED=2]="SIGNAL_CONNECTED",n[n.ICE_ESTABLISHED=3]="ICE_ESTABLISHED",n[n.MEDIA_CAPTURED=4]="MEDIA_CAPTURED",n[n.MEDIA_PUBLISHED=5]="MEDIA_PUBLISHED",n[n.COMPLETED=6]="COMPLETED",n))(vo||{});var Mo,yo,Zi=class{constructor(e,t,i,r){this.sdk=e;this.sdkListener=t;this.progressCallback=i;this.completionCallback=r;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 Yi;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=(Mo=this.sdkListener.onNetworkQuality)==null?void 0:Mo.bind(this.sdkListener);this.onPreview=this.sdkListener.onPreview.bind(this.sdkListener);this.onDeviceChange=(yo=this.sdkListener.onDeviceChange)==null?void 0:yo.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 Xi(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()},go)}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 ze=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.id=e}};var er=(a,e,t)=>c(void 0,null,function*(){let r=Error("something went wrong during fetch");for(let s=0;s<4;s++)try{let o=yield fetch(a,e),n=yield o.clone().json();if(t&&t.length&&!o.ok&&t.includes(n.code))throw S.APIErrors.ServerErrors(n.code,"GET_TOKEN",n.message,!1);return o}catch(o){r=o}throw["Failed to fetch","NetworkError"].some(s=>r.message.includes(s))?S.APIErrors.EndpointUnreachable("GET_TOKEN",r.message):r});var ht=class{constructor(e,t){this.sdk=e;this.sdkListener=t;this.recordedAudio=fo;this.sdk.setIsDiagnostics(!0),this.initSdkWithLocalPeer()}get localPeer(){var e;return(e=this.sdk)==null?void 0:e.store.getLocalPeer()}checkBrowserSupport(){Ct(),Ht()}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,o,n,d;if(this.initSdkWithLocalPeer(),!this.localPeer)throw new Error("Local peer not found");this.sdk.store.setSimulcastEnabled(!1),this.localPeer.role=M(h({},pt),{publishParams:M(h({},pt.publishParams),{allowed:["video"]})});let t=new Oe().video(new j().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");(o=this.sdk)==null||o.deviceManager.init(!0),this.localPeer.videoTrack=r,(d=(n=this.sdk)==null?void 0:n.listener)==null||d.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=To}){var u,p,m,T;this.initSdkWithLocalPeer(g=>{this.stopMicCheck(),t==null||t(g)});let o=yield this.getLocalAudioTrack(e);if((u=this.sdk)==null||u.deviceManager.init(!0),!this.localPeer)throw new Error("Local peer not found");if(!o)throw new Error("No audio track found");this.localPeer.audioTrack=o,(p=this.sdk)==null||p.initPreviewTrackAudioLevelMonitor(),(T=(m=this.sdk)==null?void 0:m.listener)==null||T.onPeerUpdate(9,[this.localPeer]),this.mediaRecorder=new MediaRecorder(o.stream.nativeStream);let n=[];this.mediaRecorder.ondataavailable=function(g){n.push(g.data)},this.mediaRecorder.onstop=()=>{var f,E;let g=new Blob(n,{type:(f=this.mediaRecorder)==null?void 0:f.mimeType});this.recordedAudio=URL.createObjectURL(g),(E=this.onStopMicCheck)==null||E.call(this)},this.mediaRecorder.start();let d=setTimeout(()=>{this.stopMicCheck()},r);this.onStopMicCheck=()=>{clearTimeout(d),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){return c(this,null,function*(){if(!this.sdk)throw new Error("SDK not found");this.connectivityCheck=new Zi(this.sdk,this.sdkListener,e,t);let r=yield this.getAuthToken(i);yield this.sdk.leave(),yield this.sdk.join({authToken:r,userName:"diagnostics-test"},this.connectivityCheck),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:s=>{var o;(o=this.connectivityCheck)==null||o.handleConnectionQualityUpdate(s)}})})}stopConnectivityCheck(){return c(this,null,function*(){var e;return(e=this.connectivityCheck)==null?void 0:e.cleanupAndReport()})}initSdkWithLocalPeer(e){var r,s,o;this.sdkListener&&((r=this.sdk)==null||r.initStoreAndManagers(M(h({},this.sdkListener),{onError:n=>{e==null||e(n),this.sdkListener.onError(n)}})));let t=new je({name:"diagnostics-peer",role:pt,type:"regular"});(s=this.sdk)==null||s.store.addPeer(t);let i=new ze("diagnostics-room");this.sdk.store.setRoom(i),this.sdkListener.onRoomUpdate("ROOM_PEER_COUNT_UPDATED",i),(o=this.sdk)==null||o.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 er(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(h({},pt),{publishParams:M(h({},pt.publishParams),{allowed:["audio"]})});let t=new Oe().audio(new K().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 tr=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(X(t.peerId)),r=$i[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(X(t.peerId)));else if([12,13,14].includes(e))this.syncRoomState(r),i||(i=this.store.getState(X(t.peerId)));else{let s=N.convertPeer(t);this.setState(o=>{let n=o.peers[s.id];Qe(n,s)&&(oe(n.auxiliaryTracks,s.auxiliaryTracks)&&(n.auxiliaryTracks=s.auxiliaryTracks),Object.assign(n,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 Qi(this.sdk,this.setSessionStoreValueLocally.bind(this)),this.actionBatcher=new ji(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 O){if(t==="none"){b.d("layer none will be ignored");return}if(((r=this.store.getState(Rs(e)))==null?void 0:r.preferredLayer)===t){b.d(`preferred layer is already ${t}`);return}this.setState(o=>{let n=o.tracks[e];n&&(n.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(te);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(He),t=!0;e||(t=!1,this.logPossibleInconsistency("room leave is called when no room is connected"));let i=this.store.getState(te);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(ae);t&&(yield this.setEnabledTrack(t,e))})}setLocalVideoEnabled(e){return c(this,null,function*(){let t=this.store.getState(z);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(o=>{o.tracks[e]?o.tracks[e].displayEnabled=t:this.logPossibleInconsistency("track id not found for setEnabled")},"displayEnabled");try{yield this.setEnabledSDKTrack(e,t),this.syncRoomState("setEnabled")}catch(o){throw this.setState(n=>{n.tracks[e].displayEnabled=!t},"rollbackDisplayEnabled"),this.hmsNotifications.sendError(N.convertException(o)),o}let r=t?3:2;this.hmsNotifications.sendTrackUpdate(r,e)})}setAudioSettings(e){return c(this,null,function*(){let t=this.store.getState(ae);t&&(yield this.setSDKLocalAudioTrackSettings(t,e),this.syncRoomState("setAudioSettings"))})}setVideoSettings(e){return c(this,null,function*(){let t=this.store.getState(z);t&&(yield this.setSDKLocalVideoTrackSettings(t,e),this.syncRoomState("setVideoSettings"))})}switchCamera(){return c(this,null,function*(){let e=this.store.getState(z);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(fe),s=t.map(d=>r[d]),{message_id:o,timestamp:n}=yield this.sdk.sendGroupMessage(e,s,i);this.updateMessageInStore({message:e,recipientRoles:t,type:i,id:o,time:n})})}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(o=>{o.messages.byID[r.id]=r,o.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())}),Gi)});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(z);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(ae);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 o={[e]:t};s.appData=o}},`setAppData-${e}`)}rejectChangeRole(e){this.removeRoleChangeRequest(e)}endRoom(e,t){return c(this,null,function*(){let i=this.store.getState(Ms);if(!(i!=null&&i.endRoom)){b.w("You are not allowed to perform this action - endRoom");return}let r=this.store.getState(te);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(o=>{o.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)})}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&&uo(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(fe);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 zi(this.store,this),yield this.beamSpeakerLabelsLogger.start())})}initDiagnostics(){let e=new ht(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),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,kt())},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),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(X((r=e.requestedBy)==null?void 0:r.peerId));this.hmsNotifications.sendLeaveRoom(M(h({},e),{requestedBy:t||void 0}));let i=e.roomEnded||!t?"roomEnded":"removedFromRoom";b.i(`resetting state after peer removed ${i}`,e),this.resetState(i)}onDeviceChange(e){let t=e.devices;if(!t)return;let i=this.store.getState(ee);if(this.setState(r=>{oe(r.devices.audioInput,t.audioInput)||(r.devices.audioInput=t.audioInput),oe(r.devices.videoInput,t.videoInput)||(r.devices.videoInput=t.videoInput),oe(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){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),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=Ki[e];this.setState(r=>{let s=t.reduce((o,n)=>{var d;return o[n.id]=M(h({},n),{questions:(d=n.questions)==null?void 0:d.map(u=>{var p,m;return M(h({},u),{answer:u.answer?h({},u.answer):void 0,options:(p=u.options)==null?void 0:p.map(T=>h({},T)),responses:(m=u.responses)==null?void 0:m.map(T=>h({},T))})})}),o},{});mo(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(Wi)?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(Wi)?(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={},o={},n,d=this.sdk.getPeers();for(let g of d){let f=N.convertPeer(g);t[f.id]=f,i.push(f.id),o[f.id]={peerID:f.id,downlinkQuality:g.networkQuality||-1};let E=[g.audioTrack,g.videoTrack,...g.auxiliaryTracks];for(let v of E){if(!v)continue;let R=N.convertTrack(v);r[R.id]=R}if(g.isLocal){let v=g;n=this.getPreviewFields(v),Object.assign(s,this.getMediaSettings(v))}}let u=this.sdk.getRecordingState(),p=this.sdk.getRTMPState(),m=this.sdk.getHLSState(),T=this.sdk.getTranscriptionState();this.setState(g=>{var v;g.room.peers=i;let f=g.peers,E=g.tracks;po(f,t),ho(E,r),Object.assign(g.settings,s),g.room.isConnected&&Object.assign(g.connectionQualities,o),(v=g.preview)!=null&&v.localPeer&&(n!=null&&n.localPeer)?Object.assign(g.preview,n):g.preview=n,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,m,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 Jt(t,"audio",this.syncPlaylistState.bind(this),this.store),this.videoPlaylist=new Jt(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(J),r=t.filter(o=>!i[o.peerId]);if(this.syncRoomState("peersJoined"),this.store.getState(He)){let o=[];for(let n of t){let d=this.store.getState(X(n.peerId));d&&o.push(d)}this.hmsNotifications.sendPeerList(o)}else r.forEach(o=>{let n=this.store.getState(X(o.peerId));n&&this.hmsNotifications.sendPeerUpdate(0,n)});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(o=>{let n=o.tracks[s.id];Qe(n,s)&&(Os(n,s),Object.assign(n,s))},r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}}onMessageReceived(e){let t=N.convertMessage(e,this.store.getState(Pe));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 o=s.track.trackId;i[o]=s.audioLevel,t.speakers[o]||(t.speakers[o]={audioLevel:s.audioLevel,peerID:s.peer.peerId,trackID:o})});let r=Object.entries(t.speakers);for(let[s,o]of r)o.audioLevel=i[s]||0,o.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(X((s=e.requestedBy)==null?void 0:s.peerId)),i=this.getStoreLocalTrackIDfromSDKTrack(e.track),r=this.store.getState($t(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(X((s=e.requestedBy)==null?void 0:s.peerId));e.enabled||this.syncRoomState("changeMultiTrackStateRequest");let i=[],r=this.store.getState(_);for(let o of e.tracks){let n=this.getStoreLocalTrackIDfromSDKTrack(o);n&&r[n]&&i.push(r[n])}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,o=e.trackId;if(r)if(o===r.audioTrack)delete r.audioTrack;else if(o===r.videoTrack)delete r.videoTrack;else{let n=r.auxiliaryTracks.indexOf(o);n>-1&&r.auxiliaryTracks.splice(n,1)}delete s[o]},"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(Ss),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 _e?(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(ee);if((t==null?void 0:t.videoTrack)!==e)return!1;let i=this.store.getState(Ts),r=this.store.getState(Gi);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(z);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(z);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(ae);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(gs).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(fs)&&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(o=>o&&typeof o.bitrate=="number"&&o.bitrate>0))}};var ir=a=>U?`${a} ${document.title}`:a;var rr=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,o=Date.now(),n=0,d=re(i).then(()=>{this.controller.abort()});try{let m=(u=(yield fetch(`${t}?${Date.now()}`,{signal:s})).body)==null?void 0:u.getReader();if(!m)throw Error("unable to process request");let T=()=>c(this,null,function*(){if(m)try{let g=!1;for(;!g;){let{value:f,done:E}=yield m.read();g=E,f&&(n+=f.byteLength,this.sendScore({scoreMap:r,downloadedSize:n,startTime:o}))}}catch(g){g.name!=="AbortError"&&l.d(this.TAG,g)}});return Promise.race([T(),d]).then(()=>{this.sendScore({scoreMap:r,downloadedSize:n,startTime:o,finished:!0})}).catch(g=>{l.d(this.TAG,g),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:g.message}))})}catch(p){p.name!=="AbortError"?(l.d(this.TAG,p),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:p.message}))):l.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,n=t/1024/s*8,d=-1;for(let u in e){let p=e[u];n>=p.low&&(!p.high||n<=p.high)&&(d=Number(u))}this.updateScoreToListener(d),r&&this.eventBus.analytics.publish(y.previewNetworkQuality({score:d,downLink:n.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 Qt=class{constructor(e,t,i,r,s,o){this.store=e;this.transport=t;this.deviceManager=i;this.publish=r;this.removeAuxiliaryTrack=s;this.listener=o;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,E,v,R,$;let r=new Set(e.publishParams.allowed),s=new Set(t.publishParams.allowed),o=this.removeTrack(r,s,"video"),n=this.removeTrack(r,s,"audio"),d=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((E=e.publishParams.simulcast)==null?void 0:E.screen,(v=t.publishParams.simulcast)==null?void 0:v.screen),m=($=(R=this.store.getLocalPeer())==null?void 0:R.videoTrack)==null?void 0:$.enabled;yield this.removeAudioTrack(n),yield this.removeVideoTracks(o||u),yield this.removeScreenTracks(d||p);let T=this.getSettings();u&&(T.isVideoMuted=!m),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(o=>{var d;let n=(d=t==null?void 0:t.layers)==null?void 0:d.find(u=>u.rid===o.rid);return(n==null?void 0:n.maxBitrate)!==o.maxBitrate||(n==null?void 0:n.maxFramerate)!==o.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,o;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=((o=this.deviceManager.currentSelection.audioOutput)==null?void 0:o.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 Us=class{constructor(){this.TAG="[HTTPAnalyticsTransport]";this.failedEvents=new Me("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"?Ha:Ca;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=>{l.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))}},Ce=new Us;var zt=class{constructor(e){this.type=e.type,this.source=e.source||"regular",this.description="",e instanceof we?(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 Yt=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=Lt(this.env);this.polls=new Map;this.whiteboards=new Map;this.addPermissionToRole=(e,t,i,r)=>{var o;if(!this.knownRoles[e]){l.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(h({},s[t]),{[r]:[i]}):t==="whiteboard"&&(s[t]||(s[t]=[]),(o=s[t])==null||o.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(o=>this.addPermissionToRole(o,"whiteboard","admin")),(r=t==null?void 0:t.reader)==null||r.forEach(o=>this.addPermissionToRole(o,"whiteboard","read")),(s=t==null?void 0:t.writer)==null||s.forEach(o=>this.addPermissionToRole(o,"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))};this.handleNoiseCancellationPlugin=e=>{this.room&&(this.room.isNoiseCancellationEnabled=!!(e!=null&&e.enabled)&&!!this.room.isNoiseCancellationEnabled)}}getConfig(){return this.config}setSimulcastEnabled(e){this.simulcastEnabled=e}removeRemoteTracks(){this.tracks.forEach(e=>{(e instanceof se||e instanceof O)&&(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 O)}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(o=>o.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=Lt(this.env,e)}setRoom(e){this.room=e}setKnownRoles(e){var i,r;if(this.knownRoles=e.known_roles,this.addPluginsToRoles(e.plugins),this.roleDetailsArrived=!0,this.templateAppData=e.app_data,!this.simulcastEnabled)return;let t=(i=this.knownRoles[e.name])==null?void 0:i.publishParams;this.videoLayers=this.convertSimulcastLayers((r=t.simulcast)==null?void 0:r.video),this.updatePeersPolicy()}hasRoleDetailsArrived(){return this.roleDetailsArrived}setConfig(e){var t,i,r;if(Z.rememberDevices(!!e.rememberDeviceSelection),e.rememberDeviceSelection){let s=Z.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*(){for(let t of this.getAudioTracks())yield t.setVolume(e)})}updateAudioOutputDevice(e){return c(this,null,function*(){let t=[];this.getAudioTracks().forEach(i=>{i instanceof se&&t.push(i.setOutputDevice(e))}),yield Promise.all(t)})}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(h({},e),{layers:(e.layers||[]).map(t=>M(h({},t),{maxBitrate:t.maxBitrate*1e3}))})}getSimulcastDefinitionsForPeer(e,t){var n,d,u;if([!e||!e.role,t==="screen",!this.simulcastEnabled].some(p=>!!p))return[];let i=this.getPolicyForRole(e.role.name).publishParams,r,s,o;return t==="regular"?(r=(n=i.simulcast)==null?void 0:n.video,s=i.video.width,o=i.video.height):t==="screen"&&(r=(d=i.simulcast)==null?void 0:d.screen,s=i.screen.width,o=i.screen.height),((u=r==null?void 0:r.layers)==null?void 0:u.map(p=>{let m=Ne[p.rid],T={width:Math.floor(s/p.scaleResolutionDownBy),height:Math.floor(o/p.scaleResolutionDownBy)};return{layer:m,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}case"noiseCancellation":{this.handleNoiseCancellationPlugin(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,Ce.setEnv(i)}};var sr=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(),l.d(this.TAG,"Wake lock released")}catch(e){let t=e;l.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)&&(l.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)){l.d(this.TAG,"Wake lock feature not supported");return}this.wakeLock=yield navigator.wakeLock.request("screen"),l.d(this.TAG,"Wake lock acquired")}catch(e){let t=e;l.w(this.TAG,"Error acquiring wake lock",`name=${t.name}, message=${t.message}`)}})}};var ar=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();l.d(this.TAG,"Max buffer size reached","Removed event to accommodate new events",t)}return this}flushFailedClientEvents(){Ce.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){l.w(this.TAG,"Flush Failed",t)}}sendClientEventOnHTTP(e){var r,s,o,n;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:(o=t==null?void 0:t.startedAt)==null?void 0:o.getTime(),role:(n=i==null?void 0:i.role)==null?void 0:n.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},Ce.sendEvent(e)}};var Eo=require("uuid");var ko={autoplayFailed:void 0,initialized:!1,autoplayCheckPromise:void 0},Xt=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=h({},ko);this.handleAudioPaused=e=>c(this,null,function*(){l.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})=>{l.d(this.TAG,"Track updated",`${e}`)};this.handleTrackAdd=r=>c(this,[r],function*({track:e,peer:t,callListener:i=!0}){var o,n;let s=document.createElement("audio");s.style.display="none",s.id=e.trackId,s.addEventListener("pause",this.handleAudioPaused),s.onerror=()=>c(this,null,function*(){var u,p;l.e(this.TAG,"error on audio element",s.error);let d=S.TracksErrors.AudioPlaybackError(`Audio playback error for track - ${e.trackId} code - ${(u=s==null?void 0:s.error)==null?void 0:u.code}`);this.eventBus.analytics.publish(y.audioPlaybackError(d)),((p=s==null?void 0:s.error)==null?void 0:p.code)===MediaError.MEDIA_ERR_DECODE&&(this.removeAudioElement(s,e),yield re(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),yield e.setVolume(this.volume),l.d(this.TAG,"Audio track added",`${e}`),this.init(),(o=this.audioSink)==null||o.append(s),this.outputDevice&&(yield e.setOutputDevice(this.outputDevice)),s.srcObject=new MediaStream([e.nativeTrack]),i&&((n=this.listener)==null||n.onTrackUpdate(0,e,t)),yield this.handleAutoplayError(e)});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),l.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&&(l.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*(){yield this.store.updateAudioOutputVolume(e),this.volume=e})}unblockAutoplay(){return c(this,null,function*(){this.autoPausedTracks.size>0&&(yield this.unpauseAudioTracks()),yield de.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,Eo.v4)()}`,(e&&document.getElementById(e)||document.body).append(t),this.audioSink=t,l.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=h({},ko)}playAudioFor(e){return c(this,null,function*(){let t=e.getAudioElement();if(!t){l.w(this.TAG,"No audio element found on track",e.trackId);return}try{yield t.play(),this.state.autoplayFailed=!1,this.autoPausedTracks.delete(e),l.d(this.TAG,"Played track",`${e}`)}catch(i){this.autoPausedTracks.add(e),l.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 or=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.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 Zt=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);return i&&(this.outputDevice=i,yield this.store.updateAudioOutputDevice(i),this.eventBus.analytics.publish(y.deviceChange({isUserSelection:t,selection:{audioOutput:i},devices:this.getDevices(),type:"audioOutput"})),Z.updateSelection("audioOutput",{deviceId:i.deviceId,groupId:i.groupId})),i});this.getCurrentSelection=()=>{var o,n;let e=this.store.getLocalPeer(),t=this.createIdentifier((o=e==null?void 0:e.audioTrack)==null?void 0:o.getMediaTrackSettings()),i=this.createIdentifier((n=e==null?void 0:e.videoTrack)==null?void 0:n.getMediaTrackSettings()),r=this.audioInput.find(d=>this.createIdentifier(d)===t),s=this.videoInput.find(d=>this.createIdentifier(d)===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),Z.setDevices({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput]}),this.logDevices("Enumerate Devices")}catch(e){l.e(this.TAG,"Failed enumerating devices",e)}});this.updateToActualDefaultDevice=()=>c(this,null,function*(){var r,s,o,n,d;let e=this.store.getLocalPeer();if(!((s=(r=this.store.getConfig())==null?void 0:r.settings)==null?void 0:s.videoDeviceId)&&(e!=null&&e.videoTrack)&&(yield e.videoTrack.setSettings({deviceId:(o=this.videoInput[0])==null?void 0:o.deviceId},!0)),!((d=(n=this.store.getConfig())==null?void 0:n.settings)==null?void 0:d.audioInputDeviceId)&&(e!=null&&e.audioTrack)){let u=()=>{var T;let m=this.audioInput.find(g=>!g.label.toLowerCase().includes("iphone"));return na()&&m?m==null?void 0:m.deviceId:(T=this.getNewAudioInputDevice())==null?void 0:T.deviceId};u()&&(yield e.audioTrack.setSettings({deviceId:u()},!0))}});this.handleDeviceChange=Ii(()=>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){l.d(this.TAG,"No Audio track on local peer");return}if(!this.audioInputChanged){l.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"})),l.e(this.TAG,"Audio device not found");return}let{settings:i}=e,r=new K().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){l.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){l.d(this.TAG,"No video track on local peer");return}if(!this.videoInputChanged){l.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"})),l.e(this.TAG,"Video device not found");return}let{settings:i}=e,r=new j().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){l.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=()=>{"ondevicechange"in navigator.mediaDevices||(this.timer=setTimeout(()=>{c(this,null,function*(){yield this.enumerateDevices(),yield this.autoSelectAudioOutput(),this.startPollingForDevices()})},5e3))};this.autoSelectAudioOutput=()=>c(this,null,function*(){var d,u;if("ondevicechange"in navigator.mediaDevices||!((d=this.store.getLocalPeer())!=null&&d.joinedAt))return;let{bluetoothDevice:e,earpiece:t,speakerPhone:i,wired:r}=this.categorizeAudioInputDevices(),s=(u=this.store.getLocalPeer())==null?void 0:u.audioTrack;if(!s||!t)return;let o=this.getManuallySelectedAudioDevice(),n=(o==null?void 0:o.deviceId)||(e==null?void 0:e.deviceId)||(r==null?void 0:r.deviceId)||(i==null?void 0:i.deviceId);if(l.d(this.TAG,"externalDeviceID",n),!(s.settings.deviceId===n&&this.earpieceSelected))try{if(!this.earpieceSelected){if((e==null?void 0:e.deviceId)===n){this.earpieceSelected=!0;return}yield s.setSettings({deviceId:t==null?void 0:t.deviceId},!0),this.earpieceSelected=!0}yield s.setSettings({deviceId:n},!0)}catch(p){this.eventBus.error.publish(p)}});let i=({enabled:r,track:s})=>r&&s.source==="regular";this.eventBus.localVideoEnabled.waitFor(i).then(()=>c(this,null,function*(){yield this.enumerateDevices(),this.videoInputChanged&&this.eventBus.deviceChange.publish({devices:this.getDevices()})})),this.eventBus.localAudioEnabled.waitFor(i).then(()=>c(this,null,function*(){yield this.enumerateDevices(),this.audioInputChanged&&this.eventBus.deviceChange.publish({devices:this.getDevices()})})),this.eventBus.deviceChange.subscribe(({type:r,isUserSelection:s,selection:o})=>{if(s){let n=r==="video"?"videoInput":r,d=this[n].find(u=>this.createIdentifier(u)===this.createIdentifier(o));this.eventBus.analytics.publish(y.deviceChange({selection:{[n]:d},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()),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(o=>o.deviceId!=="default"&&t.label.includes(o.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 o=Ai(s.label);o==="SPEAKERPHONE"?t=s:o==="WIRED"?i=s:o==="BLUETOOTH"?e=s:o==="EARPIECE"&&(r=s)}return{bluetoothDevice:e,speakerPhone:t,wired:i,earpiece:r}}getAudioOutputDeviceMatchingInput(e){var o,n;let t=((n=(o=this.store.getConfig())==null?void 0:o.settings)==null?void 0:n.speakerAutoSelectionBlacklist)||[];if(t==="all"||!e)return;let i=e.label.toLowerCase()||"";if(t.some(d=>i.includes(d.toLowerCase())))return;let r=this.audioOutput.find(d=>e.deviceId!=="default"&&d.label===e.label);if(r)return r;let s=this.audioOutput.find(d=>d.groupId===e.groupId);if(s&&this.audioOutput[0].deviceId==="default"&&s.groupId===this.audioOutput[0].groupId)return s}logDevices(e=""){l.d(this.TAG,e,JSON.stringify({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput],selected:this.getCurrentSelection()},null,4))}};var nr=class{constructor(e,t){this.deviceManager=e;this.audioSinkManager=t}getVolume(){return this.audioSinkManager.getVolume()}setVolume(e){if(e<0||e>100)throw Error("Please pass a valid number between 0-100");this.audioSinkManager.setVolume(e)}getDevice(){return this.deviceManager.outputDevice}setDevice(e){return this.deviceManager.updateOutputDevice(e,!0)}unblockAutoplay(){return c(this,null,function*(){yield this.audioSinkManager.unblockAutoplay(),yield de.resumeContext()})}};var ei=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}){l.d(this.TAG,`sendFeedback: feedbackEndpoint=${t} peerId=${i.peer.peer_id} session=${i.peer.session_id} `);let o=new URL("v2/client/feedback",t),n=M(h({},i),{payload:r});try{let d=yield fetch(o,{headers:{Authorization:`Bearer ${e}`},body:JSON.stringify(n),method:"POST"});try{this.handleError(d);return}catch(u){throw l.e(this.TAG,"error",u.message,d.status),u instanceof k?u:S.APIErrors.ServerErrors(d.status,"FEEDBACK",u.message)}}catch(d){let u=d;throw["Failed to fetch","NetworkError","ECONNRESET"].some(p=>u.message.includes(p))?S.APIErrors.EndpointUnreachable("FEEDBACK",u.message):u}})}};ei.TAG="[FeedbackService]";var Po=require("eventemitter2");var x=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 mt=class{constructor(){this.eventEmitter=new Po.EventEmitter2;this.analytics=new x(F.ANALYTICS,this.eventEmitter);this.deviceChange=new x(F.DEVICE_CHANGE,this.eventEmitter);this.localAudioEnabled=new x(F.LOCAL_AUDIO_ENABLED,this.eventEmitter);this.localVideoEnabled=new x(F.LOCAL_VIDEO_ENABLED,this.eventEmitter);this.localVideoUnmutedNatively=new x(F.LOCAL_VIDEO_UNMUTED_NATIVELY,this.eventEmitter);this.localAudioUnmutedNatively=new x(F.LOCAL_AUDIO_UNMUTED_NATIVELY,this.eventEmitter);this.statsUpdate=new x(F.STATS_UPDATE,this.eventEmitter);this.trackDegraded=new x(F.TRACK_DEGRADED,this.eventEmitter);this.trackRestored=new x(F.TRACK_RESTORED,this.eventEmitter);this.trackAudioLevelUpdate=new x(F.TRACK_AUDIO_LEVEL_UPDATE,this.eventEmitter);this.audioPluginFailed=new x(F.AUDIO_PLUGIN_FAILED,this.eventEmitter);this.localAudioSilence=new x(F.LOCAL_AUDIO_SILENCE,this.eventEmitter);this.policyChange=new x(F.POLICY_CHANGE,this.eventEmitter);this.localRoleUpdate=new x(F.LOCAL_ROLE_UPDATE,this.eventEmitter);this.audioTrackUpdate=new x(F.AUDIO_TRACK_UPDATE,this.eventEmitter);this.audioTrackAdded=new x(F.AUDIO_TRACK_ADDED,this.eventEmitter);this.audioTrackRemoved=new x(F.AUDIO_TRACK_REMOVED,this.eventEmitter);this.autoplayError=new x(F.AUTOPLAY_ERROR,this.eventEmitter);this.leave=new x(F.LEAVE,this.eventEmitter);this.error=new x(F.ERROR,this.eventEmitter)}};var cr=class{constructor(e,t,i){this.store=e;this.listener=t;this.audioListener=i}handleActiveSpeakers(e){var s,o,n;let t=e["speaker-list"],i=t.map(d=>({audioLevel:d.level,peer:this.store.getPeerById(d.peer_id),track:this.store.getTrackById(d.track_id)}));(s=this.audioListener)==null||s.onAudioLevelUpdate(i),this.store.updateSpeakers(i);let r=t[0];if(r){let d=this.store.getPeerById(r.peer_id);(o=this.listener)==null||o.onPeerUpdate(4,d)}else(n=this.listener)==null||n.onPeerUpdate(5,null)}};var dr=class{constructor(e){this.listener=e;this.TAG="[BroadcastManager]"}handleNotification(e,t){e==="on-broadcast"&&this.handleBroadcast(t)}handleBroadcast(e){var t,i;l.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 lr=class{constructor(e,t){this.store=e;this.listener=t}handleQualityUpdate(e){var r;let i=e.peers.map(s=>{let o=this.store.getPeerById(s.peer_id);return o&&o.updateNetworkQuality(s.downlink_score),{peerID:s.peer_id,downlinkQuality:s.downlink_score}});(r=this.listener)==null||r.onConnectionQualityUpdate(i)}};var St=class{constructor(e,t,i){this.store=e;this.eventBus=t;this.listener=i;this.TAG="[TrackManager]";this.tracksToProcess=new Map;this.handleTrackAdd=e=>{l.d(this.TAG,"ONTRACKADD",`${e}`),this.tracksToProcess.set(e.trackId,e),this.processPendingTracks()};this.handleTrackRemovedPermanently=e=>{l.d(this.TAG,"ONTRACKREMOVE permanently",e),Object.keys(e.tracks).forEach(i=>{var n;let r=this.store.getTrackState(i);if(!r)return;let s=this.store.getTrackById(i);if(!s){l.d(this.TAG,"Track not found in store");return}s.type==="audio"&&this.eventBus.audioTrackRemoved.publish(s),this.store.removeTrack(s);let o=this.store.getPeerById(r.peerId);o&&(this.removePeerTracks(o,s),(n=this.listener)==null||n.onTrackUpdate(1,s,o))})};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 O&&this.setLayer(r,i)}};this.handleTrackUpdate=(e,t=!0)=>{var s,o;let i=this.store.getPeerById(e.peer.peer_id),r=e.peer;if(!i&&!r){l.d(this.TAG,"Track Update ignored - Peer not added to store");return}i||(i=Ee(r,this.store),this.store.addPeer(i));for(let n in e.tracks){let d=Object.assign({},(s=this.store.getTrackState(n))==null?void 0:s.trackInfo),u=e.tracks[n],p=this.store.getTrackById(n);if(this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:h(h({},d),u)}),!p||this.tracksToProcess.has(n))this.processTrackInfo(u,e.peer.peer_id,t),this.processPendingTracks();else{p.setEnabled(!u.mute);let m=this.processTrackUpdate(p,d,u);m&&((o=this.listener)==null||o.onTrackUpdate(m,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){l.d(this.TAG,"TrackState not added to store",`peerId - ${t.peerId}`,`trackId -${t.trackId}`);return}let r=this.store.getPeerById(i.peerId);if(!r){l.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,t.setEnabled(!i.trackInfo.mute),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)})}}handleTrackMetadataAdd(e){l.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;l.d(this.TAG,"ONTRACKREMOVE",`${e}`);let i=this.store.getTrackState(e.trackId);if(!i)return;if(!this.store.hasTrack(e)){l.d(this.TAG,"Track not found in store");return}if(t){this.store.removeTrack(e);let o=this.store.getPeerById(i.peerId);if(!o)return;this.removePeerTracks(o,e),(s=this.listener)==null||s.onTrackUpdate(1,e,o),e.type==="audio"&&this.eventBus.audioTrackRemoved.publish(e)}}setLayer(e,t){var s,o;let i=this.store.getPeerByTrackId(e.trackId);if(!i)return;e.setLayerFromServer(t)?(s=this.listener)==null||s.onTrackUpdate(5,e,i):(o=this.listener)==null||o.onTrackUpdate(6,e,i)}removePeerTracks(e,t){let i=e.auxiliaryTracks.indexOf(t);i>-1?(e.auxiliaryTracks.splice(i,1),l.d(this.TAG,"auxiliary track removed",`${t}`)):t.type==="audio"&&e.audioTrack===t?(e.audioTrack=void 0,l.d(this.TAG,"audio track removed",`${t}`)):t.type==="video"&&e.videoTrack===t&&(e.videoTrack=void 0,l.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),l.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(o=>o.trackId===i.trackId);s===-1?(e.auxiliaryTracks.push(i),this.store.addTrack(i)):(e.auxiliaryTracks[s].replaceTrack(i),this.store.addTrack(e.auxiliaryTracks[s]))}l.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 ur=class extends St{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)){l.d(this.TAG,`no peer in store for peerId: ${i}`);return}let o=new Ae(new MediaStream,this.transport.getSubscribeConnection()),n=Ie.getEmptyVideoTrack();n.enabled=!t.mute;let d=new O(o,n,t.source,(u=this.store.getRoom())==null?void 0:u.disableNoneLayerRequest);d.setTrackId(t.track_id),d.peerId=s.peerId,d.logIdentifier=s.name,this.addVideoTrack(s,d),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&&ye(t.videoTrack.nativeTrack)}isPeerRoleSubscribed(t){var s,o,n,d;if(!t)return!0;let i=this.store.getLocalPeer(),r=this.store.getPeerById(t);return r&&((d=(o=(s=i==null?void 0:i.role)==null?void 0:s.subscribeParams)==null?void 0:o.subscribeToRoles)==null?void 0:d.includes((n=r.role)==null?void 0:n.name))}};var pr=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(o=>!e[o.peerId]);r.length>0&&l.d(this.TAG,`${r}`),r.forEach(o=>{var d;let n={peer_id:o.peerId,role:((d=o.role)==null?void 0:d.name)||"",info:{name:o.name,data:o.metadata||"",user_id:o.customerUserId||"",type:o.type},tracks:{},groups:[],realtime:o.realtime};this.peerManager.handlePeerLeave(n)});let s=[];i.forEach(o=>{let n=this.store.getPeerById(o.peer_id),d=Object.values(o.tracks);n&&(this.store.getPeerTracks(n.peerId).forEach(p=>{var m;o.tracks[p.trackId]||(this.removePeerTrack(n,p.trackId),(m=this.listener)==null||m.onTrackUpdate(1,p,n))}),d.forEach(p=>{this.store.getTrackById(p.track_id)||this.store.setTrackState({peerId:n.peerId,trackInfo:p})}),this.trackManager.handleTrackUpdate({peer:o,tracks:o.tracks},!1),this.peerManager.handlePeerUpdate(o)),s.push(o)}),s.length>0&&this.peerManager.handlePeerList(s)}}handleNotification(e,t,i){if(e==="peer-list"){let r=t;i?(l.d(this.TAG,"RECONNECT_PEER_LIST event",JSON.stringify(r,null,2)),this.handleReconnectPeerList(r)):(l.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(l.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(o=>o.trackId===t);s>=0&&e.auxiliaryTracks.splice(s,1)}}};var L=a=>a?new Date(a):void 0;var hr=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(o=>o.peer_id));this.store.getRemotePeers().forEach(({peerId:o,fromRoomState:n})=>{!i.has(o)&&n&&this.store.removePeer(o)});for(let o of e)t.push(this.makePeer(o));(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,o;let t=this.store.getPeerById(e.peer_id);this.store.removePeer(e.peer_id),l.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(n=>{var d;(d=this.listener)==null||d.onTrackUpdate(1,n,t)}),(o=this.listener)==null||o.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,o,n,d,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),(o=this.listener)==null||o.onPeerUpdate(13,t);return}if(!t){l.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),(n=this.listener)==null||n.onPeerUpdate(8,t)}let i=t.isHandRaised;t.updateGroups(e.groups);let r=(d=e.groups)==null?void 0:d.includes(Re);i!==r&&((u=this.listener)==null||u.onPeerUpdate(12,t)),this.handlePeerInfoUpdate(h({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=Ee(e,this.store),t.realtime=e.realtime,t.joinedAt=L(e.joined_at),t.fromRoomState=!!e.is_from_room_state,this.store.addPeer(t),l.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 mr=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:l.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 Bs=(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))(Bs||{});var ti=(a,e,t)=>{let i=t==="qa"?_a:wa,r=new URL(i);return r.searchParams.set("endpoint",`https://${e}`),r.searchParams.set("token",a),r.toString()};var Sr=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 o;if(!this.isEnabled)return l.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(h({},t),{title:e==null?void 0:e.title,attributes:e==null?void 0:e.attributes,id:r.id,url:ti(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),(o=this.listener)==null||o.onWhiteboardUpdate(s)})}close(e){return c(this,null,function*(){var r;if(!this.isEnabled)return l.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 o=yield this.transport.signal.getWhiteboard({id:s.id}),n=this.store.getLocalPeer(),u=(n==null?void 0:n.customerUserId)===o.owner?(i=(t=n.role)==null?void 0:t.permissions.whiteboard)==null?void 0:i.includes("admin"):o.permissions.length>0,p=M(h({},s),{id:o.id,url:ti(o.token,o.addr,this.store.getEnv()),token:o.token,addr:o.addr,owner:o.owner,permissions:o.permissions,open:u});this.store.setWhiteboard(p),(r=this.listener)==null||r.onWhiteboardUpdate(p)}})}getCreateOptionsWithDefaults(e){var o;let t=Object.values(this.store.getKnownRoles()),i=[],r=[],s=[];return t.forEach(n=>{var d,u,p;(d=n.permissions.whiteboard)!=null&&d.includes("read")&&i.push(n.name),(u=n.permissions.whiteboard)!=null&&u.includes("write")&&r.push(n.name),(p=n.permissions.whiteboard)!=null&&p.includes("admin")&&s.push(n.name)}),{title:(e==null?void 0:e.title)||`${(o=this.store.getRoom())==null?void 0:o.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 ii=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.whiteboard=new Sr(e,t,i)}setListener(e){this.listener=e,this.whiteboard.setListener(e)}createPoll(e){return c(this,null,function*(){var o,n;let t={customerID:"userid",peerID:"peerid",userName:"username"},{poll_id:i}=yield this.transport.signal.setPollInfo(M(h({},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=gr(M(h({},e),{poll_id:e.id,state:"created",created_by:(o=this.store.getLocalPeer())==null?void 0:o.peerId}));s.questions=r.questions.map(({question:d,options:u,answer:p})=>M(h({},d),{options:u,answer:p})),(n=this.listener)==null||n.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 n,d;let o=this.getQuestionInPoll(i,s.questionIndex);return o.type==="single-choice"?(s.option=s.option||((n=s.options)==null?void 0:n[0])||-1,delete s.text,delete s.options):o.type==="multiple-choice"?((d=s.options)==null||d.sort(),delete s.text,delete s.option):(delete s.option,delete s.options),s.skipped&&(delete s.option,delete s.options,delete s.text),h({duration:0,type:o.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,m;let r=this.store.getPoll(e);if(!r)throw new Error("Invalid poll ID - Poll not found");let s=(m=(p=this.store.getLocalPeer())==null?void 0:p.role)==null?void 0:m.permissions,o=!!(s!=null&&s.pollRead||s!=null&&s.pollWrite);if(r.anonymous||r.state!=="stopped"||!o)return{entries:[],hasNext:!1};let n=yield this.transport.signal.fetchPollLeaderboard({poll_id:r.id,count:i,offset:t}),d={avgScore:n.avg_score,avgTime:n.avg_time,votedUsers:n.voted_users,totalUsers:n.total_users,correctUsers:n.correct_users};return{entries:n.questions.map(T=>({position:T.position,totalResponses:T.total_responses,correctResponses:T.correct_responses,duration:T.duration,peer:T.peer,score:T.score})),hasNext:!n.last,summary:d}})}getPollResponses(e,t){return c(this,null,function*(){var s,o;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:n,peer:d,final:u})=>{var m,T;let p=(m=e==null?void 0:e.questions)==null?void 0:m.find(g=>g.index===n.question);if(p){let g={id:n.response_id,questionIndex:n.question,option:n.option,options:n.options,text:n.text,responseFinal:u,peer:{peerid:d.peerid,userHash:d.hash,userid:d.userid,username:d.username},skipped:n.skipped,type:n.type,update:n.update},f=p.responses&&!t?[...p.responses]:[];(T=r.questions)!=null&&T[n.question-1]&&(r.questions[n.question-1].responses=[...f,g])}}),this.store.setPoll(r),(o=this.listener)==null||o.onPollsUpdate(4,[r])})}getPolls(){return c(this,null,function*(){var s,o,n;let e=yield this.transport.signal.getPollsList({count:50,state:"started"}),t=[],i=(o=(s=this.store.getLocalPeer())==null?void 0:s.role)==null?void 0:o.permissions.pollWrite,r=[...e.polls];if(i){let d=yield this.transport.signal.getPollsList({count:50,state:"created"}),u=yield this.transport.signal.getPollsList({count:50,state:"stopped"});r=[...d.polls,...r,...u.polls]}for(let d of r){let u=yield this.transport.signal.getPollQuestions({poll_id:d.poll_id,index:0,count:50}),p=gr(d),m=this.store.getPoll(d.poll_id);p.questions=u.questions.map(({question:T,options:g,answer:f},E)=>{var v,R;return M(h({},T),{options:g,answer:f,responses:(R=(v=m==null?void 0:m.questions)==null?void 0:v[E])==null?void 0:R.responses})}),t.push(p),this.store.setPoll(p)}return(n=this.listener)==null||n.onPollsUpdate(3,t),t})}createQuestionSetParams(e,t){var o,n;if(e.index){let d=(o=e.options)==null?void 0:o.map((u,p)=>M(h({},u),{index:p+1}));return{question:M(h({},e),{index:t+1}),options:d,answer:e.answer}}let i=M(h({},e),{index:t+1}),r,s=e.answer||{hidden:!1};return Array.isArray(e.options)&&["single-choice","multiple-choice"].includes(e.type)?(r=(n=e.options)==null?void 0:n.map((d,u)=>({index:u+1,text:d.text,weight:d.weight})),e.type==="single-choice"?s.option=e.options.findIndex(d=>d.isCorrectAnswer)+1||void 0:s.options=e.options.map((d,u)=>d.isCorrectAnswer?u+1:void 0).filter(d=>!!d)):(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}},gr=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 Tr=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 o=this.store.getPoll(s.poll_id);if(o&&o.state==="started"){(i=this.listener)==null||i.onPollsUpdate(1,[o]);return}let n=yield this.transport.signal.getPollQuestions({poll_id:s.poll_id,index:0,count:50}),d=gr(s);d.questions=n.questions.map(({question:u,options:p,answer:m})=>M(h({},u),{options:p,answer:m})),yield this.updatePollResponses(d,!0),t.push(d),this.store.setPoll(d)}(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 o=yield this.transport.signal.getPollResult({poll_id:r.poll_id});this.updatePollResult(s,o),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=h({},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 o,n;let s=(o=e.questions)==null?void 0:o.find(d=>d.index===r.question);s&&(s.result=h({},s.result),s.result.correctResponses=r.correct,s.result.skippedCount=r.skipped,s.result.totalResponses=r.total,(n=r.options)==null||n.forEach((d,u)=>{var m;let p=(m=s.options)==null?void 0:m[u];p&&p.voteCount!==d&&(p.voteCount=d)}))})}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:o,final:n})=>{var p;let d=(p=e==null?void 0:e.questions)==null?void 0:p.find(m=>m.index===s.question);if(!d)return;let u={id:s.response_id,questionIndex:s.question,option:s.option,options:s.options,text:s.text,responseFinal:n,peer:{peerid:o.peerid,userHash:o.hash,userid:o.userid,username:o.username},skipped:s.skipped,type:s.type,update:s.update};Array.isArray(d.responses)&&d.responses.length>0?d.responses.find(({id:m})=>m===u.id)||d.responses.push(u):d.responses=[u]})})}};var fr=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,o=this.store.getLocalPeerTracks().find(d=>d.publishedTrackId===i);if(!o)return;let n=()=>{var d;(d=this.listener)==null||d.onChangeTrackStateRequest({requestedBy:s,track:o,enabled:!r})};if(r){if(o.enabled===!r)return;o.setEnabled(!r).then(n)}else n()}handleChangeTrackStateRequest(e){var u;let{type:t,source:i,value:r,requested_by:s}=e,o=s?this.store.getPeerById(s):void 0,n=!r,d=this.getTracksToBeUpdated({type:t,source:i,enabled:n});if(d.length!==0)if(n)(u=this.listener)==null||u.onChangeMultiTrackStateRequest({requestedBy:o,tracks:d,type:t,source:i,enabled:!0});else{let p=[];for(let m of d)p.push(m.setEnabled(!1));Promise.all(p).then(()=>{var m;(m=this.listener)==null||m.onChangeMultiTrackStateRequest({requestedBy:o,tracks:d,enabled:!1})})}}getTracksToBeUpdated({type:e,source:t,enabled:i}){let s=this.store.getLocalPeerTracks();return e&&(s=s.filter(o=>o.type===e)),t&&(s=s.filter(o=>o.source===t)),s.filter(o=>o.enabled!==i)}};var vr=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){l.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){l.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,m,T;let{recording:t,streaming:i,transcriptions:r,session_id:s,started_at:o,name:n}=e,d=this.store.getRoom();if(!d){l.w(this.TAG,"on room state - room not present");return}d.name=n,d.rtmp.running=this.isStreamingRunning((u=i==null?void 0:i.rtmp)==null?void 0:u.state),d.rtmp.startedAt=L((p=i==null?void 0:i.rtmp)==null?void 0:p.started_at),d.rtmp.state=(m=i==null?void 0:i.rtmp)==null?void 0:m.state,d.recording.server=this.getPeerListSFURecording(t),d.recording.browser=this.getPeerListBrowserRecording(t),d.recording.hls=this.getPeerListHLSRecording(t),d.hls=this.convertHls(i==null?void 0:i.hls),d.transcriptions=this.addTranscriptionDetail(r),d.sessionId=s,d.startedAt=L(o),(T=this.listener)==null||T.onRoomUpdate("RECORDING_STATE_UPDATED",d)}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)})):[]}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 o,n,d;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((o=e==null?void 0:e.variants)==null?void 0:o[s].started_at),initialisedAt:L((n=e==null?void 0:e.variants)==null?void 0:n[s].initialised_at),state:r.state,stream_type:r==null?void 0:r.stream_type}):i.variants.push({initialisedAt:L((d=e==null?void 0:e.variants)==null?void 0:d[s].initialised_at),url:""})}),i):(l.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){l.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){l.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){l.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){l.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 l.e(this.TAG,"error in streaming/recording",i),i}};var Mr=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 yr=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){switch(e){case"on-whiteboard-update":{this.handleWhiteboardUpdate(t);break}default:break}}handleWhiteboardUpdate(e){return c(this,null,function*(){var n;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",o={id:e.id,title:e.title,attributes:e.attributes};if(o.open=r?i==null?void 0:i.open:s,o.owner=o.open?e.owner:void 0,o.open)if(r)o.url=i==null?void 0:i.url,o.token=i==null?void 0:i.token,o.addr=i==null?void 0:i.addr,o.permissions=i==null?void 0:i.permissions;else{let d=yield this.transport.signal.getWhiteboard({id:e.id});o.url=ti(d.token,d.addr,this.store.getEnv()),o.token=d.token,o.addr=d.addr,o.permissions=d.permissions,o.open=d.permissions.length>0}this.store.setWhiteboard(o),(n=this.listener)==null||n.onWhiteboardUpdate(o)})}};var kr=class{constructor(e,t,i,r,s,o){this.store=e;this.transport=i;this.listener=r;this.audioListener=s;this.connectionQualityListener=o;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 n=this.transport.isFlagEnabled("onDemandTracks");this.trackManager=n?new ur(this.store,t,this.transport,this.listener):new St(this.store,t,this.listener),this.peerManager=new hr(this.store,this.trackManager,this.listener),this.peerListManager=new pr(this.store,this.peerManager,this.trackManager,this.listener),this.broadcastManager=new dr(this.listener),this.policyChangeManager=new mr(this.store,t),this.requestManager=new fr(this.store,this.listener),this.activeSpeakerManager=new cr(this.store,this.listener,this.audioListener),this.connectionQualityManager=new lr(this.store,this.connectionQualityListener),this.roomUpdateManager=new vr(this.store,this.listener),this.sessionMetadataManager=new Mr(this.store,this.listener),this.pollsManager=new Tr(this.store,this.transport,this.listener),this.whiteboardManager=new yr(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,o;let i=e.method,r=e.params;["active-speakers","sfu-stats","on-connection-quality-update",void 0].includes(i)||l.d(this.TAG,`Received notification - ${i}`,{notification:r}),i==="sfu-stats"&&(s=window.HMS)!=null&&s.ON_SFU_STATS&&typeof((o=window.HMS)==null?void 0:o.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){l.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 Er=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 Pr=class{constructor(e,t,i="",r="",s="https://prod-init.100ms.live/init",o=!1,n){this.authToken=e;this.peerId=t;this.peerName=i;this.data=r;this.endpoint=s;this.autoSubscribeVideo=o;this.iceServers=n}};var Q=(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))(Q||{}),bo={0:[],1:[],2:[1],3:[1],4:[1]};var br=(n=>(n.Disconnected="Disconnected",n.Connecting="Connecting",n.Joined="Joined",n.Preview="Preview",n.Failed="Failed",n.Reconnecting="Reconnecting",n.Leaving="Leaving",n))(br||{});var Ar=class{constructor(e){this.promise=new Promise((t,i)=>{this.resolve=t,this.reject=i,e(t,i)})}};var Ir=class{constructor(e,t){this.onStateChange=e;this.sendEvent=t;this.TAG="[RetryScheduler]";this.inProgress=new Map;this.retryTaskIds=[]}schedule(n){return c(this,arguments,function*({category:e,error:t,task:i,originalState:r,maxRetryTime:s=6e4,changeState:o=!0}){yield this.scheduleTask({category:e,error:t,changeState:o,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:o,maxRetryTime:n=6e4,failedRetryCount:d=0}){if(l.d(this.TAG,"schedule: ",{category:Q[e],error:t}),d===0){let v=this.inProgress.get(e);if(v){l.d(this.TAG,`schedule: Already a task for ${Q[e]} scheduled, waiting for its completion`),yield v.promise;return}let R=new Ar(($,ue)=>{});this.inProgress.set(e,R),this.sendEvent(t,e)}let p=!1,m=bo[e];for(let v in m){let R=m[parseInt(v)];try{let $=this.inProgress.get(R);$&&(l.d(this.TAG,`schedule: Suspending retry task of ${Q[e]}, waiting for ${Q[R]} to recover`),yield $.promise,l.d(this.TAG,`schedule: Resuming retry task ${Q[e]} as it's dependency ${Q[R]} is recovered`))}catch($){l.d(this.TAG,`schedule: Stopping retry task of ${Q[e]} as it's dependency ${Q[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()-o;if(g>=n||p)return t.description+=`. [${Q[e]}] Could not recover after ${g} milliseconds`,p&&(t.description+=` Could not recover all of it's required dependencies - [${m.map(v=>Q[v]).toString()}]`),t.isTerminal=!0,T(t);i&&this.onStateChange("Reconnecting",t);let f=this.getDelayForRetryCount(e);l.d(this.TAG,`schedule: [${Q[e]}] [failedRetryCount=${d}] Scheduling retry task in ${f}ms`);let E;try{E=yield this.setTimeoutPromise(r,f)}catch(v){E=!1;let R=v;if(R.isTerminal)return l.e(this.TAG,`[${Q[e]}] Un-caught terminal exception ${R.name} in retry-task`,v),T(R);l.w(this.TAG,`[${Q[e]}] Un-caught exception ${R.name} in retry-task, initiating retry`,v)}if(E){let v=this.inProgress.get(e);this.inProgress.delete(e),v==null||v.resolve(d),i&&this.inProgress.size===0&&this.onStateChange(s),l.d(this.TAG,`schedule: [${Q[e]}] [failedRetryCount=${d}] Recovered \u267B\uFE0F after ${g}ms`)}else yield this.scheduleTask({category:e,error:t,changeState:i,task:r,originalState:s,maxRetryTime:n,failedAt:o,failedRetryCount:d+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 o=yield e();o&&this.retryTaskIds.splice(this.retryTaskIds.indexOf(s),1),i(o)}catch(o){r(o)}}),t);this.retryTaskIds.push(s)})})}};var Rr=class extends Ue{constructor(){super(100);this.localStorage=new Me("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 Hr=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 l.w(this.TAG,"Rate limit exceeded",t),t}try{this.sendSingleEvent(e),this.flushFailedEvents()}catch(t){l.w(this.TAG,"sendEvent failed",t)}}flushFailedEvents(e){var t;try{for(l.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):Ce.sendEvent(i))}}catch(i){l.w(this.TAG,"flushFailedEvents failed",i)}}sendSingleEvent(e){try{this.transportProvider.sendEvent(e),l.d(this.TAG,"Sent event",e.name,e)}catch(t){throw l.w(this.TAG,`${this.transportProvider.TAG}.sendEvent failed, adding to local storage events`,{event:e,error:t}),this.failedEvents.enqueue(e),t}}};var Cr=class extends Hr{constructor(t){super();this.transportProvider=t;this.failedEvents=new Rr}};var gt=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.stop=()=>{this.shouldSendEvent&&this.sendEvent(),this.eventBus.statsUpdate.unsubscribe(this.handleStatsUpdate.bind(this)),this.shouldSendEvent=!1};this.start()}start(){this.shouldSendEvent||(this.stop(),this.shouldSendEvent=!0,this.eventBus.statsUpdate.subscribe(this.handleStatsUpdate.bind(this)),this.startLoop().catch(e=>l.e("[StatsAnalytics]",e.message)))}startLoop(){return c(this,null,function*(){for(;this.shouldSendEvent;)yield re(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()})}},Tt=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?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)}},Lr=(a,e)=>a&&e&&(a.frameWidth!==e.frameWidth||a.frameHeight!==e.frameHeight),Dr=(a,e)=>a&&e&&a.enabled!==e.enabled,ri=a=>Object.entries(a).filter(([,e])=>e!==void 0).reduce((e,[t,i])=>(e[t]=i,e),{});var si=class extends gt{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(o=>{o.track.type==="audio"?t.push(o.toAnalytics()):o.track.type==="video"&&i.push(o.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()}handleStatsUpdate(t){let i=!1,r=t.getLocalTrackStats();Object.keys(r).forEach(s=>{let o=r[s],n=this.store.getLocalPeerTracks().find(d=>d.getTrackIDBeingSent()===s);Object.keys(o).forEach(d=>{var g,f,E;let u=o[d];if(!n)return;let p=this.getTrackIdentifier(n.trackId,u),m=M(h({},u),{availableOutgoingBitrate:(f=(g=t.getLocalPeerStats())==null?void 0:g.publish)==null?void 0:f.availableOutgoingBitrate});if(p&&this.trackAnalytics.has(p))(E=this.trackAnalytics.get(p))==null||E.pushTempStat(m);else if(n){let v=new Vs({track:n,sampleWindowSize:this.sampleWindowSize,rid:u.rid,ssrc:u.ssrc.toString(),kind:u.kind});v.pushTempStat(m),this.trackAnalytics.set(this.getTrackIdentifier(n.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}},Vs=class extends Tt{constructor(){super(...arguments);this.samples=[];this.collateSample=()=>{let t=this.getLatestStat(),i=t.qualityLimitationDurations,r=i&&{bandwidth_sec:i.bandwidth,cpu_sec:i.cpu,other_sec:i.other},s=t.frameHeight?{height_px:this.getLatestStat().frameHeight,width_px:this.getLatestStat().frameWidth}:void 0,o=this.calculateAverage("jitter",!1),n=o?Math.round(o*1e3):void 0,d=this.calculateAverage("roundTripTime",!1),u=d?Math.round(d*1e3):void 0;return ri({timestamp:Date.now(),avg_available_outgoing_bitrate_bps:this.calculateAverage("availableOutgoingBitrate"),avg_bitrate_bps:this.calculateAverage("bitrate"),avg_fps:this.calculateAverage("framesPerSecond"),total_packets_lost:this.getLatestStat().packetsLost,total_packets_sent:this.getLatestStat().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:n,avg_round_trip_time_ms:u,total_quality_limitation:r,resolution:s})};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===30||Dr(i,r)||i.kind==="video"&&Lr(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}};var ai=class extends gt{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(o=>{o.track.type==="audio"?t.push(o.toAnalytics()):o.track.type==="video"&&i.push(o.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,E;let o=this.store.getTrackById(s),n=i[s],d=(f=this.trackAnalytics.get(s))==null?void 0:f.getLatestStat(),p=((v,R)=>{let $=(R==null?void 0:R.jitterBufferDelay)||0,ue=(R==null?void 0:R.jitterBufferEmittedCount)||0,ve=((v==null?void 0:v.jitterBufferDelay)||0)-$,pe=((v==null?void 0:v.jitterBufferEmittedCount)||0)-ue;return pe>0?ve*1e3/pe:(R==null?void 0:R.calculatedJitterBufferDelay)||0})(n,d),m=this.calculateAvSyncForStat(n,t),T=M(h({},n),{calculatedJitterBufferDelay:p,avSync:m});if(n.kind==="video"){let v=o.getPreferredLayerDefinition();T.expectedFrameHeight=v==null?void 0:v.resolution.height,T.expectedFrameWidth=v==null?void 0:v.resolution.width}if(this.trackAnalytics.has(s))(E=this.trackAnalytics.get(s))==null||E.pushTempStat(T);else if(o){let v=new Gs({track:o,sampleWindowSize:this.sampleWindowSize,ssrc:n.ssrc.toString(),kind:n.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,o=r==null?void 0:r.videoTrack;if(!(s&&o&&s.enabled&&o.enabled))return xt;let d=i.getRemoteTrackStats(s.trackId);if(!d)return xt;if(d.estimatedPlayoutTimestamp)return d.estimatedPlayoutTimestamp-t.estimatedPlayoutTimestamp}},Gs=class extends Tt{constructor(){super(...arguments);this.samples=[];this.collateSample=()=>{let t=this.getLatestStat(),i=this.getFirstStat(),r={timestamp:Date.now(),total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount"),avg_jitter_buffer_delay:this.calculateAverage("calculatedJitterBufferDelay",!1)};if(t.kind==="video")return ri(M(h({},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 ri(M(h({},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||Dr(i,r)||i.kind==="video"&&Lr(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!==xt);return i.length===0?xt:i.reduce((r,s)=>r+s,0)/i.length}};var ft=(t=>(t[t.Publish=0]="Publish",t[t.Subscribe=1]="Subscribe",t))(ft||{});var oi=Ge(require("sdp-transform"));function Ao(a,e){var r;let t=oi.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 d,u,p;let o=(d=s.msid)==null?void 0:d.split(" ")[0],n=(u=i.find(m=>m.type===s.type&&m.stream_id===o))==null?void 0:u.track_id;n&&(s.msid=(p=s.msid)==null?void 0:p.replace(/\s(.+)/,` ${n}`))}),{type:a.type,sdp:oi.write(t)}}function Io(a,e){var s;if(!(a!=null&&a.sdp)||!e)return;let i=oi.parse(a.sdp).media.find(o=>me(o.mid)&&parseInt(o.mid)===parseInt(e));return(s=i==null?void 0:i.msid)==null?void 0:s.split(" ")[1]}function Ro(a){return a.sdp.includes("usedtx=1")?a:{type:a.type,sdp:a.sdp.replace("useinbandfec=1","useinbandfec=1;usedtx=1")}}var Le="[HMSConnection]",Ye=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 l.d(Le,`[role=${this.role}] createOffer offer=${JSON.stringify(i,null,1)}`),Ro(Ao(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 l.d(Le,`[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{l.d(Le,`[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{l.d(Le,`[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"){l.d(Le,`[role=${this.role}] addIceCandidate signalling state closed`);return}l.d(Le,`[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,o=()=>{typeof s.getSelectedCandidatePair=="function"&&(this.selectedCandidatePair=s.getSelectedCandidatePair(),this.selectedCandidatePair&&(this.observer.onSelectedCandidatePairChange(this.selectedCandidatePair),l.d(Le,`${ft[this.role]} connection`,`selected ${i||"unknown"} candidate pair`,JSON.stringify(this.selectedCandidatePair,null,2))))};typeof s.onselectedcandidatepairchange=="function"&&(s.onselectedcandidatepairchange=o),o()}})}catch(e){l.w(Le,`Error in logging selected ice candidate pair for ${ft[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 G&&e.settings.maxFramerate,s=this.getSenders().find(o=>{var n;return((n=o==null?void 0:o.track)==null?void 0:n.id)===e.getTrackIDBeingSent()});if(s){let o=s.getParameters();o.encodings.length===1&&(i&&(o.encodings[0].maxBitrate=i*1e3),r&&(o.encodings[0].maxFramerate=r)),yield s.setParameters(o)}else l.w(Le,`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 ni=class extends Ye{constructor(t,i,r){super(0,t);this.TAG="[HMSPublishConnection]";this.observer=r,this.nativeConnection=new RTCPeerConnection(i),this.channel=this.nativeConnection.createDataChannel(_i,{protocol:"SCTP"}),this.channel.onerror=s=>l.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 o;this.observer.onDTLSTransportError(new Error((o=s==null?void 0:s.error)==null?void 0:o.errorDetail)||"DTLS Transport failed")})}}close(){super.close(),this.channel.close()}initAfterJoin(){this.nativeConnection.onnegotiationneeded=()=>c(this,null,function*(){l.d(this.TAG,"onnegotiationneeded"),yield this.observer.onRenegotiationNeeded()})}};var Ho=Ge(require("eventemitter2")),Co=require("uuid");var ci=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){l.d(this.TAG,`[${this.metadata}] Sending [size=${e.length}] message=${e}`),this.nativeChannel.send(e)}close(){this.nativeChannel.close()}};var di=class extends Ye{constructor(t,i,r,s){super(1,t);this.isFlagEnabled=r;this.TAG="[HMSSubscribeConnection]";this.remoteStreams=new Map;this.MAX_RETRIES=3;this.pendingMessageQueue=[];this.eventEmitter=new Ho.default({maxListeners:60});this.handlePendingApiMessages=()=>{this.eventEmitter.emit("open",!0),this.pendingMessageQueue.length>0&&(l.d(this.TAG,"Found pending message queue, sending messages"),this.pendingMessageQueue.forEach(t=>this.sendOverApiDataChannel(t)),this.pendingMessageQueue.length=0)};this.sendMessage=(t,i)=>c(this,null,function*(){var s;((s=this.apiChannel)==null?void 0:s.readyState)!=="open"&&(yield this.eventEmitter.waitFor("open"));let r;for(let o=0;o<this.MAX_RETRIES;o++){this.apiChannel.send(t),r=yield this.waitForResponse(i);let n=r.error;if(n){if(n.code===404){l.d(this.TAG,`Track not found ${i}`,{request:t,try:o+1,error:n});break}if(l.d(this.TAG,`Failed sending ${i}`,{request:t,try:o+1,error:n}),!(n.code/100===5||n.code===429))throw Error(`code=${n.code}, message=${n.message}`);let u=(2+Math.random()*2)*1e3;yield Be(u)}else break}return r});this.waitForResponse=t=>c(this,null,function*(){let i=yield this.eventEmitter.waitFor("message",function(s){return s.includes(t)}),r=JSON.parse(i[0]);return l.d(this.TAG,`response for ${t} -`,JSON.stringify(r,null,2)),r});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===_i&&(this.apiChannel=new ci(t.channel,{onMessage:i=>{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 m=new Ae(i,this);this.remoteStreams.set(r,m)}i.addEventListener("removetrack",m=>{if(m.track.id!==t.track.id)return;let T=s.tracks.findIndex(g=>{var f;return g.nativeTrack.id===m.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),o=t.track.kind==="audio",n=o?se:O,d=o?new n(s,t.track):new n(s,t.track,void 0,this.isFlagEnabled("disableNoneLayerRequest"));t.track.kind==="video"&&s.setVideoLayerLocally("none","addTrack","subscribeConnection"),d.transceiver=t.transceiver;let u=Io(this.remoteDescription,(p=t.transceiver)==null?void 0:p.mid);u&&d.setSdpTrackId(u),s.tracks.push(d),this.observer.onTrackAdd(d)}}sendOverApiDataChannel(t){this.apiChannel&&this.apiChannel.readyState==="open"?this.apiChannel.send(t):(l.w(this.TAG,`API Data channel not ${this.apiChannel?"open":"present"}, queueing`,t),this.pendingMessageQueue.push(t))}sendOverApiDataChannelWithResponse(t,i){return c(this,null,function*(){let r=(0,Co.v4)();if(t.method==="prefer-video-track-state"&&this.isFlagEnabled("disableVideoTrackAutoUnsubscribe")&&t.params.max_spatial_layer==="none")return l.d(this.TAG,"video auto unsubscribe is disabled, request is ignored"),{id:r};let s=JSON.stringify(h({id:i||r,jsonrpc:"2.0"},t));return this.sendMessage(s,r)})}close(){var t;super.close(),(t=this.apiChannel)==null||t.close()}};var Lo=(a,e)=>!e||e.length===0?a:e.map(i=>({urls:i.urls,credentialType:"password",credential:i.password,username:i.userName}));var _r="[InitService]",li=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(n){return c(this,arguments,function*({token:e,peerId:t,userAgent:i,initEndpoint:r="https://prod-init.100ms.live",region:s="",iceServers:o}){l.d(_r,`fetchInitConfig: initEndpoint=${r} token=${e} peerId=${t} region=${s} `);let d=md(r,t,i,s);try{let u=yield fetch(d,{headers:{Authorization:`Bearer ${e}`}});try{let p=yield u.clone().json();return this.handleError(u,p),l.d(_r,`config is ${JSON.stringify(p,null,2)}`),Sd(p,o)}catch(p){let m=yield u.text();throw l.e(_r,"json error",p.message,m),p instanceof k?p:S.APIErrors.ServerErrors(u.status,"INIT",p.message)}}catch(u){let p=u;throw["Failed to fetch","NetworkError","ECONNRESET"].some(m=>p.message.includes(m))?S.APIErrors.EndpointUnreachable("INIT",p.message):p}})}};function md(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 l.e(_r,s.name,s.message),s}}function Sd(a,e){var t;return M(h({},a),{rtcConfiguration:M(h({},a.rtcConfiguration),{iceServers:Lo((t=a.rtcConfiguration)==null?void 0:t.ice_servers,e)})})}var Do=require("uuid");var ui=class{constructor(e){this.TAG="[SIGNAL]: ";this.pongResponseTimes=new Ue(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=()=>{l.d(this.TAG,"Window network offline"),this.setIsConnected(!1,"Window network offline")};this.onlineListener=()=>{l.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=""){l.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,Do.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((n,d)=>{this.callbacks.set(i,{resolve:n,reject:d,metadata:{method:e}})})}catch(o){if(o instanceof k)throw o;let n=o;throw S.WebsocketMethodErrors.ServerErrors(Number(n.code),$r(e),n.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=()=>{l.e(this.TAG,"Error from websocket"),r=!0,i(S.WebSocketConnectionErrors.FailedToConnect("JOIN","Error opening websocket connection"))};this.onCloseHandler=n=>{l.w(`Websocket closed code=${n.code}`),r?this.setIsConnected(!1,`code: ${n.code}${n.code!==1e3?", unexpected websocket close":""}`):(r=!0,i(S.WebSocketConnectionErrors.AbnormalClose("JOIN",`Error opening websocket connection - websocket closed unexpectedly with code=${n.code}`)))},this.socket.addEventListener("error",s);let o=()=>{var n,d;r=!0,t(),this.setIsConnected(!0),this.id++,(n=this.socket)==null||n.removeEventListener("open",o),(d=this.socket)==null||d.removeEventListener("error",s),this.pingPongLoop(this.id)};this.socket.addEventListener("open",o),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,o,n){return c(this,null,function*(){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("JOIN","Failed to send join over WS connection");let d={name:e,disableVidAutoSub:i,data:t,offer:n,server_sub_degrade:r,simulcast:s,onDemandTracks:o},u=yield this.internalCall("join",d);return this.isJoinCompleted=!0,this.pendingTrickle.forEach(({target:p,candidate:m})=>this.trickle(p,m)),this.pendingTrickle.length=0,l.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",h({},e))})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.call("rtmp-stop",{})})}startHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-start",h({},e))})}stopHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-stop",h({},e))})}startTranscription(e){return c(this,null,function*(){yield this.call("transcription-start",h({},e))})}stopTranscription(e){return c(this,null,function*(){yield this.call("transcription-stop",h({},e))})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.call("hls-timed-metadata",h({},e))})}updatePeer(e){return c(this,null,function*(){yield this.call("peer-update",h({},e))})}getPeer(e){return c(this,null,function*(){return yield this.call("get-peer",h({},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",h({},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",h({},e))}getPollInfo(e){return this.call("poll-info-get",h({},e))}setPollQuestions(e){return this.call("poll-questions-set",h({},e))}startPoll(e){return this.call("poll-start",h({},e))}stopPoll(e){return this.call("poll-stop",h({},e))}getPollQuestions(e){return this.call("poll-questions-get",h({},e))}setPollResponses(e){return this.call("poll-response",h({},e))}getPollResponses(e){return this.call("poll-responses",h({},e))}getPollsList(e){return this.call("poll-list",h({},e))}getPollResult(e){return this.call("poll-result",h({},e))}createWhiteboard(e){return this.validateConnection(),this.call("whiteboard-create",h({},e))}getWhiteboard(e){return this.validateConnection(),this.call("whiteboard-get",h({},e))}fetchPollLeaderboard(e){return this.call("poll-leaderboard",h({},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":l.w(this.TAG,e.params);break;default:this.observer.onNotification(e);break}}rejectPendingCalls(e=""){this.callbacks.forEach((t,i)=>{var r,s,o,n;((r=t.metadata)==null?void 0:r.method)!=="ping"&&(l.e(this.TAG,`rejecting pending callback ${(s=t.metadata)==null?void 0:s.method}, id=${i}`),t.reject(S.WebSocketConnectionErrors.WebSocketConnectionLost((o=t.metadata)!=null&&o.method?$r((n=t.metadata)==null?void 0:n.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?(l.d(this.TAG,`Pong timeout ${e}, pageHidden=${oa()}`),this.id===e&&this.setIsConnected(!1,"ping pong failure")):setTimeout(()=>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(),l.d(this.TAG,`Try number ${s} sending ${e}`,t),yield this.internalCall(e,t)}catch(o){if(r=o,l.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 d=(2+Math.random()*2)*1e3;yield Be(d)}throw l.e(`Sending ${e} over WS failed after ${Math.min(s,3)} retries`,{method:e,params:t,error:r}),r})}};var wo=()=>{if(!U||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 I="[HMSTransport]:",pi=class{constructor(e,t,i,r,s,o,n){this.observer=e;this.deviceManager=t;this.store=i;this.eventBus=r;this.analyticsEventsService=s;this.analyticsTimer=o;this.pluginUsageTracker=n;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){l.d(I,"ignoring old offer");return}yield this.subscribeConnection.setRemoteDescription(e),l.d(I,`[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),l.d(I,"[role=SUBSCRIBE] onOffer renegotiation DONE \u2705")}catch(t){l.d(I,"[role=SUBSCRIBE] onOffer renegotiation FAILED \u274C",t),this.state="Failed";let i;t instanceof k?i=t:i=S.GenericErrors.Unknown("SUBSCRIBE",t.message),this.observer.onFailure(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*(){l.d(I,"socket offline",br[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;l.d(I,"socket online",br[this.state]),this.analyticsSignalTransport.flushFailedEvents((e=this.store.getLocalPeer())==null?void 0:e.peerId)},onNetworkOnline:()=>{this.analyticsEventsService.flushFailedClientEvents()}};this.signal=new ui(this.signalObserver);this.analyticsSignalTransport=new Cr(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)&&(l.d(I,"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(ot,{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(nt,{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;l.d(I,"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 Oi(this.store,this.eventBus);let d=(u,p)=>c(this,null,function*(){u!==this.state&&(this.state=u,yield this.observer.onStateChange(this.state,p))});this.retryScheduler=new Ir(d,this.sendErrorAnalyticsEvent.bind(this)),this.eventBus.statsUpdate.subscribe(u=>{var m,T;let p=((T=(m=u.getLocalPeerStats())==null?void 0:m.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,o){return c(this,null,function*(){let n=yield this.connect(e,t,i,r,s,o);return this.state="Preview",this.observer.onStateChange(this.state),n})}join(e,t,i,r,s=!1,o){return c(this,null,function*(){l.d(I,"join: started \u23F0");try{(!this.signal.isConnected||!this.initConfig)&&(yield this.connect(e,r,t,i,s,o)),this.validateNotDisconnected("connect"),this.initConfig&&(yield this.waitForLocalRoleAvailability(),yield this.createConnectionsAndNegotiateJoin(i,s),this.initStatsAnalytics(),l.d(I,"\u2705 join: Negotiated over PUBLISH connection"))}catch(n){l.e(I,`join: failed \u274C [token=${e}]`,n),this.state="Failed";let d=n;throw d.isTerminal=d.isTerminal||d.code===500,yield this.observer.onStateChange(this.state,d),d}l.d(I,"\u2705 join: successful"),this.state="Joined",this.observer.onStateChange(this.state)})}connect(e,t,i,r,s=!1,o){return c(this,null,function*(){this.setTransportStateForConnect(),this.joinParameters=new Pr(e,i,r.name,r.metaData,t,s,o);try{return yield this.internalConnect(e,t,i,o)}catch(n){if(n instanceof k&&([P.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,P.WebSocketConnectionErrors.FAILED_TO_CONNECT,P.WebSocketConnectionErrors.ABNORMAL_CLOSE,P.APIErrors.ENDPOINT_UNREACHABLE].includes(n.code)||n.code.toString().startsWith("5")||n.code.toString().startsWith("429"))){let u=()=>c(this,null,function*(){return yield this.internalConnect(e,t,i,o),!!(this.initConfig&&this.initConfig.endpoint)});yield this.retryScheduler.schedule({category:0,error:n,task:u,originalState:this.state,changeState:!1})}else throw n}})}leave(i){return c(this,arguments,function*(e,t="user request"){var r,s,o;this.retryScheduler.reset(),this.joinParameters=void 0,l.d(I,"leaving in transport");try{let n=this.pluginUsageTracker.getPluginUsage("HMSKrispPlugin");if(n&&this.eventBus.analytics.publish(y.getKrispUsage(n)),this.state="Leaving",(r=this.publishStatsAnalytics)==null||r.stop(),(s=this.subscribeStatsAnalytics)==null||s.stop(),(o=this.webrtcInternals)==null||o.cleanup(),this.clearPeerConnections(),e)try{this.signal.leave(t),l.d(I,"signal leave done")}catch(d){l.w(I,"failed to send leave on websocket to server",d)}this.analyticsEventsService.flushFailedClientEvents(),this.analyticsEventsService.reset(),yield this.signal.close()}catch(n){this.eventBus.analytics.publish(y.disconnect(n)),l.e(I,"leave: FAILED \u274C",n)}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,o;l.time("sfu migration"),this.clearPeerConnections();let e=this.store.getPeerMap();this.store.removeRemoteTracks();for(let n in e){let d=e[n];d.isLocal||(d.audioTrack=void 0,d.videoTrack=void 0,d.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 n=t.audioTrack.stream;i.get(n.id)||i.set(n.id,new ge(new MediaStream));let d=t.audioTrack.clone(i.get(n.id));this.store.removeTrack(t.audioTrack),t.audioTrack.cleanup(),yield this.publishTrack(d),t.audioTrack=d}if(t.videoTrack){let n=t.videoTrack.stream;i.get(n.id)||i.set(n.id,new ge(new MediaStream)),this.store.removeTrack(t.videoTrack);let d=t.videoTrack.clone(i.get(n.id));t.videoTrack.cleanup(),yield this.publishTrack(d),t.videoTrack=d}let r=[];for(;t.auxiliaryTracks.length>0;){let n=t.auxiliaryTracks.shift();if(n){let d=n.stream;i.get(d.id)||i.set(d.id,new ge(n.source==="screen"?d.nativeStream.clone():new MediaStream)),this.store.removeTrack(n);let u=n.clone(i.get(d.id));u.type==="video"&&u.source==="screen"&&(this.screenStream.add(d.nativeStream),this.screenStream.add(u.stream.nativeStream),u.nativeTrack.addEventListener("ended",this.onScreenshareStop)),n.cleanup(),yield this.publishTrack(u),r.push(u)}}t.auxiliaryTracks=r,i.clear(),(o=(s=this.listener)==null?void 0:s.onSFUMigration)==null||o.call(s),l.timeEnd("sfu migration")})}trackUpdate(e,t){var s;let r=Array.from(this.trackStates.values()).find(o=>e.type===o.type&&e.source===o.source);if(r){let o=new zt(M(h({},r),{mute:!t}));this.trackStates.set(r.track_id,o),l.d(I,"Track Update",this.trackStates,e),this.signal.trackUpdate(new Map([[r.track_id,o]]));let n=this.store.getLocalPeer();n&&t===e.enabled&&((s=this.listener)==null||s.onTrackUpdate(t?3:2,e,n))}}publishTrack(e){return c(this,null,function*(){e.publishedTrackId=e.getTrackIDBeingSent(),l.d(I,`\u23F3 publishTrack: trackId=${e.trackId}, toPublishTrackId=${e.publishedTrackId}`,`${e}`),this.trackStates.set(e.publishedTrackId,new zt(e));let t=new Promise((s,o)=>{this.callbacks.set(ot,{promise:{resolve:s,reject:o},action:"PUBLISH",extra:{}})}),i=e.stream;i.setConnection(this.publishConnection);let r=this.store.getSimulcastLayers(e.source);i.addTransceiver(e,r),l.time(`publish-${e.trackId}-${e.type}`),yield t,l.timeEnd(`publish-${e.trackId}-${e.type}`),this.store.addTrack(e),yield i.setMaxBitrateAndFramerate(e).then(()=>{l.d(I,`Setting maxBitrate=${e.settings.maxBitrate} kpbs${e instanceof G?` and maxFramerate=${e.settings.maxFramerate}`:""} for ${e.source} ${e.type} ${e.trackId}`)}).catch(s=>l.w(I,"Failed setting maxBitrate and maxFramerate",s)),e.isPublished=!0,l.d(I,`\u2705 publishTrack: trackId=${e.trackId}`,`${e}`,this.callbacks)})}unpublishTrack(e){return c(this,null,function*(){if(l.d(I,`\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(o=>e.type===o.type&&e.source===o.source);s&&this.trackStates.delete(s.track_id)}let t=new Promise((r,s)=>{this.callbacks.set(ot,{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),l.d(I,`\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,o,n=!1)=>{(["disconnected","failed"].includes(o)?l.w.bind(l):l.d.bind(l))(I,`${ft[s]} ${n?"ice":""} connection state change: ${o}`)};if(this.initConfig){let s={onRenegotiationNeeded:()=>c(this,null,function*(){yield this.performPublishRenegotiation()}),onDTLSTransportStateChange:n=>{var p,m,T;if((n==="failed"?l.w.bind(l):l.d.bind(l))(I,`Publisher on dtls transport state change: ${n}`),!n||this.lastPublishDtlsState===n||(this.lastPublishDtlsState=n,this.publishDtlsStateTimer!==0&&(clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0),n!=="connecting"&&n!=="failed"))return;let u=(T=(m=(p=this.initConfig)==null?void 0:p.config)==null?void 0:m.dtlsStateTimeouts)==null?void 0:T[n];!u||u<=0||(this.publishDtlsStateTimer=window.setTimeout(()=>{var f;let g=(f=this.publishConnection)==null?void 0:f.nativeConnection.connectionState;if(g&&n&&g===n){let E=S.WebrtcErrors.ICEFailure("PUBLISH",`DTLS transport state ${n} timeout:${u}ms`,!0);this.eventBus.analytics.publish(y.disconnect(E)),this.observer.onFailure(E)}},u))},onDTLSTransportError:n=>{l.e(I,`onDTLSTransportError ${n.name} ${n.message}`,n),this.eventBus.analytics.publish(y.disconnect(n))},onIceConnectionChange:n=>c(this,null,function*(){e(0,n,!0)}),onConnectionStateChange:n=>c(this,null,function*(){var d,u,p,m,T,g,f,E;e(0,n,!1),n!=="new"&&(n==="connected"?((d=this.connectivityListener)==null||d.onICESuccess(!0),(u=this.publishConnection)==null||u.handleSelectedIceCandidatePairs()):n==="failed"?yield this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEFailure("PUBLISH",`local candidate - ${(T=(m=(p=this.publishConnection)==null?void 0:p.selectedCandidatePair)==null?void 0:m.local)==null?void 0:T.candidate}; remote candidate - ${(E=(f=(g=this.publishConnection)==null?void 0:g.selectedCandidatePair)==null?void 0:f.remote)==null?void 0:E.candidate}`)):this.publishDisconnectTimer=window.setTimeout(()=>{var v,R,$,ue,ve,pe,Mt;((v=this.publishConnection)==null?void 0:v.connectionState)!=="connected"&&this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEDisconnected("PUBLISH",`local candidate - ${(ue=($=(R=this.publishConnection)==null?void 0:R.selectedCandidatePair)==null?void 0:$.local)==null?void 0:ue.candidate}; remote candidate - ${(Mt=(pe=(ve=this.publishConnection)==null?void 0:ve.selectedCandidatePair)==null?void 0:pe.remote)==null?void 0:Mt.candidate}`))},5e3))}),onIceCandidate:n=>{var d;(d=this.connectivityListener)==null||d.onICECandidate(n,!0)},onSelectedCandidatePairChange:n=>{var d;(d=this.connectivityListener)==null||d.onSelectedICECandidatePairChange(n,!0)}},o={onApiChannelMessage:n=>{this.observer.onNotification(JSON.parse(n))},onTrackAdd:n=>{l.d(I,"[Subscribe] onTrackAdd",`${n}`),this.observer.onTrackAdd(n)},onTrackRemove:n=>{l.d(I,"[Subscribe] onTrackRemove",`${n}`),this.observer.onTrackRemove(n)},onIceConnectionChange:n=>c(this,null,function*(){var d;if(e(1,n,!0),n==="connected"){let u=this.callbacks.get(nt);this.callbacks.delete(nt),(d=this.connectivityListener)==null||d.onICESuccess(!1),u&&u.promise.resolve(!0)}}),onConnectionStateChange:n=>c(this,null,function*(){var d,u,p,m,T,g,f;if(e(1,n,!1),n==="failed")yield this.handleIceConnectionFailure(1,S.WebrtcErrors.ICEFailure("SUBSCRIBE",`local candidate - ${(p=(u=(d=this.subscribeConnection)==null?void 0:d.selectedCandidatePair)==null?void 0:u.local)==null?void 0:p.candidate}; remote candidate - ${(g=(T=(m=this.subscribeConnection)==null?void 0:m.selectedCandidatePair)==null?void 0:T.remote)==null?void 0:g.candidate}`));else if(n==="disconnected")setTimeout(()=>{var E,v,R,$,ue,ve,pe;((E=this.subscribeConnection)==null?void 0:E.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 - ${(pe=(ve=(ue=this.subscribeConnection)==null?void 0:ue.selectedCandidatePair)==null?void 0:ve.remote)==null?void 0:pe.candidate}`))},5e3);else if(n==="connected"){(f=this.subscribeConnection)==null||f.handleSelectedIceCandidatePairs();let E=this.callbacks.get(nt);this.callbacks.delete(nt),E&&E.promise.resolve(!0)}}),onIceCandidate:n=>{var d;(d=this.connectivityListener)==null||d.onICECandidate(n,!1)},onSelectedCandidatePairChange:n=>{var d;(d=this.connectivityListener)==null||d.onSelectedICECandidatePairChange(n,!1)}};this.publishConnection||(this.publishConnection=new ni(this.signal,this.initConfig.rtcConfiguration,s)),this.subscribeConnection||(this.subscribeConnection=new di(this.signal,this.initConfig.rtcConfiguration,this.isFlagEnabled.bind(this),o))}(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(o){l.e(I,"Join negotiation failed \u274C",o);let n=o instanceof k?o:S.WebsocketMethodErrors.ServerErrors(500,"JOIN",`Websocket join error - ${o.message}`),d=parseInt(`${n.code/100}`)===5||[P.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,429].includes(n.code);if(n.code===410&&(n.isTerminal=!0),d){this.joinRetryCount=0,n.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:n,task:u,originalState:"Joined",changeState:!1})}else throw o}})}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(l.d(I,"\u23F3 join: Negotiating over PUBLISH connection"),!this.publishConnection)return l.e(I,"Publish peer connection not found, cannot negotiate"),!1;let s=yield this.publishConnection.createOffer();yield this.publishConnection.setLocalDescription(s);let o=this.isFlagEnabled("subscribeDegradation"),n=this.isFlagEnabled("simulcast"),d=this.isFlagEnabled("onDemandTracks"),u=yield this.signal.join(e,t,!i,o,n,d,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}){l.d(I,"\u23F3 join: Negotiating Non-WebRTC");let s=this.isFlagEnabled("subscribeDegradation"),o=this.isFlagEnabled("simulcast"),n=this.isFlagEnabled("onDemandTracks"),d=yield this.signal.join(e,t,!i,s,o,n);return this.setSFUNodeId(d==null?void 0:d.sfu_node_id),!!d})}negotiateOnFirstPublish(){return c(this,null,function*(){if(l.d(I,"\u23F3 Negotiating offer over PUBLISH connection"),!this.publishConnection)return l.e(I,"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*(){l.d(I,"\u23F3 [role=PUBLISH] onRenegotiationNeeded START",this.trackStates);let t=this.callbacks.get(ot);if(!t){l.w(I,"no callback found for renegotiation");return}if(!this.publishConnection){l.e(I,"Publish peer connection not found, cannot renegotiate");return}try{let i=yield this.publishConnection.createOffer(this.trackStates,e);yield this.publishConnection.setLocalDescription(i),l.time("renegotiation-offer-exchange");let r=yield this.signal.offer(i,this.trackStates);this.callbacks.delete(ot),l.timeEnd("renegotiation-offer-exchange"),yield this.publishConnection.setRemoteDescription(r),t.promise.resolve(!0),l.d(I,"[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),l.d(I,"[role=PUBLISH] onRenegotiationNeeded FAILED \u274C")}})}handleIceConnectionFailure(e,t){return c(this,null,function*(){this.retryScheduler.isTaskInProgress(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 o,n,d;l.d(I,"connect: started \u23F0");let s=new Date;try{this.analyticsTimer.start("init_response_time"),this.initConfig=yield li.fetchInitConfig({token:e,peerId:i,userAgent:this.store.getUserAgent(),initEndpoint:t,iceServers:r}),(o=this.connectivityListener)==null||o.onInitSuccess(this.initConfig.endpoint);let u=this.store.getRoom();return u&&(u.effectsKey=(n=this.initConfig.config.vb)==null?void 0:n.effectsKey,u.isEffectsEnabled=this.isFlagEnabled("effectsSDKEnabled"),u.disableNoneLayerRequest=this.isFlagEnabled("disableNoneLayerRequest"),u.isVBEnabled=this.isFlagEnabled("vb"),u.isHipaaEnabled=this.isFlagEnabled("hipaa"),u.isNoiseCancellationEnabled=this.isFlagEnabled("noiseCancellation")),this.analyticsTimer.end("init_response_time"),Ce.setWebsocketEndpoint(this.initConfig.endpoint),this.validateNotDisconnected("post init"),yield this.openSignal(e,i),this.observer.onConnected(),(d=this.connectivityListener)==null||d.onSignallingSuccess(),this.store.setSimulcastEnabled(this.isFlagEnabled("simulcast")),l.d(I,"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)),l.e(I,"\u274C internal connect: failed",u),u}})}validateNotDisconnected(e){if(this.state==="Disconnected")throw l.w(I,"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");l.d(I,"\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",La),i.searchParams.set("protocol_spec",Da),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"),l.d(I,"\u2705 internal connect: connected to ws endpoint")})}initStatsAnalytics(){var e,t;this.isFlagEnabled("publishStats")&&(this.publishStatsAnalytics=new si(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 ai(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 o,n,d,u,p,m,T,g;let e=wo(),t=typeof document!="undefined"&&document.hidden,i=this.store.getRemoteVideoTracks().filter(f=>f.degraded).length,r=(u=(d=(n=(o=this.getWebrtcInternals())==null?void 0:o.getCurrentStats())==null?void 0:n.getLocalPeerStats())==null?void 0:d.publish)==null?void 0:u.bitrate,s=(g=(T=(m=(p=this.getWebrtcInternals())==null?void 0:p.getCurrentStats())==null?void 0:m.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 Nr(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 No={published:!1,isInitialised:!1,isReconnecting:!1,isPreviewInProgress:!1,isPreviewCalled:!1,isJoinInProgress:!1,deviceManagersInitialised:!1},Or=class{constructor(){this.TAG="[HMSSdk]:";this.transportState="Disconnected";this.analyticsTimer=new Di;this.sdkState=h({},No);this.isDiagnostics=!1;this.playlistSettings={video:{bitrate:cs},audio:{bitrate:ds}};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=o=>c(this,null,function*(){var n,d;yield this.internalLeave(!0,o),!this.sdkState.isPreviewInProgress&&!this.sdkState.isJoinInProgress&&((d=(n=this.errorListener)==null?void 0:n.onError)==null||d.call(n,o)),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,l.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.handleDeviceChange=e=>{var i,r;if(e.isUserSelection)return;l.d(this.TAG,"Device Change event",e),(r=(i=this.deviceChangeListener)==null?void 0:i.onDeviceChange)==null||r.call(i,e),(()=>{var s,o,n,d;if(e.error&&e.type){let u=e.type.includes("audio")?(s=this.localPeer)==null?void 0:s.audioTrack:(o=this.localPeer)==null?void 0:o.videoTrack;(n=this.errorListener)==null||n.onError(e.error),[P.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,P.TracksErrors.DEVICE_IN_USE,P.TracksErrors.DEVICE_NOT_AVAILABLE].includes(e.error.code)&&u&&(u.setEnabled(!1),(d=this.listener)==null||d.onTrackUpdate(2,u,this.localPeer))}})()};this.handleAudioPluginError=e=>{var t;l.e(this.TAG,"Audio Plugin Error event",e),(t=this.errorListener)==null||t.onError(e)};this.handleError=e=>{var t;l.e(this.TAG,e),(t=this.errorListener)==null||t.onError(e)};this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){var r;this.deviceManager.currentSelection=this.deviceManager.getCurrentSelection(),yield this.transport.handleLocalRoleUpdate({oldRole:e,newRole:t}),yield(r=this.roleChangeManager)==null?void 0:r.handleLocalPeerRoleUpdate({oldRole:e,newRole:t}),yield this.interactivityCenter.whiteboard.handleLocalRoleUpdate()});this.unpauseRemoteVideoTracks=()=>{this.store.getRemoteVideoTracks().forEach(e=>e.handleTrackUnmute())};this.sendAudioPresenceFailed=()=>{var t;let e=S.TracksErrors.NoAudioDetected("PREVIEW");l.w(this.TAG,"Audio Presence Failure",this.transportState,e),this.isDiagnostics&&((t=this.listener)==null||t.onError(e))};this.sendJoinAnalyticsEvent=(e=!1,t)=>{this.eventBus.analytics.publish(y.join(M(h({error:t},this.analyticsTimer.getTimes()),{time:this.analyticsTimer.getTimeTaken("join_time"),is_preview_called:e,retries_join:this.transport.joinRetryCount})))};this.sendPreviewAnalyticsEvent=e=>{this.eventBus.analytics.publish(y.preview(M(h({error:e},this.analyticsTimer.getTimes()),{time:this.analyticsTimer.getTimeTaken("preview_time")})))};this.sendAnalyticsEvent=e=>{this.isDiagnostics||this.analyticsEventsService.queue(e).flush()}}setSessionPeerInfo(e,t){var r,s,o,n;let i=this.store.getRoom();if(!t||!i){l.e(this.TAG,"setSessionPeerInfo> Local peer or room is undefined");return}this.sessionPeerInfo={peer:{peer_id:t.peerId,role:(r=t.role)==null?void 0:r.name,joined_at:((s=t.joinedAt)==null?void 0:s.valueOf())||0,room_name:i.name,session_started_at:((o=i.startedAt)==null?void 0:o.valueOf())||0,user_data:t.customerUserId,user_name:t.name,template_id:i.templateId,session_id:i.sessionId,token:(n=this.store.getConfig())==null?void 0:n.authToken},agent:this.store.getUserAgent(),device_id:fi(),cluster:{websocket_url:e},timestamp:Date.now()}}initNotificationManager(){this.notificationManager||(this.notificationManager=new kr(this.store,this.eventBus,this.transport,this.listener,this.audioListener))}initStoreAndManagers(e){var t,i;if(this.listener=e,this.errorListener=e,this.deviceChangeListener=e,(t=this.store)==null||t.setErrorListener(this.errorListener),this.sdkState.isInitialised){(i=this.notificationManager)==null||i.setListener(this.listener),this.audioSinkManager.setListener(this.listener),this.interactivityCenter.setListener(this.listener),this.transport.setListener(this.listener);return}this.sdkState.isInitialised=!0,this.store=new Yt,this.store.setErrorListener(this.errorListener),this.eventBus=new mt,this.pluginUsageTracker=new or(this.eventBus),this.wakeLockManager=new sr,this.networkTestManager=new rr(this.eventBus,this.listener),this.playlistManager=new Vt(this,this.eventBus),this.deviceManager=new Zt(this.store,this.eventBus),this.audioSinkManager=new Xt(this.store,this.deviceManager,this.eventBus),this.audioOutput=new nr(this.deviceManager,this.audioSinkManager),this.audioSinkManager.setListener(this.listener),this.eventBus.autoplayError.subscribe(this.handleAutoplayError),this.localTrackManager=new Ie(this.store,this.observer,this.deviceManager,this.eventBus,this.analyticsTimer),this.analyticsEventsService=new ar(this.store),this.transport=new pi(this.observer,this.deviceManager,this.store,this.eventBus,this.analyticsEventsService,this.analyticsTimer,this.pluginUsageTracker),"onInitSuccess"in e&&this.transport.setConnectivityListener(e),this.sessionStore=new Er(this.transport),this.interactivityCenter=new ii(this.transport,this.store,this.listener),this.eventBus.analytics.subscribe(this.sendAnalyticsEvent),this.eventBus.deviceChange.subscribe(this.handleDeviceChange),this.eventBus.localVideoUnmutedNatively.subscribe(this.unpauseRemoteVideoTracks),this.eventBus.localAudioUnmutedNatively.subscribe(this.unpauseRemoteVideoTracks),this.eventBus.audioPluginFailed.subscribe(this.handleAudioPluginError),this.eventBus.error.subscribe(this.handleError)}validateJoined(e){if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION",`Not connected - ${e}`)}sendHLSAnalytics(e){this.sendAnalyticsEvent(y.hlsPlayerError(e))}refreshDevices(){return c(this,null,function*(){this.validateJoined("refreshDevices"),yield this.deviceManager.init(!0)})}getWebrtcInternals(){var e;return(e=this.transport)==null?void 0:e.getWebrtcInternals()}getDebugInfo(){var r;if(!this.transport)throw l.e(this.TAG,"Transport is not defined"),new Error("getDebugInfo can only be called after join");let e=this.transport.getWebsocketEndpoint(),t=Object.values(Bs).filter(s=>this.transport.isFlagEnabled(s)),i=(r=this.store.getConfig())==null?void 0:r.initEndpoint;return{websocketURL:e,enabledFlags:t,initEndpoint:i}}getSessionStore(){return this.sessionStore}getPlaylistManager(){return this.playlistManager}getRecordingState(){var e;return(e=this.store.getRoom())==null?void 0:e.recording}getRTMPState(){var e;return(e=this.store.getRoom())==null?void 0:e.rtmp}getHLSState(){var e;return(e=this.store.getRoom())==null?void 0:e.hls}getTranscriptionState(){var e;return(e=this.store.getRoom())==null?void 0:e.transcriptions}getTemplateAppData(){return this.store.getTemplateAppData()}getInteractivityCenter(){return this.interactivityCenter}getPeerListIterator(e){return new xi(this.transport,this.store,e)}updatePlaylistSettings(e){e.video&&Object.assign(this.playlistSettings.video,e.video),e.audio&&Object.assign(this.playlistSettings.audio,e.audio)}get localPeer(){var e;return(e=this.store)==null?void 0:e.getLocalPeer()}preview(e,t){return c(this,null,function*(){if(Ct(),Ht(),this.sdkState.isPreviewInProgress)return Promise.reject(S.GenericErrors.PreviewAlreadyInProgress("PREVIEW","Preview already called"));if(["Joined","Reconnecting"].includes(this.transportState))return this.midCallPreview(e.asRole,e.settings);this.analyticsTimer.start("preview_time"),this.setUpPreview(e,t);let i=!1,r=!1,s=setTimeout(()=>{var o,n;(!i||!r)&&((n=(o=this.listener)==null?void 0:o.onNetworkQuality)==null||n.call(o,-1))},3e3);return new Promise((o,n)=>{let d=()=>c(this,null,function*(){var m;if(this.localPeer){let T=e.asRole&&this.store.getPolicyForRole(e.asRole);this.localPeer.asRole=T||this.localPeer.role}let u=yield this.localTrackManager.getTracksToPublish(e.settings);u.forEach(T=>{var g;if(this.setLocalPeerTrack(T),T.isTrackNotPublishing()){let f=S.TracksErrors.NoDataInTrack(`${T.type} track has no data. muted: ${T.nativeTrack.muted}, readyState: ${T.nativeTrack.readyState}`);l.e(this.TAG,f),this.sendAnalyticsEvent(y.publish({devices:this.deviceManager.getDevices(),error:f})),(g=this.listener)==null||g.onError(f)}}),(m=this.localPeer)!=null&&m.audioTrack&&this.initPreviewTrackAudioLevelMonitor(),yield this.initDeviceManagers(),this.sdkState.isPreviewInProgress=!1,this.analyticsTimer.end("preview_time");let p=this.store.getRoom();p&&t.onPreview(p,u),this.sendPreviewAnalyticsEvent(),o()});this.eventBus.policyChange.subscribeOnce(d),this.eventBus.leave.subscribeOnce(this.handlePreviewError),this.eventBus.leave.subscribeOnce(u=>n(u)),this.transport.preview(e.authToken,e.initEndpoint,this.localPeer.peerId,{name:e.userName,metaData:e.metaData||""},e.autoVideoSubscribe,e.iceServers).then(u=>{var p;i=!0,clearTimeout(s),u&&e.captureNetworkQualityInPreview&&this.networkTestManager.start((p=u.config)==null?void 0:p.networkHealth).then(()=>{r=!0})}).catch(u=>{this.handlePreviewError(u),n(u)})})})}midCallPreview(e,t){return c(this,null,function*(){var s,o;if(!this.localPeer||this.transportState!=="Joined")throw S.GenericErrors.NotConnected("VALIDATION","Not connected - midCallPreview");let i=e&&this.store.getPolicyForRole(e);if(!i)throw S.GenericErrors.InvalidRole("PREVIEW",`role ${e} does not exist in policy`);this.localPeer.asRole=i;let r=yield this.localTrackManager.getTracksToPublish(t);r.forEach(n=>this.setLocalPeerTrack(n)),(s=this.localPeer)!=null&&s.audioTrack&&this.initPreviewTrackAudioLevelMonitor(),yield this.initDeviceManagers(),(o=this.listener)==null||o.onPreview(this.store.getRoom(),r)})}cancelMidCallPreview(){return c(this,null,function*(){var e,t,i;if((!this.localPeer||!this.localPeer.isInPreview())&&l.w(this.TAG,"Cannot cancel mid call preview as preview is not in progress"),(e=this.localPeer)!=null&&e.asRole&&this.localPeer.role){let r=this.localPeer.asRole,s=this.localPeer.role;delete this.localPeer.asRole,yield(t=this.roleChangeManager)==null?void 0:t.diffRolesAndPublishTracks({oldRole:r,newRole:s}),(i=this.listener)==null||i.onPeerUpdate(8,this.localPeer)}})}join(e,t){return c(this,null,function*(){var d,u,p,m,T,g,f,E;if(Ct(),Ht(),this.sdkState.isPreviewInProgress)throw S.GenericErrors.NotReady("JOIN","Preview is in progress, can't join");(u=(d=this.eventBus)==null?void 0:d.leave)==null||u.unsubscribe(this.handlePreviewError),this.analyticsTimer.start("join_time"),this.sdkState.isJoinInProgress=!0;let{roomId:i,userId:r,role:s}=Nr(e.authToken),o=((m=(p=this.localPeer)==null?void 0:p.asRole)==null?void 0:m.name)||((g=(T=this.localPeer)==null?void 0:T.role)==null?void 0:g.name);(f=this.networkTestManager)==null||f.stop(),this.commonSetup(e,i,t),this.removeDevicesFromConfig(e),this.store.setConfig(e),this.store.createAndSetUserAgent(this.frameworkInfo),de.resumeContext();let n=this.store.getConfig();n!=null&&n.autoManageWakeLock&&this.wakeLockManager.acquireLock(),this.localPeer?(this.localPeer.name=e.userName,this.localPeer.role=this.store.getPolicyForRole(s),this.localPeer.customerUserId=r,this.localPeer.metadata=e.metaData,delete this.localPeer.asRole):this.createAndAddLocalPeerToStore(e,s,r),this.roleChangeManager=new Qt(this.store,this.transport,this.deviceManager,this.getAndPublishTracks.bind(this),this.removeTrack.bind(this),this.listener),this.eventBus.localRoleUpdate.subscribe(this.handleLocalRoleUpdate),l.d(this.TAG,`\u23F3 Joining room ${i}`),l.time(`join-room-${i}`);try{yield this.transport.join(e.authToken,this.localPeer.peerId,{name:e.userName,metaData:e.metaData},e.initEndpoint,e.autoVideoSubscribe,e.iceServers),l.d(this.TAG,`\u2705 Joined room ${i}`),this.analyticsTimer.start("peer_list_time"),yield this.notifyJoin(),this.sdkState.isJoinInProgress=!1,yield this.publish(e.settings,o),yield this.deviceManager.autoSelectAudioOutput()}catch(v){throw this.analyticsTimer.end("join_time"),this.sdkState.isJoinInProgress=!1,(E=this.listener)==null||E.onError(v),this.sendJoinAnalyticsEvent(this.sdkState.isPreviewCalled,v),l.e(this.TAG,"Unable to join room",v),v}l.timeEnd(`join-room-${i}`)})}stringifyMetadata(e){e.metaData&&typeof e.metaData!="string"?e.metaData=JSON.stringify(e.metaData):e.metaData||(e.metaData="")}cleanup(){var e,t,i;this.cleanDeviceManagers(),this.eventBus.analytics.unsubscribe(this.sendAnalyticsEvent),this.eventBus.localVideoUnmutedNatively.unsubscribe(this.unpauseRemoteVideoTracks),this.eventBus.localAudioUnmutedNatively.unsubscribe(this.unpauseRemoteVideoTracks),this.eventBus.error.unsubscribe(this.handleError),this.analyticsTimer.cleanup(),Z.cleanup(),this.playlistManager.cleanup(),(e=this.wakeLockManager)==null||e.cleanup(),Ie.cleanup(),this.notificationManager=void 0,l.cleanup(),this.sdkState=h({},No),this.localPeer&&((t=this.localPeer.audioTrack)==null||t.cleanup(),this.localPeer.audioTrack=void 0,(i=this.localPeer.videoTrack)==null||i.cleanup(),this.localPeer.videoTrack=void 0),this.store.cleanup(),this.listener=void 0,this.roleChangeManager&&this.eventBus.localRoleUpdate.unsubscribe(this.handleLocalRoleUpdate)}leave(e){return this.internalLeave(e)}internalLeave(e=!0,t){return c(this,null,function*(){var r,s,o,n;let i=(r=this.store)==null?void 0:r.getRoom();if(i){for(;(this.sdkState.isPreviewInProgress||this.sdkState.isJoinInProgress)&&!(t!=null&&t.isTerminal);)yield Be(100);let d=i.id;this.setSessionPeerInfo(this.transport.getWebsocketEndpoint()||"",this.localPeer),(s=this.networkTestManager)==null||s.stop(),this.eventBus.leave.publish(t);let u=(o=this.localPeer)==null?void 0:o.peerId;l.d(this.TAG,`\u23F3 Leaving room ${d}, peerId=${u}`),yield(n=this.transport)==null?void 0:n.leave(e,t?"sdk request":"user request"),this.cleanup(),l.d(this.TAG,`\u2705 Left room ${d}, peerId=${u}`)}})}getAuthTokenByRoomCode(e,t){return c(this,null,function*(){let i=(t||{}).endpoint||"https://auth.100ms.live/v2/token";this.analyticsTimer.start("GET_TOKEN");let r=yield er(i,{method:"POST",body:JSON.stringify({code:e.roomCode,user_id:e.userId})},[429,500,501,502,503,504,505,506,507,508,509,510,511]),s=yield r.json();if(this.analyticsTimer.end("GET_TOKEN"),!r.ok)throw S.APIErrors.ServerErrors(s.code,"GET_TOKEN",s.message,!1);let{token:o}=s;if(!o)throw Error(s.message);return o})}getLocalPeer(){return this.store.getLocalPeer()}getPeers(){return this.store.getPeers()}getPeerMap(){return this.store.getPeerMap()}getAudioOutput(){return this.audioOutput}sendMessage(e,t){this.sendMessageInternal({message:t,type:e})}sendBroadcastMessage(e,t){return c(this,null,function*(){return yield this.sendMessageInternal({message:e,type:t})})}sendGroupMessage(e,t,i){return c(this,null,function*(){let r=this.store.getKnownRoles();if((t.filter(o=>r[o.name])||[]).length===0)throw S.GenericErrors.ValidationFailed("No valid role is present",t);return yield this.sendMessageInternal({message:e,recipientRoles:t,type:i})})}sendDirectMessage(e,t,i){return c(this,null,function*(){var o,n;if(((o=this.localPeer)==null?void 0:o.peerId)===t)throw S.GenericErrors.ValidationFailed("Cannot send message to self");let r=!!((n=this.store.getRoom())!=null&&n.large_room_optimization),s=this.store.getPeerById(t);if(!s)if(r){let d=yield this.transport.signal.getPeer({peer_id:t});if(!d)throw S.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);s=Ee(d,this.store)}else throw S.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);return yield this.sendMessageInternal({message:e,recipientPeer:s,type:i})})}submitSessionFeedback(e,t){return c(this,null,function*(){if(!this.sessionPeerInfo)throw l.e(this.TAG,"submitSessionFeedback> session is undefined"),new Error("session is undefined");let i=this.sessionPeerInfo.peer.token;if(!i)throw l.e(this.TAG,"submitSessionFeedback> token is undefined"),new Error("Internal error, token is not present");try{yield ei.sendFeedback({token:i,info:this.sessionPeerInfo,feedback:e,eventEndpoint:t}),l.i(this.TAG,"submitSessionFeedback> submitted feedback"),this.sessionPeerInfo=void 0}catch(r){throw l.e(this.TAG,"submitSessionFeedback> error occured ",r),new Error("Unable to submit feedback")}})}getPeer(e){return c(this,null,function*(){let t=yield this.transport.signal.getPeer({peer_id:e});if(t)return Ee(t,this.store)})}findPeerByName(r){return c(this,arguments,function*({query:e,limit:t=10,offset:i}){let{peers:s,offset:o,eof:n}=yield this.transport.signal.findPeerByName({query:e==null?void 0:e.toLowerCase(),limit:t,offset:i});return s.length>0?{offset:o,eof:n,peers:s.map(d=>Ee({peer_id:d.peer_id,role:d.role,groups:[],info:{name:d.name,data:"",user_id:"",type:d.type}},this.store))}:{offset:o,peers:[]}})}sendMessageInternal(s){return c(this,arguments,function*({recipientRoles:e,recipientPeer:t,type:i="chat",message:r}){if(r.replace(/\u200b/g," ").trim()==="")throw l.w(this.TAG,"sendMessage","Ignoring empty message send"),S.GenericErrors.ValidationFailed("Empty message not allowed");let o={info:{message:r,type:i}};return e!=null&&e.length&&(o.roles=e.map(n=>n.name)),t!=null&&t.peerId&&(o.peer_id=t.peerId),l.d(this.TAG,"Sending Message: ",o),yield this.transport.signal.broadcast(o)})}startScreenShare(e,t){return c(this,null,function*(){var n,d,u;let i=this.store.getPublishParams();if(!i)return;let{allowed:r}=i;if(!(r&&r.includes("screen"))){l.e(this.TAG,`Role ${(n=this.localPeer)==null?void 0:n.role} cannot share screen`);return}if((u=(d=this.localPeer)==null?void 0:d.auxiliaryTracks)!=null&&u.find(p=>p.source==="screen"))throw Error("Cannot share multiple screens");let o=yield this.getScreenshareTracks(e,t);if(!this.localPeer){l.d(this.TAG,"Screenshared when not connected"),o.forEach(p=>{p.cleanup()});return}this.transport.setOnScreenshareStop(()=>{this.stopEndedScreenshare(e)}),yield this.transport.publish(o),o.forEach(p=>{var m,T,g;p.peerId=(m=this.localPeer)==null?void 0:m.peerId,(T=this.localPeer)==null||T.auxiliaryTracks.push(p),(g=this.listener)==null||g.onTrackUpdate(0,p,this.localPeer)})})}stopEndedScreenshare(e){return c(this,null,function*(){l.d(this.TAG,"\u2705 Screenshare ended natively"),yield this.stopScreenShare(),e()})}stopScreenShare(){return c(this,null,function*(){var t;l.d(this.TAG,"\u2705 Screenshare ended from app");let e=(t=this.localPeer)==null?void 0:t.auxiliaryTracks.filter(i=>i.source==="screen");if(e)for(let i of e)yield this.removeTrack(i.trackId)})}addTrack(e,t="regular"){return c(this,null,function*(){var u,p,m,T;if(!e){l.w(this.TAG,"Please pass a valid MediaStreamTrack");return}if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot addTrack");if(this.localPeer.auxiliaryTracks.find(g=>g.trackId===e.id))return;let r=e.kind,s=new MediaStream([e]),o=new ge(s),n=r==="audio"?le:G,d=new n(o,e,t,this.eventBus);yield this.applySettings(d),yield this.setPlaylistSettings({track:e,hmsTrack:d,source:t}),yield(u=this.transport)==null?void 0:u.publish([d]),d.peerId=(p=this.localPeer)==null?void 0:p.peerId,(m=this.localPeer)==null||m.auxiliaryTracks.push(d),(T=this.listener)==null||T.onTrackUpdate(0,d,this.localPeer)})}removeTrack(e,t=!1){return c(this,null,function*(){var r;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot removeTrack");let i=this.localPeer.auxiliaryTracks.findIndex(s=>s.trackId===e);if(i>-1){let s=this.localPeer.auxiliaryTracks[i];s.isPublished?yield this.transport.unpublish([s]):yield s.cleanup(),t||this.stopPlaylist(s),this.localPeer.auxiliaryTracks.splice(i,1),(r=this.listener)==null||r.onTrackUpdate(1,s,this.localPeer)}else l.w(this.TAG,`No track found for ${e}`)})}setAnalyticsLevel(e){this.analyticsEventsService.level=e}setLogLevel(e){l.level=e}addAudioListener(e){var t;this.audioListener=e,(t=this.notificationManager)==null||t.setAudioListener(e)}addConnectionQualityListener(e){var t;(t=this.notificationManager)==null||t.setConnectionQualityListener(e)}setIsDiagnostics(e){this.isDiagnostics=e}changeRole(e,t,i=!1){return c(this,null,function*(){var r;yield(r=this.transport)==null?void 0:r.signal.requestRoleChange({requested_for:e,role:t,force:i})})}changeRoleOfPeer(e,t,i=!1){return c(this,null,function*(){var r;yield(r=this.transport)==null?void 0:r.signal.requestRoleChange({requested_for:e,role:t,force:i})})}changeRoleOfPeersWithRoles(e,t){return c(this,null,function*(){var i;e.length<=0||!t||(yield(i=this.transport)==null?void 0:i.signal.requestBulkRoleChange({roles:e.map(r=>r.name),role:t,force:!0}))})}acceptChangeRole(e){return c(this,null,function*(){var t,i;yield(i=this.transport)==null?void 0:i.signal.acceptRoleChangeRequest({requested_by:(t=e.requestedBy)==null?void 0:t.peerId,role:e.role.name,token:e.token})})}endRoom(e,t){return c(this,null,function*(){var i;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot end room");yield(i=this.transport)==null?void 0:i.signal.endRoom(e,t),yield this.leave()})}removePeer(e,t){return c(this,null,function*(){var i;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot remove peer");yield(i=this.transport)==null?void 0:i.signal.removePeer({requested_for:e,reason:t})})}startRTMPOrRecording(e){return c(this,null,function*(){var i,r;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot start streaming or recording");let t={meeting_url:e.meetingURL,record:e.record};(i=e.rtmpURLs)!=null&&i.length&&(t.rtmp_urls=e.rtmpURLs),e.resolution&&(t.resolution=e.resolution),yield(r=this.transport)==null?void 0:r.signal.startRTMPOrRecording(t)})}stopRTMPAndRecording(){return c(this,null,function*(){var e;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot stop streaming or recording");yield(e=this.transport)==null?void 0:e.signal.stopRTMPAndRecording()})}startHLSStreaming(e){return c(this,null,function*(){var i;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot start HLS streaming");let t={};e&&e.variants&&e.variants.length>0&&(t.variants=e.variants.map(r=>{let s={meeting_url:r.meetingURL};return r.metadata&&(s.metadata=r.metadata),s})),e!=null&&e.recording&&(t.hls_recording={single_file_per_layer:e.recording.singleFilePerLayer,hls_vod:e.recording.hlsVod}),yield(i=this.transport)==null?void 0:i.signal.startHLSStreaming(t)})}stopHLSStreaming(e){return c(this,null,function*(){var t,i,r;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot stop HLS streaming");if(e){let s={variants:(t=e==null?void 0:e.variants)==null?void 0:t.map(o=>{let n={meeting_url:o.meetingURL};return o.metadata&&(n.metadata=o.metadata),n})};yield(i=this.transport)==null?void 0:i.signal.stopHLSStreaming(s)}yield(r=this.transport)==null?void 0:r.signal.stopHLSStreaming()})}startTranscription(e){return c(this,null,function*(){var i;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot start transcriptions");let t={mode:e.mode};yield(i=this.transport)==null?void 0:i.signal.startTranscription(t)})}stopTranscription(e){return c(this,null,function*(){var i;if(!this.localPeer)throw S.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot stop transcriptions");if(!e)throw S.GenericErrors.Signalling("VALIDATION","No mode is passed to stop the transcription");let t={mode:e.mode};yield(i=this.transport)==null?void 0:i.signal.stopTranscription(t)})}sendHLSTimedMetadata(e){return c(this,null,function*(){var t;if(this.validateJoined("sendHLSTimedMetadata"),e.length>0){let i={metadata_objs:e};yield(t=this.transport)==null?void 0:t.signal.sendHLSTimedMetadata(i)}})}changeName(e){return c(this,null,function*(){var i,r;this.validateJoined("changeName");let t=this.store.getLocalPeer();t&&t.name!==e&&(yield(i=this.transport)==null?void 0:i.signal.updatePeer({name:e}),(r=this.notificationManager)==null||r.updateLocalPeer({name:e}))})}changeMetadata(e){return c(this,null,function*(){var t,i;this.validateJoined("changeMetadata"),yield(t=this.transport)==null?void 0:t.signal.updatePeer({data:e}),(i=this.notificationManager)==null||i.updateLocalPeer({metadata:e})})}setSessionMetadata(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.setSessionMetadata({key:"default",data:e})})}getSessionMetadata(){return c(this,null,function*(){var t;return(yield(t=this.transport)==null?void 0:t.signal.getSessionMetadata("default")).data})}getRoles(){return Object.values(this.store.getKnownRoles())}changeTrackState(e,t){return c(this,null,function*(){var r;if(e.type==="video"&&e.source!=="regular"){l.w(this.TAG,"Muting non-regular video tracks is currently not supported");return}if(e.enabled===t){l.w(this.TAG,`Aborting change track state, track already has enabled - ${t}`,e);return}if(!this.store.getTrackById(e.trackId))throw S.GenericErrors.ValidationFailed("No track found for change track state",e);let i=this.store.getPeerByTrackId(e.trackId);if(!i)throw S.GenericErrors.ValidationFailed("No peer found for change track state",e);yield(r=this.transport)==null?void 0:r.signal.requestTrackStateChange({requested_for:i.peerId,track_id:e.trackId,stream_id:e.stream.id,mute:!t})})}changeMultiTrackState(e){return c(this,null,function*(){var o;if(typeof e.enabled!="boolean")throw S.GenericErrors.ValidationFailed("Pass a boolean for enabled");let{enabled:t,roles:i,type:r,source:s}=e;yield(o=this.transport)==null?void 0:o.signal.requestMultiTrackStateChange({value:!t,type:r,source:s,roles:i==null?void 0:i.map(n=>n==null?void 0:n.name)})})}raiseLocalPeerHand(){return c(this,null,function*(){var e;this.validateJoined("raiseLocalPeerHand"),yield(e=this.transport)==null?void 0:e.signal.joinGroup(Re)})}lowerLocalPeerHand(){return c(this,null,function*(){var e;this.validateJoined("lowerLocalPeerHand"),yield(e=this.transport)==null?void 0:e.signal.leaveGroup(Re)})}raiseRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.addToGroup(e,Re)})}lowerRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.removeFromGroup(e,Re)})}setFrameworkInfo(e){this.frameworkInfo=h(h({},this.frameworkInfo),e)}attachVideo(e,t){return c(this,null,function*(){let i=this.store.getConfig();i!=null&&i.autoManageVideo?e.attach(t):yield e.addSink(t)})}detachVideo(e,t){return c(this,null,function*(){let i=this.store.getConfig();i!=null&&i.autoManageVideo?e.detach(t):yield e.removeSink(t)})}publish(e,t){return c(this,null,function*(){var i,r,s;if([this.store.getPublishParams(),!this.sdkState.published,!$e].every(o=>!!o)){let o=t&&t!==((r=(i=this.localPeer)==null?void 0:i.role)==null?void 0:r.name)?()=>{var n;return(n=this.roleChangeManager)==null?void 0:n.diffRolesAndPublishTracks({oldRole:this.store.getPolicyForRole(t),newRole:this.localPeer.role})}:()=>this.getAndPublishTracks(e);yield(s=o==null?void 0:o())==null?void 0:s.catch(n=>{var d;l.e(this.TAG,"Error in publish",n),(d=this.listener)==null||d.onError(n)})}})}getAndPublishTracks(e){return c(this,null,function*(){var i,r;let t=yield this.localTrackManager.getTracksToPublish(e);yield this.setAndPublishTracks(t),(r=(i=this.localPeer)==null?void 0:i.audioTrack)==null||r.initAudioLevelMonitor(),this.sdkState.published=!0})}setAndPublishTracks(e){return c(this,null,function*(){var t,i;for(let r of e){if(yield this.transport.publish([r]),r.isTrackNotPublishing()){let s=S.TracksErrors.NoDataInTrack(`${r.type} track has no data. muted: ${r.nativeTrack.muted}, readyState: ${r.nativeTrack.readyState}`);l.e(this.TAG,s),this.sendAnalyticsEvent(y.publish({devices:this.deviceManager.getDevices(),error:s})),(t=this.listener)==null||t.onError(s)}this.setLocalPeerTrack(r),(i=this.listener)==null||i.onTrackUpdate(0,r,this.localPeer)}yield this.initDeviceManagers()})}setLocalPeerTrack(e){var t;switch(e.peerId=(t=this.localPeer)==null?void 0:t.peerId,e.type){case"audio":this.localPeer.audioTrack=e;break;case"video":this.localPeer.videoTrack=e;break}}initDeviceManagers(){return c(this,null,function*(){var e,t,i,r,s;this.sdkState.deviceManagersInitialised||(this.sdkState.deviceManagersInitialised=!0,yield this.deviceManager.init(),(yield this.deviceManager.updateOutputDevice((t=(e=this.store.getConfig())==null?void 0:e.settings)==null?void 0:t.audioOutputDeviceId))||(yield this.deviceManager.updateOutputDevice((r=(i=Z.getSelection())==null?void 0:i.audioOutput)==null?void 0:r.deviceId)),this.audioSinkManager.init((s=this.store.getConfig())==null?void 0:s.audioSinkElementId))})}cleanDeviceManagers(){this.eventBus.deviceChange.unsubscribe(this.handleDeviceChange),this.eventBus.audioPluginFailed.unsubscribe(this.handleAudioPluginError),this.eventBus.autoplayError.unsubscribe(this.handleAutoplayError),this.deviceManager.cleanup(),this.audioSinkManager.cleanup()}initPreviewTrackAudioLevelMonitor(){var t;let e=(t=this.localPeer)==null?void 0:t.audioTrack;e==null||e.initAudioLevelMonitor(),this.eventBus.trackAudioLevelUpdate.subscribe(i=>{var s;let r=i&&i.track.trackId===(e==null?void 0:e.trackId)?[{audioLevel:i.audioLevel,peer:this.localPeer,track:e}]:[];this.store.updateSpeakers(r),(s=this.audioListener)==null||s.onAudioLevelUpdate(r)}),this.eventBus.localAudioSilence.subscribe(this.sendAudioPresenceFailed)}notifyJoin(){var i;let e=this.store.getLocalPeer(),t=this.store.getRoom();if(!t){l.w(this.TAG,"notify join - room not present");return}if(t.joinedAt=new Date,e&&(e.joinedAt=t.joinedAt),e!=null&&e.role){this.analyticsTimer.end("join_time"),(i=this.listener)==null||i.onJoin(t);return}return new Promise((r,s)=>{this.eventBus.policyChange.subscribeOnce(()=>{var o;this.analyticsTimer.end("join_time"),(o=this.listener)==null||o.onJoin(t),r()}),this.eventBus.leave.subscribeOnce(o=>{s(o)})})}setUpPreview(e,t){this.sdkState.isPreviewCalled=!0,this.sdkState.isPreviewInProgress=!0;let{roomId:i,userId:r,role:s}=Nr(e.authToken);this.commonSetup(e,i,t),this.store.setConfig(e),this.store.createAndSetUserAgent(this.frameworkInfo),this.createAndAddLocalPeerToStore(e,s,r,e.asRole)}setPlaylistSettings(r){return c(this,arguments,function*({track:e,hmsTrack:t,source:i}){var s,o;if(i==="videoplaylist"){let n={};if(e.kind==="audio")n.maxBitrate=((s=this.playlistSettings.audio)==null?void 0:s.bitrate)||ds;else{n.maxBitrate=((o=this.playlistSettings.video)==null?void 0:o.bitrate)||cs;let{width:d,height:u}=e.getSettings();n.width=d,n.height=u}yield t.setSettings(n)}else i==="audioplaylist"&&(yield t.setSettings({maxBitrate:64}))})}createAndAddLocalPeerToStore(e,t,i,r){let s=this.store.getPolicyForRole(t),o=r?this.store.getPolicyForRole(r):void 0,n=new je({name:e.userName||"",customerUserId:i,metadata:e.metaData||"",role:s,asRole:o||s,type:"regular"});this.store.addPeer(n)}commonSetup(e,t,i){this.stringifyMetadata(e),e.initEndpoint||(e.initEndpoint="https://prod-init.100ms.live"),this.initStoreAndManagers(i),this.store.getRoom()||this.store.setRoom(new ze(t))}removeDevicesFromConfig(e){this.store.getConfig()&&e.settings&&(delete e.settings.audioOutputDeviceId,delete e.settings.videoDeviceId,delete e.settings.audioInputDeviceId)}getScreenshareTracks(e,t){return c(this,null,function*(){let i=this.transport.isFlagEnabled("scaleScreenshareBasedOnPixels"),[r,s]=yield this.localTrackManager.getLocalScreen(t,i),o=()=>{this.stopEndedScreenshare(e)},n=[];if(t!=null&&t.audioOnly){if(r.nativeTrack.stop(),!s)throw S.TracksErrors.NothingToReturn("TRACK","Select share audio when sharing screen","No audio found");n.push(s),s.nativeTrack.addEventListener("ended",o)}else n.push(r),r.nativeTrack.addEventListener("ended",o),s&&n.push(s);return n})}stopPlaylist(e){e.source==="audioplaylist"?this.playlistManager.stop("audio"):e.source==="videoplaylist"&&this.playlistManager.stop("video")}applySettings(e){return c(this,null,function*(){pa(this.store);let t=this.store.getPublishParams();if(t){if(e instanceof G){let i=e.source==="regular"?"video":e.source==="screen"?"screen":"";if(!i||!t.allowed.includes(i))return;let r=t[i];if(!r)return;let s=new j().codec(r.codec).maxBitrate(r.bitRate).maxFramerate(r.frameRate).setWidth(r.width).setHeight(r.height).build();yield e.setSettings(s)}else if(e instanceof le){if(!t.allowed.includes("audio"))return;let i=new K().codec(t.audio.codec).maxBitrate(t.audio.bitRate).build();yield e.setSettings(i)}}})}};var Xe=class a{constructor(e,t,i){this.getStats=()=>(this.stats||(this.stats=new vt(this.store,this.sdk)),this.stats);this.getDiagnosticsSDK=()=>(this.diagnostics||(this.diagnostics=this.actions.initDiagnostics()),this.diagnostics);e?this.store=e:this.store=a.createNewHMSStore(ir("HMSStore"),kt),i?this.notifications=i:this.notifications=new qi(this.store),t?this.actions=t:(this.sdk=new Or,this.actions=new tr(this.store,this.sdk,this.notifications)),this.actions.setFrameworkInfo({type:"js",sdkVersion:qr().version}),this.initialTriggerOnSubscribe=!1,U&&(window.__hms=this)}triggerOnSubscribe(){this.initialTriggerOnSubscribe||(a.makeStoreTriggerOnSubscribe(this.store),this.initialTriggerOnSubscribe=!0)}getStore(){return this.store}getHMSActions(){return this.actions}getActions(){return this.actions}getNotifications(){return{onNotification:this.notifications.onNotification}}static createNewHMSStore(e,t){let i=(0,Uo.default)(()=>t()),r=i.setState;i.setState=n=>{let d=typeof n=="function"?(0,Oo.produce)(n):n;r(d)};let s=i.getState;i.getState=n=>n?n(s()):s(),a.compareWithShallowCheckInSubscribe(i);let o=a.setUpDevtools(i,e);return M(h({},i),{namedSetState:o})}static makeStoreTriggerOnSubscribe(e){let t=e.subscribe;e.subscribe=(i,r,s)=>(i(e.getState(r),void 0),t(i,r,s))}static compareWithShallowCheckInSubscribe(e){let t=e.subscribe;e.subscribe=(i,r,s)=>(r||(r=o=>o),s=s||xo.default,t(i,r,s))}static setUpDevtools(e,t){let i;try{i=window.__REDUX_DEVTOOLS_EXTENSION__||window.top.__REDUX_DEVTOOLS_EXTENSION__}catch(o){}if(!i)return o=>{e.setState(o)};let r=i.connect(a.devtoolsOptions(t));r.prefix=t?`${t} > `:"";let s=e.setState;return e.setState=o=>{s(o),r.send(`${r.prefix}setState`,e.getState())},r.subscribe(a.devtoolsSubscribe(r,e,s)),r.send("setUpStore",e.getState()),(o,n)=>{s(o);let d=n||`${r.prefix}action`;r.send(d,e.getState())}}static devtoolsOptions(e){return{name:e,actionsBlacklist:["audioLevel","playlistProgress","connectionQuality"]}}static devtoolsSubscribe(e,t,i){return r=>{var s,o,n,d;if(r.type==="DISPATCH"&&r.state)["JUMP_TO_ACTION","JUMP_TO_STATE"].includes(r.payload.type)?i(JSON.parse(r.state)):t.setState(JSON.parse(r.state));else if(r.type==="DISPATCH"&&((s=r.payload)==null?void 0:s.type)==="COMMIT")e.init(t.getState());else if(r.type==="DISPATCH"&&((o=r.payload)==null?void 0:o.type)==="IMPORT_STATE"){let u=(n=r.payload.nextLiftedState)==null?void 0:n.actionsById;(((d=r.payload.nextLiftedState)==null?void 0:d.computedStates)||[]).forEach(({state:m},T)=>{let g=u[T]||`${e.prefix}setState`;T===0?e.init(m):(i(m),e.send(g,t.getState()))})}}}};var Vo=(a,e,t)=>{let i;t.getState(te)==="Connected"&&(i=Bo(a,e,t)),t.subscribe(r=>{["Connected","Reconnecting"].includes(r)?i||(i=Bo(a,e,t)):["Disconnected","Failed"].includes(r)&&i&&(kd(e,r),i(),i=void 0)},te)},Bo=(a,e,t)=>{var s,o;let i=Md(t,e);(s=a.getWebrtcInternals())==null||s.start();let r=(o=a.getWebrtcInternals())==null?void 0:o.onStatsChange(n=>yd(e,n,t,a));return()=>{i(),r&&r()}},Md=(a,e)=>{let t,i,r;return a.getState(Pe)?e.namedSetState(s=>{s.localPeer.id=a.getState(Pe)},"localpeer-id"):t=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.id=s},"localpeer-id")},Pe),a.getState(z)?e.namedSetState(s=>{s.localPeer.videoTrack=a.getState(z)},"localpeer-videotrack-id"):i=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.videoTrack=s},"localpeer-videotrack-id")},z),a.getState(ae)?e.namedSetState(s=>{s.localPeer.audioTrack=a.getState(ae)},"localpeer-audiotrack-id"):r=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.audioTrack=s},"localpeer-audiotrack-id")},ae),()=>{t==null||t(),i==null||i(),r==null||r()}},yd=(a,e,t,i)=>{let r=t.getState(_);a.namedSetState(s=>{let o=t.getState(Pe),n={},d=Object.keys(r).filter(p=>r[p].peerId!==o);for(let p of d){let m=e.getRemoteTrackStats(p);m&&(n[p]=m)}Ns(s.remoteTrackStats,n);let u={[o]:e.getLocalPeerStats()};Ns(s.peerStats,u),So(s.localTrackStats,e.getLocalTrackStats(),i.store.getLocalPeerTracks())},"webrtc-stats")},kd=(a,e="resetState")=>{a.namedSetState(t=>{Object.assign(t,Et())},e)};var vt=class{constructor(e,t){this.hmsStore=e;this.sdk=t;this.store=Xe.createNewHMSStore(ir("HMSStatsStore"),Et),this.getState=this.store.getState,this.subscribe=this.store.subscribe,this.getPublishPeerConnection=()=>new Promise(i=>{var r,s;this.hmsStore.getState(te)==="Connected"?i((s=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:s.getPublishPeerConnection()):this.hmsStore.subscribe(o=>{var n,d;o==="Connected"&&i((d=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:d.getPublishPeerConnection())},te)}),this.getSubscribePeerConnection=()=>new Promise(i=>{var r,s;this.hmsStore.getState(te)==="Connected"?i((s=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:s.getSubscribePeerConnection()):this.hmsStore.subscribe(o=>{var n,d;o==="Connected"&&i((d=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:d.getSubscribePeerConnection())},te)}),this.sdk&&Vo(this.sdk,this.store,this.hmsStore)}};var q=require("reselect");var Ed=a=>a.localPeer.id,Pd=a=>a.localPeer.audioTrack,bd=a=>a.localPeer.videoTrack,Ad=(a,e)=>e,Fo=(a,e)=>e,Id=a=>a.remoteTrackStats,Go=a=>a.peerStats,Ws=a=>a.localTrackStats,De=(0,q.createSelector)([Go,Ed],(a,e)=>a[e]),Rd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.packetsLost}),Hd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.jitter}),Cd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.bitrate}),Ld=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.bitrate}),Dd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.availableOutgoingBitrate}),wd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.availableIncomingBitrate}),_d=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.bytesSent}),Nd=(0,q.createSelector)(De,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.bytesReceived}),Od=(0,q.createSelector)([Go,Ad],(a,e)=>e?a[e]:void 0),xd=(0,q.createSelector)([Id,Fo],(a,e)=>e?a[e]:void 0),$s=(0,q.createSelector)([Ws,Fo],(a,e)=>e?a[e]:void 0),Ud=H(Od),Bd=H(xd),Vd=(0,q.createSelector)([Ws,Pd],(a,e)=>{var t;return e?(t=a[e])==null?void 0:t[0]:void 0}),Fd=H((0,q.createSelector)($s,a=>a==null?void 0:a[0])),Gd=(0,q.createSelector)([Ws,bd],(a,e)=>{var t;return e?(t=a[e])==null?void 0:t[0]:void 0}),Wd=H((0,q.createSelector)($s,a=>a)),$d=a=>H((0,q.createSelector)($s,e=>{let t=Object.keys(Ne).find(i=>Ne[i]===a);return a&&(e==null?void 0:e.find(i=>i.rid===t))||(e==null?void 0:e[0])})),Wo={localPeerStats:De,packetsLost:Rd,jitter:Hd,publishBitrate:Cd,subscribeBitrate:Ld,availablePublishBitrate:Dd,availableSubscribeBitrate:wd,totalBytesSent:_d,totalBytesReceived:Nd,peerStatsByID:Ud,trackStatsByID:Bd,localAudioTrackStatsByID:Fd,localVideoTrackStatsByID:Wd,localVideoTrackStatsByLayer:$d,localAudioTrackStats:Vd,localVideoTrackStats:Gd};
|
|
92
92
|
//# sourceMappingURL=index.cjs.js.map
|