@100mslive/hms-video-store 0.12.3 → 0.12.4-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +7 -7
- package/dist/index.cjs.js.map +3 -3
- package/dist/index.js +7 -7
- package/dist/index.js.map +3 -3
- package/dist/sdk/LocalTrackManager.d.ts +2 -1
- package/dist/signal/init/models.d.ts +2 -1
- package/package.json +2 -2
- package/src/sdk/LocalTrackManager.ts +35 -2
- package/src/sdk/index.ts +3 -2
- package/src/signal/init/models.ts +1 -0
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var io=Object.create;var at=Object.defineProperty,ro=Object.defineProperties,so=Object.getOwnPropertyDescriptor,ao=Object.getOwnPropertyDescriptors,oo=Object.getOwnPropertyNames,Jt=Object.getOwnPropertySymbols,Ts=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty,fs=Object.prototype.propertyIsEnumerable,no=Reflect.get;var gs=(a,e,t)=>e in a?at(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,S=(a,e)=>{for(var t in e||(e={}))dr.call(e,t)&&gs(a,t,e[t]);if(Jt)for(var t of Jt(e))fs.call(e,t)&&gs(a,t,e[t]);return a},v=(a,e)=>ro(a,ao(e));var lr=(a,e)=>{var t={};for(var i in a)dr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&Jt)for(var i of Jt(a))e.indexOf(i)<0&&fs.call(a,i)&&(t[i]=a[i]);return t};var co=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),lo=(a,e)=>{for(var t in e)at(a,t,{get:e[t],enumerable:!0})},vs=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of oo(e))!dr.call(a,r)&&r!==t&&at(a,r,{get:()=>e[r],enumerable:!(i=so(e,r))||i.enumerable});return a};var Ce=(a,e,t)=>(t=a!=null?io(Ts(a)):{},vs(e||!a||!a.__esModule?at(t,"default",{value:a,enumerable:!0}):t,a)),uo=a=>vs(at({},"__esModule",{value:!0}),a);var q=(a,e,t)=>no(Ts(a),t,e);var c=(a,e,t)=>new Promise((i,r)=>{var s=l=>{try{n(t.next(l))}catch(u){r(u)}},o=l=>{try{n(t.throw(l))}catch(u){r(u)}},n=l=>l.done?i(l.value):Promise.resolve(l.value).then(s,o);n((t=t.apply(a,e)).next())});var Dr=co((zd,tn)=>{tn.exports={version:"0.12.3",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:"d36c03b7026a62b55165c282de0e616ede74b966"}});var Xc={};lo(Xc,{DeviceType:()=>Ur,DomainCategory:()=>Ir,EventBus:()=>et,HLSPlaylistType:()=>xr,HMSAudioPluginType:()=>ii,HMSLogLevel:()=>br,HMSMessageType:()=>Ms,HMSNotificationSeverity:()=>ur,HMSNotificationTypes:()=>zt,HMSPlaylistType:()=>pr,HMSPluginUnsupportedTypes:()=>ri,HMSReactiveStore:()=>Be,HMSRecordingState:()=>Or,HMSRoomState:()=>Qt,HMSStats:()=>st,HMSVideoPluginCanvasContextType:()=>ci,HMSVideoPluginType:()=>ni,createDefaultStatsStore:()=>nt,createDefaultStoreState:()=>ot,parsedUserAgent:()=>de,selectAppData:()=>Pn,selectAppDataByPath:()=>bn,selectAudioPlaylist:()=>Pr,selectAudioPlaylistTrackByPeerID:()=>Bn,selectAudioTrackByID:()=>In,selectAudioTrackByPeerID:()=>ka,selectAudioTrackVolume:()=>is,selectAudioVolumeByPeerID:()=>Kn,selectAuxiliaryAudioByPeerID:()=>On,selectAuxiliaryTracksByPeerID:()=>Ln,selectAvailableRoleNames:()=>Oo,selectBroadcastMessages:()=>Aa,selectBroadcastMessagesUnreadCount:()=>zn,selectCameraStreamByPeerID:()=>Cn,selectConnectionQualities:()=>go,selectConnectionQualityByPeerID:()=>Nn,selectDegradedTracks:()=>Lo,selectDevices:()=>So,selectDidIJoinWithin:()=>vc,selectDominantSpeaker:()=>Eo,selectEffectsKey:()=>Ko,selectErrors:()=>Ps,selectFullAppData:()=>Xt,selectHLSState:()=>Vo,selectHMSBroadcastMessages:()=>As,selectHMSMessages:()=>Fe,selectHMSMessagesCount:()=>Do,selectHMSStats:()=>to,selectHandRaisedPeers:()=>Qo,selectHasPeerHandRaised:()=>sc,selectIsAllowedToPreviewMedia:()=>uc,selectIsAllowedToPublish:()=>lc,selectIsAllowedToSubscribe:()=>xo,selectIsAudioLocallyMuted:()=>ts,selectIsConnectedToRoom:()=>me,selectIsEffectsEnabled:()=>Wo,selectIsInPreview:()=>Tr,selectIsLargeRoom:()=>$o,selectIsLocalAudioEnabled:()=>bo,selectIsLocalAudioPluginPresent:()=>gc,selectIsLocalScreenShared:()=>ei,selectIsLocalVideoDisplayEnabled:()=>gr,selectIsLocalVideoEnabled:()=>Zt,selectIsLocalVideoPluginPresent:()=>Sc,selectIsLocallyMutedByPeerID:()=>$n,selectIsPeerAudioEnabled:()=>Fn,selectIsPeerVideoEnabled:()=>Gn,selectIsRoleAllowedToPublish:()=>pc,selectIsScreenShareLocallyMutedByPeerID:()=>Wn,selectIsSomeoneScreenSharing:()=>Ao,selectLocalAudioTrackID:()=>X,selectLocalMediaSettings:()=>mr,selectLocalPeer:()=>j,selectLocalPeerID:()=>ce,selectLocalPeerName:()=>Mo,selectLocalPeerRole:()=>ht,selectLocalPeerRoleName:()=>yo,selectLocalTrackIDs:()=>Sr,selectLocalVideoTrackID:()=>$,selectMessageByMessageID:()=>oc,selectMessageIDsInOrder:()=>hr,selectMessagesByPeerID:()=>Yn,selectMessagesByRole:()=>Xn,selectMessagesMap:()=>pt,selectMessagesUnreadCountByPeerID:()=>ec,selectMessagesUnreadCountByRole:()=>Zn,selectPeerAudioByID:()=>_n,selectPeerByCondition:()=>Tc,selectPeerByID:()=>W,selectPeerCount:()=>To,selectPeerMetadata:()=>rc,selectPeerName:()=>ac,selectPeerNameByID:()=>An,selectPeerScreenSharing:()=>bs,selectPeerSharingAudio:()=>Io,selectPeerSharingAudioPlaylist:()=>Co,selectPeerSharingVideoPlaylist:()=>Ho,selectPeers:()=>ie,selectPeersByCondition:()=>fc,selectPeersByRole:()=>tc,selectPeersByRoles:()=>ic,selectPeersMap:()=>G,selectPeersScreenSharing:()=>Ro,selectPeersWithAudioStatus:()=>nc,selectPermissions:()=>vr,selectPollByID:()=>rs,selectPolls:()=>Jo,selectPollsMap:()=>Mr,selectPreviewRole:()=>fr,selectPreviewRoleName:()=>Is,selectRTMPState:()=>Bo,selectRecentError:()=>ho,selectRecordingState:()=>Uo,selectRemotePeers:()=>Po,selectRoleByRoleName:()=>Ia,selectRoleChangeRequest:()=>dc,selectRolesMap:()=>re,selectRoom:()=>U,selectRoomID:()=>mo,selectRoomStartTime:()=>Go,selectRoomStarted:()=>No,selectRoomState:()=>J,selectScreenAudioTrackByID:()=>Rn,selectScreenShareAudioByPeerID:()=>es,selectScreenShareByPeerID:()=>Vn,selectScreenSharesByPeerId:()=>Zr,selectScreenVideoTrackByID:()=>Hn,selectScreenshareAudioVolumeByPeerID:()=>qn,selectSessionId:()=>Fo,selectSessionMetadata:()=>jo,selectSessionStore:()=>En,selectSimulcastLayerByTrack:()=>jn,selectSpeakers:()=>Es,selectTemplateAppData:()=>qo,selectTrackAudioByID:()=>Dn,selectTrackByID:()=>At,selectTracksMap:()=>D,selectUnreadHMSBroadcastMessagesCount:()=>_o,selectUnreadHMSMessagesCount:()=>wo,selectVideoPlaylist:()=>Er,selectVideoPlaylistAudioTrackByPeerID:()=>Un,selectVideoPlaylistVideoTrackByPeerID:()=>xn,selectVideoTrackByID:()=>Xr,selectVideoTrackByPeerID:()=>ya,selectWhiteboard:()=>zo,selectWhiteboards:()=>Rs,simulcastMapping:()=>Ie});module.exports=uo(Xc);var Qt=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(Qt||{});var ot=()=>({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}),nt=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var Ms=(e=>(e.CHAT="chat",e))(Ms||{});var ur=(t=>(t.INFO="info",t.ERROR="error",t))(ur||{}),zt=(C=>(C.PEER_JOINED="PEER_JOINED",C.PEER_LEFT="PEER_LEFT",C.PEER_LIST="PEER_LIST",C.NEW_MESSAGE="NEW_MESSAGE",C.ERROR="ERROR",C.RECONNECTING="RECONNECTING",C.RECONNECTED="RECONNECTED",C.TRACK_ADDED="TRACK_ADDED",C.TRACK_REMOVED="TRACK_REMOVED",C.TRACK_MUTED="TRACK_MUTED",C.TRACK_UNMUTED="TRACK_UNMUTED",C.TRACK_DEGRADED="TRACK_DEGRADED",C.TRACK_RESTORED="TRACK_RESTORED",C.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",C.ROLE_UPDATED="ROLE_UPDATED",C.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",C.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",C.ROOM_ENDED="ROOM_ENDED",C.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",C.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",C.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",C.NAME_UPDATED="NAME_UPDATED",C.METADATA_UPDATED="METADATA_UPDATED",C.POLL_CREATED="POLL_CREATED",C.POLL_STARTED="POLL_STARTED",C.POLL_STOPPED="POLL_STOPPED",C.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",C.POLLS_LIST="POLLS_LIST",C.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",C))(zt||{});var pr=(t=>(t.audio="audio",t.video="video",t))(pr||{});var P=require("reselect");function Le(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];po(s)&&(i=ct(s)?s:i,t=dt(s)?s:t)}return{video:t,audio:i}}function ct(a){return a&&a.type==="audio"}function dt(a){return a&&a.type==="video"}function po(a){return a&&a.source==="screen"}function Yt(a){return a&&a.source==="audioplaylist"}function lt(a){return a&&a.source==="videoplaylist"}function ys(a){return a?!!(a!=null&&a.degraded):!1}function Ve(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function ks(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function ut(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 U=a=>a.room,Ps=a=>a.errors,ho=(0,P.createSelector)(Ps,a=>a.length===0?null:a.at(-1)),mo=(0,P.createSelector)(U,a=>a.id),G=a=>a.peers,pt=a=>a.messages.byID,hr=a=>a.messages.allIDs,D=a=>a.tracks,mr=a=>a.settings,Xt=a=>a.appData,So=a=>a.devices,Es=a=>a.speakers,go=a=>a.connectionQualities,me=(0,P.createSelector)([U],a=>a&&a.isConnected),To=(0,P.createSelector)([me,U],(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)),fo=a=>a.hideLocalPeer,ie=(0,P.createSelector)([U,G,fo],(a,e,t)=>t?a.peers.filter(i=>a.localPeer!==i).map(i=>e[i]):a.peers.map(i=>e[i])),vo=(0,P.createSelector)(D,a=>Object.values(a)),j=(0,P.createSelector)(U,G,(a,e)=>e[a.localPeer]),ce=(0,P.createSelector)(U,a=>a.localPeer),Mo=(0,P.createSelector)(j,a=>a==null?void 0:a.name),yo=(0,P.createSelector)(j,a=>a==null?void 0:a.roleName),X=(0,P.createSelector)(j,a=>a==null?void 0:a.audioTrack),$=(0,P.createSelector)(j,a=>a==null?void 0:a.videoTrack),ko=(0,P.createSelector)(j,a=>a==null?void 0:a.auxiliaryTracks),Sr=(0,P.createSelector)([X,$,ko],(a,e,t)=>{let i=t?[...t]:[];return a&&i.unshift(a),e&&i.unshift(e),i}),Po=(0,P.createSelector)(ie,a=>a.filter(e=>!e.isLocal)),Eo=(0,P.createSelector)(G,Es,(a,e)=>{let t=Object.entries(e).sort((i,r)=>{var n,l;let s=((n=i[1])==null?void 0:n.audioLevel)||0;return(((l=r[1])==null?void 0:l.audioLevel)||0)>s?1:-1});if(t.length>0&&t[0][1].audioLevel&&t[0][1].audioLevel>0){let i=t[0][1].peerID;if(i in a)return a[i]}return null}),bo=a=>{let e=j(a);return Ve(a,e==null?void 0:e.audioTrack)},Zt=a=>{let e=j(a);return Ve(a,e==null?void 0:e.videoTrack)},gr=a=>{let e=j(a);return ks(a,e==null?void 0:e.videoTrack)},ei=(0,P.createSelector)(j,D,(a,e)=>{let{video:t,audio:i}=Le(e,a);return!!(t||i)}),bs=(0,P.createSelector)(G,D,(a,e)=>{let t;for(let i in a){let r=a[i],{video:s,audio:o}=Le(e,r);if(s)return r;o&&!t&&(t=r)}return t}),Ao=(0,P.createSelector)(bs,a=>!!a),Io=(0,P.createSelector)(G,D,(a,e)=>{for(let t in a){let i=a[t],{audio:r,video:s}=Le(e,i);if(!s&&r)return i}}),Ro=(0,P.createSelector)(G,D,(a,e)=>{let t=[],i=[];for(let r in a){let s=a[r],{video:o,audio:n}=Le(e,s);o?t.push(s):n&&i.push(s)}return t.concat(i)}),Ho=(0,P.createSelector)(G,D,(a,e)=>{for(let t in e){let i=e[t];if(lt(i)&&dt(i)&&i.peerId)return a[i.peerId]}}),Co=(0,P.createSelector)(G,D,(a,e)=>{for(let t in e){let i=e[t];if(Yt(i)&&i.peerId)return a[i.peerId]}}),Lo=(0,P.createSelector)(vo,a=>a.filter(ys)),Do=(0,P.createSelector)(hr,a=>a.length),wo=(0,P.createSelector)(pt,a=>Object.values(a).filter(e=>!e.read).length),Fe=(0,P.createSelector)(hr,pt,(a,e)=>{let t=[];return a.forEach(i=>{t.push(e[i])}),t}),As=(0,P.createSelector)(Fe,a=>a.filter(e=>{var t;return!e.recipientPeer&&!(e.recipientRoles&&((t=e.recipientRoles)==null?void 0:t.length)>0)})),_o=(0,P.createSelector)(As,a=>a.filter(e=>!e.read).length),J=(0,P.createSelector)([U],a=>a&&a.roomState),Tr=(0,P.createSelector)(J,a=>a==="Preview"),No=(0,P.createSelector)(U,a=>a.roomState!=="Disconnected"),re=a=>a.roles,Oo=(0,P.createSelector)([re],a=>Object.keys(a)),ht=(0,P.createSelector)([j,re],(a,e)=>a!=null&&a.roleName?e[a.roleName]:null),Is=a=>{var e;return(e=a.preview)==null?void 0:e.asRole},fr=(0,P.createSelector)([Is,re],(a,e)=>a?e[a]:null),xo=(0,P.createSelector)([ht],a=>{var e;return(e=a==null?void 0:a.subscribeParams)!=null&&e.subscribeToRoles?a.subscribeParams.subscribeToRoles.length>0:!1}),vr=(0,P.createSelector)(ht,a=>a==null?void 0:a.permissions),Uo=(0,P.createSelector)(U,a=>a.recording),Bo=(0,P.createSelector)(U,a=>a.rtmp),Vo=(0,P.createSelector)(U,a=>a.hls),Fo=(0,P.createSelector)(U,a=>a.sessionId),Go=(0,P.createSelector)(U,a=>a.startedAt),$o=(0,P.createSelector)(U,a=>!!a.isLargeRoom),Wo=(0,P.createSelector)(U,a=>!!a.isEffectsEnabled),Ko=(0,P.createSelector)(U,a=>a.effectsKey),qo=a=>a.templateAppData,jo=a=>a.sessionMetadata,Mr=a=>a.polls,Jo=a=>Object.values(a.polls),Qo=(0,P.createSelector)(ie,a=>a.filter(e=>e.isHandRaised)),Rs=a=>a.whiteboards,zo=(0,P.createSelector)(Rs,a=>Object.values(a)[0]);var yr=require("reselect");var Hs=(a="audio")=>e=>e.playlist[a].list,kr=(a="audio")=>e=>e.playlist[a].selection,Cs=(a="audio")=>e=>e.playlist[a].progress,Ls=(a="audio")=>e=>e.playlist[a].currentTime,Ds=(a="audio")=>e=>e.playlist[a].playbackRate,ws=(a="audio")=>e=>e.playlist[a].volume,_s=(a="audio")=>(0,yr.createSelector)(Hs(a),e=>Object.values(e)),Ns=(a="audio")=>(0,yr.createSelector)(Hs(a),kr(a),(e,t)=>{if(t.id)return e[t.id]}),Pr={selection:kr("audio"),progress:Cs("audio"),currentTime:Ls("audio"),playbackRate:Ds("audio"),volume:ws("audio"),list:_s("audio"),selectedItem:Ns("audio")},Er={selection:kr("video"),progress:Cs("video"),currentTime:Ls("video"),playbackRate:Ds("video"),volume:ws("video"),list:_s("video"),selectedItem:Ns("video")};var H=require("reselect");function b(a){return e=>t=>a(t,e)}var br=(l=>(l[l.VERBOSE=0]="VERBOSE",l[l.DEBUG=1]="DEBUG",l[l.INFO=2]="INFO",l[l.WARN=3]="WARN",l[l.TIME=4]="TIME",l[l.TIMEEND=5]="TIMEEND",l[l.ERROR=6]="ERROR",l[l.NONE=7]="NONE",l))(br||{}),Yo=typeof window!="undefined"&&typeof window.expect!="undefined",d=class{static v(e,...t){this.log(0,e,...t)}static d(e,...t){this.log(1,e,...t)}static i(e,...t){this.log(2,e,...t)}static w(e,...t){this.log(3,e,...t)}static e(e,...t){this.log(6,e,...t)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,t,...i){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(t,...i);break}case 1:{console.debug(t,...i);break}case 2:{console.info(t,...i);break}case 3:{console.warn(t,...i);break}case 6:{console.error(t,...i);break}case 4:{performance.mark(i[0]);break}case 5:{let r=i[0];try{let s=performance.measure(r,r);this.log(1,t,r,s==null?void 0:s.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(s){this.log(1,t,r,s)}break}}}};d.level=Yo?7:0;var Ge=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var Bs=require("ua-parser-js"),de=new Bs.UAParser,w=typeof window!="undefined",Os,De=typeof window=="undefined"&&!((Os=de.getBrowser().name)!=null&&Os.toLowerCase().includes("electron"));var Xo=()=>!De,pd=Xo(),we=()=>de.getDevice().type==="mobile",Vs=()=>typeof document!="undefined"&&document.hidden,Ar=()=>{var a;return((a=de.getOS().name)==null?void 0:a.toLowerCase())==="ios"},xs,Us,Fs=((Us=(xs=de.getBrowser())==null?void 0:xs.name)==null?void 0:Us.toLowerCase())==="firefox";var ti=a=>a?`{
|
|
1
|
+
"use strict";var io=Object.create;var at=Object.defineProperty,ro=Object.defineProperties,so=Object.getOwnPropertyDescriptor,ao=Object.getOwnPropertyDescriptors,oo=Object.getOwnPropertyNames,Jt=Object.getOwnPropertySymbols,Ts=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty,fs=Object.prototype.propertyIsEnumerable,no=Reflect.get;var gs=(a,e,t)=>e in a?at(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,S=(a,e)=>{for(var t in e||(e={}))dr.call(e,t)&&gs(a,t,e[t]);if(Jt)for(var t of Jt(e))fs.call(e,t)&&gs(a,t,e[t]);return a},v=(a,e)=>ro(a,ao(e));var lr=(a,e)=>{var t={};for(var i in a)dr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&Jt)for(var i of Jt(a))e.indexOf(i)<0&&fs.call(a,i)&&(t[i]=a[i]);return t};var co=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),lo=(a,e)=>{for(var t in e)at(a,t,{get:e[t],enumerable:!0})},vs=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of oo(e))!dr.call(a,r)&&r!==t&&at(a,r,{get:()=>e[r],enumerable:!(i=so(e,r))||i.enumerable});return a};var Ce=(a,e,t)=>(t=a!=null?io(Ts(a)):{},vs(e||!a||!a.__esModule?at(t,"default",{value:a,enumerable:!0}):t,a)),uo=a=>vs(at({},"__esModule",{value:!0}),a);var q=(a,e,t)=>no(Ts(a),t,e);var c=(a,e,t)=>new Promise((i,r)=>{var s=l=>{try{n(t.next(l))}catch(u){r(u)}},o=l=>{try{n(t.throw(l))}catch(u){r(u)}},n=l=>l.done?i(l.value):Promise.resolve(l.value).then(s,o);n((t=t.apply(a,e)).next())});var wr=co((zd,tn)=>{tn.exports={version:"0.12.4-alpha.0",license:"MIT",repository:{type:"git",url:"https://github.com/100mslive/web-sdks.git",directory:"packages/hms-video-store"},main:"dist/index.cjs.js",module:"dist/index.js",typings:"dist/index.d.ts",files:["dist","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:"9d71fb326cd5235a5ddb8093703f69653d46949d"}});var Xc={};lo(Xc,{DeviceType:()=>Ur,DomainCategory:()=>Ir,EventBus:()=>et,HLSPlaylistType:()=>xr,HMSAudioPluginType:()=>ii,HMSLogLevel:()=>br,HMSMessageType:()=>Ms,HMSNotificationSeverity:()=>ur,HMSNotificationTypes:()=>zt,HMSPlaylistType:()=>pr,HMSPluginUnsupportedTypes:()=>ri,HMSReactiveStore:()=>Be,HMSRecordingState:()=>Or,HMSRoomState:()=>Qt,HMSStats:()=>st,HMSVideoPluginCanvasContextType:()=>ci,HMSVideoPluginType:()=>ni,createDefaultStatsStore:()=>nt,createDefaultStoreState:()=>ot,parsedUserAgent:()=>de,selectAppData:()=>Pn,selectAppDataByPath:()=>bn,selectAudioPlaylist:()=>Pr,selectAudioPlaylistTrackByPeerID:()=>Bn,selectAudioTrackByID:()=>In,selectAudioTrackByPeerID:()=>ka,selectAudioTrackVolume:()=>is,selectAudioVolumeByPeerID:()=>Kn,selectAuxiliaryAudioByPeerID:()=>On,selectAuxiliaryTracksByPeerID:()=>Ln,selectAvailableRoleNames:()=>Oo,selectBroadcastMessages:()=>Aa,selectBroadcastMessagesUnreadCount:()=>zn,selectCameraStreamByPeerID:()=>Cn,selectConnectionQualities:()=>go,selectConnectionQualityByPeerID:()=>Nn,selectDegradedTracks:()=>Lo,selectDevices:()=>So,selectDidIJoinWithin:()=>vc,selectDominantSpeaker:()=>Eo,selectEffectsKey:()=>Ko,selectErrors:()=>Ps,selectFullAppData:()=>Xt,selectHLSState:()=>Vo,selectHMSBroadcastMessages:()=>As,selectHMSMessages:()=>Fe,selectHMSMessagesCount:()=>wo,selectHMSStats:()=>to,selectHandRaisedPeers:()=>Qo,selectHasPeerHandRaised:()=>sc,selectIsAllowedToPreviewMedia:()=>uc,selectIsAllowedToPublish:()=>lc,selectIsAllowedToSubscribe:()=>xo,selectIsAudioLocallyMuted:()=>ts,selectIsConnectedToRoom:()=>me,selectIsEffectsEnabled:()=>$o,selectIsInPreview:()=>Tr,selectIsLargeRoom:()=>Wo,selectIsLocalAudioEnabled:()=>bo,selectIsLocalAudioPluginPresent:()=>gc,selectIsLocalScreenShared:()=>ei,selectIsLocalVideoDisplayEnabled:()=>gr,selectIsLocalVideoEnabled:()=>Zt,selectIsLocalVideoPluginPresent:()=>Sc,selectIsLocallyMutedByPeerID:()=>Wn,selectIsPeerAudioEnabled:()=>Fn,selectIsPeerVideoEnabled:()=>Gn,selectIsRoleAllowedToPublish:()=>pc,selectIsScreenShareLocallyMutedByPeerID:()=>$n,selectIsSomeoneScreenSharing:()=>Ao,selectLocalAudioTrackID:()=>X,selectLocalMediaSettings:()=>mr,selectLocalPeer:()=>j,selectLocalPeerID:()=>ce,selectLocalPeerName:()=>Mo,selectLocalPeerRole:()=>ht,selectLocalPeerRoleName:()=>yo,selectLocalTrackIDs:()=>Sr,selectLocalVideoTrackID:()=>W,selectMessageByMessageID:()=>oc,selectMessageIDsInOrder:()=>hr,selectMessagesByPeerID:()=>Yn,selectMessagesByRole:()=>Xn,selectMessagesMap:()=>pt,selectMessagesUnreadCountByPeerID:()=>ec,selectMessagesUnreadCountByRole:()=>Zn,selectPeerAudioByID:()=>_n,selectPeerByCondition:()=>Tc,selectPeerByID:()=>$,selectPeerCount:()=>To,selectPeerMetadata:()=>rc,selectPeerName:()=>ac,selectPeerNameByID:()=>An,selectPeerScreenSharing:()=>bs,selectPeerSharingAudio:()=>Io,selectPeerSharingAudioPlaylist:()=>Co,selectPeerSharingVideoPlaylist:()=>Ho,selectPeers:()=>ie,selectPeersByCondition:()=>fc,selectPeersByRole:()=>tc,selectPeersByRoles:()=>ic,selectPeersMap:()=>G,selectPeersScreenSharing:()=>Ro,selectPeersWithAudioStatus:()=>nc,selectPermissions:()=>vr,selectPollByID:()=>rs,selectPolls:()=>Jo,selectPollsMap:()=>Mr,selectPreviewRole:()=>fr,selectPreviewRoleName:()=>Is,selectRTMPState:()=>Bo,selectRecentError:()=>ho,selectRecordingState:()=>Uo,selectRemotePeers:()=>Po,selectRoleByRoleName:()=>Ia,selectRoleChangeRequest:()=>dc,selectRolesMap:()=>re,selectRoom:()=>U,selectRoomID:()=>mo,selectRoomStartTime:()=>Go,selectRoomStarted:()=>No,selectRoomState:()=>J,selectScreenAudioTrackByID:()=>Rn,selectScreenShareAudioByPeerID:()=>es,selectScreenShareByPeerID:()=>Vn,selectScreenSharesByPeerId:()=>Zr,selectScreenVideoTrackByID:()=>Hn,selectScreenshareAudioVolumeByPeerID:()=>qn,selectSessionId:()=>Fo,selectSessionMetadata:()=>jo,selectSessionStore:()=>En,selectSimulcastLayerByTrack:()=>jn,selectSpeakers:()=>Es,selectTemplateAppData:()=>qo,selectTrackAudioByID:()=>wn,selectTrackByID:()=>At,selectTracksMap:()=>w,selectUnreadHMSBroadcastMessagesCount:()=>_o,selectUnreadHMSMessagesCount:()=>Do,selectVideoPlaylist:()=>Er,selectVideoPlaylistAudioTrackByPeerID:()=>Un,selectVideoPlaylistVideoTrackByPeerID:()=>xn,selectVideoTrackByID:()=>Xr,selectVideoTrackByPeerID:()=>ya,selectWhiteboard:()=>zo,selectWhiteboards:()=>Rs,simulcastMapping:()=>Ie});module.exports=uo(Xc);var Qt=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(Qt||{});var ot=()=>({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}),nt=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var Ms=(e=>(e.CHAT="chat",e))(Ms||{});var ur=(t=>(t.INFO="info",t.ERROR="error",t))(ur||{}),zt=(C=>(C.PEER_JOINED="PEER_JOINED",C.PEER_LEFT="PEER_LEFT",C.PEER_LIST="PEER_LIST",C.NEW_MESSAGE="NEW_MESSAGE",C.ERROR="ERROR",C.RECONNECTING="RECONNECTING",C.RECONNECTED="RECONNECTED",C.TRACK_ADDED="TRACK_ADDED",C.TRACK_REMOVED="TRACK_REMOVED",C.TRACK_MUTED="TRACK_MUTED",C.TRACK_UNMUTED="TRACK_UNMUTED",C.TRACK_DEGRADED="TRACK_DEGRADED",C.TRACK_RESTORED="TRACK_RESTORED",C.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",C.ROLE_UPDATED="ROLE_UPDATED",C.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",C.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",C.ROOM_ENDED="ROOM_ENDED",C.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",C.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",C.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",C.NAME_UPDATED="NAME_UPDATED",C.METADATA_UPDATED="METADATA_UPDATED",C.POLL_CREATED="POLL_CREATED",C.POLL_STARTED="POLL_STARTED",C.POLL_STOPPED="POLL_STOPPED",C.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",C.POLLS_LIST="POLLS_LIST",C.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",C))(zt||{});var pr=(t=>(t.audio="audio",t.video="video",t))(pr||{});var E=require("reselect");function Le(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];po(s)&&(i=ct(s)?s:i,t=dt(s)?s:t)}return{video:t,audio:i}}function ct(a){return a&&a.type==="audio"}function dt(a){return a&&a.type==="video"}function po(a){return a&&a.source==="screen"}function Yt(a){return a&&a.source==="audioplaylist"}function lt(a){return a&&a.source==="videoplaylist"}function ys(a){return a?!!(a!=null&&a.degraded):!1}function Ve(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function ks(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function ut(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 U=a=>a.room,Ps=a=>a.errors,ho=(0,E.createSelector)(Ps,a=>a.length===0?null:a.at(-1)),mo=(0,E.createSelector)(U,a=>a.id),G=a=>a.peers,pt=a=>a.messages.byID,hr=a=>a.messages.allIDs,w=a=>a.tracks,mr=a=>a.settings,Xt=a=>a.appData,So=a=>a.devices,Es=a=>a.speakers,go=a=>a.connectionQualities,me=(0,E.createSelector)([U],a=>a&&a.isConnected),To=(0,E.createSelector)([me,U],(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)),fo=a=>a.hideLocalPeer,ie=(0,E.createSelector)([U,G,fo],(a,e,t)=>t?a.peers.filter(i=>a.localPeer!==i).map(i=>e[i]):a.peers.map(i=>e[i])),vo=(0,E.createSelector)(w,a=>Object.values(a)),j=(0,E.createSelector)(U,G,(a,e)=>e[a.localPeer]),ce=(0,E.createSelector)(U,a=>a.localPeer),Mo=(0,E.createSelector)(j,a=>a==null?void 0:a.name),yo=(0,E.createSelector)(j,a=>a==null?void 0:a.roleName),X=(0,E.createSelector)(j,a=>a==null?void 0:a.audioTrack),W=(0,E.createSelector)(j,a=>a==null?void 0:a.videoTrack),ko=(0,E.createSelector)(j,a=>a==null?void 0:a.auxiliaryTracks),Sr=(0,E.createSelector)([X,W,ko],(a,e,t)=>{let i=t?[...t]:[];return a&&i.unshift(a),e&&i.unshift(e),i}),Po=(0,E.createSelector)(ie,a=>a.filter(e=>!e.isLocal)),Eo=(0,E.createSelector)(G,Es,(a,e)=>{let t=Object.entries(e).sort((i,r)=>{var n,l;let s=((n=i[1])==null?void 0:n.audioLevel)||0;return(((l=r[1])==null?void 0:l.audioLevel)||0)>s?1:-1});if(t.length>0&&t[0][1].audioLevel&&t[0][1].audioLevel>0){let i=t[0][1].peerID;if(i in a)return a[i]}return null}),bo=a=>{let e=j(a);return Ve(a,e==null?void 0:e.audioTrack)},Zt=a=>{let e=j(a);return Ve(a,e==null?void 0:e.videoTrack)},gr=a=>{let e=j(a);return ks(a,e==null?void 0:e.videoTrack)},ei=(0,E.createSelector)(j,w,(a,e)=>{let{video:t,audio:i}=Le(e,a);return!!(t||i)}),bs=(0,E.createSelector)(G,w,(a,e)=>{let t;for(let i in a){let r=a[i],{video:s,audio:o}=Le(e,r);if(s)return r;o&&!t&&(t=r)}return t}),Ao=(0,E.createSelector)(bs,a=>!!a),Io=(0,E.createSelector)(G,w,(a,e)=>{for(let t in a){let i=a[t],{audio:r,video:s}=Le(e,i);if(!s&&r)return i}}),Ro=(0,E.createSelector)(G,w,(a,e)=>{let t=[],i=[];for(let r in a){let s=a[r],{video:o,audio:n}=Le(e,s);o?t.push(s):n&&i.push(s)}return t.concat(i)}),Ho=(0,E.createSelector)(G,w,(a,e)=>{for(let t in e){let i=e[t];if(lt(i)&&dt(i)&&i.peerId)return a[i.peerId]}}),Co=(0,E.createSelector)(G,w,(a,e)=>{for(let t in e){let i=e[t];if(Yt(i)&&i.peerId)return a[i.peerId]}}),Lo=(0,E.createSelector)(vo,a=>a.filter(ys)),wo=(0,E.createSelector)(hr,a=>a.length),Do=(0,E.createSelector)(pt,a=>Object.values(a).filter(e=>!e.read).length),Fe=(0,E.createSelector)(hr,pt,(a,e)=>{let t=[];return a.forEach(i=>{t.push(e[i])}),t}),As=(0,E.createSelector)(Fe,a=>a.filter(e=>{var t;return!e.recipientPeer&&!(e.recipientRoles&&((t=e.recipientRoles)==null?void 0:t.length)>0)})),_o=(0,E.createSelector)(As,a=>a.filter(e=>!e.read).length),J=(0,E.createSelector)([U],a=>a&&a.roomState),Tr=(0,E.createSelector)(J,a=>a==="Preview"),No=(0,E.createSelector)(U,a=>a.roomState!=="Disconnected"),re=a=>a.roles,Oo=(0,E.createSelector)([re],a=>Object.keys(a)),ht=(0,E.createSelector)([j,re],(a,e)=>a!=null&&a.roleName?e[a.roleName]:null),Is=a=>{var e;return(e=a.preview)==null?void 0:e.asRole},fr=(0,E.createSelector)([Is,re],(a,e)=>a?e[a]:null),xo=(0,E.createSelector)([ht],a=>{var e;return(e=a==null?void 0:a.subscribeParams)!=null&&e.subscribeToRoles?a.subscribeParams.subscribeToRoles.length>0:!1}),vr=(0,E.createSelector)(ht,a=>a==null?void 0:a.permissions),Uo=(0,E.createSelector)(U,a=>a.recording),Bo=(0,E.createSelector)(U,a=>a.rtmp),Vo=(0,E.createSelector)(U,a=>a.hls),Fo=(0,E.createSelector)(U,a=>a.sessionId),Go=(0,E.createSelector)(U,a=>a.startedAt),Wo=(0,E.createSelector)(U,a=>!!a.isLargeRoom),$o=(0,E.createSelector)(U,a=>!!a.isEffectsEnabled),Ko=(0,E.createSelector)(U,a=>a.effectsKey),qo=a=>a.templateAppData,jo=a=>a.sessionMetadata,Mr=a=>a.polls,Jo=a=>Object.values(a.polls),Qo=(0,E.createSelector)(ie,a=>a.filter(e=>e.isHandRaised)),Rs=a=>a.whiteboards,zo=(0,E.createSelector)(Rs,a=>Object.values(a)[0]);var yr=require("reselect");var Hs=(a="audio")=>e=>e.playlist[a].list,kr=(a="audio")=>e=>e.playlist[a].selection,Cs=(a="audio")=>e=>e.playlist[a].progress,Ls=(a="audio")=>e=>e.playlist[a].currentTime,ws=(a="audio")=>e=>e.playlist[a].playbackRate,Ds=(a="audio")=>e=>e.playlist[a].volume,_s=(a="audio")=>(0,yr.createSelector)(Hs(a),e=>Object.values(e)),Ns=(a="audio")=>(0,yr.createSelector)(Hs(a),kr(a),(e,t)=>{if(t.id)return e[t.id]}),Pr={selection:kr("audio"),progress:Cs("audio"),currentTime:Ls("audio"),playbackRate:ws("audio"),volume:Ds("audio"),list:_s("audio"),selectedItem:Ns("audio")},Er={selection:kr("video"),progress:Cs("video"),currentTime:Ls("video"),playbackRate:ws("video"),volume:Ds("video"),list:_s("video"),selectedItem:Ns("video")};var H=require("reselect");function I(a){return e=>t=>a(t,e)}var br=(l=>(l[l.VERBOSE=0]="VERBOSE",l[l.DEBUG=1]="DEBUG",l[l.INFO=2]="INFO",l[l.WARN=3]="WARN",l[l.TIME=4]="TIME",l[l.TIMEEND=5]="TIMEEND",l[l.ERROR=6]="ERROR",l[l.NONE=7]="NONE",l))(br||{}),Yo=typeof window!="undefined"&&typeof window.expect!="undefined",d=class{static v(e,...t){this.log(0,e,...t)}static d(e,...t){this.log(1,e,...t)}static i(e,...t){this.log(2,e,...t)}static w(e,...t){this.log(3,e,...t)}static e(e,...t){this.log(6,e,...t)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,t,...i){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(t,...i);break}case 1:{console.debug(t,...i);break}case 2:{console.info(t,...i);break}case 3:{console.warn(t,...i);break}case 6:{console.error(t,...i);break}case 4:{performance.mark(i[0]);break}case 5:{let r=i[0];try{let s=performance.measure(r,r);this.log(1,t,r,s==null?void 0:s.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(s){this.log(1,t,r,s)}break}}}};d.level=Yo?7:0;var Ge=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var Bs=require("ua-parser-js"),de=new Bs.UAParser,_=typeof window!="undefined",Os,we=typeof window=="undefined"&&!((Os=de.getBrowser().name)!=null&&Os.toLowerCase().includes("electron"));var Xo=()=>!we,pd=Xo(),De=()=>de.getDevice().type==="mobile",Vs=()=>typeof document!="undefined"&&document.hidden,Ar=()=>{var a;return((a=de.getOS().name)==null?void 0:a.toLowerCase())==="ios"},xs,Us,Fs=((Us=(xs=de.getBrowser())==null?void 0:xs.name)==null?void 0:Us.toLowerCase())==="firefox";var ti=a=>a?`{
|
|
2
2
|
trackId: ${a.id};
|
|
3
3
|
kind: ${a.kind};
|
|
4
4
|
enabled: ${a.enabled};
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
source: ${this.source};
|
|
14
14
|
enabled: ${this.enabled};
|
|
15
15
|
nativeTrack: ${ti(this.nativeTrack)};
|
|
16
|
-
}`}};var Pe=class extends ke{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?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){d.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){d.d("[HMSAudioTrack]",this.logIdentifier,"device is null",`${this}`);return}if(!this.audioElement){d.d("[HMSAudioTrack]",this.logIdentifier,"no audio element to set output",`${this}`),this.outputDevice=t;return}try{typeof this.audioElement.setSinkId=="function"&&(Fs||(yield(i=this.audioElement)==null?void 0:i.setSinkId(t.deviceId)),this.outputDevice=t)}catch(r){d.d("[HMSAudioTrack]","error in setSinkId",r)}})}subscribeToAudio(t){return c(this,null,function*(){this.stream instanceof Se&&(yield this.stream.setAudio(t,this.trackId,this.logIdentifier))})}};var ta=Ce(require("lodash.isequal"));var Js=require("uuid");var Ir=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Ir||{});function Zo(){if(
|
|
16
|
+
}`}};var Pe=class extends ke{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?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){d.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){d.d("[HMSAudioTrack]",this.logIdentifier,"device is null",`${this}`);return}if(!this.audioElement){d.d("[HMSAudioTrack]",this.logIdentifier,"no audio element to set output",`${this}`),this.outputDevice=t;return}try{typeof this.audioElement.setSinkId=="function"&&(Fs||(yield(i=this.audioElement)==null?void 0:i.setSinkId(t.deviceId)),this.outputDevice=t)}catch(r){d.d("[HMSAudioTrack]","error in setSinkId",r)}})}subscribeToAudio(t){return c(this,null,function*(){this.stream instanceof Se&&(yield this.stream.setAudio(t,this.trackId,this.logIdentifier))})}};var ta=Ce(require("lodash.isequal"));var Js=require("uuid");var Ir=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Ir||{});function Zo(){if(_&&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 We=Zo();var Ws=require("uuid");var M={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},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 f=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`{
|
|
17
17
|
code: ${this.code};
|
|
18
18
|
name: ${this.name};
|
|
19
19
|
action: ${this.action};
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
description: ${this.description};
|
|
22
22
|
isTerminal: ${this.isTerminal};
|
|
23
23
|
nativeError: ${(t=this.nativeError)==null?void 0:t.message};
|
|
24
|
-
}`}};function Rr(a){switch(a){case"join":return"JOIN";case"offer":return"PUBLISH";case"answer":return"SUBSCRIBE";case"track-update":return"TRACK";default:return"NONE"}}var en=["join","offer","answer","trickle","on-error","JOIN"],m={WebSocketConnectionErrors:{FailedToConnect(a,e=""){return new f(M.WebSocketConnectionErrors.FAILED_TO_CONNECT,"WebsocketFailedToConnect",a,`[WS]: ${e}`,`[WS]: ${e}`)},WebSocketConnectionLost(a,e=""){return new f(M.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,"WebSocketConnectionLost",a,"Network connection lost ",e)},AbnormalClose(a,e=""){return new f(M.WebSocketConnectionErrors.ABNORMAL_CLOSE,"WebSocketAbnormalClose",a,"Websocket closed abnormally",e)}},APIErrors:{ServerErrors(a,e,t="",i=!0){return new f(a,"ServerErrors",e,`[${e}]: Server error ${t}`,t,i)},EndpointUnreachable(a,e=""){return new f(M.APIErrors.ENDPOINT_UNREACHABLE,"EndpointUnreachable",a,`Endpoint is not reachable - ${e}`,e)},InvalidTokenFormat(a,e=""){return new f(M.APIErrors.INVALID_TOKEN_FORMAT,"InvalidTokenFormat",a,`Token is not in proper JWT format - ${e}`,e,!0)},InitConfigNotAvailable(a,e=""){return new f(M.APIErrors.INIT_CONFIG_NOT_AVAILABLE,"InitError",a,`[INIT]: ${e}`,`[INIT]: ${e}`)}},TracksErrors:{GenericTrack(a,e=""){return new f(M.TracksErrors.GENERIC_TRACK,"GenericTrack",a,`[TRACK]: ${e}`,`[TRACK]: ${e}`)},CantAccessCaptureDevice(a,e,t=""){return new f(M.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,"CantAccessCaptureDevice",a,`User denied permission to access capture device - ${e}`,t)},DeviceNotAvailable(a,e,t=""){return new f(M.TracksErrors.DEVICE_NOT_AVAILABLE,"DeviceNotAvailable",a,`[TRACK]: Capture device is no longer available - ${e}`,t)},DeviceInUse(a,e,t=""){return new f(M.TracksErrors.DEVICE_IN_USE,"DeviceInUse",a,`[TRACK]: Capture device is in use by another application - ${e}`,t)},DeviceLostMidway(a,e,t=""){return new f(M.TracksErrors.DEVICE_LOST_MIDWAY,"DeviceLostMidway",a,`Lost access to capture device midway - ${e}`,t)},NothingToReturn(a,e="",t="There is no media to return. Please select either video or audio or both."){return new f(M.TracksErrors.NOTHING_TO_RETURN,"NothingToReturn",a,t,e)},InvalidVideoSettings(a,e=""){return new f(M.TracksErrors.INVALID_VIDEO_SETTINGS,"InvalidVideoSettings",a,"Cannot enable simulcast when no video settings are provided",e)},AutoplayBlocked(a,e=""){return new f(M.TracksErrors.AUTOPLAY_ERROR,"AutoplayBlocked",a,"Autoplay blocked because the user didn't interact with the document first",e)},CodecChangeNotPermitted(a,e=""){return new f(M.TracksErrors.CODEC_CHANGE_NOT_PERMITTED,"CodecChangeNotPermitted",a,"Codec can't be changed mid call.",e)},OverConstrained(a,e,t=""){return new f(M.TracksErrors.OVER_CONSTRAINED,"OverConstrained",a,`[TRACK]: Requested constraints cannot be satisfied with the device hardware - ${e}`,t)},NoAudioDetected(a,e="Please check the mic or use another audio input"){return new f(M.TracksErrors.NO_AUDIO_DETECTED,"NoAudioDetected",a,"No audio input detected from microphone",e)},SystemDeniedPermission(a,e,t=""){return new f(M.TracksErrors.SYSTEM_DENIED_PERMISSION,"SystemDeniedPermission",a,`Operating System denied permission to access capture device - ${e}`,t)},CurrentTabNotShared(){return new f(M.TracksErrors.CURRENT_TAB_NOT_SHARED,"CurrentTabNotShared","TRACK","The app requires you to share the current tab","You must screen share the current tab in order to proceed")},AudioPlaybackError(a){return new f(M.TracksErrors.AUDIO_PLAYBACK_ERROR,"Audio playback error","TRACK",a,a)},SelectedDeviceMissing(a){return new f(M.TracksErrors.SELECTED_DEVICE_MISSING,"SelectedDeviceMissing","TRACK",`Could not detect selected ${a} device`,`Please check connection to the ${a} device`,!1)}},WebrtcErrors:{CreateOfferFailed(a,e=""){return new f(M.WebrtcErrors.CREATE_OFFER_FAILED,"CreateOfferFailed",a,`[${a.toString()}]: Failed to create offer. `,e)},CreateAnswerFailed(a,e=""){return new f(M.WebrtcErrors.CREATE_ANSWER_FAILED,"CreateAnswerFailed",a,`[${a.toString()}]: Failed to create answer. `,e)},SetLocalDescriptionFailed(a,e=""){return new f(M.WebrtcErrors.SET_LOCAL_DESCRIPTION_FAILED,"SetLocalDescriptionFailed",a,`[${a.toString()}]: Failed to set offer. `,e)},SetRemoteDescriptionFailed(a,e=""){return new f(M.WebrtcErrors.SET_REMOTE_DESCRIPTION_FAILED,"SetRemoteDescriptionFailed",a,`[${a.toString()}]: Failed to set answer. `,e,!0)},ICEFailure(a,e="",t=!1){return new f(M.WebrtcErrors.ICE_FAILURE,"ICEFailure",a,`[${a.toString()}]: Ice connection state FAILED`,e,t)},ICEDisconnected(a,e=""){return new f(M.WebrtcErrors.ICE_DISCONNECTED,"ICEDisconnected",a,`[${a.toString()}]: Ice connection state DISCONNECTED`,e)},StatsFailed(a,e=""){return new f(M.WebrtcErrors.STATS_FAILED,"StatsFailed",a,`Failed to WebRTC get stats - ${e}`,e)}},WebsocketMethodErrors:{ServerErrors(a,e,t){return new f(a,"ServerErrors",e,t,t,en.includes(e))},AlreadyJoined(a,e=""){return new f(M.WebsocketMethodErrors.ALREADY_JOINED,"AlreadyJoined",a,"[JOIN]: You have already joined this room.",e)},CannotJoinPreviewInProgress(a,e=""){return new f(M.WebsocketMethodErrors.CANNOT_JOIN_PREVIEW_IN_PROGRESS,"CannotJoinPreviewInProgress",a,"[JOIN]: Cannot join if preview is in progress",e)}},GenericErrors:{NotConnected(a,e=""){return new f(M.GenericErrors.NOT_CONNECTED,"NotConnected",a,"Client is not connected",e)},Signalling(a,e){return new f(M.GenericErrors.SIGNALLING,"Signalling",a,`Unknown signalling error: ${a.toString()} ${e} `,e)},Unknown(a,e){return new f(M.GenericErrors.UNKNOWN,"Unknown",a,`Unknown exception: ${e}`,e)},NotReady(a,e=""){return new f(M.GenericErrors.NOT_READY,"NotReady",a,e,e)},JsonParsingFailed(a,e,t=""){return new f(M.GenericErrors.JSON_PARSING_FAILED,"JsonParsingFailed",a,`Failed to parse JSON message - ${e}`,t)},TrackMetadataMissing(a,e=""){return new f(M.GenericErrors.TRACK_METADATA_MISSING,"TrackMetadataMissing",a,"Track Metadata Missing",e)},RTCTrackMissing(a,e=""){return new f(M.GenericErrors.RTC_TRACK_MISSING,"RTCTrackMissing",a,"RTC Track missing",e)},PeerMetadataMissing(a,e=""){return new f(M.GenericErrors.PEER_METADATA_MISSING,"PeerMetadataMissing",a,"Peer Metadata Missing",e)},ValidationFailed(a,e){return new f(M.GenericErrors.VALIDATION_FAILED,"ValidationFailed","VALIDATION",a,e?JSON.stringify(e):"")},InvalidRole(a,e){return new f(M.GenericErrors.INVALID_ROLE,"InvalidRole",a,"Invalid role. Join with valid role",e,!0)},PreviewAlreadyInProgress(a,e=""){return new f(M.GenericErrors.PREVIEW_IN_PROGRESS,"PreviewAlreadyInProgress",a,"[Preview]: Cannot join if preview is in progress",e)},LocalStorageAccessDenied(a="Access to localStorage has been denied"){return new f(M.GenericErrors.LOCAL_STORAGE_ACCESS_DENIED,"LocalStorageAccessDenied","NONE","LocalStorageAccessDenied",a)},MissingMediaDevices(){return new f(M.GenericErrors.MISSING_MEDIADEVICES,"MissingMediaDevices","JOIN","navigator.mediaDevices is undefined. 100ms SDK won't work on this website as WebRTC is not supported on HTTP endpoints(missing navigator.mediaDevices). Please ensure you're using the SDK either on localhost or a valid HTTPS endpoint.","",!0)},MissingRTCPeerConnection(){return new f(M.GenericErrors.MISSING_RTCPEERCONNECTION,"MissingRTCPeerConnection","JOIN","RTCPeerConnection which is a core requirement for WebRTC call was not found, this could be due to an unsupported browser or browser extensions blocking WebRTC","",!0)}},MediaPluginErrors:{PlatformNotSupported(a,e=""){return new f(7001,"PlatformNotSupported",a,"Check HMS Docs to see the list of supported platforms",e)},InitFailed(a,e=""){return new f(7002,"InitFailed",a,"Plugin init failed",e)},ProcessingFailed(a,e=""){return new f(7003,"ProcessingFailed",a,"Plugin processing failed",e)},AddAlreadyInProgress(a,e=""){return new f(7004,"AddAlreadyInProgress",a,"Plugin add already in progress",e)},DeviceNotSupported(a,e=""){return new f(7005,"DeviceNotSupported",a,"Check HMS Docs to see the list of supported devices",e)}},PlaylistErrors:{NoEntryToPlay(a,e){return new f(M.PlaylistErrors.NO_ENTRY_TO_PLAY,"NoEntryToPlay",a,"Reached end of playlist",e)},NoEntryPlaying(a,e){return new f(M.PlaylistErrors.NO_ENTRY_IS_PLAYING,"NoEntryIsPlaying",a,"No entry is playing at this time",e)}}};var Hr=class{constructor(){this.valuesMap=new Map}getItem(e){return this.valuesMap.has(e)?String(this.valuesMap.get(e)):null}setItem(e,t){this.valuesMap.set(e,t)}removeItem(e){this.valuesMap.delete(e)}clear(){this.valuesMap.clear()}key(e){if(arguments.length===0)throw new TypeError("Failed to execute 'key' on 'Storage': 1 argument required, but only 0 present.");return Array.from(this.valuesMap.keys())[e]}get length(){return this.valuesMap.size}},Gs=()=>{try{w&&!localStorage&&(window.localStorage=new Hr)}catch(a){d.e("Error initialising localStorage",m.GenericErrors.LocalStorageAccessDenied())}};var le=class{constructor(e){this.key=e;this.storage=null}getStorage(){try{return w&&!this.storage&&(Gs(),this.storage=window.localStorage),this.storage}catch(e){return d.e("Error initialising localStorage",m.GenericErrors.LocalStorageAccessDenied()),null}}get(){var i;let e=(i=this.getStorage())==null?void 0:i.getItem(this.key);return e?JSON.parse(e):void 0}set(e){var i;let t=JSON.stringify(e);(i=this.getStorage())==null||i.setItem(this.key,t)}clear(){var e;(e=this.getStorage())==null||e.removeItem(this.key)}};var Ws=()=>{let a,e=new le("hms-analytics-deviceId"),t=e.get();return t?a=t:(a=(0,$s.v4)(),e.set(a)),a};var Ks="[VALIDATIONS]";function se(a){return a!=null}var Cr=()=>{if(!se(RTCPeerConnection)){let a=m.GenericErrors.MissingRTCPeerConnection();throw d.e(Ks,a),a}},Lr=()=>{if(!se(navigator.mediaDevices)){let a=m.GenericErrors.MissingMediaDevices();throw d.e(Ks,a),a}};var qs=Dr().version;function mt(a="prod",e){let t="web",i=$e!=="LOCAL"&&a==="prod"?"prod":"debug";if(De)return js({os:"web_nodejs",os_version:process.version,sdk:t,sdk_version:qs,env:i,domain:$e,is_prebuilt:!!(e!=null&&e.isPrebuilt),framework:"node",framework_version:process.version,framework_sdk_version:e==null?void 0:e.sdkVersion});let r=de.getOS(),s=de.getDevice(),o=de.getBrowser(),n=wr(`web_${r.name}`),l=r.version||"",u=wr(`${o.name}_${o.version}`),p=u;return s.type&&(p=`${wr(`${s.vendor}_${s.type}`)}/${u}`),js({os:n,os_version:l,sdk:t,sdk_version:qs,device_model:p,env:i,domain:$e,is_prebuilt:!!(e!=null&&e.isPrebuilt),framework:e==null?void 0:e.type,framework_version:e==null?void 0:e.version,framework_sdk_version:e==null?void 0:e.sdkVersion})}function wr(a){return a.replace(/ /g,"_")}var js=(a,e=",")=>Object.keys(a).filter(t=>se(a[t])).map(t=>`${t}:${a[t]}`).join(e);var R=class{constructor({name:e,level:t,properties:i,includesPII:r,timestamp:s}){this.metadata={peer:{},userAgent:mt()};this.name=e,this.level=t,this.includesPII=r||!1,this.properties=i||{},this.timestamp=s||new Date().getTime(),this.event_id=(0,Js.v4)(),this.device_id=Ws()}toSignalParams(){return{name:this.name,info:v(S({},this.properties),{timestamp:this.timestamp,domain:$e}),timestamp:new Date().getTime()}}};var y=class{static connect(e,t,i=new Date,r=new Date,s){let o=this.eventNameFor("connect",e===void 0),n=e?2:1,l=this.getPropertiesWithError(v(S({},t),{[this.KEY_REQUESTED_AT]:i==null?void 0:i.getTime(),[this.KEY_RESPONDED_AT]:r==null?void 0:r.getTime(),endpoint:s}),e);return new R({name:o,level:n,properties:l})}static disconnect(e,t){let i="disconnected",r=e?2:1,s=this.getPropertiesWithError(t,e);return new R({name:i,level:r,properties:s})}static preview(i){var r=i,{error:e}=r,t=lr(r,["error"]);let s=this.eventNameFor("preview",e===void 0),o=e?2:1,n=this.getPropertiesWithError(t,e);return new R({name:s,level:o,properties:n})}static join(i){var r=i,{error:e}=r,t=lr(r,["error"]);let s=this.eventNameFor("join",e===void 0),o=e?2:1,n=this.getPropertiesWithError(v(S({},t),{is_preview_called:!!t.is_preview_called}),e);return new R({name:s,level:o,properties:n})}static publish({devices:e,settings:t,error:i}){let r=this.eventNameFor("publish",i===void 0),s=i?2:1,o=this.getPropertiesWithError({devices:e,audio:t==null?void 0:t.audio,video:t==null?void 0:t.video},i);return new R({name:r,level:s,properties:o})}static hlsPlayerError(e){return new R({name:"hlsPlayerError",level:2,properties:this.getErrorProperties(e)})}static subscribeFail(e){let t=this.eventNameFor("subscribe",!1),i=2,r=this.getErrorProperties(e);return new R({name:t,level:i,properties:r})}static leave(){return new R({name:"leave",level:1})}static autoplayError(){return new R({name:"autoplayError",level:2})}static audioPlaybackError(e){return new R({name:"audioPlaybackError",level:2,properties:this.getErrorProperties(e)})}static deviceChange({isUserSelection:e,selection:t,type:i,devices:r,error:s}){let o=this.eventNameFor(s?"publish":`device.${i}`,s===void 0),n=s?2:1,l=this.getPropertiesWithError({selection:t,devices:r,isUserSelection:e},s);return new R({name:o,level:n,properties:l})}static performance(e){let t="perf.stats",i=1,r=e.toAnalyticsProperties();return new R({name:t,level:i,properties:r})}static rtcStats(e){let t="rtc.stats",i=1,r=e.toAnalyticsProperties();return new R({name:t,level:i,properties:r})}static rtcStatsFailed(e){let t="rtc.stats.failed",i=2;return new R({name:t,level:i,properties:this.getErrorProperties(e)})}static degradationStats(e,t){let i="video.degradation.stats",r=1,s={degradedAt:e.degradedAt,trackId:e.trackId};if(!t&&e.degradedAt instanceof Date){let o=new Date,n=o.valueOf()-e.degradedAt.valueOf();s=v(S({},s),{duration:n,restoredAt:o})}return new R({name:i,level:r,properties:s})}static audioDetectionFail(e,t){let i=this.getPropertiesWithError({device:t},e),r=2,s="audiopresence.failed";return new R({name:s,level:r,properties:i})}static previewNetworkQuality(e){return new R({name:"perf.networkquality.preview",level:e.error?2:1,properties:e})}static publishStats(e){return new R({name:"publisher.stats",level:1,properties:e})}static subscribeStats(e){return new R({name:"subscriber.stats",level:1,properties:e})}static getKrispUsage(e){return new R({name:"krisp.usage",level:1,properties:{duration:e}})}static eventNameFor(e,t){return`${e}.${t?"success":"failed"}`}static getPropertiesWithError(e,t){let i=this.getErrorProperties(t);return e=S(S({},i),e),e}static getErrorProperties(e){return e?e instanceof f?e.toAnalyticsProperties():{error_name:e.name,error_message:e.message,error_description:e.cause}:{}}};y.KEY_REQUESTED_AT="requested_at",y.KEY_RESPONDED_AT="responded_at";var _r=class{constructor(){this.storage=new le("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){d.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)}},Q=new _r;var ii=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(ii||{}),ri=(t=>(t.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",t.DEVICE_NOT_SUPPORTED="DEVICE_NOT_SUPPORTED",t))(ri||{});var ae=class{static failure(e,t){let i="mediaPlugin.failed",r=2,s=S({plugin_name:e},t.toAnalyticsProperties());return new R({name:i,level:r,properties:s})}static audioPluginFailure(e,t,i){let r="mediaPlugin.failed",s=2,o=S({plugin_name:e,sampleRate:t},i.toAnalyticsProperties());return new R({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 R({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 R({name:i,level:r,properties:s})}static stats({pluginName:e,duration:t,loadTime:i,avgPreProcessingTime:r,avgProcessingTime:s,inputFrameRate:o,pluginFrameRate:n}){let l="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 R({name:l,level:u,properties:p})}};var si=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(ae.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(ae.audioPluginStats(t)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(ae.audioPluginFailure(e,this.pluginSampleRate[e],t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){d.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),d.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let s=m.MediaPluginErrors.InitFailed("AUDIO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw d.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 rn=48e3,sn=()=>navigator.userAgent.indexOf("Firefox")!==-1,St=class{constructor(e,t){this.eventBus=t;this.TAG="[AudioPluginsManager]";this.pluginAddInProgress=!1;this.hmsTrack=e,this.pluginsMap=new Map,this.analytics=new si(t),this.createAudioContext()}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(!t){d.w("no name provided by the plugin");return}if(this.pluginAddInProgress){let r=m.MediaPluginErrors.AddAlreadyInProgress("AUDIO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.added(t,this.audioContext.sampleRate),this.analytics.failure(t,r),d.w("can't add another plugin when previous add is in progress"),r}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)){d.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()}catch(s){throw d.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)d.i(this.TAG,`plugin is supported,- ${t.getName()}`);else if(this.analytics.added(e,this.audioContext.sampleRate),i.errType==="PLATFORM_NOT_SUPPORTED"){let r=m.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=m.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*(){yield this.removePluginInternal(e),this.pluginsMap.size===0?(yield this.cleanup(),d.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*(){var e;(e=this.audioContext)==null||e.close(),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)})}initAudioNodes(){return c(this,null,function*(){if(this.audioContext){if(!this.sourceNode){let e=new MediaStream([this.hmsTrack.nativeTrack]);this.sourceNode=this.audioContext.createMediaStreamSource(e)}if(!this.destinationNode){this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputTrack=this.destinationNode.stream.getAudioTracks()[0];try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(e){throw d.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();d.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){d.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)){d.w(this.TAG,`plugin - ${t} not found to remove.`);return}d.i(this.TAG,`removing plugin ${t}`),this.pluginsMap.delete(t),e.stop(),this.analytics.removed(t)})}createAudioContext(){this.audioContext||(sn()?this.audioContext=new AudioContext:this.audioContext=new AudioContext({sampleRate:rn}))}};var Nr=Ce(require("webrtc-adapter"));function an(a,e){let t=a.toLowerCase();return t.includes("device not found")?m.TracksErrors.DeviceNotAvailable("TRACK",e,a):t.includes("permission denied")?m.TracksErrors.CantAccessCaptureDevice("TRACK",e,a):m.TracksErrors.GenericTrack("TRACK",a)}function on(a,e=""){if(Nr.default.browserDetails.browser==="chrome"&&a.name==="NotAllowedError"&&a.message.includes("denied by system"))return m.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);if(Nr.default.browserDetails.browser==="firefox"&&a.name==="NotFoundError"){let i=m.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 m.TracksErrors.OverConstrained("TRACK",e,a.constraint);case"NotAllowedError":return m.TracksErrors.CantAccessCaptureDevice("TRACK",e,a.message);case"NotFoundError":return m.TracksErrors.DeviceNotAvailable("TRACK",e,a.message);case"NotReadableError":return m.TracksErrors.DeviceInUse("TRACK",e,a.message);case"TypeError":return m.TracksErrors.NothingToReturn("TRACK",a.message);default:return an(a.message,e)}}function We(a,e){let t=on(a,e);return t.addNativeError(a),t}function Qs(a){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({audio:a?a.toConstraints():!1})).getAudioTracks()[0]}catch(e){throw We(e,"audio")}})}function zs(a){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({video:a?a.toConstraints():!1})).getVideoTracks()[0]}catch(e){throw We(e,"video")}})}function ue(a){return"canvas"in a||a.label==="MediaStreamAudioDestinationNode"||a.label===""}var Ee={audioContext:null,getAudioContext(){return this.audioContext||(this.audioContext=new AudioContext),this.audioContext},resumeContext(){return c(this,null,function*(){try{return yield this.getAudioContext().resume()}catch(a){d.e("AudioContext",a)}})}};var be=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 Ys=`(function workerSetup() {
|
|
24
|
+
}`}};function Rr(a){switch(a){case"join":return"JOIN";case"offer":return"PUBLISH";case"answer":return"SUBSCRIBE";case"track-update":return"TRACK";default:return"NONE"}}var en=["join","offer","answer","trickle","on-error","JOIN"],m={WebSocketConnectionErrors:{FailedToConnect(a,e=""){return new f(M.WebSocketConnectionErrors.FAILED_TO_CONNECT,"WebsocketFailedToConnect",a,`[WS]: ${e}`,`[WS]: ${e}`)},WebSocketConnectionLost(a,e=""){return new f(M.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,"WebSocketConnectionLost",a,"Network connection lost ",e)},AbnormalClose(a,e=""){return new f(M.WebSocketConnectionErrors.ABNORMAL_CLOSE,"WebSocketAbnormalClose",a,"Websocket closed abnormally",e)}},APIErrors:{ServerErrors(a,e,t="",i=!0){return new f(a,"ServerErrors",e,`[${e}]: Server error ${t}`,t,i)},EndpointUnreachable(a,e=""){return new f(M.APIErrors.ENDPOINT_UNREACHABLE,"EndpointUnreachable",a,`Endpoint is not reachable - ${e}`,e)},InvalidTokenFormat(a,e=""){return new f(M.APIErrors.INVALID_TOKEN_FORMAT,"InvalidTokenFormat",a,`Token is not in proper JWT format - ${e}`,e,!0)},InitConfigNotAvailable(a,e=""){return new f(M.APIErrors.INIT_CONFIG_NOT_AVAILABLE,"InitError",a,`[INIT]: ${e}`,`[INIT]: ${e}`)}},TracksErrors:{GenericTrack(a,e=""){return new f(M.TracksErrors.GENERIC_TRACK,"GenericTrack",a,`[TRACK]: ${e}`,`[TRACK]: ${e}`)},CantAccessCaptureDevice(a,e,t=""){return new f(M.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,"CantAccessCaptureDevice",a,`User denied permission to access capture device - ${e}`,t)},DeviceNotAvailable(a,e,t=""){return new f(M.TracksErrors.DEVICE_NOT_AVAILABLE,"DeviceNotAvailable",a,`[TRACK]: Capture device is no longer available - ${e}`,t)},DeviceInUse(a,e,t=""){return new f(M.TracksErrors.DEVICE_IN_USE,"DeviceInUse",a,`[TRACK]: Capture device is in use by another application - ${e}`,t)},DeviceLostMidway(a,e,t=""){return new f(M.TracksErrors.DEVICE_LOST_MIDWAY,"DeviceLostMidway",a,`Lost access to capture device midway - ${e}`,t)},NothingToReturn(a,e="",t="There is no media to return. Please select either video or audio or both."){return new f(M.TracksErrors.NOTHING_TO_RETURN,"NothingToReturn",a,t,e)},InvalidVideoSettings(a,e=""){return new f(M.TracksErrors.INVALID_VIDEO_SETTINGS,"InvalidVideoSettings",a,"Cannot enable simulcast when no video settings are provided",e)},AutoplayBlocked(a,e=""){return new f(M.TracksErrors.AUTOPLAY_ERROR,"AutoplayBlocked",a,"Autoplay blocked because the user didn't interact with the document first",e)},CodecChangeNotPermitted(a,e=""){return new f(M.TracksErrors.CODEC_CHANGE_NOT_PERMITTED,"CodecChangeNotPermitted",a,"Codec can't be changed mid call.",e)},OverConstrained(a,e,t=""){return new f(M.TracksErrors.OVER_CONSTRAINED,"OverConstrained",a,`[TRACK]: Requested constraints cannot be satisfied with the device hardware - ${e}`,t)},NoAudioDetected(a,e="Please check the mic or use another audio input"){return new f(M.TracksErrors.NO_AUDIO_DETECTED,"NoAudioDetected",a,"No audio input detected from microphone",e)},SystemDeniedPermission(a,e,t=""){return new f(M.TracksErrors.SYSTEM_DENIED_PERMISSION,"SystemDeniedPermission",a,`Operating System denied permission to access capture device - ${e}`,t)},CurrentTabNotShared(){return new f(M.TracksErrors.CURRENT_TAB_NOT_SHARED,"CurrentTabNotShared","TRACK","The app requires you to share the current tab","You must screen share the current tab in order to proceed")},AudioPlaybackError(a){return new f(M.TracksErrors.AUDIO_PLAYBACK_ERROR,"Audio playback error","TRACK",a,a)},SelectedDeviceMissing(a){return new f(M.TracksErrors.SELECTED_DEVICE_MISSING,"SelectedDeviceMissing","TRACK",`Could not detect selected ${a} device`,`Please check connection to the ${a} device`,!1)}},WebrtcErrors:{CreateOfferFailed(a,e=""){return new f(M.WebrtcErrors.CREATE_OFFER_FAILED,"CreateOfferFailed",a,`[${a.toString()}]: Failed to create offer. `,e)},CreateAnswerFailed(a,e=""){return new f(M.WebrtcErrors.CREATE_ANSWER_FAILED,"CreateAnswerFailed",a,`[${a.toString()}]: Failed to create answer. `,e)},SetLocalDescriptionFailed(a,e=""){return new f(M.WebrtcErrors.SET_LOCAL_DESCRIPTION_FAILED,"SetLocalDescriptionFailed",a,`[${a.toString()}]: Failed to set offer. `,e)},SetRemoteDescriptionFailed(a,e=""){return new f(M.WebrtcErrors.SET_REMOTE_DESCRIPTION_FAILED,"SetRemoteDescriptionFailed",a,`[${a.toString()}]: Failed to set answer. `,e,!0)},ICEFailure(a,e="",t=!1){return new f(M.WebrtcErrors.ICE_FAILURE,"ICEFailure",a,`[${a.toString()}]: Ice connection state FAILED`,e,t)},ICEDisconnected(a,e=""){return new f(M.WebrtcErrors.ICE_DISCONNECTED,"ICEDisconnected",a,`[${a.toString()}]: Ice connection state DISCONNECTED`,e)},StatsFailed(a,e=""){return new f(M.WebrtcErrors.STATS_FAILED,"StatsFailed",a,`Failed to WebRTC get stats - ${e}`,e)}},WebsocketMethodErrors:{ServerErrors(a,e,t){return new f(a,"ServerErrors",e,t,t,en.includes(e))},AlreadyJoined(a,e=""){return new f(M.WebsocketMethodErrors.ALREADY_JOINED,"AlreadyJoined",a,"[JOIN]: You have already joined this room.",e)},CannotJoinPreviewInProgress(a,e=""){return new f(M.WebsocketMethodErrors.CANNOT_JOIN_PREVIEW_IN_PROGRESS,"CannotJoinPreviewInProgress",a,"[JOIN]: Cannot join if preview is in progress",e)}},GenericErrors:{NotConnected(a,e=""){return new f(M.GenericErrors.NOT_CONNECTED,"NotConnected",a,"Client is not connected",e)},Signalling(a,e){return new f(M.GenericErrors.SIGNALLING,"Signalling",a,`Unknown signalling error: ${a.toString()} ${e} `,e)},Unknown(a,e){return new f(M.GenericErrors.UNKNOWN,"Unknown",a,`Unknown exception: ${e}`,e)},NotReady(a,e=""){return new f(M.GenericErrors.NOT_READY,"NotReady",a,e,e)},JsonParsingFailed(a,e,t=""){return new f(M.GenericErrors.JSON_PARSING_FAILED,"JsonParsingFailed",a,`Failed to parse JSON message - ${e}`,t)},TrackMetadataMissing(a,e=""){return new f(M.GenericErrors.TRACK_METADATA_MISSING,"TrackMetadataMissing",a,"Track Metadata Missing",e)},RTCTrackMissing(a,e=""){return new f(M.GenericErrors.RTC_TRACK_MISSING,"RTCTrackMissing",a,"RTC Track missing",e)},PeerMetadataMissing(a,e=""){return new f(M.GenericErrors.PEER_METADATA_MISSING,"PeerMetadataMissing",a,"Peer Metadata Missing",e)},ValidationFailed(a,e){return new f(M.GenericErrors.VALIDATION_FAILED,"ValidationFailed","VALIDATION",a,e?JSON.stringify(e):"")},InvalidRole(a,e){return new f(M.GenericErrors.INVALID_ROLE,"InvalidRole",a,"Invalid role. Join with valid role",e,!0)},PreviewAlreadyInProgress(a,e=""){return new f(M.GenericErrors.PREVIEW_IN_PROGRESS,"PreviewAlreadyInProgress",a,"[Preview]: Cannot join if preview is in progress",e)},LocalStorageAccessDenied(a="Access to localStorage has been denied"){return new f(M.GenericErrors.LOCAL_STORAGE_ACCESS_DENIED,"LocalStorageAccessDenied","NONE","LocalStorageAccessDenied",a)},MissingMediaDevices(){return new f(M.GenericErrors.MISSING_MEDIADEVICES,"MissingMediaDevices","JOIN","navigator.mediaDevices is undefined. 100ms SDK won't work on this website as WebRTC is not supported on HTTP endpoints(missing navigator.mediaDevices). Please ensure you're using the SDK either on localhost or a valid HTTPS endpoint.","",!0)},MissingRTCPeerConnection(){return new f(M.GenericErrors.MISSING_RTCPEERCONNECTION,"MissingRTCPeerConnection","JOIN","RTCPeerConnection which is a core requirement for WebRTC call was not found, this could be due to an unsupported browser or browser extensions blocking WebRTC","",!0)}},MediaPluginErrors:{PlatformNotSupported(a,e=""){return new f(7001,"PlatformNotSupported",a,"Check HMS Docs to see the list of supported platforms",e)},InitFailed(a,e=""){return new f(7002,"InitFailed",a,"Plugin init failed",e)},ProcessingFailed(a,e=""){return new f(7003,"ProcessingFailed",a,"Plugin processing failed",e)},AddAlreadyInProgress(a,e=""){return new f(7004,"AddAlreadyInProgress",a,"Plugin add already in progress",e)},DeviceNotSupported(a,e=""){return new f(7005,"DeviceNotSupported",a,"Check HMS Docs to see the list of supported devices",e)}},PlaylistErrors:{NoEntryToPlay(a,e){return new f(M.PlaylistErrors.NO_ENTRY_TO_PLAY,"NoEntryToPlay",a,"Reached end of playlist",e)},NoEntryPlaying(a,e){return new f(M.PlaylistErrors.NO_ENTRY_IS_PLAYING,"NoEntryIsPlaying",a,"No entry is playing at this time",e)}}};var Hr=class{constructor(){this.valuesMap=new Map}getItem(e){return this.valuesMap.has(e)?String(this.valuesMap.get(e)):null}setItem(e,t){this.valuesMap.set(e,t)}removeItem(e){this.valuesMap.delete(e)}clear(){this.valuesMap.clear()}key(e){if(arguments.length===0)throw new TypeError("Failed to execute 'key' on 'Storage': 1 argument required, but only 0 present.");return Array.from(this.valuesMap.keys())[e]}get length(){return this.valuesMap.size}},Gs=()=>{try{_&&!localStorage&&(window.localStorage=new Hr)}catch(a){d.e("Error initialising localStorage",m.GenericErrors.LocalStorageAccessDenied())}};var le=class{constructor(e){this.key=e;this.storage=null}getStorage(){try{return _&&!this.storage&&(Gs(),this.storage=window.localStorage),this.storage}catch(e){return d.e("Error initialising localStorage",m.GenericErrors.LocalStorageAccessDenied()),null}}get(){var i;let e=(i=this.getStorage())==null?void 0:i.getItem(this.key);return e?JSON.parse(e):void 0}set(e){var i;let t=JSON.stringify(e);(i=this.getStorage())==null||i.setItem(this.key,t)}clear(){var e;(e=this.getStorage())==null||e.removeItem(this.key)}};var $s=()=>{let a,e=new le("hms-analytics-deviceId"),t=e.get();return t?a=t:(a=(0,Ws.v4)(),e.set(a)),a};var Ks="[VALIDATIONS]";function se(a){return a!=null}var Cr=()=>{if(!se(RTCPeerConnection)){let a=m.GenericErrors.MissingRTCPeerConnection();throw d.e(Ks,a),a}},Lr=()=>{if(!se(navigator.mediaDevices)){let a=m.GenericErrors.MissingMediaDevices();throw d.e(Ks,a),a}};var qs=wr().version;function mt(a="prod",e){let t="web",i=We!=="LOCAL"&&a==="prod"?"prod":"debug";if(we)return js({os:"web_nodejs",os_version:process.version,sdk:t,sdk_version:qs,env:i,domain:We,is_prebuilt:!!(e!=null&&e.isPrebuilt),framework:"node",framework_version:process.version,framework_sdk_version:e==null?void 0:e.sdkVersion});let r=de.getOS(),s=de.getDevice(),o=de.getBrowser(),n=Dr(`web_${r.name}`),l=r.version||"",u=Dr(`${o.name}_${o.version}`),p=u;return s.type&&(p=`${Dr(`${s.vendor}_${s.type}`)}/${u}`),js({os:n,os_version:l,sdk:t,sdk_version:qs,device_model:p,env:i,domain:We,is_prebuilt:!!(e!=null&&e.isPrebuilt),framework:e==null?void 0:e.type,framework_version:e==null?void 0:e.version,framework_sdk_version:e==null?void 0:e.sdkVersion})}function Dr(a){return a.replace(/ /g,"_")}var js=(a,e=",")=>Object.keys(a).filter(t=>se(a[t])).map(t=>`${t}:${a[t]}`).join(e);var R=class{constructor({name:e,level:t,properties:i,includesPII:r,timestamp:s}){this.metadata={peer:{},userAgent:mt()};this.name=e,this.level=t,this.includesPII=r||!1,this.properties=i||{},this.timestamp=s||new Date().getTime(),this.event_id=(0,Js.v4)(),this.device_id=$s()}toSignalParams(){return{name:this.name,info:v(S({},this.properties),{timestamp:this.timestamp,domain:We}),timestamp:new Date().getTime()}}};var y=class{static connect(e,t,i=new Date,r=new Date,s){let o=this.eventNameFor("connect",e===void 0),n=e?2:1,l=this.getPropertiesWithError(v(S({},t),{[this.KEY_REQUESTED_AT]:i==null?void 0:i.getTime(),[this.KEY_RESPONDED_AT]:r==null?void 0:r.getTime(),endpoint:s}),e);return new R({name:o,level:n,properties:l})}static disconnect(e,t){let i="disconnected",r=e?2:1,s=this.getPropertiesWithError(t,e);return new R({name:i,level:r,properties:s})}static preview(i){var r=i,{error:e}=r,t=lr(r,["error"]);let s=this.eventNameFor("preview",e===void 0),o=e?2:1,n=this.getPropertiesWithError(t,e);return new R({name:s,level:o,properties:n})}static join(i){var r=i,{error:e}=r,t=lr(r,["error"]);let s=this.eventNameFor("join",e===void 0),o=e?2:1,n=this.getPropertiesWithError(v(S({},t),{is_preview_called:!!t.is_preview_called}),e);return new R({name:s,level:o,properties:n})}static publish({devices:e,settings:t,error:i}){let r=this.eventNameFor("publish",i===void 0),s=i?2:1,o=this.getPropertiesWithError({devices:e,audio:t==null?void 0:t.audio,video:t==null?void 0:t.video},i);return new R({name:r,level:s,properties:o})}static hlsPlayerError(e){return new R({name:"hlsPlayerError",level:2,properties:this.getErrorProperties(e)})}static subscribeFail(e){let t=this.eventNameFor("subscribe",!1),i=2,r=this.getErrorProperties(e);return new R({name:t,level:i,properties:r})}static leave(){return new R({name:"leave",level:1})}static autoplayError(){return new R({name:"autoplayError",level:2})}static audioPlaybackError(e){return new R({name:"audioPlaybackError",level:2,properties:this.getErrorProperties(e)})}static deviceChange({isUserSelection:e,selection:t,type:i,devices:r,error:s}){let o=this.eventNameFor(s?"publish":`device.${i}`,s===void 0),n=s?2:1,l=this.getPropertiesWithError({selection:t,devices:r,isUserSelection:e},s);return new R({name:o,level:n,properties:l})}static performance(e){let t="perf.stats",i=1,r=e.toAnalyticsProperties();return new R({name:t,level:i,properties:r})}static rtcStats(e){let t="rtc.stats",i=1,r=e.toAnalyticsProperties();return new R({name:t,level:i,properties:r})}static rtcStatsFailed(e){let t="rtc.stats.failed",i=2;return new R({name:t,level:i,properties:this.getErrorProperties(e)})}static degradationStats(e,t){let i="video.degradation.stats",r=1,s={degradedAt:e.degradedAt,trackId:e.trackId};if(!t&&e.degradedAt instanceof Date){let o=new Date,n=o.valueOf()-e.degradedAt.valueOf();s=v(S({},s),{duration:n,restoredAt:o})}return new R({name:i,level:r,properties:s})}static audioDetectionFail(e,t){let i=this.getPropertiesWithError({device:t},e),r=2,s="audiopresence.failed";return new R({name:s,level:r,properties:i})}static previewNetworkQuality(e){return new R({name:"perf.networkquality.preview",level:e.error?2:1,properties:e})}static publishStats(e){return new R({name:"publisher.stats",level:1,properties:e})}static subscribeStats(e){return new R({name:"subscriber.stats",level:1,properties:e})}static getKrispUsage(e){return new R({name:"krisp.usage",level:1,properties:{duration:e}})}static eventNameFor(e,t){return`${e}.${t?"success":"failed"}`}static getPropertiesWithError(e,t){let i=this.getErrorProperties(t);return e=S(S({},i),e),e}static getErrorProperties(e){return e?e instanceof f?e.toAnalyticsProperties():{error_name:e.name,error_message:e.message,error_description:e.cause}:{}}};y.KEY_REQUESTED_AT="requested_at",y.KEY_RESPONDED_AT="responded_at";var _r=class{constructor(){this.storage=new le("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){d.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)}},Q=new _r;var ii=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(ii||{}),ri=(t=>(t.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",t.DEVICE_NOT_SUPPORTED="DEVICE_NOT_SUPPORTED",t))(ri||{});var ae=class{static failure(e,t){let i="mediaPlugin.failed",r=2,s=S({plugin_name:e},t.toAnalyticsProperties());return new R({name:i,level:r,properties:s})}static audioPluginFailure(e,t,i){let r="mediaPlugin.failed",s=2,o=S({plugin_name:e,sampleRate:t},i.toAnalyticsProperties());return new R({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 R({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 R({name:i,level:r,properties:s})}static stats({pluginName:e,duration:t,loadTime:i,avgPreProcessingTime:r,avgProcessingTime:s,inputFrameRate:o,pluginFrameRate:n}){let l="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 R({name:l,level:u,properties:p})}};var si=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(ae.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(ae.audioPluginStats(t)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(ae.audioPluginFailure(e,this.pluginSampleRate[e],t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){d.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),d.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let s=m.MediaPluginErrors.InitFailed("AUDIO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw d.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 rn=48e3,sn=()=>navigator.userAgent.indexOf("Firefox")!==-1,St=class{constructor(e,t){this.eventBus=t;this.TAG="[AudioPluginsManager]";this.pluginAddInProgress=!1;this.hmsTrack=e,this.pluginsMap=new Map,this.analytics=new si(t),this.createAudioContext()}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(!t){d.w("no name provided by the plugin");return}if(this.pluginAddInProgress){let r=m.MediaPluginErrors.AddAlreadyInProgress("AUDIO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.added(t,this.audioContext.sampleRate),this.analytics.failure(t,r),d.w("can't add another plugin when previous add is in progress"),r}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)){d.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()}catch(s){throw d.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)d.i(this.TAG,`plugin is supported,- ${t.getName()}`);else if(this.analytics.added(e,this.audioContext.sampleRate),i.errType==="PLATFORM_NOT_SUPPORTED"){let r=m.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=m.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*(){yield this.removePluginInternal(e),this.pluginsMap.size===0?(yield this.cleanup(),d.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*(){var e;(e=this.audioContext)==null||e.close(),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)})}initAudioNodes(){return c(this,null,function*(){if(this.audioContext){if(!this.sourceNode){let e=new MediaStream([this.hmsTrack.nativeTrack]);this.sourceNode=this.audioContext.createMediaStreamSource(e)}if(!this.destinationNode){this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputTrack=this.destinationNode.stream.getAudioTracks()[0];try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(e){throw d.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();d.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){d.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)){d.w(this.TAG,`plugin - ${t} not found to remove.`);return}d.i(this.TAG,`removing plugin ${t}`),this.pluginsMap.delete(t),e.stop(),this.analytics.removed(t)})}createAudioContext(){this.audioContext||(sn()?this.audioContext=new AudioContext:this.audioContext=new AudioContext({sampleRate:rn}))}};var Nr=Ce(require("webrtc-adapter"));function an(a,e){let t=a.toLowerCase();return t.includes("device not found")?m.TracksErrors.DeviceNotAvailable("TRACK",e,a):t.includes("permission denied")?m.TracksErrors.CantAccessCaptureDevice("TRACK",e,a):m.TracksErrors.GenericTrack("TRACK",a)}function on(a,e=""){if(Nr.default.browserDetails.browser==="chrome"&&a.name==="NotAllowedError"&&a.message.includes("denied by system"))return m.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);if(Nr.default.browserDetails.browser==="firefox"&&a.name==="NotFoundError"){let i=m.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 m.TracksErrors.OverConstrained("TRACK",e,a.constraint);case"NotAllowedError":return m.TracksErrors.CantAccessCaptureDevice("TRACK",e,a.message);case"NotFoundError":return m.TracksErrors.DeviceNotAvailable("TRACK",e,a.message);case"NotReadableError":return m.TracksErrors.DeviceInUse("TRACK",e,a.message);case"TypeError":return m.TracksErrors.NothingToReturn("TRACK",a.message);default:return an(a.message,e)}}function $e(a,e){let t=on(a,e);return t.addNativeError(a),t}function Qs(a){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({audio:a?a.toConstraints():!1})).getAudioTracks()[0]}catch(e){throw $e(e,"audio")}})}function zs(a){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({video:a?a.toConstraints():!1})).getVideoTracks()[0]}catch(e){throw $e(e,"video")}})}function ue(a){return"canvas"in a||a.label==="MediaStreamAudioDestinationNode"||a.label===""}var Ee={audioContext:null,getAudioContext(){return this.audioContext||(this.audioContext=new AudioContext),this.audioContext},resumeContext(){return c(this,null,function*(){try{return yield this.getAudioContext().resume()}catch(a){d.e("AudioContext",a)}})}};var be=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 Ys=`(function workerSetup() {
|
|
25
25
|
function ticker() {
|
|
26
26
|
self.postMessage('tick');
|
|
27
27
|
}
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
break;
|
|
36
36
|
}
|
|
37
37
|
};
|
|
38
|
-
})()`;function z(a){if(a<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,a)})}function Ae(a){if(a<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return z(a);let e=new Worker(URL.createObjectURL(new Blob([Ys],{type:"application/javascript"})));return e.postMessage(["start",a]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function Xs(){if(typeof Worker=="undefined")return{sleep:e=>z(e)};let a=new Worker(URL.createObjectURL(new Blob([Ys],{type:"application/javascript"})));return{sleep:e=>(a.postMessage(["start",e]),new Promise(t=>{a.onmessage=i=>{i.data==="tick"&&t()}}))}}function ai(a,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{a.apply(r,i)},e)}}var cn=35,dn=5,oi=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 be(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 z(20)}});try{let r=new MediaStream([this.track.nativeTrack]);this.analyserNode=this.createAnalyserNodeForStream(r)}catch(r){d.w(this.TAG,"Unable to initialize AudioContext",r)}}start(){this.stop(),this.isMonitored=!0,d.d(this.TAG,"Starting track Monitor",`${this.track}`),this.loop().then(()=>d.d(this.TAG,"Stopping track Monitor",`${this.track}`))}stop(){if(!this.analyserNode){d.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 z(this.interval)})}sendAudioLevel(e=0){if(e=e>cn?e:0,Math.abs(this.audioLevel-e)>dn){this.audioLevel=e;let i={track:this.track,audioLevel:this.audioLevel};this.audioLevelEvent.publish(i)}}getMaxAudioLevelOverPeriod(){if(!this.analyserNode){d.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){d.d(this.TAG,"AudioContext not initialized");return}let e=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(e);let t=.009,i=t;for(let o of e)i=Math.max(i,(o-128)/128);let r=(Math.log(t)-Math.log(i))/Math.log(t);return Math.ceil(Math.min(Math.max(r*100,0),100))}isSilentThisInstant(){if(!this.analyserNode){d.d(this.TAG,"AudioContext not initialized");return}let e=new Uint8Array(this.analyserNode.fftSize);return this.analyserNode.getByteTimeDomainData(e),!e.some(t=>t!==128&&t!==0)}createAnalyserNodeForStream(e){let t=Ee.getAudioContext(),i=t.createAnalyser();return t.createMediaStreamSource(e).connect(i),i}};var Or=(n=>(n.NONE="none",n.INITIALISED="initialised",n.STARTED="started",n.PAUSED="paused",n.RESUMED="resumed",n.STOPPED="stopped",n.FAILED="failed",n))(Or||{});var xr=(t=>(t.DVR="dvr",t.NO_DVR="no-dvr",t))(xr||{});var Ie={f:"high",h:"medium",q:"low"};var Ur=(i=>(i.videoInput="videoInput",i.audioInput="audioInput",i.audioOutput="audioOutput",i))(Ur||{});var oe=class{constructor(){this._volume=1;this._codec="opus";this._maxBitrate=32;this._deviceId="default";this._advanced=[{googEchoCancellation:{exact:!0}},{googExperimentalEchoCancellation:{exact:!0}},{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}},{googHighpassFilter:{exact:!0}},{googAudioMirroring:{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=e,this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}build(){return new _e(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced)}},_e=class{constructor(e,t,i,r,s){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=s}toConstraints(){return{deviceId:this.deviceId,advanced:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}};var ee=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 Ne(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate,this._facingMode)}},Ne=class{constructor(e,t,i,r,s,o,n,l){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=n,this.deviceId=s,this.advanced=o,this.facingMode=l}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 we()&&this.height&&this.width&&this.height>this.width?{width:this.height,height:this.width}:{width:this.width,height:this.height}}};var gt=class{constructor(){this._video=new ee().build();this._audio=new oe().build();this._screen=new ee().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 m.TracksErrors.NothingToReturn("TRACK");if(this._video===null&&this._simulcast)throw m.TracksErrors.InvalidVideoSettings("TRACK","Cannot enable simulcast when no video settings are provided");return new Ke(this._video,this._audio,this._simulcast,this._screen||void 0)}},Ke=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=S(S({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=S(S({},this.video.toAnalyticsProperties()),e)),e}};function ea(a,e){return function(i){return!(0,ta.default)(a[i],e[i])}}var ne=class a extends Pe{constructor(t,i,r,s,o=new oe().build()){super(t,i,r);this.eventBus=s;this.TAG="[HMSLocalAudioTrack]";this.isPublished=!1;this.handleVisibilityChange=()=>c(this,null,function*(){document.visibilityState==="visible"&&(yield this.replaceTrackWith(this.settings))});this.replaceSenderTrack=()=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){d.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(this.processedTrack||this.nativeTrack)});this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=ea(t,this.settings);r("maxBitrate")&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this)),r("advanced")&&(yield this.replaceTrackWith(t))});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(ea(t,this.settings)("deviceId")){this.manuallySelectedDeviceId=i?this.manuallySelectedDeviceId:t.deviceId,d.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&&(Q.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.settings=o,o.deviceId!==i.getSettings().deviceId&&!ue(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new St(this,s),this.setFirstTrackId(i.id),Ar()&&w&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}getManuallySelectedDeviceId(){return this.manuallySelectedDeviceId}resetManuallySelectedDeviceId(){this.manuallySelectedDeviceId=void 0}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop();let r=!!this.audioLevelMonitor;try{let s=yield Qs(t);s.enabled=this.enabled,d.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",s),yield this.stream.replaceStreamTrack(i,s),this.nativeTrack=s,yield this.replaceSenderTrack(),r&&this.initAudioLevelMonitor()}catch(s){throw this.isPublished&&this.eventBus.analytics.publish(y.publish({error:s})),s}try{yield this.pluginsManager.reprocessPlugins()}catch(s){this.eventBus.audioPluginFailed.publish(s)}})}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(t&&ue(this.nativeTrack)&&(yield this.replaceTrackWith(this.settings)),yield q(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(ue(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(),d.d(this.TAG,"Monitor Audio Level for",this,this.getMediaTrackSettings().deviceId),this.audioLevelMonitor=new oi(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;q(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.isPublished=!1,this.destroyAudioLevelMonitor(),Ar()&&w&&document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}getTrackIDBeingSent(){return this.processedTrack?this.processedTrack.id:this.nativeTrack.id}getTrackBeingSent(){return this.processedTrack||this.nativeTrack}buildNewSettings(t){let{volume:i,codec:r,maxBitrate:s,deviceId:o,advanced:n}=S(S({},this.settings),t);return new _e(i,r,s,o,n)}};var te=class a extends Pe{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield q(a.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var qe=class extends ke{constructor(t,i,r){super(t,i,r);this.type="video";this.sinkCount=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 s=r.getVideoTracks()[0];if((s==null?void 0:s.id)===i.id){if(!s.muted&&s.readyState==="live")return;this.reduceSinkCount()}else this.reduceSinkCount()}t.srcObject=new MediaStream([i]),this.sinkCount++}reduceSinkCount(){this.sinkCount>0&&this.sinkCount--}};var da=Ce(require("lodash.isequal"));var aa=require("uuid");var Tt={none:-1,low:0,medium:1,high:2},ln=.5,ia=(a,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...a].sort((o,n)=>Tt[o.layer]-Tt[n.layer]),s=e[i]*((window==null?void 0:window.devicePixelRatio)||1);for(let o=0;o<r.length;o++){let{resolution:n,layer:l}=r[o],u=n[i];if(s<=u){t=l;break}else{let p=r[o+1],h=p?p.resolution[i]:Number.POSITIVE_INFINITY;if((s-u)/(h-u)<ln){t=l;break}}}return t};var Br=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=w&&typeof window.IntersectionObserver!="undefined";return e||d.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},ra=new Br;var Vr=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(ai(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=w&&typeof window.ResizeObserver!="undefined";return e||d.w(this.TAG,"Resize Observer is not supported"),e}},sa=new Vr;var je=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))?(d.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)):(d.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 N)||(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,aa.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(),d.d(this.TAG,`Adding video element for ${this.track}`,this.id),this.videoElements.add(e),this.videoElements.size>=10&&d.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):w&&(this.isElementInViewport(e)?this.track.addSink(e):this.track.removeSink(e)),this.resizeObserver?this.resizeObserver.observe(e,this.handleResize):this.track instanceof N&&(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),d.d(this.TAG,`Removing video element for ${this.track}`)}getVideoElements(){return Array.from(this.videoElements)}init(){w&&(this.resizeObserver=sa,this.intersectionObserver=ra)}isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft,r=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{opacity:n,display:l}=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)&&l!=="none"}selectMaxLayer(){return c(this,null,function*(){if(!(this.track instanceof N)||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=ia(this.track.getSimulcastDefinitions(),{width:r,height:s});e?e=Tt[o]>Tt[e]?o:e:e=o}e&&(d.d(this.TAG,`selecting max layer ${e} for the track`,`${this.track}`),yield this.track.setPreferredLayer(e))})}};var ni=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(ni||{}),ci=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(ci||{});var ft=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 Je=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new ft,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 ft,t&&(this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t),this.eventBus.analytics.publish(ae.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(ae.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(ae.failure(e,t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){d.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),d.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let s=m.MediaPluginErrors.InitFailed("VIDEO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw d.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=m.MediaPluginErrors.ProcessingFailed("VIDEO_PLUGINS",`Failed during processing of plugin${s.message||s}`);throw d.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 oa=24,un=320,pn=240,vt=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.reusableWorker=Xs();this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new Je(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===""){d.w("no name provided by the plugin");return}let s=m.MediaPluginErrors.AddAlreadyInProgress("VIDEO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.failure(r,s),d.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===""){d.w("no name provided by the plugin");return}if(this.pluginsMap.has(i)){d.w(this.TAG,`plugin - ${e.getName()} already added.`);return}let r=this.hmsTrack.getMediaTrackSettings().frameRate||oa,s=0;t&&t>0?(d.i(this.TAG,`adding plugin ${e.getName()} with framerate ${t}`),t<r&&(s=Math.ceil(r/t)-1),this.analytics.added(i,r,t)):(d.i(this.TAG,`adding plugin ${e.getName()}`),this.analytics.added(i,r)),d.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 l=this.canvases.length;l<=this.pluginsMap.size;l++)this.canvases[l]=document.createElement("canvas");yield this.startPluginsLoop((n=e.getContextType)==null?void 0:n.call(e))}catch(l){throw d.e(this.TAG,"failed to add plugin",l),yield this.removePlugin(e),l}})}validatePlugin(e){return e.checkSupport()}validateAndThrow(e,t){let i=this.validatePlugin(t);if(i.isSupported)d.i(this.TAG,`plugin is supported,- ${t.getName()}`);else{let r;switch(i.errType){case"PLATFORM_NOT_SUPPORTED":throw r=m.MediaPluginErrors.PlatformNotSupported("VIDEO_PLUGINS","platform not supported, see docs"),this.analytics.failure(e,r),r;case"DEVICE_NOT_SUPPORTED":throw r=m.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)){d.w(this.TAG,`plugin - ${t} not found to remove.`);return}d.i(this.TAG,`removing plugin ${t}`),this.removePluginEntry(t),this.pluginsMap.size===0&&(d.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 Ae(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,d.e(this.TAG,"error in setting processed track",t),t}this.pluginsLoop().then(()=>{d.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||oa,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){d.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(l){d.e(this.TAG,`error in processing plugin ${i}`,l)}});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){d.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=un,height:t=pn}=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 di=class{constructor(e){this.plugins=new Set,this.analytics=new Je(e)}addPlugins(e){e.forEach(t=>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),d.e("Could not apply plugin",s,r)}}return t}getPlugins(){return Array.from(this.plugins).map(e=>e.getName())}};var na=require("uuid");var hn=["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"],li=class{constructor(){this.eventPerformanceMeasures={}}start(e){performance.mark(e)}end(e){var t;try{this.eventPerformanceMeasures[e]=performance.measure(e,e),d.d("[HMSPerformanceTiming]",e,(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration)}catch(i){d.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[...hn,...e].reduce((t,i)=>v(S({},t),{[i]:this.getTimeTaken(i)}),{})}cleanup(){this.eventPerformanceMeasures={}}};var Fr={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default"},pe,ui,ge=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=Fr){let t=this.getAVTrackSettings(e);if(!t)return[];let i=!!t.audio,r=!!t.video,s=[],{videoTrack:o,audioTrack:n}=yield this.updateCurrentLocalTrackSettings(t),l=(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 h={audio:i&&!n&&(e.isAudioMuted?"empty":!0),video:r&&!o&&(e.isVideoMuted?"empty":!0)};h.audio&&this.analyticsTimer.start("local_audio_track_time"),h.video&&this.analyticsTimer.start("local_video_track_time");try{d.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:h}),s=yield this.getLocalTracks(h,t,l)}catch(g){s=yield this.retryGetLocalTracks(g,t,h,l)}return h.audio&&this.analyticsTimer.end("local_audio_track_time"),h.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 Ke(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})}getLocalScreen(e){return c(this,null,function*(){var h;let t=yield this.getOrDefaultScreenshareConfig(e),i=this.getScreenshareSettings(t.videoOnly),r={video:v(S({},i==null?void 0:i.video.toConstraints(!0)),{displaySurface:t.displaySurface}),preferCurrentTab:t.preferCurrentTab,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio};if(i!=null&&i.audio){let g=(h=i==null?void 0:i.audio)==null?void 0:h.toConstraints();delete g.advanced,r.audio=v(S({},g),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})}let s;try{d.d("retrieving screenshare with ",{config:t},{constraints:r}),s=yield navigator.mediaDevices.getDisplayMedia(r)}catch(g){d.w(this.TAG,"error in getting screenshare - ",g);let T=We(g,"screen");throw this.eventBus.analytics.publish(y.publish({error:T,devices:this.deviceManager.getDevices(),settings:new Ke(i==null?void 0:i.video,i==null?void 0:i.audio,!1)})),T}let o=[],n=new Oe(s),l=s.getVideoTracks()[0],u=new B(n,l,"screen",this.eventBus,i==null?void 0:i.video);u.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"screen"));try{let g=this.validateCurrentTabCapture(u,t.forceCurrentTab);u.isCurrentTab=g,yield u.cropTo(t.cropTarget)}catch(g){throw s.getTracks().forEach(T=>T.stop()),g}o.push(u);let p=s.getAudioTracks()[0];if(p){let g=new ne(n,p,"screen",this.eventBus,i==null?void 0:i.audio);o.push(g)}return d.v(this.TAG,"getLocalScreen",o),o})}setScreenCaptureHandleConfig(e){var t;!((t=navigator.mediaDevices)!=null&&t.setCaptureHandleConfig)||this.isInIframe()||(e=e||{},Object.assign(e,{handle:(0,na.v4)(),exposeOrigin:!1,permittedOrigins:[window.location.origin]}),d.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 d.e(this.TAG,"current tab was not shared with forceCurrentTab as true"),m.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){d.e(this.TAG,e)}})}static getEmptyVideoTrack(e){var n,l,u;let t=((n=e==null?void 0:e.getSettings())==null?void 0:n.width)||320,i=((l=e==null?void 0:e.getSettings())==null?void 0:l.height)||240,r=1;pe||(pe=document.createElement("canvas"),pe.width=t,pe.height=i,(u=pe.getContext("2d"))==null||u.fillRect(0,0,t,i)),ui||(ui=setInterval(()=>{let p=pe==null?void 0:pe.getContext("2d");p&&p.fillRect(0,0,1,1)},1e3/r));let o=pe.captureStream(r).getVideoTracks()[0];return o.enabled=!1,o}static getEmptyAudioTrack(){let e=Ee.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(ui),ui=void 0,pe=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 We(t,s)}})}getAVTrackSettings(e){let t=this.getAudioSettings(e),i=this.getVideoSettings(e);return!t&&!i?null:new gt().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 f&&e.action==="TRACK"){this.observer.onFailure(e);let s=e.code===M.TracksErrors.OVER_CONSTRAINED,o=e.message.includes("audio"),n=e.message.includes("video");if(s){let l=new gt().video(new Ne).audio(new _e).build();d.w(this.TAG,"Fetch AV Tracks failed with overconstrained error",{fetchTrackOptions:i},{error:e});try{return yield this.getLocalTracks(i,l,r)}catch(u){let p=u instanceof f?u.nativeError:u,h=u;if((p==null?void 0:p.name)==="OverconstrainedError"){let g=m.TracksErrors.GenericTrack("TRACK","Overconstrained error after dropping all constraints");g.addNativeError(p),h=g}return yield this.retryGetLocalTracks(h,t,i,r)}}i.audio=o?"empty":i.audio,i.video=n?"empty":i.video,d.w(this.TAG,"Fetch AV Tracks failed",{fetchTrackOptions:i},e);try{return yield this.getLocalTracks(i,t,r)}catch(l){return d.w(this.TAG,"Fetch empty tacks failed",l),i.audio=i.audio&&"empty",i.video=i.video&&"empty",this.observer.onFailure(l),yield this.getLocalTracks(i,t,r)}}else return d.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":"unknown(video or audio)"}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 oe().codec(t.audio.codec).maxBitrate(t.audio.bitRate).deviceId(s||Fr.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 ee().codec(o.codec).maxBitrate(o.bitRate).maxFramerate(o.frameRate).setWidth(o.width).setHeight(o.height).deviceId(s||Fr.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 ee().maxBitrate(i.bitRate,!1).codec(i.codec).maxFramerate(i.frameRate).setWidth(i.width).setHeight(i.height).build(),audio:e?void 0:new oe().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 Oe(new MediaStream(e));let o=[];if(s&&(t!=null&&t.audio)){let n=new ne(i,s,"regular",this.eventBus,t.audio);o.push(n)}if(r&&(t!=null&&t.video)){let n=new B(i,r,"regular",this.eventBus,t.video);n.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"regular")),o.push(n)}return o}};function ca(a,e){return function(i){return!(0,da.default)(a[i],e[i])}}var B=class a extends qe{constructor(t,i,r,s,o=new ee().build()){super(t,i,r);this.eventBus=s;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"){d.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:l,advanced:u,facingMode:p}=S(S({},this.settings),t);return new Ne(i,r,s,o,l,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=ca(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(ca(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&&(Q.updateSelection("videoInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"video",selection:{deviceId:t.deviceId,groupId:s}}))}});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*(){document.visibilityState==="hidden"&&this.source==="regular"?(this.enabledStateBeforeBackground=this.enabled,this.nativeTrack.enabled=!1,this.replaceSenderTrack(this.nativeTrack)):(this.nativeTrack.enabled=this.enabledStateBeforeBackground,this.replaceSenderTrack(this.nativeTrack)),this.eventBus.localVideoEnabled.publish({enabled:this.nativeTrack.enabled,track:this})});t.tracks.push(this),this.setVideoHandler(new je(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new vt(this,s),this.mediaStreamPluginsManager=new di(s),this.setFirstTrackId(this.trackId),w&&we()&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}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 q(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()}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||ue(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;q(a.prototype,this,"cleanup").call(this),this.transceiver=void 0,yield this.pluginsManager.cleanup(),(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,w&&we()&&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 d.e(this.TAG,"failed to crop screenshare capture - ",i),m.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"){d.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}),Q.updateSelection("videoInput",{deviceId:this.settings.deviceId,groupId:this.nativeTrack.getSettings().groupId})})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop();try{let r=yield zs(t);return d.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){throw this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=ge.getEmptyVideoTrack(t);return t==null||t.stop(),d.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)})}};var Qe="renegotiation-callback-id",pi="ion-sfu";var ze="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var la="https://event.100ms.live/v2/client/report",ua="https://event-nonprod.100ms.live/v2/client/report";var Mt=Math.pow(2,31)-1,V={DEVICE_CHANGE:"device-change",LOCAL_AUDIO_ENABLED:"local-audio-enabled",LOCAL_VIDEO_ENABLED:"local-video-enabled",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"},pa="2.5",ha="20231201",Te="_handraise",$r=1e3,Wr=64;var N=class a extends qe{constructor(t,i,r){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new Kr;this.preferredLayer="high";this.setVideoHandler(new je(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&&(q(a.prototype,this,"setEnabled").call(this,t),this.videoHandler.updateSinks(!0))})}setPreferredLayer(t){return c(this,null,function*(){if(t==="none"){d.w("layer none will be ignored");return}if(this.preferredLayer=t,!!this.shouldSendVideoLayer(t,"preferLayer")){if(!this.hasSinks()){d.d(`[Remote Track] ${this.logIdentifier}
|
|
38
|
+
})()`;function z(a){if(a<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,a)})}function Ae(a){if(a<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return z(a);let e=new Worker(URL.createObjectURL(new Blob([Ys],{type:"application/javascript"})));return e.postMessage(["start",a]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function Xs(){if(typeof Worker=="undefined")return{sleep:e=>z(e)};let a=new Worker(URL.createObjectURL(new Blob([Ys],{type:"application/javascript"})));return{sleep:e=>(a.postMessage(["start",e]),new Promise(t=>{a.onmessage=i=>{i.data==="tick"&&t()}}))}}function ai(a,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{a.apply(r,i)},e)}}var cn=35,dn=5,oi=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 be(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 z(20)}});try{let r=new MediaStream([this.track.nativeTrack]);this.analyserNode=this.createAnalyserNodeForStream(r)}catch(r){d.w(this.TAG,"Unable to initialize AudioContext",r)}}start(){this.stop(),this.isMonitored=!0,d.d(this.TAG,"Starting track Monitor",`${this.track}`),this.loop().then(()=>d.d(this.TAG,"Stopping track Monitor",`${this.track}`))}stop(){if(!this.analyserNode){d.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 z(this.interval)})}sendAudioLevel(e=0){if(e=e>cn?e:0,Math.abs(this.audioLevel-e)>dn){this.audioLevel=e;let i={track:this.track,audioLevel:this.audioLevel};this.audioLevelEvent.publish(i)}}getMaxAudioLevelOverPeriod(){if(!this.analyserNode){d.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){d.d(this.TAG,"AudioContext not initialized");return}let e=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(e);let t=.009,i=t;for(let o of e)i=Math.max(i,(o-128)/128);let r=(Math.log(t)-Math.log(i))/Math.log(t);return Math.ceil(Math.min(Math.max(r*100,0),100))}isSilentThisInstant(){if(!this.analyserNode){d.d(this.TAG,"AudioContext not initialized");return}let e=new Uint8Array(this.analyserNode.fftSize);return this.analyserNode.getByteTimeDomainData(e),!e.some(t=>t!==128&&t!==0)}createAnalyserNodeForStream(e){let t=Ee.getAudioContext(),i=t.createAnalyser();return t.createMediaStreamSource(e).connect(i),i}};var Or=(n=>(n.NONE="none",n.INITIALISED="initialised",n.STARTED="started",n.PAUSED="paused",n.RESUMED="resumed",n.STOPPED="stopped",n.FAILED="failed",n))(Or||{});var xr=(t=>(t.DVR="dvr",t.NO_DVR="no-dvr",t))(xr||{});var Ie={f:"high",h:"medium",q:"low"};var Ur=(i=>(i.videoInput="videoInput",i.audioInput="audioInput",i.audioOutput="audioOutput",i))(Ur||{});var oe=class{constructor(){this._volume=1;this._codec="opus";this._maxBitrate=32;this._deviceId="default";this._advanced=[{googEchoCancellation:{exact:!0}},{googExperimentalEchoCancellation:{exact:!0}},{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}},{googHighpassFilter:{exact:!0}},{googAudioMirroring:{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=e,this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}build(){return new _e(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced)}},_e=class{constructor(e,t,i,r,s){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=s}toConstraints(){return{deviceId:this.deviceId,advanced:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}};var ee=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 Ne(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate,this._facingMode)}},Ne=class{constructor(e,t,i,r,s,o,n,l){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=n,this.deviceId=s,this.advanced=o,this.facingMode=l}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 De()&&this.height&&this.width&&this.height>this.width?{width:this.height,height:this.width}:{width:this.width,height:this.height}}};var gt=class{constructor(){this._video=new ee().build();this._audio=new oe().build();this._screen=new ee().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 m.TracksErrors.NothingToReturn("TRACK");if(this._video===null&&this._simulcast)throw m.TracksErrors.InvalidVideoSettings("TRACK","Cannot enable simulcast when no video settings are provided");return new Ke(this._video,this._audio,this._simulcast,this._screen||void 0)}},Ke=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=S(S({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=S(S({},this.video.toAnalyticsProperties()),e)),e}};function ea(a,e){return function(i){return!(0,ta.default)(a[i],e[i])}}var ne=class a extends Pe{constructor(t,i,r,s,o=new oe().build()){super(t,i,r);this.eventBus=s;this.TAG="[HMSLocalAudioTrack]";this.isPublished=!1;this.handleVisibilityChange=()=>c(this,null,function*(){document.visibilityState==="visible"&&(yield this.replaceTrackWith(this.settings))});this.replaceSenderTrack=()=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){d.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(this.processedTrack||this.nativeTrack)});this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=ea(t,this.settings);r("maxBitrate")&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this)),r("advanced")&&(yield this.replaceTrackWith(t))});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(ea(t,this.settings)("deviceId")){this.manuallySelectedDeviceId=i?this.manuallySelectedDeviceId:t.deviceId,d.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&&(Q.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.settings=o,o.deviceId!==i.getSettings().deviceId&&!ue(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new St(this,s),this.setFirstTrackId(i.id),Ar()&&_&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}getManuallySelectedDeviceId(){return this.manuallySelectedDeviceId}resetManuallySelectedDeviceId(){this.manuallySelectedDeviceId=void 0}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop();let r=!!this.audioLevelMonitor;try{let s=yield Qs(t);s.enabled=this.enabled,d.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",s),yield this.stream.replaceStreamTrack(i,s),this.nativeTrack=s,yield this.replaceSenderTrack(),r&&this.initAudioLevelMonitor()}catch(s){throw this.isPublished&&this.eventBus.analytics.publish(y.publish({error:s})),s}try{yield this.pluginsManager.reprocessPlugins()}catch(s){this.eventBus.audioPluginFailed.publish(s)}})}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(t&&ue(this.nativeTrack)&&(yield this.replaceTrackWith(this.settings)),yield q(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(ue(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(),d.d(this.TAG,"Monitor Audio Level for",this,this.getMediaTrackSettings().deviceId),this.audioLevelMonitor=new oi(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;q(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.isPublished=!1,this.destroyAudioLevelMonitor(),Ar()&&_&&document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}getTrackIDBeingSent(){return this.processedTrack?this.processedTrack.id:this.nativeTrack.id}getTrackBeingSent(){return this.processedTrack||this.nativeTrack}buildNewSettings(t){let{volume:i,codec:r,maxBitrate:s,deviceId:o,advanced:n}=S(S({},this.settings),t);return new _e(i,r,s,o,n)}};var te=class a extends Pe{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield q(a.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var qe=class extends ke{constructor(t,i,r){super(t,i,r);this.type="video";this.sinkCount=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 s=r.getVideoTracks()[0];if((s==null?void 0:s.id)===i.id){if(!s.muted&&s.readyState==="live")return;this.reduceSinkCount()}else this.reduceSinkCount()}t.srcObject=new MediaStream([i]),this.sinkCount++}reduceSinkCount(){this.sinkCount>0&&this.sinkCount--}};var da=Ce(require("lodash.isequal"));var aa=require("uuid");var Tt={none:-1,low:0,medium:1,high:2},ln=.5,ia=(a,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...a].sort((o,n)=>Tt[o.layer]-Tt[n.layer]),s=e[i]*((window==null?void 0:window.devicePixelRatio)||1);for(let o=0;o<r.length;o++){let{resolution:n,layer:l}=r[o],u=n[i];if(s<=u){t=l;break}else{let p=r[o+1],h=p?p.resolution[i]:Number.POSITIVE_INFINITY;if((s-u)/(h-u)<ln){t=l;break}}}return t};var Br=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=_&&typeof window.IntersectionObserver!="undefined";return e||d.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},ra=new Br;var Vr=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(ai(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=_&&typeof window.ResizeObserver!="undefined";return e||d.w(this.TAG,"Resize Observer is not supported"),e}},sa=new Vr;var je=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))?(d.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)):(d.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,aa.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(),d.d(this.TAG,`Adding video element for ${this.track}`,this.id),this.videoElements.add(e),this.videoElements.size>=10&&d.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):_&&(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),d.d(this.TAG,`Removing video element for ${this.track}`)}getVideoElements(){return Array.from(this.videoElements)}init(){_&&(this.resizeObserver=sa,this.intersectionObserver=ra)}isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft,r=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{opacity:n,display:l}=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)&&l!=="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=ia(this.track.getSimulcastDefinitions(),{width:r,height:s});e?e=Tt[o]>Tt[e]?o:e:e=o}e&&(d.d(this.TAG,`selecting max layer ${e} for the track`,`${this.track}`),yield this.track.setPreferredLayer(e))})}};var ni=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(ni||{}),ci=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(ci||{});var ft=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 Je=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new ft,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 ft,t&&(this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t),this.eventBus.analytics.publish(ae.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(ae.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(ae.failure(e,t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){d.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),d.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let s=m.MediaPluginErrors.InitFailed("VIDEO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw d.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=m.MediaPluginErrors.ProcessingFailed("VIDEO_PLUGINS",`Failed during processing of plugin${s.message||s}`);throw d.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 oa=24,un=320,pn=240,vt=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.reusableWorker=Xs();this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new Je(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===""){d.w("no name provided by the plugin");return}let s=m.MediaPluginErrors.AddAlreadyInProgress("VIDEO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.failure(r,s),d.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===""){d.w("no name provided by the plugin");return}if(this.pluginsMap.has(i)){d.w(this.TAG,`plugin - ${e.getName()} already added.`);return}let r=this.hmsTrack.getMediaTrackSettings().frameRate||oa,s=0;t&&t>0?(d.i(this.TAG,`adding plugin ${e.getName()} with framerate ${t}`),t<r&&(s=Math.ceil(r/t)-1),this.analytics.added(i,r,t)):(d.i(this.TAG,`adding plugin ${e.getName()}`),this.analytics.added(i,r)),d.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 l=this.canvases.length;l<=this.pluginsMap.size;l++)this.canvases[l]=document.createElement("canvas");yield this.startPluginsLoop((n=e.getContextType)==null?void 0:n.call(e))}catch(l){throw d.e(this.TAG,"failed to add plugin",l),yield this.removePlugin(e),l}})}validatePlugin(e){return e.checkSupport()}validateAndThrow(e,t){let i=this.validatePlugin(t);if(i.isSupported)d.i(this.TAG,`plugin is supported,- ${t.getName()}`);else{let r;switch(i.errType){case"PLATFORM_NOT_SUPPORTED":throw r=m.MediaPluginErrors.PlatformNotSupported("VIDEO_PLUGINS","platform not supported, see docs"),this.analytics.failure(e,r),r;case"DEVICE_NOT_SUPPORTED":throw r=m.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)){d.w(this.TAG,`plugin - ${t} not found to remove.`);return}d.i(this.TAG,`removing plugin ${t}`),this.removePluginEntry(t),this.pluginsMap.size===0&&(d.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 Ae(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,d.e(this.TAG,"error in setting processed track",t),t}this.pluginsLoop().then(()=>{d.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||oa,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){d.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(l){d.e(this.TAG,`error in processing plugin ${i}`,l)}});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){d.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=un,height:t=pn}=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 di=class{constructor(e){this.plugins=new Set,this.analytics=new Je(e)}addPlugins(e){e.forEach(t=>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),d.e("Could not apply plugin",s,r)}}return t}getPlugins(){return Array.from(this.plugins).map(e=>e.getName())}};var na=require("uuid");var hn=["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"],li=class{constructor(){this.eventPerformanceMeasures={}}start(e){performance.mark(e)}end(e){var t;try{this.eventPerformanceMeasures[e]=performance.measure(e,e),d.d("[HMSPerformanceTiming]",e,(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration)}catch(i){d.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[...hn,...e].reduce((t,i)=>v(S({},t),{[i]:this.getTimeTaken(i)}),{})}cleanup(){this.eventPerformanceMeasures={}}};var Fr={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default"},pe,ui,ge=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=Fr){let t=this.getAVTrackSettings(e);if(!t)return[];let i=!!t.audio,r=!!t.video,s=[],{videoTrack:o,audioTrack:n}=yield this.updateCurrentLocalTrackSettings(t),l=(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 h={audio:i&&!n&&(e.isAudioMuted?"empty":!0),video:r&&!o&&(e.isVideoMuted?"empty":!0)};h.audio&&this.analyticsTimer.start("local_audio_track_time"),h.video&&this.analyticsTimer.start("local_video_track_time");try{d.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:h}),s=yield this.getLocalTracks(h,t,l)}catch(g){s=yield this.retryGetLocalTracks(g,t,h,l)}return h.audio&&this.analyticsTimer.end("local_audio_track_time"),h.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 Ke(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:l,videoHeight:u}=r,p=i.screen,h=p.width*p.height,g=l/u,T=p.width/p.height;if(g>T){let P=t.video,A=g/T,D=Math.sqrt(A);l*u>h?(P.width=l/D,P.height=u/D):(P.height=u*D,P.width=l*D),yield e.getVideoTracks()[0].applyConstraints(P)}}))})}getLocalScreen(e,t=!1){return c(this,null,function*(){var g;let i=yield this.getOrDefaultScreenshareConfig(e),r=this.getScreenshareSettings(i.videoOnly),s={video:v(S({},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 T=(g=r==null?void 0:r.audio)==null?void 0:g.toConstraints();delete T.advanced,s.audio=v(S({},T),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})}let o;try{d.d("retrieving screenshare with ",{config:i},{constraints:s}),o=yield navigator.mediaDevices.getDisplayMedia(s),t&&(yield this.optimizeScreenShareConstraint(o,s))}catch(T){d.w(this.TAG,"error in getting screenshare - ",T);let P=$e(T,"screen");throw this.eventBus.analytics.publish(y.publish({error:P,devices:this.deviceManager.getDevices(),settings:new Ke(r==null?void 0:r.video,r==null?void 0:r.audio,!1)})),P}let n=[],l=new Oe(o),u=o.getVideoTracks()[0],p=new B(l,u,"screen",this.eventBus,r==null?void 0:r.video);p.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"screen"));try{let T=this.validateCurrentTabCapture(p,i.forceCurrentTab);p.isCurrentTab=T,yield p.cropTo(i.cropTarget)}catch(T){throw o.getTracks().forEach(P=>P.stop()),T}n.push(p);let h=o.getAudioTracks()[0];if(h){let T=new ne(l,h,"screen",this.eventBus,r==null?void 0:r.audio);n.push(T)}return d.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,na.v4)(),exposeOrigin:!1,permittedOrigins:[window.location.origin]}),d.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 d.e(this.TAG,"current tab was not shared with forceCurrentTab as true"),m.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){d.e(this.TAG,e)}})}static getEmptyVideoTrack(e){var n,l,u;let t=((n=e==null?void 0:e.getSettings())==null?void 0:n.width)||320,i=((l=e==null?void 0:e.getSettings())==null?void 0:l.height)||240,r=1;pe||(pe=document.createElement("canvas"),pe.width=t,pe.height=i,(u=pe.getContext("2d"))==null||u.fillRect(0,0,t,i)),ui||(ui=setInterval(()=>{let p=pe==null?void 0:pe.getContext("2d");p&&p.fillRect(0,0,1,1)},1e3/r));let o=pe.captureStream(r).getVideoTracks()[0];return o.enabled=!1,o}static getEmptyAudioTrack(){let e=Ee.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(ui),ui=void 0,pe=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 $e(t,s)}})}getAVTrackSettings(e){let t=this.getAudioSettings(e),i=this.getVideoSettings(e);return!t&&!i?null:new gt().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 f&&e.action==="TRACK"){this.observer.onFailure(e);let s=e.code===M.TracksErrors.OVER_CONSTRAINED,o=e.message.includes("audio"),n=e.message.includes("video");if(s){let l=new gt().video(new Ne).audio(new _e).build();d.w(this.TAG,"Fetch AV Tracks failed with overconstrained error",{fetchTrackOptions:i},{error:e});try{return yield this.getLocalTracks(i,l,r)}catch(u){let p=u instanceof f?u.nativeError:u,h=u;if((p==null?void 0:p.name)==="OverconstrainedError"){let g=m.TracksErrors.GenericTrack("TRACK","Overconstrained error after dropping all constraints");g.addNativeError(p),h=g}return yield this.retryGetLocalTracks(h,t,i,r)}}i.audio=o?"empty":i.audio,i.video=n?"empty":i.video,d.w(this.TAG,"Fetch AV Tracks failed",{fetchTrackOptions:i},e);try{return yield this.getLocalTracks(i,t,r)}catch(l){return d.w(this.TAG,"Fetch empty tacks failed",l),i.audio=i.audio&&"empty",i.video=i.video&&"empty",this.observer.onFailure(l),yield this.getLocalTracks(i,t,r)}}else return d.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":"unknown(video or audio)"}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 oe().codec(t.audio.codec).maxBitrate(t.audio.bitRate).deviceId(s||Fr.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 ee().codec(o.codec).maxBitrate(o.bitRate).maxFramerate(o.frameRate).setWidth(o.width).setHeight(o.height).deviceId(s||Fr.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 ee().maxBitrate(i.bitRate,!1).codec(i.codec).maxFramerate(i.frameRate).setWidth(i.width).setHeight(i.height).build(),audio:e?void 0:new oe().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 Oe(new MediaStream(e));let o=[];if(s&&(t!=null&&t.audio)){let n=new ne(i,s,"regular",this.eventBus,t.audio);o.push(n)}if(r&&(t!=null&&t.video)){let n=new B(i,r,"regular",this.eventBus,t.video);n.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"regular")),o.push(n)}return o}};function ca(a,e){return function(i){return!(0,da.default)(a[i],e[i])}}var B=class a extends qe{constructor(t,i,r,s,o=new ee().build()){super(t,i,r);this.eventBus=s;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"){d.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:l,advanced:u,facingMode:p}=S(S({},this.settings),t);return new Ne(i,r,s,o,l,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=ca(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(ca(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&&(Q.updateSelection("videoInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"video",selection:{deviceId:t.deviceId,groupId:s}}))}});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*(){document.visibilityState==="hidden"&&this.source==="regular"?(this.enabledStateBeforeBackground=this.enabled,this.nativeTrack.enabled=!1,this.replaceSenderTrack(this.nativeTrack)):(this.nativeTrack.enabled=this.enabledStateBeforeBackground,this.replaceSenderTrack(this.nativeTrack)),this.eventBus.localVideoEnabled.publish({enabled:this.nativeTrack.enabled,track:this})});t.tracks.push(this),this.setVideoHandler(new je(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new vt(this,s),this.mediaStreamPluginsManager=new di(s),this.setFirstTrackId(this.trackId),_&&De()&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}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 q(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()}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||ue(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;q(a.prototype,this,"cleanup").call(this),this.transceiver=void 0,yield this.pluginsManager.cleanup(),(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,_&&De()&&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 d.e(this.TAG,"failed to crop screenshare capture - ",i),m.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"){d.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}),Q.updateSelection("videoInput",{deviceId:this.settings.deviceId,groupId:this.nativeTrack.getSettings().groupId})})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop();try{let r=yield zs(t);return d.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){throw this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=ge.getEmptyVideoTrack(t);return t==null||t.stop(),d.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)})}};var Qe="renegotiation-callback-id",pi="ion-sfu";var ze="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var la="https://event.100ms.live/v2/client/report",ua="https://event-nonprod.100ms.live/v2/client/report";var Mt=Math.pow(2,31)-1,V={DEVICE_CHANGE:"device-change",LOCAL_AUDIO_ENABLED:"local-audio-enabled",LOCAL_VIDEO_ENABLED:"local-video-enabled",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"},pa="2.5",ha="20231201",Te="_handraise",Wr=1e3,$r=64;var O=class a extends qe{constructor(t,i,r){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new Kr;this.preferredLayer="high";this.setVideoHandler(new je(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&&(q(a.prototype,this,"setEnabled").call(this,t),this.videoHandler.updateSinks(!0))})}setPreferredLayer(t){return c(this,null,function*(){if(t==="none"){d.w("layer none will be ignored");return}if(this.preferredLayer=t,!!this.shouldSendVideoLayer(t,"preferLayer")){if(!this.hasSinks()){d.d(`[Remote Track] ${this.logIdentifier}
|
|
39
39
|
streamId=${this.stream.id}
|
|
40
40
|
trackId=${this.trackId}
|
|
41
41
|
saving ${t}, source=${this.source}
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
streamId=${this.stream.id}
|
|
55
55
|
trackId=${this.trackId}
|
|
56
56
|
Failed to set layer ${t}, source=${i}
|
|
57
|
-
error=${r.message}`),r}})}shouldSendVideoLayer(t,i){let r=this.getLayer();return this.degraded&&t==="none"?!0:r===t?(d.d(`[Remote Track] ${this.logIdentifier}`,`Not sending update, already on layer ${t}, source=${i}`),!1):!0}},Kr=class{constructor(){this.history=[]}push(e){e.time=new Date().toISOString().split("T")[1],this.history.push(e)}};var Oe=class extends Ge{constructor(){super(...arguments);this.TAG="[HMSLocalStream]";this.connection=null}setConnection(t){this.connection=t}addTransceiver(t,i){let r=this.connection.addTransceiver(t.getTrackBeingSent(),{streams:[this.nativeStream],direction:"sendonly",sendEncodings:this.getTrackEncodings(t,i)});return this.setPreferredCodec(r,t.nativeTrack.kind),t.transceiver=r,r}setMaxBitrateAndFramerate(t){return c(this,null,function*(){var i;yield(i=this.connection)==null?void 0:i.setMaxBitrateAndFramerate(t)})}setPreferredCodec(t,i){}replaceStreamTrack(t,i){this.nativeStream.addTrack(i),this.nativeStream.removeTrack(t)}removeSender(t){var s,o;if(!this.connection||this.connection.connectionState==="closed"){d.d(this.TAG,"publish connection is not initialised or closed");return}let i=(s=t.transceiver)==null?void 0:s.sender;if(!i){d.w(this.TAG,`No sender found for trackId=${t.trackId}`);return}(o=this.connection)==null||o.removeTrack(i);let r=this.tracks.indexOf(t);r!==-1?this.tracks.splice(r,1):d.w(this.TAG,`Cannot find ${t.trackId} in locally stored tracks`)}getTrackEncodings(t,i){let r=[];if(t instanceof B)if(i.length>0)d.d(this.TAG,"Simulcast enabled with layers",i),r.push(...i);else{let s={active:this.nativeStream.active};t.settings.maxBitrate&&!
|
|
57
|
+
error=${r.message}`),r}})}shouldSendVideoLayer(t,i){let r=this.getLayer();return this.degraded&&t==="none"?!0:r===t?(d.d(`[Remote Track] ${this.logIdentifier}`,`Not sending update, already on layer ${t}, source=${i}`),!1):!0}},Kr=class{constructor(){this.history=[]}push(e){e.time=new Date().toISOString().split("T")[1],this.history.push(e)}};var Oe=class extends Ge{constructor(){super(...arguments);this.TAG="[HMSLocalStream]";this.connection=null}setConnection(t){this.connection=t}addTransceiver(t,i){let r=this.connection.addTransceiver(t.getTrackBeingSent(),{streams:[this.nativeStream],direction:"sendonly",sendEncodings:this.getTrackEncodings(t,i)});return this.setPreferredCodec(r,t.nativeTrack.kind),t.transceiver=r,r}setMaxBitrateAndFramerate(t){return c(this,null,function*(){var i;yield(i=this.connection)==null?void 0:i.setMaxBitrateAndFramerate(t)})}setPreferredCodec(t,i){}replaceStreamTrack(t,i){this.nativeStream.addTrack(i),this.nativeStream.removeTrack(t)}removeSender(t){var s,o;if(!this.connection||this.connection.connectionState==="closed"){d.d(this.TAG,"publish connection is not initialised or closed");return}let i=(s=t.transceiver)==null?void 0:s.sender;if(!i){d.w(this.TAG,`No sender found for trackId=${t.trackId}`);return}(o=this.connection)==null||o.removeTrack(i);let r=this.tracks.indexOf(t);r!==-1?this.tracks.splice(r,1):d.w(this.TAG,`Cannot find ${t.trackId} in locally stored tracks`)}getTrackEncodings(t,i){let r=[];if(t instanceof B)if(i.length>0)d.d(this.TAG,"Simulcast enabled with layers",i),r.push(...i);else{let s={active:this.nativeStream.active};t.settings.maxBitrate&&!we&&(s.maxBitrate=t.settings.maxBitrate),r.push(s)}return r}};var Se=class extends Ge{constructor(t,i){super(t);this.audio=!0;this.video="none";this.connection=i}setAudio(t,i,r){return c(this,null,function*(){this.audio!==t&&(this.audio=t,d.d(`[Remote stream] ${r||""}
|
|
58
58
|
streamId=${this.id}
|
|
59
59
|
trackId=${i}
|
|
60
60
|
subscribing audio - ${this.audio}`),yield this.connection.sendOverApiDataChannelWithResponse({params:{subscribed:this.audio,track_id:i},method:"prefer-audio-track-state"}))})}setVideoLayerLocally(t,i,r){this.video=t,d.d(`[Remote stream] ${i}
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
Setting layer field to=${t}`)}setVideoLayer(t,i,r,s){return d.d(`[Remote stream] ${r}
|
|
64
64
|
streamId=${this.id}
|
|
65
65
|
trackId=${i}
|
|
66
|
-
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 ma=(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={},l={},u={};r==null||r.forEach(p=>{switch(p.type){case"outbound-rtp":l[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(S({},l)).forEach(p=>{var
|
|
66
|
+
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 ma=(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={},l={},u={};r==null||r.forEach(p=>{switch(p.type){case"outbound-rtp":l[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(S({},l)).forEach(p=>{var D,ye;let h=(D=l[p])==null?void 0:D.codecId,g=h?n[h]:void 0,T;g&&(T=g.substring(g.indexOf("/")+1));let P=v(S({},l[p]),{rid:(ye=l[p])==null?void 0:ye.rid}),A=u[P.ssrc];s[p]=v(S({},P),{bitrate:Jr("bytesSent",P,i==null?void 0:i[p]),packetsLost:A==null?void 0:A.packetsLost,jitter:A==null?void 0:A.jitter,roundTripTime:A==null?void 0:A.roundTripTime,totalRoundTripTime:A==null?void 0:A.totalRoundTripTime,peerName:t,peerID:e.peerId,enabled:e.enabled,codec:T})})}catch(n){a.analytics.publish(y.rtcStatsFailed(m.WebrtcErrors.StatsFailed("TRACK",`Error getting local track stats ${e.trackId} - ${n.message}`))),d.w("[HMSWebrtcStats]","Error in getting local track stats",e,n,n.name)}return s}}),Sa=(a,e,t,i)=>c(void 0,null,function*(){var l;let r;try{r=yield(l=e.transceiver)==null?void 0:l.receiver.getStats()}catch(u){a.analytics.publish(y.rtcStatsFailed(m.WebrtcErrors.StatsFailed("TRACK",`Error getting remote track stats ${e.trackId} - ${u.message}`))),d.w("[HMSWebrtcStats]","Error in getting remote track stats",e,u)}let s=mn(r),o=Jr("bytesReceived",s,i),n=qr("packetsLost",s,i);return s!=null&&s.remote&&Object.assign(s.remote,{packetsLostRate:qr("packetsLost",s.remote,i==null?void 0:i.remote)}),s&&v(S({},s),{bitrate:o,packetsLostRate:n,peerID:e.peerId,enabled:e.enabled,peerName:t,codec:s.codec})}),mn=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})},jr=(a,e,t)=>{let i=Sn(e),r=Jr(a==="publish"?"bytesSent":"bytesReceived",i,t&&t[a]);return i&&Object.assign(i,{bitrate:r})},Sn=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},ga=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},Ta=(a,e)=>Array.from(new Set(a.concat(e))),Jr=(a,e,t)=>qr(a,e,t)*8,qr=(a,e,t)=>{let i=e&&e[a],r=t?t[a]:null;return[e,t,se(i),se(r)].every(o=>!!o)?Qr(i,r,e==null?void 0:e.timestamp,t==null?void 0:t.timestamp)*1e3:0},Qr=(a,e,t,i)=>se(a)&&se(e)&&t&&i?(a-e)/(t-i):0;var hi=class{constructor(e,t,i){this.getStats=e;this.store=t;this.eventBus=i;this.TAG="[HMSWebrtcStats]";this.peerStats={};this.remoteTrackStats={};this.localTrackStats={};this.getLocalPeerStats=()=>this.peerStats[this.localPeerID];this.getRemoteTrackStats=e=>this.remoteTrackStats[e];this.getAllRemoteTracksStats=()=>this.remoteTrackStats;this.getLocalTrackStats=()=>this.localTrackStats;this.updateStats=()=>c(this,null,function*(){yield this.updateLocalPeerStats(),yield this.updateLocalTrackStats(),yield this.updateRemoteTrackStats()});this.updateLocalPeerStats=()=>c(this,null,function*(){var p,h,g,T,P,A;let e=this.getLocalPeerStats(),t;try{t=yield(h=(p=this.getStats).publish)==null?void 0:h.call(p)}catch(D){this.eventBus.analytics.publish(y.rtcStatsFailed(m.WebrtcErrors.StatsFailed("PUBLISH",D.message))),d.w(this.TAG,"Error in getting publish stats",D)}let i=t&&jr("publish",t,e),r;try{r=yield(T=(g=this.getStats).subscribe)==null?void 0:T.call(g)}catch(D){this.eventBus.analytics.publish(y.rtcStatsFailed(m.WebrtcErrors.StatsFailed("SUBSCRIBE",D.message))),d.w(this.TAG,"Error in getting subscribe stats",D)}let s=r&&jr("subscribe",r,e),{packetsLost:o,jitter:n}=ga(r),l=Qr(o,(P=e==null?void 0:e.subscribe)==null?void 0:P.packetsLost,s==null?void 0:s.timestamp,(A=e==null?void 0:e.subscribe)==null?void 0:A.timestamp),u=s&&Object.assign(s,{packetsLostRate:l,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 te),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 Sa(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=Ta(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 ma(this.eventBus,s,o,this.localTrackStats[r]);n&&(this.localTrackStats[r]=n)}else delete this.localTrackStats[r]}});var r;this.localPeerID=(r=this.store.getLocalPeer())==null?void 0:r.peerId}};var mi=class{constructor(e,t,i,r){this.store=e;this.eventBus=t;this.publishConnection=i;this.subscribeConnection=r;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.eventBus.statsUpdate.publish(this.hmsStats)})}getPublishPeerConnection(){return this.publishConnection}getSubscribePeerConnection(){return this.subscribeConnection}getCurrentStats(){return this.hmsStats}onStatsChange(e){return this.eventBus.statsUpdate.subscribe(e),()=>{this.eventBus.statsUpdate.unsubscribe(e)}}setPeerConnections({publish:e,subscribe:t}){var i,r;this.publishConnection=e,this.subscribeConnection=t,this.hmsStats=new hi({publish:(i=this.publishConnection)==null?void 0:i.getStats.bind(this.publishConnection),subscribe:(r=this.subscribeConnection)==null?void 0:r.getStats.bind(this.subscribeConnection)},this.store,this.eventBus)}start(){return c(this,null,function*(){if(this.isMonitored){d.d(this.TAG,"Already started");return}this.stop(),this.isMonitored=!0,d.d(this.TAG,"Starting Webrtc Stats Monitor"),this.startLoop().then(()=>d.d(this.TAG,"Stopping Webrtc Stats Monitor")).catch(e=>{this.eventBus.analytics.publish(y.rtcStatsFailed(m.WebrtcErrors.StatsFailed("PUBLISH",e.message))),d.e(this.TAG,e.message)})})}stop(){this.isMonitored=!1}startLoop(){return c(this,null,function*(){for(;this.isMonitored;)yield this.handleStatsUpdate(),yield z(this.interval)})}cleanup(){this.stop(),this.eventBus.statsUpdate.removeAllListeners()}};var Ye=class{constructor({peerId:e,name:t,isLocal:i,customerUserId:r,metadata:s,role:o,joinedAt:n,groups:l,realtime:u}){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=l,this.realtime=u,o&&(this.role=o)}get isHandRaised(){var e;return!!((e=this.groups)!=null&&e.includes(Te))}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`{
|
|
67
67
|
name: ${this.name};
|
|
68
68
|
role: ${(e=this.role)==null?void 0:e.name};
|
|
69
69
|
peerId: ${this.peerId};
|
|
@@ -79,5 +79,5 @@
|
|
|
79
79
|
${this.asRole?`asRole: ${this.asRole.name};`:""}
|
|
80
80
|
${this.audioTrack?`audioTrack: ${(i=this.audioTrack)==null?void 0:i.trackId};`:""}
|
|
81
81
|
${this.videoTrack?`videoTrack: ${(r=this.videoTrack)==null?void 0:r.trackId};`:""}
|
|
82
|
-
}`}};var kt=class extends Ye{constructor(t){super(v(S({},t),{isLocal:!1}));this.isLocal=!1;this.auxiliaryTracks=[];this.fromRoomState=!1;this.fromRoomState=!!t.fromRoomState}};var Re=(a,e)=>new kt({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});var Si=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(v(S({},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=Re(i,this.store);t.push(r)}),t}updateState(e){this.isEnd=e.eof,this.total=e.total,e.iterator&&(this.iterator=e.iterator)}};var Ze=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(),d.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=>{d.d(this.TAG,"AudioContext close error",e.message)})}};var va=require("eventemitter2"),He=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 gi=class extends He{constructor(){super(...arguments);this.audioElement=null;this.TAG="[PlaylistAudioManager]";this.seeked=!1}play(t){return c(this,null,function*(){return this.audioElement=this.getAudioElement(),new Promise((i,r)=>{this.audioElement=this.getAudioElement(),this.audioElement.src=t,this.seeked=!1,this.audioElement.onerror=()=>{let s=`Error loading ${t}`;d.e(this.TAG,s),this.stop(),r(s)},this.audioElement.oncanplaythrough=()=>c(this,null,function*(){try{if(!this.audioElement)return;if(this.audioContextManager.resumeContext(),this.track)this.seeked?this.seeked=!1:(yield this.audioElement.play(),i([this.track]));else{yield this.audioElement.play();let s=this.audioContextManager.getAudioTrack();this.track=s,i([s])}}catch(s){d.e(this.TAG,"Error playing audio",t,s.message),r(s)}}),this.audioElement.onseeked=()=>{this.seeked=!0}})})}getTracks(){return this.track?[this.track.id]:[]}getElement(){return this.audioElement||(this.audioElement=this.getAudioElement()),this.audioElement}stop(){var t,i,r;(t=this.audioElement)==null||t.pause(),(i=this.audioElement)==null||i.removeAttribute("src"),this.audioElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.track=void 0}getAudioElement(){if(this.audioElement)return this.audioElement;let t=document.createElement("audio");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new Ze(t),t}};var Ti=class extends He{constructor(){super(...arguments);this.TAG="[PlaylistVideoManager]";this.videoElement=null;this.canvasContext=null;this.tracks=[];this.DEFAUL_FPS=24;this.seeked=!1;this.drawImage=()=>{var t,i,r;this.videoElement&&!this.videoElement.paused&&!this.videoElement.ended&&((r=this.canvasContext)==null||r.drawImage(this.videoElement,0,0,(t=this.canvas)==null?void 0:t.width,(i=this.canvas)==null?void 0:i.height),this.timer=setTimeout(()=>{this.drawImage()},1e3/this.DEFAUL_FPS))}}play(t){return this.videoElement=this.getVideoElement(),this.createCanvas(),new Promise((i,r)=>{this.videoElement=this.getVideoElement(),this.videoElement.src=t,this.seeked=!1,this.videoElement.onerror=()=>{let s=`Error loading ${t}`;d.e(this.TAG,s),this.stop(),r(s)},this.videoElement.oncanplaythrough=()=>c(this,null,function*(){var s,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 l=this.canvas.captureStream();if(!l){d.e(this.TAG,"Browser does not support captureStream");return}this.videoElement.onplay=this.drawImage,yield this.audioContextManager.resumeContext(),yield this.videoElement.play();let u=this.audioContextManager.getAudioTrack();l.addTrack(u),l.getTracks().forEach(p=>{this.tracks.push(p)}),i(this.tracks)}else this.seeked?(this.seeked=!1,(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(l){d.e(this.TAG,"Error playing video",t,l.message),r(l)}}),this.videoElement.onseeked=()=>{this.seeked=!0}})}getTracks(){return this.tracks.map(t=>t.id)}getElement(){return this.videoElement||(this.videoElement=this.getVideoElement()),this.videoElement}stop(){var t,i,r;(t=this.videoElement)==null||t.pause(),(i=this.videoElement)==null||i.removeAttribute("src"),this.videoElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.clearCanvasAndTracks()}clearCanvasAndTracks(){var t;this.tracks=[],(t=this.canvasContext)==null||t.clearRect(0,0,this.canvas.width,this.canvas.height),clearTimeout(this.timer)}getVideoElement(){if(this.videoElement)return this.videoElement;let t=document.createElement("video");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new Ze(t),t}createCanvas(){this.canvas||(this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"))}};var fi={audio:{list:[],currentIndex:-1,isAutoplayOn:!0},video:{list:[],currentIndex:-1,isAutoplayOn:!0}},Pt=class extends He{constructor(t,i){super();this.sdk=t;this.eventBus=i;this.state={audio:S({},fi.audio),video:S({},fi.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),d.d(this.TAG,"Playlist track added",ti(t))});this.removeTrack=t=>c(this,null,function*(){yield this.sdk.removeTrack(t,!0),d.d(this.TAG,"Playlist track removed",t)});this.audioManager=new gi,this.videoManager=new Ti,this.addListeners()}getList(t="audio"){return this.state[t].list}setList(t){if(!t||t.length===0){d.w(this.TAG,"Please pass in a list of HMSPlaylistItem's");return}t.forEach(i=>{this.state[i.type].list.find(r=>r.id===i.id)||this.state[i.type].list.push(i)})}clearList(t){return c(this,null,function*(){this.isPlaying(t)&&(yield this.stop(t)),this.state[t].list=[]})}removeItem(t,i){return c(this,null,function*(){let{list:r,currentIndex:s}=this.state[i],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 m.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 m.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 l=this.state[r].list.findIndex(p=>p.id===i);if(!i||l===-1){d.w(this.TAG,"Pass a valid id");return}let u=this.state[r].list[l].url;t?yield this.play(u,r):yield this.pause(u,r),this.state[r].currentIndex=l,this.setDuration(r)})}playNext(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r>=i.length-1)throw m.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 m.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:S({},fi.audio),video:S({},fi.video)},this.eventBus.localAudioEnabled.unsubscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.unsubscribe(this.handlePausePlaylist),this.audioManager.stop(),this.videoManager.stop()}onProgress(t){this.videoManager.on("progress",()=>{try{t({type:"video",progress:this.getCurrentProgress("video")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}}),this.audioManager.on("progress",()=>{try{t({type:"audio",progress:this.getCurrentProgress("audio")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}})}onNewTrackStart(t){this.on("newTrackStart",t)}onPlaylistEnded(t){this.on("playlistEnded",t)}onCurrentTrackEnded(t){this.on("currentTrackEnded",t)}getElement(t="audio"){return t==="audio"?this.audioManager.getElement():this.videoManager.getElement()}removeTracks(){return c(this,arguments,function*(t="audio"){let r=(t==="audio"?this.audioManager:this.videoManager).getTracks();for(let s of r)yield this.removeTrack(s)})}play(r){return c(this,arguments,function*(t,i="audio"){let s=i==="audio"?this.audioManager:this.videoManager,o=s.getElement();if(this.isItemCurrentlyPlaying(t,i)){d.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 l of n)yield this.addTrack(l,i==="audio"?"audioplaylist":"videoplaylist")}})}isItemCurrentlyPlaying(t,i){let r=this.getElement(i);return!!(r&&!r.paused&&r.src.includes(t))}setDuration(t="audio"){let i=this.getElement(t),{list:r,currentIndex:s}=this.state[t];r[s]&&(r[s].duration=(i==null?void 0:i.duration)||0),this.emit("newTrackStart",r[s])}pause(r){return c(this,arguments,function*(t,i="audio"){let s=this.getElement(i);s&&!s.paused&&s.src.includes(t)?(s.pause(),d.d(this.TAG,"paused url",t)):d.w(this.TAG,"The passed in url is not currently playing")})}addListeners(){this.audioManager.on("ended",()=>this.handleEnded("audio")),this.videoManager.on("ended",()=>this.handleEnded("video")),this.eventBus.localAudioEnabled.subscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.subscribe(this.handlePausePlaylist)}handleEnded(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r,isAutoplayOn:s}=this.state[t];r===i.length-1?(yield this.stop(t),this.emit("playlistEnded",t)):s?this.playNext(t):yield this.pause(i[r].url,t),this.emit("currentTrackEnded",i[r])})}};var Et="HMS-Store:",k=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(Et,...t);break}case 1:{console.debug(Et,...t);break}case 2:{console.info(Et,...t);break}case 3:{console.warn(Et,...t);break}case 6:{console.error(Et,...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}}}};k.level=0;var zr=(a,e)=>e,bt=(a,e)=>e,Ma=(a,e)=>e,gn=(a,e)=>e,Tn=(a,e)=>e,Y=(0,H.createSelector)([G,zr],(a,e)=>e?a[e]:null),Yr=(0,H.createSelector)([D,bt],(a,e)=>e?a[e]:null),fn=(0,H.createSelector)([D,bt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="video"?t:null}),vn=(0,H.createSelector)([D,bt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="audio"?t:null}),Mn=(0,H.createSelector)([D,bt],(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}),yn=(0,H.createSelector)([D,bt],(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}),kn=(0,H.createSelector)([Mr,Tn],(a,e)=>e?a[e]:null),W=b(Y),Pn=b((0,H.createSelector)([Xt,gn],(a,e)=>{if(a)return e?a[e]:a}));function En(a){return e=>{if(e.sessionStore)return a?e.sessionStore[a]:e.sessionStore}}var bn=(...a)=>(0,H.createSelector)([Xt],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}}),An=b((0,H.createSelector)(Y,a=>a==null?void 0:a.name)),At=b(Yr),Xr=b(fn),In=b(vn),Rn=b(Mn),Hn=b(yn),ya=b((a,e)=>{let t=Y(a,e);if(t&&t.videoTrack&&t.videoTrack!=="")return a.tracks[t.videoTrack]}),ka=b((a,e)=>{let t=Y(a,e);if(t&&t.audioTrack&&t.audioTrack!=="")return a.tracks[t.audioTrack]}),Cn=ya,Ln=b((a,e)=>{let t=Y(a,e);return(t==null?void 0:t.auxiliaryTracks.map(i=>a.tracks[i]))||[]}),Pa=(a,e)=>e?a.speakers[e]:null,Dn=b((0,H.createSelector)(Pa,a=>(a==null?void 0:a.audioLevel)||0)),wn=(a,e)=>{let t=ka(e)(a);return Pa(a,t==null?void 0:t.id)},_n=b((0,H.createSelector)(wn,a=>(a==null?void 0:a.audioLevel)||0)),Nn=b((a,e)=>{if(e)return a.connectionQualities[e]}),On=b((a,e)=>{let t=Y(a,e);if(t){let i=t==null?void 0:t.auxiliaryTracks.find(r=>ct(a.tracks[r]));return i?a.tracks[i]:void 0}}),xn=b((0,H.createSelector)(D,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return lt(r)&&dt(r)});return t?a[t]:void 0})),Un=b((0,H.createSelector)(D,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return lt(r)&&ct(r)});return t?a[t]:void 0})),Bn=b((0,H.createSelector)(D,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return Yt(r)&&ct(r)});return t?a[t]:void 0})),Zr=b((0,H.createSelector)(D,Y,(a,e)=>Le(a,e))),Vn=a=>(0,H.createSelector)(Zr(a),e=>e.video),es=a=>(0,H.createSelector)(Zr(a),e=>e.audio),Fn=b((a,e)=>{let t=Y(a,e);return Ve(a,t==null?void 0:t.audioTrack)}),Gn=b((a,e)=>{let t=Y(a,e);return Ve(a,t==null?void 0:t.videoTrack)}),ts=b((a,e)=>{if(e&&a.tracks[e])return a.tracks[e].volume===0}),$n=b((a,e)=>{let t=Y(a,e);return ts(t==null?void 0:t.audioTrack)(a)}),Wn=b((a,e)=>{let t=es(e)(a);return ts(t==null?void 0:t.id)(a)}),is=b((a,e)=>{let t=Yr(a,e);if(t){if(t.type!=="audio"){k.w("Please pass audio track here");return}return t.volume}}),Kn=b((a,e)=>{let t=Y(a,e);return is(t==null?void 0:t.audioTrack)(a)}),qn=b((a,e)=>{let t=es(e)(a);return is(t==null?void 0:t.id)(a)}),jn=b((a,e)=>{let t=Yr(a,e);if(t){if(t.type!=="video"){k.w("Please pass video track here");return}return t.layer}}),Ea=(0,H.createSelector)([Fe,ce,zr],(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)})}),ba=(0,H.createSelector)([Fe,Ma],(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})}),Aa=(0,H.createSelector)(Fe,a=>a.filter(e=>{var t;return!e.recipientPeer&&!((t=e.recipientRoles)!=null&&t.length)})),Jn=(0,H.createSelector)([ba,Ma],a=>a?a.filter(e=>!e.read).length:0),Qn=(0,H.createSelector)([Ea,zr],a=>a?a.filter(e=>!e.read).length:0),zn=(0,H.createSelector)(Aa,a=>a.filter(e=>!e.read).length),Yn=b(Ea),Xn=b(ba),Zn=b(Jn),ec=b(Qn),tc=a=>(0,H.createSelector)([ie],e=>e.filter(t=>t.roleName===a)),ic=a=>(0,H.createSelector)([ie],e=>e.filter(t=>t.roleName?a.includes(t.roleName):!1)),rc=a=>(0,H.createSelector)(W(a),e=>{try{return e!=null&&e.metadata&&e.metadata!==""?JSON.parse(e.metadata):{}}catch(t){return console.error("cannot parse peer metadata",t),{}}}),sc=a=>(0,H.createSelector)(W(a),e=>!!(e!=null&&e.isHandRaised)),ac=a=>(0,H.createSelector)(W(a),e=>e==null?void 0:e.name),rs=b(kn),oc=a=>(0,H.createSelector)(pt,e=>e[a]);var It=require("reselect");var nc=(0,It.createSelector)([G,D],(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}})),cc=a=>a.roleChangeRequests[0]||null,dc=(0,It.createSelector)([cc,G,re],(a,e,t)=>a?{requestedBy:a.requestedBy?e[a.requestedBy]:void 0,role:t[a.roleName],token:a.token}:null),lc=(0,It.createSelector)([ht],a=>ut(a)),uc=(0,It.createSelector)([fr],a=>ut(a));var he=require("reselect");var Ia=a=>(0,he.createSelector)([re],e=>e[a]),pc=a=>(0,he.createSelector)(Ia(a),e=>ut(e)),hc=(0,he.createSelector)([$,D],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),mc=(0,he.createSelector)([X,D],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),Sc=a=>(0,he.createSelector)([hc],e=>e.includes(a)),gc=a=>(0,he.createSelector)([mc],e=>e.includes(a)),Tc=a=>(0,he.createSelector)(ie,e=>e.find(a)),fc=a=>(0,he.createSelector)(ie,e=>e.filter(a)),vc=a=>(0,he.createSelector)(U,e=>e.joinedAt&&Date.now()-e.joinedAt.getTime()<=a);var Ja=require("immer"),Qa=Ce(require("zustand/shallow")),za=Ce(require("zustand/vanilla"));var Ra=require("eventemitter2");var vi={0:"PEER_JOINED",1:"PEER_LEFT",8:"ROLE_UPDATED",10:"NAME_UPDATED",11:"METADATA_UPDATED",12:"HAND_RAISE_CHANGED"},Rt={0:"TRACK_ADDED",1:"TRACK_REMOVED",2:"TRACK_MUTED",3:"TRACK_UNMUTED",5:"TRACK_DEGRADED",6:"TRACK_RESTORED",4:"TRACK_DESCRIPTION_CHANGED"},Mi={0:"POLL_CREATED",1:"POLL_STARTED",2:"POLL_STOPPED",4:"POLL_VOTES_UPDATED",3:"POLLS_LIST"};var ss="hmsNotification",yi=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(ss,i),()=>{this.eventEmitter.removeListener(ss,i)}};this.store=e,this.eventEmitter=new Ra.EventEmitter2({maxListeners:Object.keys(zt).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(W(t==null?void 0:t.id))||t,r=vi[e];if(r&&i){let s=this.createNotification(r,i,"info");this.emitEvent(s)}}sendTrackUpdate(e,t){let i=this.store.getState(At(t)),r=Rt[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=Mi[e],r=this.store.getState(rs(t));if(i){let s=this.createNotification(i,r,"info");this.emitEvent(s)}}emitEvent(e){this.eventEmitter.emit(ss,e)}createNotification(e,t,i,r=""){return this.id++,{id:this.id,type:e,message:r,data:t,severity:i}}};var ki=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){k.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 Ha(a){return a instanceof te||a instanceof N}var Ca=(a,e)=>{let t=Ht(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];xe(r,s)?(Z(r.auxiliaryTracks,s.auxiliaryTracks)&&(s.auxiliaryTracks=r.auxiliaryTracks),r.groups&&Z(r.groups,s.groups)&&(s.groups=r.groups),Object.assign(r,s)):ns(r,s)?delete a[i]:Pi(r,s)&&(a[i]=s)}},La=(a,e)=>{let t=Ht(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];xe(r,s)?(os(r,s),Object.assign(r,s)):ns(r,s)?delete a[i]:Pi(r,s)&&(a[i]=s)}},Da=(a,e)=>{let t=Ht(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];xe(r,s)?(r.questions&&Z(r.questions,s.questions)&&(s.questions=r.questions),Object.assign(r,s)):Pi(r,s)&&(a[i]=s)}},as=(a,e)=>{let t=Ht(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];xe(r,s)?Object.assign(r,s):ns(r,s)?delete a[i]:Pi(r,s)&&(a[i]=s)}},wa=(a,e,t)=>{let i=t.reduce((s,o)=>(s[o.firstTrackId]=Object.values(e[o.getTrackIDBeingSent()]||{}).sort((n,l)=>!n.rid||!l.rid?0:n.rid<l.rid?-1:1),s),{}),r=Ht(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&&Z(a.plugins,e.plugins)&&(e.plugins=a.plugins),a.type==="video"&&a.layerDefinitions&&Z(a.layerDefinitions,e.layerDefinitions)&&(e.layerDefinitions=a.layerDefinitions)},xe=(a,e)=>a&&e,ns=(a,e)=>a&&!e,Pi=(a,e)=>!a&&e,Z=(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},Ht=(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 _=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}}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 te&&(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 B||t instanceof ne)&&(e.isPublished=t.isPublished)}static updateDeviceID(e,t){var i;t instanceof B||t instanceof ne?e.deviceID=t.settings.deviceId:e.deviceID=(i=t.getMediaTrackSettings())==null?void 0:i.deviceId}static enrichVideoTrack(e,t){t instanceof N&&(e.layer=t.getLayer(),e.preferredLayer=t.getPreferredLayer(),e.degraded=t.degraded),(t instanceof N||t instanceof B)&&(Z(t.getSimulcastDefinitions(),e.layerDefinitions)||(e.layerDefinitions=t.getSimulcastDefinitions()))}static enrichScreenTrack(e,t){var i,r;if(t instanceof B){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 B||t instanceof ne)&&(Z(t.getPlugins(),e.plugins)||(e.plugins=t.getPlugins()))}static convertRoom(e,t){let{recording:i,rtmp:r,hls:s}=a.convertRecordingStreamingState(e==null?void 0:e.recording,e==null?void 0:e.rtmp,e==null?void 0:e.hls);return{id:e.id,name:e.name,localPeer:t,recording:i,rtmp:r,hls:s,sessionId:e.sessionId,startedAt:e.startedAt,joinedAt:e.joinedAt,peerCount:e.peerCount,isLargeRoom:e.large_room_optimization,isEffectsEnabled:e.isEffectsEnabled,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){return{code:e.code,action:e.action,name:e.name,message:e.message,description:e.description,isTerminal:e.isTerminal,nativeError:e.nativeError,timestamp:new Date}}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 v(S({},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),l=e.getCurrentIndex(t);return e.getList(t).forEach(u=>{i[u.id]=a.convertPlaylistItem(e,u)}),{list:i,selection:{id:r==null?void 0:r.id,hasPrevious:l>0,hasNext:l<n.length-1},progress:s,volume:o,currentTime:e.getCurrentTime(t),playbackRate:e.getPlaybackRate(t)}}static convertRecordingStreamingState(e,t,i){var r;return{recording:{browser:S({running:!1},e==null?void 0:e.browser),server:S({running:!1},e==null?void 0:e.server),hls:S({running:!1},e==null?void 0:e.hls)},rtmp:S({running:!1},t),hls:{variants:((r=i==null?void 0:i.variants)==null?void 0:r.map(s=>s))||[],running:!!(i!=null&&i.running),error:i==null?void 0:i.error}}}};var Ct=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){k.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"?Pr:Er,t=this.store.getState(e.selection);if(!t.id){k.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 Ei=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 bi=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,k.d("starting audio level monitor for remote peers",this.store);let e=this.store.getState(me);k.d("starting audio levels is connected to room",e),e&&(yield this.monitorAudioLevels());let t=this.store.subscribe(this.monitorAudioLevels.bind(this),me);this.unsubs.push(t)})}stop(){return c(this,null,function*(){this.hasStarted&&(this.hasStarted=!1,this.shouldMonitor=!1,this.unsubs.forEach(e=>e()),k.d("stopped audio level monitor for remote peers"))})}monitorAudioLevels(){return c(this,null,function*(){if(!this.store.getState(me)){this.shouldMonitor&&(k.i("room no longer connected, stopping audio level monitoring for remote"),this.shouldMonitor=!1);return}if(this.shouldMonitor)return;k.i("monitoring audio levels"),this.shouldMonitor=!0;let t=()=>{this.shouldMonitor?(this.logAllPeersAudioLevels(),setTimeout(t,this.intervalMs)):k.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(ie).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 l=yield this.getAudioLevel(s,n);l.level>0&&i.push(l)}}if(i.length>0){let s={event:"app-audio-level",data:i};k.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 Ai=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,_.convertPlaylist(this.sdk.getPlaylistManager()))},e)};this.sendPeerUpdateNotification=(e,t)=>{let i=this.store.getState(W(t.peerId)),r=vi[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(W(t.peerId)));else if([12,13,14].includes(e))this.syncRoomState(r),i||(i=this.store.getState(W(t.peerId)));else{let s=_.convertPeer(t);this.setState(o=>{let n=o.peers[s.id];xe(n,s)&&(Z(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 Ei(this.sdk,this.setSessionStoreValueLocally.bind(this)),this.actionBatcher=new ki(e)}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 N){if(t==="none"){k.d("layer none will be ignored");return}if(((r=this.store.getState(Xr(e)))==null?void 0:r.preferredLayer)===t){k.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 k.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(J);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 k.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,k.e("Failed to connect to room - ",t),t}})}leave(){return c(this,null,function*(){let e=this.store.getState(me),t=!0;e||(t=!1,this.logPossibleInconsistency("room leave is called when no room is connected"));let i=this.store.getState(J);return this.setState(r=>{r.room.roomState="Disconnecting"},"leaving"),this.sdk.leave(t).then(()=>{this.resetState("leave"),this.beamSpeakerLabelsLogger&&this.beamSpeakerLabelsLogger.stop().catch(k.e),k.i("left room")}).catch(r=>{k.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(_.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(X);t&&(yield this.setEnabledTrack(t,e))})}setLocalVideoEnabled(e){return c(this,null,function*(){let t=this.store.getState($);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(_.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(X);t&&(yield this.setSDKLocalAudioTrackSettings(t,e),this.syncRoomState("setAudioSettings"))})}setVideoSettings(e){return c(this,null,function*(){let t=this.store.getState($);t&&(yield this.setSDKLocalVideoTrackSettings(t,e),this.syncRoomState("setVideoSettings"))})}switchCamera(){return c(this,null,function*(){let e=this.store.getState($);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(re),s=t.map(l=>r[l]),{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 r;if(!e.message)throw k.w("sendMessage","Failed to send message",e),Error(`sendMessage Failed - ${JSON.stringify(e)}`);let t=this.sdk.getLocalPeer(),i={read:!0,id:e.id,time:new Date(e.time),message:e.message,type:e.type||"chat",recipientPeer:e.recipientPeer,recipientRoles:e.recipientRoles,senderName:t==null?void 0:t.name,sender:t==null?void 0:t.peerId,senderRole:(r=t==null?void 0:t.role)==null?void 0:r.name,ignored:!!e.type&&this.ignoredMessageTypes.includes(e.type)};this.putMessageInStore(i)}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())}),Zt)});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),k.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 k.w("no plugin passed in for checking support"),t.errMsg="no plugin passed in for checking support",t;let i=this.store.getState($);if(!i)return k.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):(k.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 k.w('no plugin passed in for checking support"'),t.errMsg='no plugin passed in for checking support"',t;let i=this.store.getState(X);if(!i)return k.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):(k.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||k.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)})}getPeerListIterator(e){let t=this.sdk.getPeerListIterator(e);return{hasNext:()=>t.hasNext(),next:()=>c(this,null,function*(){return(yield t.next()).map(r=>_.convertPeer(r))}),findPeers:()=>c(this,null,function*(){return(yield t.findPeers()).map(r=>_.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(vr);if(!(i!=null&&i.endRoom)){k.w("You are not allowed to perform this action - endRoom");return}let r=this.store.getState(J);this.setState(s=>{s.room.roomState="Disconnecting"},"endingRoom");try{yield this.sdk.endRoom(e,t),this.resetState("endRoom")}catch(s){k.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)})}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&&Ha(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(re);t.roles=e.roles.map(r=>i[r])}yield this.sdk.changeMultiTrackState(t)})}setLogLevel(e){k.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||(k.i("enabling beam speaker labels logging"),this.beamSpeakerLabelsLogger=new bi(this.store,this),yield this.beamSpeakerLabelsLogger.start())})}resetState(e="resetState"){this.isRoomJoinCalled=!1,k.cleanup(),this.setState(t=>{Object.assign(t,ot())},e)}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)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)}),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:this.onConnectionQualityUpdate.bind(this)})})}onRemovedFromRoom(e){var r;let t=this.store.getState(W((r=e.requestedBy)==null?void 0:r.peerId));this.hmsNotifications.sendLeaveRoom(v(S({},e),{requestedBy:t||void 0}));let i=e.roomEnded||!t?"roomEnded":"removedFromRoom";k.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(j);if(this.setState(r=>{Z(r.devices.audioInput,t.audioInput)||(r.devices.audioInput=t.audioInput),Z(r.devices.videoInput,t.videoInput)||(r.devices.videoInput=t.videoInput),Z(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=_.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)}),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=Mi[e];this.setState(r=>{let s=t.reduce((o,n)=>{var l;return o[n.id]=v(S({},n),{questions:(l=n.questions)==null?void 0:l.map(u=>{var p,h;return v(S({},u),{answer:u.answer?S({},u.answer):void 0,options:(p=u.options)==null?void 0:p.map(g=>S({},g)),responses:(h=u.responses)==null?void 0:h.map(g=>S({},g))})})}),o},{});Da(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(ei)?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(ei)?(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`,k.time(`store-sync-${e}`);let t={},i=[],r={},s={},o={},n,l=this.sdk.getPeers();for(let g of l){let T=_.convertPeer(g);t[T.id]=T,i.push(T.id),o[T.id]={peerID:T.id,downlinkQuality:g.networkQuality||-1};let I=[g.audioTrack,g.videoTrack,...g.auxiliaryTracks];for(let A of I){if(!A)continue;let O=_.convertTrack(A);r[O.id]=O}if(g.isLocal){let A=g;n=this.getPreviewFields(A),Object.assign(s,this.getMediaSettings(A))}}let u=this.sdk.getRecordingState(),p=this.sdk.getRTMPState(),h=this.sdk.getHLSState();this.setState(g=>{var A;g.room.peers=i;let T=g.peers,I=g.tracks;Ca(T,t),La(I,r),Object.assign(g.settings,s),g.room.isConnected&&Object.assign(g.connectionQualities,o),(A=g.preview)!=null&&A.localPeer&&(n!=null&&n.localPeer)?Object.assign(g.preview,n):g.preview=n,Object.assign(g.roles,_.convertRoles(this.sdk.getRoles())),Object.assign(g.playlist,_.convertPlaylist(this.sdk.getPlaylistManager())),Object.assign(g.room,_.convertRecordingStreamingState(u,p,h)),Object.assign(g.templateAppData,this.sdk.getTemplateAppData())},e),k.timeEnd(`store-sync-${e}`)}onPreview(e){this.setState(t=>{var i;Object.assign(t.room,_.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 Ct(t,"audio",this.syncPlaylistState.bind(this),this.store),this.videoPlaylist=new Ct(t,"video",this.syncRoomState.bind(this),this.store),this.syncRoomState("joinSync"),this.setState(i=>{var r;Object.assign(i.room,_.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(_.convertPlaylistItem(t,i)),this.syncPlaylistState(`${i.type}PlaylistItemEnded`)})}onRoomUpdate(e,t){this.setState(i=>{var r;Object.assign(i.room,_.convertRoom(t,(r=this.sdk.getLocalPeer())==null?void 0:r.peerId))},e)}onPeerUpdate(e,t){if(![4,5].includes(e)){if(Array.isArray(t)){let i=this.store.getState(G),r=t.filter(o=>!i[o.peerId]);if(this.syncRoomState("peersJoined"),this.store.getState(me)){let o=[];for(let n of t){let l=this.store.getState(W(n.peerId));l&&o.push(l)}this.hmsNotifications.sendPeerList(o)}else r.forEach(o=>{let n=this.store.getState(W(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=Rt[e];this.syncRoomState(r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}else{let r=Rt[e]||"trackUpdate",s=_.convertTrack(t);this.setState(o=>{let n=o.tracks[s.id];xe(n,s)&&(os(n,s),Object.assign(n,s))},r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}}onMessageReceived(e){let t=_.convertMessage(e,this.store.getState(ce));t.read=!1,t.ignored=this.ignoredMessageTypes.includes(t.type),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(W((s=e.requestedBy)==null?void 0:s.peerId)),i=this.getStoreLocalTrackIDfromSDKTrack(e.track),r=this.store.getState(At(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(W((s=e.requestedBy)==null?void 0:s.peerId));e.enabled||this.syncRoomState("changeMultiTrackStateRequest");let i=[],r=this.store.getState(D);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=_.convertException(e);k.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=_.convertException(e);t.isTerminal?(this.leave().then(()=>k.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),k.e("received error from sdk",t instanceof f?`${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(mr),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}}getPreviewFields(e){var i,r;if(!e.isInPreview())return;let t=_.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 Pe?(yield i.setVolume(e),this.setState(r=>{let s=r.tracks[t];s&&s.type==="audio"&&(s.volume=e)},"trackVolume")):k.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(j);if((t==null?void 0:t.videoTrack)!==e)return!1;let i=this.store.getState(gr),r=this.store.getState(Zt);return i&&!r}logPossibleInconsistency(e){k.w("possible inconsistency detected - ",e)}addRemoveVideoPlugin(e,t,i){return c(this,null,function*(){if(!e){k.w("Invalid plugin received in store");return}let r=this.store.getState($);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){k.w("Invalid plugin received in store");return}let i=this.store.getState($);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*(){if(!e){k.w("Invalid plugin received in store");return}let i=this.store.getState(X);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`)}})}onRoleChangeRequest(e){this.setState(t=>{t.roleChangeRequests.length===0&&t.roleChangeRequests.push(_.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(Sr).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(Tr)&&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)}};var Ii=a=>w?`${a} ${document.title}`:a;var Lt=class{constructor(e){this.recording={server:{running:!1},browser:{running:!1},hls:{running:!1}};this.rtmp={running:!1};this.hls={running:!1,variants:[]};this.id=e}};var Ri=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,l=z(i).then(()=>{this.controller.abort()});try{let h=(u=(yield fetch(`${t}?${Date.now()}`,{signal:s})).body)==null?void 0:u.getReader();if(!h)throw Error("unable to process request");let g=()=>c(this,null,function*(){if(h)try{let T=!1;for(;!T;){let{value:I,done:A}=yield h.read();T=A,I&&(n+=I.byteLength,this.sendScore({scoreMap:r,downloadedSize:n,startTime:o}))}}catch(T){T.name!=="AbortError"&&d.d(this.TAG,T)}});return Promise.race([g(),l]).then(()=>{this.sendScore({scoreMap:r,downloadedSize:n,startTime:o,finished:!0})}).catch(T=>{d.d(this.TAG,T),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:T.message}))})}catch(p){p.name!=="AbortError"?(d.d(this.TAG,p),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:p.message}))):d.d(this.TAG,p)}});this.stop=()=>{this.controller.signal.aborted||this.controller.abort()};this.sendScore=({scoreMap:e,downloadedSize:t,startTime:i,finished:r=!1})=>{let s=(Date.now()-i)/1e3,n=t/1024/s*8,l=-1;for(let u in e){let p=e[u];n>=p.low&&(!p.high||n<=p.high)&&(l=Number(u))}this.updateScoreToListener(l),r&&this.eventBus.analytics.publish(y.previewNetworkQuality({score:l,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 Dt=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 T,I,A,O,ye,Ss;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"),l=this.removeTrack(r,s,"screen"),u=this.hasSimulcastDifference((T=e.publishParams.simulcast)==null?void 0:T.video,(I=t.publishParams.simulcast)==null?void 0:I.video),p=this.hasSimulcastDifference((A=e.publishParams.simulcast)==null?void 0:A.screen,(O=t.publishParams.simulcast)==null?void 0:O.screen),h=(Ss=(ye=this.store.getLocalPeer())==null?void 0:ye.videoTrack)==null?void 0:Ss.enabled;yield this.removeAudioTrack(n),yield this.removeVideoTracks(o||u),yield this.removeScreenTracks(l||p);let g=this.getSettings();u&&(g.isVideoMuted=!h),yield this.publish(g),yield this.syncDevices(g,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 l;let n=(l=t==null?void 0:t.layers)==null?void 0:l.find(u=>u.rid===o.rid);return(n==null?void 0:n.maxBitrate)!==o.maxBitrate||(n==null?void 0:n.maxFramerate)!==o.maxFramerate}))}getSettings(){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,audioInputDeviceId:(e==null?void 0:e.audioInputDeviceId)||"default",audioOutputDeviceId:(e==null?void 0:e.audioOutputDeviceId)||"default",videoDeviceId:(e==null?void 0:e.videoDeviceId)||"default"}}};var cs=class{constructor(){this.TAG="[HTTPAnalyticsTransport]";this.failedEvents=new le("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"?la:ua;fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.metadata.token}`,user_agent_v2:e.metadata.userAgent},body:JSON.stringify(t)}).then(r=>{if(r.status===401){this.removeFromStorage(e);return}if(r.status!==200)throw Error(r.statusText);this.removeFromStorage(e)}).catch(r=>{d.v(this.TAG,"Failed to send event",r,e),this.addEventToStorage(e)})}flushFailedEvents(){let e=this.failedEvents.get();e==null||e.forEach(t=>this.sendEvent(t))}addEventToStorage(e){let t=this.failedEvents.get()||[];t.find(i=>i.timestamp===e.timestamp)||(t.length===100&&t.shift(),t.push(e),this.failedEvents.set(t))}removeFromStorage(e){let t=this.failedEvents.get()||[],i=t.findIndex(r=>r.timestamp===e.timestamp);i>-1&&(t.splice(i,1),this.failedEvents.set(t))}},fe=new cs;var wt=class{constructor(){this.knownRoles={};this.peers={};this.tracks=new Map;this.peerTrackStates={};this.speakers=[];this.roleDetailsArrived=!1;this.env="prod";this.simulcastEnabled=!1;this.userAgent=mt(this.env);this.polls=new Map;this.whiteboards=new Map}getConfig(){return this.config}setSimulcastEnabled(e){this.simulcastEnabled=e}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 N)}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=mt(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(Q.rememberDevices(!!e.rememberDeviceSelection),e.rememberDeviceSelection){let s=Q.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}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 te&&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 v(S({},e),{layers:(e.layers||[]).map(t=>v(S({},t),{maxBitrate:t.maxBitrate*1e3}))})}getSimulcastDefinitionsForPeer(e,t){var n,l,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=(l=i.simulcast)==null?void 0:l.screen,s=i.screen.width,o=i.screen.height),((u=r==null?void 0:r.layers)==null?void 0:u.map(p=>{let h=Ie[p.rid],g={width:Math.floor(s/p.scaleResolutionDownBy),height:Math.floor(o/p.scaleResolutionDownBy)};return{layer:h,resolution:g}}))||[]}setPoll(e){this.polls.set(e.id,e)}getPoll(e){return this.polls.get(e)}setWhiteboard(e){this.whiteboards.set(e.id,e)}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(m.GenericErrors.InvalidRole("VALIDATION",""));return}e.role=this.getPolicyForRole(e.role.name)})}addPluginsToRoles(e){if(!e)return;let t=(i,r,s)=>{var n;let o=this.knownRoles[i].permissions;o[r]||(o[r]=[]),(n=o[r])==null||n.push(s)};Object.keys(e).forEach(i=>{var o,n,l;let r=i;if(!e[r])return;let s=e[r].permissions;(o=s==null?void 0:s.admin)==null||o.forEach(u=>t(u,r,"admin")),(n=s==null?void 0:s.reader)==null||n.forEach(u=>t(u,r,"read")),(l=s==null?void 0:s.writer)==null||l.forEach(u=>t(u,r,"write"))})}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,fe.setEnv(i)}};var Hi=class{constructor(){this.TAG="[WakeLockManager]";this.wakeLock=null;this.acquireLock=()=>c(this,null,function*(){yield this.requestWakeLock(),document==null||document.addEventListener("visibilitychange",this.visibilityHandler)});this.cleanup=()=>c(this,null,function*(){if(this.wakeLock&&!this.wakeLock.released)try{yield this.wakeLock.release(),d.d(this.TAG,"Wake lock released")}catch(e){let t=e;d.w(this.TAG,"Error while releasing wake lock",`name=${t.name}, message=${t.message}`)}this.wakeLock=null});this.visibilityHandler=()=>c(this,null,function*(){(document==null?void 0:document.visibilityState)==="visible"&&(!this.wakeLock||this.wakeLock.released)&&(d.d(this.TAG,"Re-acquiring wake lock due to visibility change"),yield this.requestWakeLock())});this.requestWakeLock=()=>c(this,null,function*(){try{if(!("wakeLock"in navigator)){d.d(this.TAG,"Wake lock feature not supported");return}this.wakeLock=yield navigator.wakeLock.request("screen"),d.d(this.TAG,"Wake lock acquired")}catch(e){let t=e;d.w(this.TAG,"Error acquiring wake lock",`name=${t.name}, message=${t.message}`)}})}};var Ci=class{constructor(e){this.store=e;this.bufferSize=100;this.TAG="[AnalyticsEventsService]";this.transport=null;this.pendingEvents=[];this.level=1}setTransport(e){this.transport=e}reset(){this.transport=null,this.pendingEvents=[]}queue(e){if(e.level>=this.level&&(this.pendingEvents.push(e),this.pendingEvents.length>this.bufferSize)){let t=this.pendingEvents.shift();d.d(this.TAG,"Max buffer size reached","Removed event to accommodate new events",t)}return this}flushFailedClientEvents(){fe.flushFailedEvents()}flush(){var e;try{for(;this.pendingEvents.length>0;){let t=this.pendingEvents.shift();t&&(t.metadata.peer.peer_id=(e=this.store.getLocalPeer())==null?void 0:e.peerId,t.metadata.userAgent=this.store.getUserAgent(),this.transport&&this.transport.transportProvider.isConnected?this.transport.sendEvent(t):this.sendClientEventOnHTTP(t))}}catch(t){d.w(this.TAG,"Flush Failed",t)}}sendClientEventOnHTTP(e){var r,s,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},fe.sendEvent(e)}};var Na=require("uuid");var _a={autoplayFailed:void 0,initialized:!1,autoplayCheckPromise:void 0},_t=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=S({},_a);this.timer=null;this.handleAudioPaused=e=>c(this,null,function*(){var s;let i=(s=e.target.srcObject)==null?void 0:s.getAudioTracks()[0];if(!(i!=null&&i.enabled))return;d.d(this.TAG,"Audio Paused",e.target.id);let r=this.store.getTrackById(e.target.id);r&&(we()?(yield z(500),this.playAudioFor(r)):this.autoPausedTracks.add(r))});this.handleTrackUpdate=({track:e})=>{d.d(this.TAG,"Track updated",`${e}`)};this.handleTrackAdd=r=>c(this,[r],function*({track:e,peer:t,callListener:i=!0}){var o,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;d.e(this.TAG,"error on audio element",s.error);let l=m.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(l)),((p=s==null?void 0:s.error)==null?void 0:p.code)===MediaError.MEDIA_ERR_DECODE&&(this.removeAudioElement(s,e),yield z(500),yield this.handleTrackAdd({track:e,peer:t,callListener:!1}))}),e.setAudioElement(s),e.setVolume(this.volume),d.d(this.TAG,"Audio track added",`${e}`),this.init(),yield this.autoSelectAudioOutput(),(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=>{e.isUserSelection||e.error||!e.selection||e.type==="video"||this.unpauseAudioTracks()};this.handleTrackRemove=e=>{this.autoPausedTracks.delete(e);let t=document.getElementById(e.trackId);t&&this.removeAudioElement(t,e),this.audioSink&&this.audioSink.childElementCount===0&&(this.state.autoplayCheckPromise=void 0,this.state.autoplayFailed=void 0),d.d(this.TAG,"Audio track removed",`${e}`)};this.unpauseAudioTracks=()=>c(this,null,function*(){let e=[];this.autoPausedTracks.forEach(t=>{e.push(this.playAudioFor(t))}),yield Promise.all(e)});this.removeAudioElement=(e,t)=>{e&&(d.d(this.TAG,"removing audio element",`${t}`),e.removeEventListener("pause",this.handleAudioPaused),e.srcObject=null,e.remove(),t.setAudioElement(null))};this.startPollingForDevices=()=>{"ondevicechange"in navigator.mediaDevices||(this.timer=setInterval(()=>{c(this,null,function*(){yield this.deviceManager.init(!0,!1),yield this.autoSelectAudioOutput()})},5e3))};this.autoSelectAudioOutput=()=>c(this,null,function*(){var e,t;if(((e=this.audioSink)==null?void 0:e.children.length)===0){let i=null,r=null,s=null,o=null;for(let l of this.deviceManager.audioInput)l.label.toLowerCase().includes("speakerphone")&&(r=l),l.label.toLowerCase().includes("wired")&&(s=l),l.label.toLowerCase().includes("bluetooth")&&(i=l),l.label.toLowerCase().includes("earpiece")&&(o=l);let n=(t=this.store.getLocalPeer())==null?void 0:t.audioTrack;if(n&&o){let l=(i==null?void 0:i.deviceId)||(s==null?void 0:s.deviceId)||(r==null?void 0:r.deviceId);if(d.d(this.TAG,"externalDeviceID",l),n.settings.deviceId===l)return;yield n.setSettings({deviceId:o==null?void 0:o.deviceId},!0),yield n.setSettings({deviceId:l},!0)}}});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.startPollingForDevices()}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&&this.unpauseAudioTracks()})}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,Na.v4)()}`,(e&&document.getElementById(e)||document.body).append(t),this.audioSink=t,d.d(this.TAG,"audio sink created",this.audioSink)}cleanup(){var e;(e=this.audioSink)==null||e.remove(),this.audioSink=void 0,this.timer&&(clearInterval(this.timer),this.timer=null),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.autoPausedTracks=new Set,this.state=S({},_a)}playAudioFor(e){return c(this,null,function*(){let t=e.getAudioElement();if(!t){d.w(this.TAG,"No audio element found on track",e.trackId);return}try{yield t.play(),this.state.autoplayFailed=!1,this.autoPausedTracks.delete(e),d.d(this.TAG,"Played track",`${e}`)}catch(i){this.autoPausedTracks.add(e),d.w(this.TAG,"Failed to play track",`${e}`,i);let r=i;if(!this.state.autoplayFailed&&r.name==="NotAllowedError"){this.state.autoplayFailed=!0;let s=m.TracksErrors.AutoplayBlocked("AUTOPLAY","");s.addNativeError(r),this.eventBus.analytics.publish(y.autoplayError()),this.eventBus.autoplayError.publish(s)}}})}};var Li=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 Nt=class{constructor(e,t){this.store=e;this.eventBus=t;this.audioInput=[];this.audioOutput=[];this.videoInput=[];this.hasWebcamPermission=!1;this.hasMicrophonePermission=!1;this.TAG="[Device Manager]:";this.initialized=!1;this.videoInputChanged=!1;this.audioInputChanged=!1;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"})),Q.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(l=>this.createIdentifier(l)===t),s=this.videoInput.find(l=>this.createIdentifier(l)===i);return{audioInput:r,videoInput:s,audioOutput:this.outputDevice}};this.computeChange=(e,t)=>e.length!==t.length?!0:t.some(i=>!e.includes(this.createIdentifier(i)));this.enumerateDevices=()=>c(this,null,function*(){try{let e=yield navigator.mediaDevices.enumerateDevices(),t=this.videoInput.map(this.createIdentifier),i=this.audioInput.map(this.createIdentifier);this.audioInput=[],this.audioOutput=[],this.videoInput=[],e.forEach(r=>{r.kind==="audioinput"&&r.label?(this.hasMicrophonePermission=!0,this.audioInput.push(r)):r.kind==="audiooutput"?this.audioOutput.push(r):r.kind==="videoinput"&&r.label&&(this.hasWebcamPermission=!0,this.videoInput.push(r))}),this.videoInputChanged=this.computeChange(t,this.videoInput),this.audioInputChanged=this.computeChange(i,this.audioInput),Q.setDevices({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput]}),this.logDevices("Enumerate Devices")}catch(e){d.e(this.TAG,"Failed enumerating devices",e)}});this.handleDeviceChange=ai(()=>c(this,null,function*(){yield this.enumerateDevices(),this.logDevices("After Device Change");let e=this.store.getLocalPeer();yield this.setOutputDevice(!0),yield this.handleAudioInputDeviceChange(e==null?void 0:e.audioTrack),yield this.handleVideoInputDeviceChange(e==null?void 0:e.videoTrack),this.eventBus.analytics.publish(y.deviceChange({selection:this.getCurrentSelection(),type:"change",devices:this.getDevices()}))}),500).bind(this);this.handleAudioInputDeviceChange=e=>c(this,null,function*(){if(!e){d.d(this.TAG,"No Audio track on local peer");return}if(!this.audioInputChanged){d.d(this.TAG,"No Change in AudioInput Device");return}let t=this.getNewAudioInputDevice();if(!t||!t.deviceId){this.eventBus.analytics.publish(y.deviceChange({selection:{audioInput:t},error:m.TracksErrors.SelectedDeviceMissing("audio"),devices:this.getDevices(),type:"audioInput"})),d.e(this.TAG,"Audio device not found");return}let{settings:i}=e,r=new oe().codec(i.codec).maxBitrate(i.maxBitrate).deviceId(t.deviceId).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"audioInput"}),this.logDevices("Audio Device Change Success")}catch(s){d.e(this.TAG,"[Audio Device Change]",s),this.eventBus.analytics.publish(y.deviceChange({selection:{audioInput:t},devices:this.getDevices(),type:"audioInput",error:s})),this.eventBus.deviceChange.publish({error:s,selection:t,type:"audioInput",devices:this.getDevices()})}});this.handleVideoInputDeviceChange=e=>c(this,null,function*(){if(!e){d.d(this.TAG,"No video track on local peer");return}if(!this.videoInputChanged){d.d(this.TAG,"No Change in VideoInput Device");return}let t=this.videoInput[0];if(!t||!t.deviceId){this.eventBus.analytics.publish(y.deviceChange({selection:{videoInput:t},error:m.TracksErrors.SelectedDeviceMissing("video"),devices:this.getDevices(),type:"video"})),d.e(this.TAG,"Video device not found");return}let{settings:i}=e,r=new ee().codec(i.codec).maxBitrate(i.maxBitrate).maxFramerate(i.maxFramerate).setWidth(i.width).setHeight(i.height).deviceId(t.deviceId).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"video"}),this.logDevices("Video Device Change Success")}catch(s){d.e(this.TAG,"[Video Device Change]",s),this.eventBus.analytics.publish(y.deviceChange({selection:{videoInput:t},devices:this.getDevices(),type:"video",error:s})),this.eventBus.deviceChange.publish({error:s,type:"video",selection:t,devices:this.getDevices()})}});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,l=this[n].find(u=>this.createIdentifier(u)===this.createIdentifier(o));this.eventBus.analytics.publish(y.deviceChange({selection:{[n]:l},devices:this.getDevices(),type:r,isUserSelection:s}))}})}init(e=!1,t=!0){return c(this,null,function*(){this.initialized&&!e||(!this.initialized&&navigator.mediaDevices.addEventListener("devicechange",this.handleDeviceChange),this.initialized=!0,yield this.enumerateDevices(),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.initialized=!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(){let e=this.store.getLocalPeer(),t=e==null?void 0:e.audioTrack,i=this.audioInput.find(s=>s.deviceId===(t==null?void 0:t.getManuallySelectedDeviceId()));if(i)return i;t==null||t.resetManuallySelectedDeviceId();let r=this.audioInput.find(s=>s.deviceId==="default");return r?this.audioInput.find(o=>o.deviceId!=="default"&&r.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()}))})}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(l=>i.includes(l.toLowerCase())))return;let r=this.audioOutput.find(l=>e.deviceId!=="default"&&l.label===e.label);if(r)return r;let s=this.audioOutput.find(l=>l.groupId===e.groupId);if(s&&this.audioOutput[0].deviceId==="default"&&s.groupId===this.audioOutput[0].groupId)return s}logDevices(e=""){d.d(this.TAG,e,JSON.stringify({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput],selected:this.getCurrentSelection()},null,4))}};var Di=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 Ee.resumeContext()})}};var Oa=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 et=class{constructor(){this.eventEmitter=new Oa.EventEmitter2;this.deviceChange=new x(V.DEVICE_CHANGE,this.eventEmitter);this.localAudioEnabled=new x(V.LOCAL_AUDIO_ENABLED,this.eventEmitter);this.localVideoEnabled=new x(V.LOCAL_VIDEO_ENABLED,this.eventEmitter);this.statsUpdate=new x(V.STATS_UPDATE,this.eventEmitter);this.trackDegraded=new x(V.TRACK_DEGRADED,this.eventEmitter);this.trackRestored=new x(V.TRACK_RESTORED,this.eventEmitter);this.trackAudioLevelUpdate=new x(V.TRACK_AUDIO_LEVEL_UPDATE,this.eventEmitter);this.audioPluginFailed=new x(V.AUDIO_PLUGIN_FAILED,this.eventEmitter);this.localAudioSilence=new x(V.LOCAL_AUDIO_SILENCE,this.eventEmitter);this.analytics=new x(V.ANALYTICS,this.eventEmitter);this.policyChange=new x(V.POLICY_CHANGE,this.eventEmitter);this.localRoleUpdate=new x(V.LOCAL_ROLE_UPDATE,this.eventEmitter);this.audioTrackUpdate=new x(V.AUDIO_TRACK_UPDATE,this.eventEmitter);this.audioTrackAdded=new x(V.AUDIO_TRACK_ADDED,this.eventEmitter);this.audioTrackRemoved=new x(V.AUDIO_TRACK_REMOVED,this.eventEmitter);this.autoplayError=new x(V.AUTOPLAY_ERROR,this.eventEmitter);this.leave=new x(V.LEAVE,this.eventEmitter)}};var Ot=class{constructor(e){this.type=e.type,this.source=e.source||"regular",this.description="",e instanceof ke?(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 wi=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(l=>({audioLevel:l.level,peer:this.store.getPeerById(l.peer_id),track:this.store.getTrackById(l.track_id)}));(s=this.audioListener)==null||s.onAudioLevelUpdate(i),this.store.updateSpeakers(i);let r=t[0];if(r){let l=this.store.getPeerById(r.peer_id);(o=this.listener)==null||o.onPeerUpdate(4,l)}else(n=this.listener)==null||n.onPeerUpdate(5,null)}};var _i=class{constructor(e){this.listener=e;this.TAG="[BroadcastManager]"}handleNotification(e,t){e==="on-broadcast"&&this.handleBroadcast(t)}handleBroadcast(e){var t,i;d.d(this.TAG,`Received Message from sender=${(t=e==null?void 0:e.peer)==null?void 0:t.peer_id}: ${e}`),(i=this.listener)==null||i.onMessageReceived(e)}};var Ni=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 tt=class{constructor(e,t,i){this.store=e;this.eventBus=t;this.listener=i;this.TAG="[TrackManager]";this.tracksToProcess=new Map;this.handleTrackAdd=e=>{d.d(this.TAG,"ONTRACKADD",`${e}`),this.tracksToProcess.set(e.trackId,e),this.processPendingTracks()};this.handleTrackRemovedPermanently=e=>{d.d(this.TAG,"ONTRACKREMOVE",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){d.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 N&&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){d.d(this.TAG,"Track Update ignored - Peer not added to store");return}i||(i=Re(r,this.store),this.store.addPeer(i));for(let n in e.tracks){let l=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:S(S({},l),u)}),!p||this.tracksToProcess.has(n))this.processTrackInfo(u,e.peer.peer_id,t),this.processPendingTracks();else{p.setEnabled(!u.mute);let h=this.processTrackUpdate(p,l,u);h&&((o=this.listener)==null||o.onTrackUpdate(h,p,i))}}};this.processTrackInfo=(e,t,i)=>{};this.processPendingTracks=()=>{new Map(this.tracksToProcess).forEach(t=>{var s;let i=this.store.getTrackState(t.trackId);if(!i){d.d(this.TAG,"TrackState not added to store",`peerId - ${t.peerId}`,`trackId -${t.trackId}`);return}let r=this.store.getPeerById(i.peerId);if(!r){d.d(this.TAG,"Peer not added to store, peerId",i.peerId);return}t.source=i.trackInfo.source,t.peerId=r.peerId,t.logIdentifier=r.name,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){d.d(this.TAG,"TRACK_METADATA_ADD",JSON.stringify(e,null,2));for(let t in e.tracks){let i=e.tracks[t];this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:i})}this.processPendingTracks()}handleTrackRemove(e,t=!0){var s;d.d(this.TAG,"ONTRACKREMOVE",`${e}`);let i=this.store.getTrackState(e.trackId);if(!i)return;if(!this.store.hasTrack(e)){d.d(this.TAG,"Track not found in store");return}if(t){this.store.removeTrack(e);let 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),d.d(this.TAG,"auxiliary track removed",`${t}`)):t.type==="audio"&&e.audioTrack===t?(e.audioTrack=void 0,d.d(this.TAG,"audio track removed",`${t}`)):t.type==="video"&&e.videoTrack===t&&(e.videoTrack=void 0,d.d(this.TAG,"video track removed",`${t}`))}addAudioTrack(e,t){var i;t.type==="audio"&&(t.source==="regular"&&(!e.audioTrack||((i=e.audioTrack)==null?void 0:i.trackId)===t.trackId)?e.audioTrack=t:e.auxiliaryTracks.push(t),this.store.addTrack(t),d.d(this.TAG,"audio track added",`${t}`))}addVideoTrack(e,t){if(t.type!=="video")return;let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);if(i.setSimulcastDefinitons(r),this.addAsPrimaryVideoTrack(e,i))e.videoTrack?e.videoTrack.replaceTrack(i):e.videoTrack=i,this.store.addTrack(e.videoTrack);else{let s=e.auxiliaryTracks.findIndex(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]))}d.d(this.TAG,"video track added",`${t}`)}addAsPrimaryVideoTrack(e,t){var i;return t.source==="regular"&&(!e.videoTrack||((i=e.videoTrack)==null?void 0:i.trackId)===t.trackId)}processTrackUpdate(e,t,i){let r;return t.mute!==i.mute?(r=i.mute?2:3,e.type==="audio"&&this.eventBus.audioTrackUpdate.publish({track:e,enabled:!i.mute})):t.description!==i.description&&(r=4),r}};var Oi=class extends tt{constructor(t,i,r,s){super(t,i,s);this.transport=r;this.TAG="[OnDemandTrackManager]";this.processTrackInfo=(t,i,r=!0)=>{var u;if(t.type!=="video")return;let s=this.store.getPeerById(i);if(!s||!this.isPeerRoleSubscribed(i)){d.d(this.TAG,`no peer in store for peerId: ${i}`);return}let o=new Se(new MediaStream,this.transport.getSubscribeConnection()),n=ge.getEmptyVideoTrack();n.enabled=!t.mute;let l=new N(o,n,t.source);l.setTrackId(t.track_id),l.peerId=s.peerId,l.logIdentifier=s.name,this.addVideoTrack(s,l),r&&((u=this.listener)==null||u.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&&ue(t.videoTrack.nativeTrack)}isPeerRoleSubscribed(t){var s,o,n,l;if(!t)return!0;let i=this.store.getLocalPeer(),r=this.store.getPeerById(t);return r&&((l=(o=(s=i==null?void 0:i.role)==null?void 0:s.subscribeParams)==null?void 0:o.subscribeToRoles)==null?void 0:l.includes((n=r.role)==null?void 0:n.name))}};var xi=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&&d.d(this.TAG,`${r}`),r.forEach(o=>{var l;let n={peer_id:o.peerId,role:((l=o.role)==null?void 0:l.name)||"",info:{name:o.name,data:o.metadata||"",user_id:o.customerUserId||""},tracks:{},groups:[],realtime:o.realtime};this.peerManager.handlePeerLeave(n)});let s=[];i.forEach(o=>{let n=this.store.getPeerById(o.peer_id),l=Object.values(o.tracks);n&&(this.store.getPeerTracks(n.peerId).forEach(p=>{var h;o.tracks[p.trackId]||(this.removePeerTrack(n,p.trackId),(h=this.listener)==null||h.onTrackUpdate(1,p,n))}),l.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?(d.d(this.TAG,"RECONNECT_PEER_LIST event",JSON.stringify(r,null,2)),this.handleReconnectPeerList(r)):(d.d(this.TAG,"PEER_LIST event",JSON.stringify(r,null,2)),this.handleInitialPeerList(r))}else if(e==="room-state"){let r=t;this.handlePreviewRoomState(r)}}removePeerTrack(e,t){var i,r;if(d.d(this.TAG,`removing track - ${t} from ${e}`),((i=e.audioTrack)==null?void 0:i.trackId)===t)e.audioTrack=void 0;else if(((r=e.videoTrack)==null?void 0:r.trackId)===t)e.videoTrack=void 0;else{let s=e.auxiliaryTracks.findIndex(o=>o.trackId===t);s>=0&&e.auxiliaryTracks.splice(s,1)}}};var L=a=>a?new Date(a):void 0;var Ui=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),d.d(this.TAG,"PEER_LEAVE",e.peer_id,`remainingPeers=${this.store.getPeers().length}`),t&&(t.audioTrack&&((i=this.listener)==null||i.onTrackUpdate(1,t.audioTrack,t)),t.videoTrack&&((r=this.listener)==null||r.onTrackUpdate(1,t.videoTrack,t)),(s=t.auxiliaryTracks)==null||s.forEach(n=>{var l;(l=this.listener)==null||l.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,l,u;let t=this.store.getPeerById(e.peer_id);if(!t&&e.realtime){t=this.makePeer(e),(s=this.listener)==null||s.onPeerUpdate(t.isHandRaised?12:14,t);return}if(t&&!t.isLocal&&!e.realtime){this.store.removePeer(t.peerId),(o=this.listener)==null||o.onPeerUpdate(13,t);return}if(!t){d.d(this.TAG,`peer ${e.peer_id} not found`);return}if(t.role&&t.role.name!==e.role){let p=this.store.getPolicyForRole(e.role);t.updateRole(p),this.updateSimulcastLayersForPeer(t),(n=this.listener)==null||n.onPeerUpdate(8,t)}let i=t.isHandRaised;t.updateGroups(e.groups);let r=(l=e.groups)==null?void 0:l.includes(Te);i!==r&&((u=this.listener)==null||u.onPeerUpdate(12,t)),this.handlePeerInfoUpdate(S({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=Re(e,this.store),t.realtime=e.realtime,t.joinedAt=L(e.joined_at),t.fromRoomState=!!e.is_from_room_state,this.store.addPeer(t),d.d(this.TAG,"adding to the peerList",`${t}`));for(let i in e.tracks){let r=e.tracks[i];this.store.setTrackState({peerId:e.peer_id,trackInfo:r}),r.type==="video"&&this.trackManager.processTrackInfo(r,e.peer_id,!1)}return t}updateSimulcastLayersForPeer(e){this.store.getPeerTracks(e.peerId).forEach(t=>{if(t.type==="video"&&["regular","screen"].includes(t.source)){let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);i.setSimulcastDefinitons(r)}})}};var Bi=class{constructor(e,t){this.store=e;this.eventBus=t}handlePolicyChange(e){let t=this.store.getLocalPeer();if(t&&!t.role){let r=e.known_roles[e.name];t.updateRole(r)}this.store.setKnownRoles(e);let i=this.store.getRoom();i?i.templateId=e.template_id:d.w("[PolicyChangeManager]","on policy change - room not present"),this.updateLocalPeerRole(e),this.eventBus.policyChange.publish(e)}updateLocalPeerRole(e){var i;let t=this.store.getLocalPeer();if(t!=null&&t.role&&t.role.name!==e.name){let r=this.store.getPolicyForRole(e.name),s=t.role;t.updateRole(r),r.name===((i=t.asRole)==null?void 0:i.name)&&delete t.asRole,this.eventBus.localRoleUpdate.publish({oldRole:s,newRole:r})}}};var Vi=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 d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e==null?void 0:e.id),i=t==null?void 0:t.id;if(t||(i=(yield this.transport.signal.createWhiteboard(this.getCreateOptionsWithDefaults(e))).id),!i)throw new Error(`Whiteboard ID: ${i} not found`);let r=yield this.transport.signal.getWhiteboard({id:i}),s=v(S({},t),{title:e==null?void 0:e.title,attributes:e==null?void 0:e.attributes,id:r.id,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 d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e);if(!t)throw new Error(`Whiteboard ID: ${e} not found`);let i={id:t.id,title:t.title,open:!1};this.store.setWhiteboard(i),(r=this.listener)==null||r.onWhiteboardUpdate(i)})}setListener(e){this.listener=e}getCreateOptionsWithDefaults(e){var o;let t=Object.values(this.store.getKnownRoles()),i=[],r=[],s=[];return t.forEach(n=>{var l,u,p;(l=n.permissions.whiteboard)!=null&&l.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 xt=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.whiteboard=new Vi(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(v(S({},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=Fi(v(S({},e),{poll_id:e.id,state:"created",created_by:(o=this.store.getLocalPeer())==null?void 0:o.peerId}));s.questions=r.questions.map(({question:l,options:u,answer:p})=>v(S({},l),{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,l;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"?((l=s.options)==null||l.sort(),delete s.text,delete s.option):(delete s.option,delete s.options),s.skipped&&(delete s.option,delete s.options,delete s.text),S({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 u,p;let r=this.store.getPoll(e);if(!r)throw new Error("Invalid poll ID - Poll not found");let s=((p=(u=this.store.getLocalPeer())==null?void 0:u.role)==null?void 0:p.permissions.pollRead)||!1;if(r.anonymous||r.state!=="stopped"||!s)return{entries:[],hasNext:!1};let o=yield this.transport.signal.fetchPollLeaderboard({poll_id:r.id,count:i,offset:t}),n={avgScore:o.avg_score,avgTime:o.avg_time,votedUsers:o.voted_users,totalUsers:o.total_users,correctUsers:o.correct_users};return{entries:o.questions.map(h=>({position:h.position,totalResponses:h.total_responses,correctResponses:h.correct_responses,duration:h.duration,peer:h.peer,score:h.score})),hasNext:!o.last,summary:n}})}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 l=yield this.transport.signal.getPollsList({count:50,state:"created"}),u=yield this.transport.signal.getPollsList({count:50,state:"stopped"});r=[...l.polls,...r,...u.polls]}for(let l of r){let u=yield this.transport.signal.getPollQuestions({poll_id:l.poll_id,index:0,count:50}),p=Fi(l),h=this.store.getPoll(l.poll_id);p.questions=u.questions.map(({question:g,options:T,answer:I},A)=>{var O,ye;return v(S({},g),{options:T,answer:I,responses:(ye=(O=h==null?void 0:h.questions)==null?void 0:O[A])==null?void 0:ye.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 l=(o=e.options)==null?void 0:o.map((u,p)=>v(S({},u),{index:p+1}));return{question:v(S({},e),{index:t+1}),options:l,answer:e.answer}}let i=v(S({},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((l,u)=>({index:u+1,text:l.text,weight:l.weight})),e.type==="single-choice"?s.option=e.options.findIndex(l=>l.isCorrectAnswer)+1||void 0:s.options=e.options.map((l,u)=>l.isCorrectAnswer?u+1:void 0).filter(l=>!!l)):(s==null||delete s.options,s==null||delete s.option),{question:i,options:r,answer:s}}getQuestionInPoll(e,t){var r;let i=(r=e==null?void 0:e.questions)==null?void 0:r.find(s=>s.index===t);if(!i)throw new Error("Invalid question index - Question not found in poll");return i}},Fi=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 Gi=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}),l=Fi(s);l.questions=n.questions.map(({question:u,options:p,answer:h})=>v(S({},u),{options:p,answer:h})),yield this.updatePollResponses(l,!0),t.push(l),this.store.setPoll(l)}(r=this.listener)==null||r.onPollsUpdate(1,t)})}handlePollStop(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let s=this.store.getPoll(r.poll_id);if(s){s.state="stopped",s.stoppedAt=L(r.stopped_at),s.stoppedBy=r.stopped_by;let 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),yield this.updatePollResponses(s,!1),t.push(s)}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(4,t))})}updatePollResult(e,t){var i;e.result=S({},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(l=>l.index===r.question);s&&(s.result=S({},s.result),s.result.correctResponses=r.correct,s.result.skippedCount=r.skipped,s.result.totalResponses=r.total,(n=r.options)==null||n.forEach((l,u)=>{var h;let p=(h=s.options)==null?void 0:h[u];p&&p.voteCount!==l&&(p.voteCount=l)}))})}updatePollResponses(e,t){return c(this,null,function*(){var r;(r=(yield this.transport.signal.getPollResponses({poll_id:e.id,index:0,count:50,self:t})).responses)==null||r.forEach(({response:s,peer:o,final:n})=>{var p;let l=(p=e==null?void 0:e.questions)==null?void 0:p.find(h=>h.index===s.question);if(!l)return;let u={id:s.response_id,questionIndex:s.question,option:s.option,options:s.options,text:s.text,responseFinal: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(l.responses)&&l.responses.length>0?l.responses.find(({id:h})=>h===u.id)||l.responses.push(u):l.responses=[u]})})}};var $i=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(l=>l.publishedTrackId===i);if(!o)return;let n=()=>{var l;(l=this.listener)==null||l.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,l=this.getTracksToBeUpdated({type:t,source:i,enabled:n});if(l.length!==0)if(n)(u=this.listener)==null||u.onChangeMultiTrackStateRequest({requestedBy:o,tracks:l,type:t,source:i,enabled:!0});else{let p=[];for(let h of l)p.push(h.setEnabled(!1));Promise.all(p).then(()=>{var h;(h=this.listener)==null||h.onChangeMultiTrackStateRequest({requestedBy:o,tracks:l,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 Wi=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;default:break}}handleRoomInfo(e){let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.description=e.description,t.large_room_optimization=e.large_room_optimization,t.max_size=e.max_size,t.name=e.name}handleSessionInfo(e){var i;let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.sessionId=e.session_id,t.peerCount!==e.peer_count&&(t.peerCount=e.peer_count,(i=this.listener)==null||i.onRoomUpdate("ROOM_PEER_COUNT_UPDATED",t))}handlePreviewRoomState(e){let{room:t}=e;this.onRoomState(t)}onRoomState(e){var l,u,p,h;let{recording:t,streaming:i,session_id:r,started_at:s,name:o}=e,n=this.store.getRoom();if(!n){d.w(this.TAG,"on room state - room not present");return}n.name=o,n.rtmp.running=this.isStreamingRunning((l=i==null?void 0:i.rtmp)==null?void 0:l.state),n.rtmp.startedAt=L((u=i==null?void 0:i.rtmp)==null?void 0:u.started_at),n.rtmp.state=(p=i==null?void 0:i.rtmp)==null?void 0:p.state,n.recording.server=this.getPeerListSFURecording(t),n.recording.browser=this.getPeerListBrowserRecording(t),n.recording.hls=this.getPeerListHLSRecording(t),n.hls=this.convertHls(i==null?void 0:i.hls),n.sessionId=r,n.startedAt=L(s),(h=this.listener)==null||h.onRoomUpdate("RECORDING_STATE_UPDATED",n)}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;i.variants.push({initialisedAt:L((o=e==null?void 0:e.variants)==null?void 0:o[s].initialised_at),url:""})}),i):(d.w(this.TAG,"on hls - room not present"),i)}updateHLSStatus(e){var r;let t=this.store.getRoom(),i=e.variants&&e.variants.length>0?this.isStreamingRunning(e.variants[0].state):!1;if(!t){d.w(this.TAG,"on hls - room not present");return}e.enabled=i,t.hls=this.convertHls(e),(r=this.listener)==null||r.onRoomUpdate("HLS_STREAMING_STATE_UPDATED",t)}convertHls(e){var r;if(e!=null&&e.variants&&e.variants.length>0?e.variants[0].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})}),i}getHLSRecording(e){var r,s;let t={running:!1},i=this.isRecordingRunning(e==null?void 0:e.state);return(i||(e==null?void 0:e.state)==="paused")&&(t={running:i,singleFilePerLayer:!!((r=e==null?void 0:e.hls_recording)!=null&&r.single_file_per_layer),hlsVod:!!((s=e==null?void 0:e.hls_recording)!=null&&s.hls_vod),startedAt:L(e==null?void 0:e.started_at),initialisedAt:L(e==null?void 0:e.initialised_at),state:e==null?void 0:e.state,error:this.toSdkError(e==null?void 0:e.error)}),t}getPeerListHLSRecording(e){var r,s;let t=e==null?void 0:e.hls;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),initialisedAt:L(t==null?void 0:t.initialised_at),state:t==null?void 0:t.state,singleFilePerLayer:(r=t==null?void 0:t.config)==null?void 0:r.single_file_per_layer,hlsVod:(s=t==null?void 0:t.config)==null?void 0:s.hls_vod}}getPeerListBrowserRecording(e){let t=e==null?void 0:e.browser;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}getPeerListSFURecording(e){let t=e==null?void 0:e.sfu;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}updateRecordingStatus(e){var s;let t=this.store.getRoom(),i=this.isRecordingRunning(e.state);if(!t){d.w(this.TAG,`set recording status running=${i} - room not present`);return}let r;e.type==="sfu"?(t.recording.server={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e.state},r="SERVER_RECORDING_STATE_UPDATED"):e.type==="HLS"?(t.recording.hls=this.getHLSRecording(e),r="RECORDING_STATE_UPDATED"):(t.recording.browser={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e==null?void 0:e.state},r="BROWSER_RECORDING_STATE_UPDATED"),(s=this.listener)==null||s.onRoomUpdate(r,t)}updateRTMPStatus(e){var r,s;let t=this.store.getRoom(),i=this.isStreamingRunning(e.state);if(!t){d.w(this.TAG,"on policy change - room not present");return}if(!i){t.rtmp={running:i,state:e.state,error:this.toSdkError(e.error)},(r=this.listener)==null||r.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t);return}t.rtmp={running:i,startedAt:i?L(e.started_at):void 0,state:e.state,error:this.toSdkError(e.error)},(s=this.listener)==null||s.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t)}toSdkError(e){if(!(e!=null&&e.code))return;let t=e.message||"error in streaming/recording",i=new f(e.code,"ServerErrors","NONE",t,t);return d.e(this.TAG,"error in streaming/recording",i),i}};var Ki=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 qi=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,!r&&o.open){let l=yield this.transport.signal.getWhiteboard({id:e.id});o.token=l.token,o.addr=l.addr,o.permissions=l.permissions}this.store.setWhiteboard(o),(n=this.listener)==null||n.onWhiteboardUpdate(o)})}};var ji=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 Oi(this.store,t,this.transport,this.listener):new tt(this.store,t,this.listener),this.peerManager=new Ui(this.store,this.trackManager,this.listener),this.peerListManager=new xi(this.store,this.peerManager,this.trackManager,this.listener),this.broadcastManager=new _i(this.listener),this.policyChangeManager=new Bi(this.store,t),this.requestManager=new $i(this.store,this.listener),this.activeSpeakerManager=new wi(this.store,this.listener,this.audioListener),this.connectionQualityManager=new Ni(this.store,this.connectionQualityListener),this.roomUpdateManager=new Wi(this.store,this.listener),this.sessionMetadataManager=new Ki(this.store,this.listener),this.pollsManager=new Gi(this.store,this.transport,this.listener),this.whiteboardManager=new qi(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)||d.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){d.d(this.TAG,`Ignoring sfu notification - ${e}`,{notification:t});return}this.trackManager.handleTrackRemovedPermanently(t);break}case"on-track-layer-update":{this.trackManager.handleTrackLayerUpdate(t);break}case"active-speakers":this.activeSpeakerManager.handleActiveSpeakers(t);break;case"on-connection-quality-update":this.connectionQualityManager.handleQualityUpdate(t);break;case"on-policy-change":this.policyChangeManager.handlePolicyChange(t);break;default:break}}};var Ji=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 Qi=class{constructor(e,t,i="",r="",s="https://prod-init.100ms.live/init",o=!1){this.authToken=e;this.peerId=t;this.peerName=i;this.data=r;this.endpoint=s;this.autoSubscribeVideo=o}};var K=(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))(K||{}),xa={0:[],1:[],2:[1],3:[1],4:[1]};var zi=(n=>(n.Disconnected="Disconnected",n.Connecting="Connecting",n.Joined="Joined",n.Preview="Preview",n.Failed="Failed",n.Reconnecting="Reconnecting",n.Leaving="Leaving",n))(zi||{});var Yi=class{constructor(e){this.promise=new Promise((t,i)=>{this.resolve=t,this.reject=i,e(t,i)})}};var Xi=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,maxFailedRetries:s=5,changeState:o=!0}){yield this.scheduleTask({category:e,error:t,changeState:o,task:i,originalState:r,maxFailedRetries:s})})}reset(){this.retryTaskIds.forEach(e=>clearTimeout(e)),this.retryTaskIds=[],this.inProgress.clear()}isTaskInProgress(e){return!!this.inProgress.get(e)}scheduleTask(l){return c(this,arguments,function*({category:e,error:t,changeState:i,task:r,originalState:s,maxFailedRetries:o=5,failedRetryCount:n=0}){if(d.d(this.TAG,"schedule: ",{category:K[e],error:t}),n===0){let T=this.inProgress.get(e);if(T){d.d(this.TAG,`schedule: Already a task for ${K[e]} scheduled, waiting for its completion`),yield T.promise;return}let I=new Yi((A,O)=>{});this.inProgress.set(e,I),this.sendEvent(t,e)}let u=!1,p=xa[e];for(let T in p){let I=p[parseInt(T)];try{let A=this.inProgress.get(I);A&&(d.d(this.TAG,`schedule: Suspending retry task of ${K[e]}, waiting for ${K[I]} to recover`),yield A.promise,d.d(this.TAG,`schedule: Resuming retry task ${K[e]} as it's dependency ${K[I]} is recovered`))}catch(A){d.d(this.TAG,`schedule: Stopping retry task of ${K[e]} as it's dependency ${K[I]} failed to recover`),u=!0;break}}if(n>=o||u){if(t.description+=`. [${K[e]}] Could not recover after ${n} tries`,u&&(t.description+=` Could not recover all of it's required dependencies - [${p.map(T=>K[T]).toString()}]`),t.isTerminal=!0,this.inProgress.delete(e),this.sendEvent(t,e),this.reset(),i)this.onStateChange("Failed",t);else throw t;return}i&&this.onStateChange("Reconnecting",t);let h=this.getDelayForRetryCount(e,n);d.d(this.TAG,`schedule: [${K[e]}] [failedRetryCount=${n}] Scheduling retry task in ${h}ms`);let g;try{g=yield this.setTimeoutPromise(r,h)}catch(T){g=!1,d.w(this.TAG,`[${K[e]}] Un-caught exception ${T.name} in retry-task, initiating retry`,T)}if(g){let T=this.inProgress.get(e);this.inProgress.delete(e),T==null||T.resolve(n),i&&this.inProgress.size===0&&this.onStateChange(s),d.d(this.TAG,`schedule: [${K[e]}] [failedRetryCount=${n}] Recovered \u267B\uFE0F`)}else yield this.scheduleTask({category:e,error:t,changeState:i,task:r,originalState:s,maxFailedRetries:o,failedRetryCount:n+1})})}getBaseDelayForTask(e,t){return e===2?2:Math.pow(2,t)}getDelayForRetryCount(e,t){let i=this.getBaseDelayForTask(e,t),r=e===2?Math.random()*2:Math.random();return Math.round(Math.min(i+r,60)*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 Zi=class extends be{constructor(){super(100);this.localStorage=new le("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 R(i);super.enqueue(r)})}};var er=class{constructor(){this.TAG="[AnalyticsTransport]"}sendEvent(e){try{this.sendSingleEvent(e),this.flushFailedEvents()}catch(t){d.w(this.TAG,"sendEvent failed",t)}}flushFailedEvents(e){var t;try{for(d.d(this.TAG,"Flushing failed events",this.failedEvents);this.failedEvents.size()>0;){let i=this.failedEvents.dequeue();i&&(((t=i.metadata)==null?void 0:t.peer.peer_id)===e||!i.metadata.peer.peer_id?this.sendSingleEvent(i):fe.sendEvent(i))}}catch(i){d.w(this.TAG,"flushFailedEvents failed",i)}}sendSingleEvent(e){try{this.transportProvider.sendEvent(e),d.d(this.TAG,"Sent event",e.name,e)}catch(t){throw d.w(this.TAG,`${this.transportProvider.TAG}.sendEvent failed, adding to local storage events`,{event:e,error:t}),this.failedEvents.enqueue(e),t}}};var tr=class extends er{constructor(t){super();this.transportProvider=t;this.failedEvents=new Zi}};var it=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=>d.e("[StatsAnanlytics]",e.message)))}startLoop(){return c(this,null,function*(){for(;this.shouldSendEvent;)yield z(this.pushInterval*1e3),this.sendEvent()})}sendEvent(){this.trackAnalytics.forEach(e=>{e.clearSamples()})}},rt=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)}},ir=(a,e)=>a&&e&&(a.frameWidth!==e.frameWidth||a.frameHeight!==e.frameHeight),rr=(a,e)=>a&&e&&a.enabled!==e.enabled,Ut=a=>Object.entries(a).filter(([,e])=>e!==void 0).reduce((e,[t,i])=>(e[t]=i,e),{});var Bt=class extends it{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(l=>l.getTrackIDBeingSent()===s);Object.keys(o).forEach(l=>{var T,I,A;let u=o[l];if(!n)return;let p=this.getTrackIdentifier(n.trackId,u),h=v(S({},u),{availableOutgoingBitrate:(I=(T=t.getLocalPeerStats())==null?void 0:T.publish)==null?void 0:I.availableOutgoingBitrate});if(p&&this.trackAnalytics.has(p))(A=this.trackAnalytics.get(p))==null||A.pushTempStat(h);else if(n){let O=new ls({track:n,sampleWindowSize:this.sampleWindowSize,rid:u.rid,ssrc:u.ssrc.toString(),kind:u.kind});O.pushTempStat(h),this.trackAnalytics.set(this.getTrackIdentifier(n.trackId,u),O)}let g=this.trackAnalytics.get(p);g!=null&&g.shouldCreateSample()&&(i=!0)})}),this.trackAnalytics.forEach(s=>{!this.store.hasTrack(s.track)&&!(s.samples.length>0)&&this.trackAnalytics.delete(s.track_id)}),i&&this.trackAnalytics.forEach(s=>{s.createSample()})}getTrackIdentifier(t,i){return i.rid?`${t}:${i.rid}`:t}},ls=class extends rt{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,l=this.calculateAverage("roundTripTime",!1),u=l?Math.round(l*1e3):void 0;return Ut({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.calculateDifferenceForSample("packetsLost"),total_packets_sent:this.calculateDifferenceForSample("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||rr(i,r)||i.kind==="video"&&ir(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}};var Vt=class extends it{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 h;let o=i[s],n=this.store.getTrackById(s),l=o.jitterBufferDelay&&o.jitterBufferEmittedCount&&o.jitterBufferDelay/o.jitterBufferEmittedCount,u=this.calculateAvSyncForStat(o,t);if(this.trackAnalytics.has(s))(h=this.trackAnalytics.get(s))==null||h.pushTempStat(v(S({},o),{calculatedJitterBufferDelay:l,avSync:u}));else if(n){let g=new ps({track:n,sampleWindowSize:this.sampleWindowSize,ssrc:o.ssrc.toString(),kind:o.kind});g.pushTempStat(v(S({},o),{calculatedJitterBufferDelay:l,avSync:u})),this.trackAnalytics.set(s,g)}let p=this.trackAnalytics.get(s);p!=null&&p.shouldCreateSample()&&(r=!0)}),this.trackAnalytics.forEach(s=>{!this.store.hasTrack(s.track)&&!(s.samples.length>0)&&this.trackAnalytics.delete(s.track_id)}),r&&this.trackAnalytics.forEach(s=>{s.createSample()})}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 Mt;let l=i.getRemoteTrackStats(s.trackId);if(!l)return Mt;if(l.estimatedPlayoutTimestamp)return l.estimatedPlayoutTimestamp-t.estimatedPlayoutTimestamp}},ps=class extends rt{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 Ut(v(S({},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"),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 Ut(v(S({},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||rr(i,r)||i.kind==="video"&&ir(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!==Mt);return i.length===0?Mt:i.reduce((r,s)=>r+s,0)/i.length}};var ar=(t=>(t[t.Publish=0]="Publish",t[t.Subscribe=1]="Subscribe",t))(ar||{});var Ft=Ce(require("sdp-transform"));function Ua(a,e){var r;let t=Ft.parse(a.sdp);if(!((r=t.origin)!=null&&r.username.startsWith("mozilla")))return a;let i=e?Array.from(e.values()):[];return t.media.forEach(s=>{var l,u,p;let o=(l=s.msid)==null?void 0:l.split(" ")[0],n=(u=i.find(h=>h.type===s.type&&h.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:Ft.write(t)}}function Ba(a,e){var s;if(!(a!=null&&a.sdp)||!e)return;let i=Ft.parse(a.sdp).media.find(o=>se(o.mid)&&parseInt(o.mid)===parseInt(e));return(s=i==null?void 0:i.msid)==null?void 0:s.split(" ")[1]}function Va(a){return a.sdp.includes("usedtx=1")?a:{type:a.type,sdp:a.sdp.replace("useinbandfec=1","useinbandfec=1;usedtx=1")}}var ve="[HMSConnection]",Ue=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"}addTransceiver(e,t){return this.nativeConnection.addTransceiver(e,t)}createOffer(e,t){return c(this,null,function*(){try{let i=yield this.nativeConnection.createOffer(t);return d.d(ve,`[role=${this.role}] createOffer offer=${JSON.stringify(i,null,1)}`),Va(Ua(i,e))}catch(i){throw m.WebrtcErrors.CreateOfferFailed(this.action,i.message)}})}createAnswer(e=void 0){return c(this,null,function*(){try{let t=yield this.nativeConnection.createAnswer(e);return d.d(ve,`[role=${this.role}] createAnswer answer=${JSON.stringify(t,null,1)}`),t}catch(t){throw m.WebrtcErrors.CreateAnswerFailed(this.action,t.message)}})}setLocalDescription(e){return c(this,null,function*(){try{d.d(ve,`[role=${this.role}] setLocalDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setLocalDescription(e)}catch(t){throw m.WebrtcErrors.SetLocalDescriptionFailed(this.action,t.message)}})}setRemoteDescription(e){return c(this,null,function*(){try{d.d(ve,`[role=${this.role}] setRemoteDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setRemoteDescription(e)}catch(t){throw m.WebrtcErrors.SetRemoteDescriptionFailed(this.action,t.message)}})}addIceCandidate(e){return c(this,null,function*(){if(this.nativeConnection.signalingState==="closed"){d.d(ve,`[role=${this.role}] addIceCandidate signalling state closed`);return}d.d(ve,`[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()}logSelectedIceCandidatePairs(){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(),d.d(ve,`${ar[this.role]} connection`,`selected ${i||"unknown"} candidate pair`,JSON.stringify(this.selectedCandidatePair,null,2)))};typeof s.onselectedcandidatepairchange=="function"&&(s.onselectedcandidatepairchange=o),o()}})}catch(e){d.w(ve,`Error in logging selected ice candidate pair for ${ar[this.role]} connection`,e)}}removeTrack(e){this.nativeConnection.signalingState!=="closed"&&this.nativeConnection.removeTrack(e)}setMaxBitrateAndFramerate(e){return c(this,null,function*(){let t=e.settings.maxBitrate,i=e instanceof B&&e.settings.maxFramerate,r=this.getSenders().find(s=>{var o;return((o=s==null?void 0:s.track)==null?void 0:o.id)===e.getTrackIDBeingSent()});if(r){let s=r.getParameters();s.encodings.length===1&&(t&&(s.encodings[0].maxBitrate=t*1e3),i&&(s.encodings[0].maxFramerate=i)),yield r.setParameters(s)}else d.w(ve,`no sender found to setMaxBitrate for track - ${e.trackId}, sentTrackId - ${e.getTrackIDBeingSent()}`)})}getStats(){return c(this,null,function*(){return yield this.nativeConnection.getStats()})}close(){return c(this,null,function*(){this.nativeConnection.close()})}getReceivers(){return this.nativeConnection.getReceivers()}};var Gt=class extends Ue{constructor(t,i,r){super(0,t);this.TAG="[HMSPublishConnection]";this.observer=r,this.nativeConnection=new RTCPeerConnection(i),this.channel=this.nativeConnection.createDataChannel(pi,{protocol:"SCTP"}),this.channel.onerror=s=>d.e(this.TAG,`publish data channel onerror ${s}`,s),this.nativeConnection.onicecandidate=({candidate:s})=>{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")})}}initAfterJoin(){this.nativeConnection.onnegotiationneeded=()=>c(this,null,function*(){d.d(this.TAG,"onnegotiationneeded"),yield this.observer.onRenegotiationNeeded()})}};var Fa=Ce(require("eventemitter2")),Ga=require("uuid");var $t=class{constructor(e,t,i=""){this.TAG="[HMSDataChannel]";this.nativeChannel=e,this.observer=t,this.metadata=i,e.onmessage=r=>{this.observer.onMessage(r.data)}}get id(){return this.nativeChannel.id}get label(){return this.nativeChannel.label}get readyState(){return this.nativeChannel.readyState}send(e){d.d(this.TAG,`[${this.metadata}] Sending [size=${e.length}] message=${e}`),this.nativeChannel.send(e)}close(){this.nativeChannel.close()}};var Wt=class a extends Ue{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 Fa.default({maxListeners:60});this.handlePendingApiMessages=()=>{this.eventEmitter.emit("open",!0),this.pendingMessageQueue.length>0&&(d.d(this.TAG,"Found pending message queue, sending messages"),this.pendingMessageQueue.forEach(t=>this.sendOverApiDataChannel(t)),this.pendingMessageQueue.length=0)};this.sendMessage=(t,i)=>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){d.d(this.TAG,`Track not found ${i}`,{request:t,try:o+1,error:n});break}if(d.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 Ae(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 d.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===pi&&(this.apiChannel=new $t(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.signal.trickle(this.role,t.candidate)},this.nativeConnection.ontrack=t=>{var u;let i=t.streams[0],r=i.id;if(!this.remoteStreams.has(r)){let p=new Se(i,this);this.remoteStreams.set(r,p)}i.addEventListener("removetrack",p=>{if(p.track.id!==t.track.id)return;let h=s.tracks.findIndex(g=>{var T;return g.nativeTrack.id===p.track.id&&t.transceiver.mid===((T=g.transceiver)==null?void 0:T.mid)});if(h>=0){let g=s.tracks[h];this.observer.onTrackRemove(g),s.tracks.splice(h,1),s.tracks.length===0&&this.remoteStreams.delete(r)}});let s=this.remoteStreams.get(r),o=t.track.kind==="audio"?te:N,n=new o(s,t.track);t.track.kind==="video"&&s.setVideoLayerLocally("none","addTrack","subscribeConnection"),n.transceiver=t.transceiver;let l=Ba(this.remoteDescription,(u=t.transceiver)==null?void 0:u.mid);l&&n.setSdpTrackId(l),s.tracks.push(n),this.observer.onTrackAdd(n)}}sendOverApiDataChannel(t){this.apiChannel&&this.apiChannel.readyState==="open"?this.apiChannel.send(t):(d.w(this.TAG,`API Data channel not ${this.apiChannel?"open":"present"}, queueing`,t),this.pendingMessageQueue.push(t))}sendOverApiDataChannelWithResponse(t,i){return c(this,null,function*(){let r=(0,Ga.v4)();if(t.method==="prefer-video-track-state"&&this.isFlagEnabled("disableVideoTrackAutoUnsubscribe")&&t.params.max_spatial_layer==="none")return d.d(this.TAG,"video auto unsubscribe is disabled, request is ignored"),{id:r};let s=JSON.stringify(S({id:i||r,jsonrpc:"2.0"},t));return this.sendMessage(s,r)})}close(){return c(this,null,function*(){var t;yield q(a.prototype,this,"close").call(this),(t=this.apiChannel)==null||t.close()})}};var or="[InitService]",Kt=class{static handleError(e,t){switch(e.status){case 404:throw m.APIErrors.EndpointUnreachable("INIT",t.message||e.statusText);case 200:break;default:throw m.APIErrors.ServerErrors(t.code||e.status,"INIT",t.message||(e==null?void 0:e.statusText))}}static fetchInitConfig(o){return c(this,arguments,function*({token:e,peerId:t,userAgent:i,initEndpoint:r="https://prod-init.100ms.live",region:s=""}){d.d(or,`fetchInitConfig: initEndpoint=${r} token=${e} peerId=${t} region=${s} `);let n=kc(r,t,i,s);try{let l=yield fetch(n,{headers:{Authorization:`Bearer ${e}`}});try{let u=yield l.clone().json();return this.handleError(l,u),d.d(or,`config is ${JSON.stringify(u,null,2)}`),Pc(u)}catch(u){let p=yield l.text();throw d.e(or,"json error",u.message,p),m.APIErrors.ServerErrors(l.status,"INIT",p)}}catch(l){let u=l;throw["Failed to fetch","NetworkError","ECONNRESET"].some(p=>u.message.includes(p))?m.APIErrors.EndpointUnreachable("INIT",u.message):u}})}};function kc(a,e,t,i){try{let r=new URL("/init",a);return i&&i.trim().length>0&&r.searchParams.set("region",i.trim()),r.searchParams.set("peer_id",e),r.searchParams.set("user_agent_v2",t),r.toString()}catch(r){let s=r;throw d.e(or,s.name,s.message),s}}function Pc(a){var e;return v(S({},a),{rtcConfiguration:v(S({},a.rtcConfiguration),{iceServers:(e=a.rtcConfiguration)==null?void 0:e.ice_servers})})}var $a=require("uuid");var qt=class{constructor(e){this.TAG="[SIGNAL]: ";this.pongResponseTimes=new be(5);this.isJoinCompleted=!1;this.pendingTrickle=[];this.socket=null;this.callbacks=new Map;this._isConnected=!1;this.id=0;this.onCloseHandler=()=>{};this.resolvePingOnAnyResponse=()=>{this.callbacks.forEach((e,t)=>{var i;((i=e.metadata)==null?void 0:i.method)==="ping"&&(e.resolve({timestamp:Date.now()}),this.callbacks.delete(t))})};this.offlineListener=()=>{d.d(this.TAG,"Window network offline"),this.setIsConnected(!1,"Window network offline")};this.onlineListener=()=>{d.d(this.TAG,"Window network online"),this.observer.onNetworkOnline()};this.observer=e,window.addEventListener("offline",this.offlineListener),window.addEventListener("online",this.onlineListener),this.onMessageHandler=this.onMessageHandler.bind(this)}get isConnected(){return this._isConnected}setIsConnected(e,t=""){d.d(this.TAG,`isConnected set id: ${this.id}, oldValue: ${this._isConnected}, newValue: ${e}`),this._isConnected!==e&&(this._isConnected&&!e?(this._isConnected=e,this.rejectPendingCalls(t),this.observer.onOffline(t)):!this._isConnected&&e&&(this._isConnected=e,this.observer.onOnline()))}getPongResponseTimes(){return this.pongResponseTimes.toList()}internalCall(e,t){return c(this,null,function*(){var s;let i=(0,$a.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,l)=>{this.callbacks.set(i,{resolve:n,reject:l,metadata:{method:e}})})}catch(o){if(o instanceof f)throw o;let n=o;throw m.WebsocketMethodErrors.ServerErrors(Number(n.code),Rr(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=()=>{d.e(this.TAG,"Error from websocket"),r=!0,i(m.WebSocketConnectionErrors.FailedToConnect("JOIN","Error opening websocket connection"))};this.onCloseHandler=n=>{d.w(`Websocket closed code=${n.code}`),r?this.setIsConnected(!1,`code: ${n.code}${n.code!==1e3?", unexpected websocket close":""}`):(r=!0,i(m.WebSocketConnectionErrors.AbnormalClose("JOIN",`Error opening websocket connection - websocket closed unexpectedly with code=${n.code}`)))},this.socket.addEventListener("error",s);let o=()=>{var n,l;r=!0,t(),this.setIsConnected(!0),this.id++,(n=this.socket)==null||n.removeEventListener("open",o),(l=this.socket)==null||l.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 m.WebSocketConnectionErrors.WebSocketConnectionLost("JOIN","Failed to send join over WS connection");let l={name:e,disableVidAutoSub:i,data:t,offer:n,server_sub_degrade:r,simulcast:s,onDemandTracks:o},u=yield this.internalCall("join",l);return this.isJoinCompleted=!0,this.pendingTrickle.forEach(({target:p,candidate:h})=>this.trickle(p,h)),this.pendingTrickle.length=0,d.d(this.TAG,`join: response=${JSON.stringify(u,null,1)}`),u})}trickle(e,t){this.isJoinCompleted?this.notify("trickle",{target:e,candidate:t}):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)})})}answer(e){this.notify("answer",{desc:e})}trackUpdate(e){this.notify("track-update",{tracks:Object.fromEntries(e)})}broadcast(e){return c(this,null,function*(){return yield this.call("broadcast",e)})}leave(){this.notify("leave",{})}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",S({},e))})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.call("rtmp-stop",{})})}startHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-start",S({},e))})}stopHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-stop",S({},e))})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.call("hls-timed-metadata",S({},e))})}updatePeer(e){return c(this,null,function*(){yield this.call("peer-update",S({},e))})}getPeer(e){return c(this,null,function*(){yield this.call("get-peer",S({},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)})}setSessionMetadata(e){if(!this.isConnected)throw m.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("set-metadata",S({},e))}listenMetadataChange(e){if(!this.isConnected)throw m.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 m.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",S({},e))}getPollInfo(e){return this.call("poll-info-get",S({},e))}setPollQuestions(e){return this.call("poll-questions-set",S({},e))}startPoll(e){return this.call("poll-start",S({},e))}stopPoll(e){return this.call("poll-stop",S({},e))}getPollQuestions(e){return this.call("poll-questions-get",S({},e))}setPollResponses(e){return this.call("poll-response",S({},e))}getPollResponses(e){return this.call("poll-responses",S({},e))}getPollsList(e){return this.call("poll-list",S({},e))}getPollResult(e){return this.call("poll-result",S({},e))}createWhiteboard(e){return this.validateConnection(),this.call("whiteboard-create",S({},e))}getWhiteboard(e){return this.validateConnection(),this.call("whiteboard-get",S({},e))}fetchPollLeaderboard(e){return this.call("poll-leaderboard",S({},e))}validateConnection(){if(!this.isConnected)throw m.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(m.WebsocketMethodErrors.ServerErrors(Number(e.params.code),"on-error",e.params.message));break;case"on-warning":d.w(this.TAG,e.params);break;default:this.observer.onNotification(e);break}}rejectPendingCalls(e=""){this.callbacks.forEach((t,i)=>{var r,s,o,n;((r=t.metadata)==null?void 0:r.method)!=="ping"&&(d.e(this.TAG,`rejecting pending callback ${(s=t.metadata)==null?void 0:s.method}, id=${i}`),t.reject(m.WebSocketConnectionErrors.WebSocketConnectionLost((o=t.metadata)!=null&&o.method?Rr((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?(d.d(this.TAG,`Pong timeout ${e}, pageHidden=${Vs()}`),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=m.WebsocketMethodErrors.ServerErrors(500,e,`Default ${e} error`);this.validateConnection();let s;for(s=1;s<=3;s++)try{return d.d(this.TAG,`Try number ${s} sending ${e}`,t),yield this.internalCall(e,t)}catch(o){if(r=o,d.e(this.TAG,`Failed sending ${e} try: ${s}`,{method:e,params:t,error:r}),!(parseInt(`${r.code/100}`)===5||r.code===429))break;let l=(2+Math.random()*2)*1e3;yield Ae(l)}throw d.e(`Sending ${e} over WS failed after ${Math.min(s,3)} retries`,{method:e,params:t,error:r}),r})}};var Wa=()=>{if(!w||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 E="[HMSTransport]:",jt=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.callbacks=new Map;this.signalObserver={onOffer:e=>c(this,null,function*(){try{if(!this.subscribeConnection)return;yield this.subscribeConnection.setRemoteDescription(e),d.d(E,`[SUBSCRIBE] Adding ${this.subscribeConnection.candidates.length} ice-candidates`,this.subscribeConnection.candidates);for(let i of this.subscribeConnection.candidates)yield this.subscribeConnection.addIceCandidate(i);this.subscribeConnection.candidates.length=0;let t=yield this.subscribeConnection.createAnswer();yield this.subscribeConnection.setLocalDescription(t),this.signal.answer(t),d.d(E,"[role=SUBSCRIBE] onOffer renegotiation DONE \u2705")}catch(t){d.d(E,"[role=SUBSCRIBE] onOffer renegotiation FAILED \u274C",t),this.state="Failed";let i;t instanceof f?i=t:i=m.GenericErrors.Unknown("PUBLISH",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*(){d.d(E,"socket offline",zi[this.state]);try{this.state!=="Leaving"&&this.joinParameters&&this.retryScheduler.schedule({category:1,error:m.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL",e),task:this.retrySignalDisconnectTask,originalState:this.state})}catch(t){console.error(t)}}),onOnline:()=>{var e;d.d(E,"socket online",zi[this.state]),this.analyticsSignalTransport.flushFailedEvents((e=this.store.getLocalPeer())==null?void 0:e.peerId)},onNetworkOnline:()=>{this.analyticsEventsService.flushFailedClientEvents()}};this.signal=new qt(this.signalObserver);this.analyticsSignalTransport=new tr(this.signal);this.publishDtlsStateTimer=0;this.lastPublishDtlsState="new";this.publishConnectionObserver={onRenegotiationNeeded:()=>c(this,null,function*(){yield this.performPublishRenegotiation()}),onDTLSTransportStateChange:e=>{var r,s,o;if((e==="failed"?d.w.bind(d):d.d.bind(d))(E,`Publisher on dtls transport state change: ${e}`),!e||this.lastPublishDtlsState===e||(this.lastPublishDtlsState=e,this.publishDtlsStateTimer!==0&&(clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0),e!=="connecting"&&e!=="failed"))return;let i=(o=(s=(r=this.initConfig)==null?void 0:r.config)==null?void 0:s.dtlsStateTimeouts)==null?void 0:o[e];!i||i<=0||(this.publishDtlsStateTimer=window.setTimeout(()=>{var l;let n=(l=this.publishConnection)==null?void 0:l.nativeConnection.connectionState;if(n&&e&&n===e){let u=m.WebrtcErrors.ICEFailure("PUBLISH",`DTLS transport state ${e} timeout:${i}ms`,!0);this.eventBus.analytics.publish(y.disconnect(u)),this.observer.onFailure(u)}},i))},onDTLSTransportError:e=>{d.e(E,`onDTLSTransportError ${e.name} ${e.message}`,e),this.eventBus.analytics.publish(y.disconnect(e))},onIceConnectionChange:e=>c(this,null,function*(){(e==="disconnected"?d.w.bind(d):d.d.bind(d))(E,`Publish ice connection state change: ${e}`)}),onConnectionStateChange:e=>c(this,null,function*(){var i,r,s,o,n;(e==="disconnected"?d.w.bind(d):d.d.bind(d))(E,`Publish connection state change: ${e}`),e==="connected"&&((i=this.publishConnection)==null||i.logSelectedIceCandidatePairs()),e==="disconnected"&&setTimeout(()=>{var l,u,p,h,g;((l=this.publishConnection)==null?void 0:l.connectionState)==="disconnected"&&this.handleIceConnectionFailure(0,m.WebrtcErrors.ICEDisconnected("PUBLISH",`local candidate - ${(p=(u=this.publishConnection)==null?void 0:u.selectedCandidatePair)==null?void 0:p.local.candidate}; remote candidate - ${(g=(h=this.publishConnection)==null?void 0:h.selectedCandidatePair)==null?void 0:g.remote.candidate}`))},5e3),e==="failed"&&(yield this.handleIceConnectionFailure(0,m.WebrtcErrors.ICEFailure("PUBLISH",`local candidate - ${(s=(r=this.publishConnection)==null?void 0:r.selectedCandidatePair)==null?void 0:s.local.candidate}; remote candidate - ${(n=(o=this.publishConnection)==null?void 0:o.selectedCandidatePair)==null?void 0:n.remote.candidate}`)))})};this.subscribeConnectionObserver={onApiChannelMessage:e=>{this.observer.onNotification(JSON.parse(e))},onTrackAdd:e=>{d.d(E,"[Subscribe] onTrackAdd",`${e}`),this.observer.onTrackAdd(e)},onTrackRemove:e=>{d.d(E,"[Subscribe] onTrackRemove",`${e}`),this.observer.onTrackRemove(e)},onIceConnectionChange:e=>c(this,null,function*(){if((e==="disconnected"?d.w.bind(d):d.d.bind(d))(E,`Subscribe ice connection state change: ${e}`),e==="connected"){let i=this.callbacks.get(ze);this.callbacks.delete(ze),i&&i.promise.resolve(!0)}}),onConnectionStateChange:e=>c(this,null,function*(){var i,r,s,o;(e==="disconnected"?d.w.bind(d):d.d.bind(d))(E,`Subscribe connection state change: ${e}`),e==="failed"&&(yield this.handleIceConnectionFailure(1,m.WebrtcErrors.ICEFailure("SUBSCRIBE",`local candidate - ${(r=(i=this.subscribeConnection)==null?void 0:i.selectedCandidatePair)==null?void 0:r.local.candidate}; remote candidate - ${(o=(s=this.subscribeConnection)==null?void 0:s.selectedCandidatePair)==null?void 0:o.remote.candidate}`))),e==="disconnected"&&setTimeout(()=>{var n,l,u,p,h;((n=this.subscribeConnection)==null?void 0:n.connectionState)==="disconnected"&&this.handleIceConnectionFailure(1,m.WebrtcErrors.ICEDisconnected("SUBSCRIBE",`local candidate - ${(u=(l=this.subscribeConnection)==null?void 0:l.selectedCandidatePair)==null?void 0:u.local.candidate}; remote candidate - ${(h=(p=this.subscribeConnection)==null?void 0:p.selectedCandidatePair)==null?void 0:h.remote.candidate}`))},5e3),e==="connected"&&this.handleSubscribeConnectionConnected()})};this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){!this.doesRoleNeedWebRTC(e)&&this.doesRoleNeedWebRTC(t)&&(d.d(E,"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(Qe,{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(ze,{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;d.d(E,"retrySignalDisconnectTask",{signalConnected:this.signal.isConnected}),this.signal.isConnected||(yield this.internalConnect(this.joinParameters.authToken,this.joinParameters.endpoint,this.joinParameters.peerId));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});var u,p;this.webrtcInternals=new mi(this.store,this.eventBus,(u=this.publishConnection)==null?void 0:u.nativeConnection,(p=this.subscribeConnection)==null?void 0:p.nativeConnection);let l=(h,g)=>c(this,null,function*(){h!==this.state&&(this.state=h,yield this.observer.onStateChange(this.state,g))});this.retryScheduler=new Xi(l,this.sendErrorAnalyticsEvent.bind(this)),this.eventBus.statsUpdate.subscribe(h=>{var T,I;let g=((I=(T=h.getLocalPeerStats())==null?void 0:T.subscribe)==null?void 0:I.bitrate)||0;this.maxSubscribeBitrate=Math.max(this.maxSubscribeBitrate,g)}),this.eventBus.localAudioEnabled.subscribe(({track:h})=>this.trackUpdate(h)),this.eventBus.localVideoEnabled.subscribe(({track:h})=>this.trackUpdate(h))}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)}preview(e,t,i,r,s=!1){return c(this,null,function*(){let o=yield this.connect(e,t,i,r,s);return this.state="Preview",this.observer.onStateChange(this.state),o})}join(e,t,i,r,s=!1){return c(this,null,function*(){d.d(E,"join: started \u23F0");try{(!this.signal.isConnected||!this.initConfig)&&(yield this.connect(e,r,t,i,s)),this.validateNotDisconnected("connect"),this.initConfig&&(yield this.waitForLocalRoleAvailability(),yield this.createConnectionsAndNegotiateJoin(i,s),yield this.initRtcStatsMonitor(),d.d(E,"\u2705 join: Negotiated over PUBLISH connection"))}catch(o){d.e(E,`join: failed \u274C [token=${e}]`,o),this.state="Failed";let n=o;throw n.isTerminal=n.isTerminal||n.code===500,yield this.observer.onStateChange(this.state,n),n}d.d(E,"\u2705 join: successful"),this.state="Joined",this.observer.onStateChange(this.state)})}connect(e,t,i,r,s=!1){return c(this,null,function*(){this.setTransportStateForConnect(),this.joinParameters=new Qi(e,i,r.name,r.metaData,t,s);try{return yield this.internalConnect(e,t,i)}catch(o){if(o instanceof f&&([M.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,M.WebSocketConnectionErrors.FAILED_TO_CONNECT,M.WebSocketConnectionErrors.ABNORMAL_CLOSE,M.APIErrors.ENDPOINT_UNREACHABLE].includes(o.code)||o.code.toString().startsWith("5")||o.code.toString().startsWith("429"))){let l=()=>c(this,null,function*(){return yield this.internalConnect(e,t,i),!!(this.initConfig&&this.initConfig.endpoint)});yield this.retryScheduler.schedule({category:0,error:o,task:l,originalState:this.state,maxFailedRetries:5,changeState:!1})}else throw o}})}leave(e){return c(this,null,function*(){var t,i,r,s,o;this.retryScheduler.reset(),this.joinParameters=void 0,d.d(E,"leaving in transport");try{let n=this.pluginUsageTracker.getPluginUsage("HMSKrispPlugin");if(n&&this.eventBus.analytics.publish(y.getKrispUsage(n)),this.state="Leaving",(t=this.publishStatsAnalytics)==null||t.stop(),(i=this.subscribeStatsAnalytics)==null||i.stop(),(r=this.webrtcInternals)==null||r.cleanup(),yield(s=this.publishConnection)==null?void 0:s.close(),yield(o=this.subscribeConnection)==null?void 0:o.close(),e)try{this.signal.leave(),d.d(E,"signal leave done")}catch(l){d.w(E,"failed to send leave on websocket to server",l)}this.analyticsEventsService.flushFailedClientEvents(),this.analyticsEventsService.reset(),yield this.signal.close()}catch(n){this.eventBus.analytics.publish(y.disconnect(n)),d.e(E,"leave: FAILED \u274C",n)}finally{this.state="Disconnected",this.observer.onStateChange(this.state)}})}publish(e){return c(this,null,function*(){for(let t of e)try{yield this.publishTrack(t)}catch(i){this.eventBus.analytics.publish(y.publish({devices:this.deviceManager.getDevices(),error:i}))}})}unpublish(e){return c(this,null,function*(){for(let t of e)yield this.unpublishTrack(t)})}trackUpdate(e){let i=Array.from(this.trackStates.values()).find(r=>e.type===r.type&&e.source===r.source);if(i){let r=new Ot(v(S({},i),{mute:!e.enabled}));this.trackStates.set(i.track_id,r),d.d(E,"Track Update",this.trackStates,e),this.signal.trackUpdate(new Map([[i.track_id,r]]))}}publishTrack(e){return c(this,null,function*(){e.publishedTrackId=e.getTrackIDBeingSent(),d.d(E,`\u23F3 publishTrack: trackId=${e.trackId}, toPublishTrackId=${e.publishedTrackId}`,`${e}`),this.trackStates.set(e.publishedTrackId,new Ot(e));let t=new Promise((s,o)=>{this.callbacks.set(Qe,{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),d.time(`publish-${e.trackId}-${e.type}`),yield t,d.timeEnd(`publish-${e.trackId}-${e.type}`),this.store.addTrack(e),yield i.setMaxBitrateAndFramerate(e).then(()=>{d.d(E,`Setting maxBitrate=${e.settings.maxBitrate} kpbs${e instanceof B?` and maxFramerate=${e.settings.maxFramerate}`:""} for ${e.source} ${e.type} ${e.trackId}`)}).catch(s=>d.w(E,"Failed setting maxBitrate and maxFramerate",s)),e.isPublished=!0,d.d(E,`\u2705 publishTrack: trackId=${e.trackId}`,`${e}`,this.callbacks)})}unpublishTrack(e){return c(this,null,function*(){if(d.d(E,`\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(Qe,{promise:{resolve:r,reject:s},action:"UNPUBLISH",extra:{}})});e.stream.removeSender(e),yield t,yield e.cleanup(),this.store.removeTrack(e),d.d(E,`\u2705 unpublishTrack: trackId=${e.trackId}`,this.callbacks)})}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(){this.initConfig&&(this.publishConnection||(this.publishConnection=new Gt(this.signal,this.initConfig.rtcConfiguration,this.publishConnectionObserver)),this.subscribeConnection||(this.subscribeConnection=new Wt(this.signal,this.initConfig.rtcConfiguration,this.isFlagEnabled.bind(this),this.subscribeConnectionObserver)))}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){d.e(E,"Join negotiation failed \u274C",o);let n=o instanceof f?o:m.WebsocketMethodErrors.ServerErrors(500,"JOIN",`Websocket join error - ${o.message}`),l=parseInt(`${n.code/100}`)===5||[M.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,429].includes(n.code);if(n.code===410&&(n.isTerminal=!0),l){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",maxFailedRetries:3,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(d.d(E,"\u23F3 join: Negotiating over PUBLISH connection"),!this.publishConnection)return d.e(E,"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"),l=this.isFlagEnabled("onDemandTracks"),u=yield this.signal.join(e,t,!i,o,n,l,s);yield this.publishConnection.setRemoteDescription(u);for(let p of this.publishConnection.candidates)yield this.publishConnection.addIceCandidate(p);return this.publishConnection.initAfterJoin(),!!u})}negotiateJoinNonWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){d.d(E,"\u23F3 join: Negotiating Non-WebRTC");let s=this.isFlagEnabled("subscribeDegradation"),o=this.isFlagEnabled("simulcast"),n=this.isFlagEnabled("onDemandTracks");return!!(yield this.signal.join(e,t,!i,s,o,n))})}negotiateOnFirstPublish(){return c(this,null,function*(){if(d.d(E,"\u23F3 Negotiating offer over PUBLISH connection"),!this.publishConnection)return d.e(E,"Publish peer connection not found, cannot negotiate"),!1;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})}performPublishRenegotiation(e){return c(this,null,function*(){d.d(E,"\u23F3 [role=PUBLISH] onRenegotiationNeeded START",this.trackStates);let t=this.callbacks.get(Qe);if(t){if(!this.publishConnection){d.e(E,"Publish peer connection not found, cannot renegotiate");return}try{let i=yield this.publishConnection.createOffer(this.trackStates,e);yield this.publishConnection.setLocalDescription(i),d.time("renegotiation-offer-exchange");let r=yield this.signal.offer(i,this.trackStates);this.callbacks.delete(Qe),d.timeEnd("renegotiation-offer-exchange"),yield this.publishConnection.setRemoteDescription(r),t.promise.resolve(!0),d.d(E,"[role=PUBLISH] onRenegotiationNeeded DONE \u2705")}catch(i){let r;i instanceof f?r=i:r=m.GenericErrors.Unknown("PUBLISH",i.message),t.promise.reject(r),d.d(E,"[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",maxFailedRetries:1}))})}internalConnect(e,t,i){return c(this,null,function*(){var s;d.d(E,"connect: started \u23F0");let r=new Date;try{this.analyticsTimer.start("init_response_time"),this.initConfig=yield Kt.fetchInitConfig({token:e,peerId:i,userAgent:this.store.getUserAgent(),initEndpoint:t});let o=this.store.getRoom();return o&&(o.effectsKey=(s=this.initConfig.config.vb)==null?void 0:s.effectsKey,o.isEffectsEnabled=this.isFlagEnabled("effectsSDKEnabled"),o.isHipaaEnabled=this.isFlagEnabled("hipaa"),o.isNoiseCancellationEnabled=this.isFlagEnabled("noiseCancellation")),this.analyticsTimer.end("init_response_time"),fe.setWebsocketEndpoint(this.initConfig.endpoint),this.validateNotDisconnected("post init"),yield this.openSignal(e,i),this.observer.onConnected(),this.store.setSimulcastEnabled(this.isFlagEnabled("simulcast")),d.d(E,"Adding Analytics Transport: JsonRpcSignal"),this.analyticsEventsService.setTransport(this.analyticsSignalTransport),this.analyticsEventsService.flush(),this.initConfig}catch(o){throw this.state!=="Reconnecting"&&this.eventBus.analytics.publish(y.connect(o,this.getAdditionalAnalyticsProperties(),r,new Date,t)),d.e(E,"\u274C internal connect: failed",o),o}})}validateNotDisconnected(e){if(this.state==="Disconnected")throw d.w(E,"aborting join as transport state is disconnected"),m.GenericErrors.ValidationFailed(`leave called before join could complete - stage=${e}`)}openSignal(e,t){return c(this,null,function*(){if(!this.initConfig)throw m.APIErrors.InitConfigNotAvailable("INIT","Init Config not found");d.d(E,"\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",pa),i.searchParams.set("protocol_spec",ha),this.endpoint=i.toString(),this.analyticsTimer.start("ws_connect_time"),yield this.signal.open(this.endpoint),this.analyticsTimer.end("ws_connect_time"),this.analyticsTimer.start("on_policy_change_time"),this.analyticsTimer.start("room_state_time"),d.d(E,"\u2705 internal connect: connected to ws endpoint")})}initRtcStatsMonitor(){return c(this,null,function*(){var e,t,i;(i=this.webrtcInternals)==null||i.setPeerConnections({publish:(e=this.publishConnection)==null?void 0:e.nativeConnection,subscribe:(t=this.subscribeConnection)==null?void 0:t.nativeConnection}),this.initStatsAnalytics()})}initStatsAnalytics(){var e,t;this.isFlagEnabled("publishStats")&&(this.publishStatsAnalytics=new Bt(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 Vt(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}handleSubscribeConnectionConnected(){var t;(t=this.subscribeConnection)==null||t.logSelectedIceCandidatePairs();let e=this.callbacks.get(ze);this.callbacks.delete(ze),e&&e.promise.resolve(!0)}setTransportStateForConnect(){if(this.state==="Failed"&&(this.state="Disconnected"),this.state!=="Disconnected"&&this.state!=="Reconnecting")throw m.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,l,u,p,h,g,T;let e=Wa(),t=typeof document!="undefined"&&document.hidden,i=this.store.getRemoteVideoTracks().filter(I=>I.degraded).length,r=(u=(l=(n=(o=this.getWebrtcInternals())==null?void 0:o.getCurrentStats())==null?void 0:n.getLocalPeerStats())==null?void 0:l.publish)==null?void 0:u.bitrate,s=(T=(g=(h=(p=this.getWebrtcInternals())==null?void 0:p.getCurrentStats())==null?void 0:h.getLocalPeerStats())==null?void 0:g.subscribe)==null?void 0:T.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}}};var qa=(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 m.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))?m.APIErrors.EndpointUnreachable("GET_TOKEN",r.message):r});function nr(a){if(!a||a.length===0)throw m.APIErrors.InvalidTokenFormat("INIT","Token cannot be an empty string or undefined or null");let e=a.split(".");if(e.length!==3)throw m.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 m.APIErrors.InvalidTokenFormat("INIT",`couldn't parse to json - ${i.message}`)}}var ja={published:!1,isInitialised:!1,isReconnecting:!1,isPreviewInProgress:!1,isPreviewCalled:!1,isJoinInProgress:!1,deviceManagersInitialised:!1},cr=class{constructor(){this.TAG="[HMSSdk]:";this.transportState="Disconnected";this.analyticsTimer=new li;this.sdkState=S({},ja);this.playlistSettings={video:{bitrate:$r},audio:{bitrate:Wr}};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,l;yield this.internalLeave(!0,o),!this.sdkState.isPreviewInProgress&&!this.sdkState.isJoinInProgress&&((l=(n=this.errorListener)==null?void 0:n.onError)==null||l.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,d.d(this.TAG,"Transport State Change",this.transportState)})};this.handlePeerLeaveRequest=e=>{var r;let t=e.requested_by?this.store.getPeerById(e.requested_by):void 0,i={roomEnded:e.room_end,reason:e.reason,requestedBy:t};(r=this.listener)==null||r.onRemovedFromRoom(i),this.internalLeave(!1)};this.handleDeviceChange=e=>{var i,r;if(e.isUserSelection)return;d.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,l;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),[M.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,M.TracksErrors.DEVICE_IN_USE,M.TracksErrors.DEVICE_NOT_AVAILABLE].includes(e.error.code)&&u&&(u.setEnabled(!1),(l=this.listener)==null||l.onTrackUpdate(2,u,this.localPeer))}})()};this.handleAudioPluginError=e=>{var t;d.e(this.TAG,"Audio Plugin Error event",e),(t=this.errorListener)==null||t.onError(e)};this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){var r;yield this.transport.handleLocalRoleUpdate({oldRole:e,newRole:t}),yield(r=this.roleChangeManager)==null?void 0:r.handleLocalPeerRoleUpdate({oldRole:e,newRole:t})});this.sendAudioPresenceFailed=()=>{let e=m.TracksErrors.NoAudioDetected("PREVIEW");d.w(this.TAG,"Audio Presence Failure",this.transportState,e)};this.sendJoinAnalyticsEvent=(e=!1,t)=>{this.eventBus.analytics.publish(y.join(v(S({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(v(S({error:e},this.analyticsTimer.getTimes()),{time:this.analyticsTimer.getTimeTaken("preview_time")})))};this.sendAnalyticsEvent=e=>{this.analyticsEventsService.queue(e).flush()}}initNotificationManager(){this.notificationManager||(this.notificationManager=new ji(this.store,this.eventBus,this.transport,this.listener,this.audioListener))}initStoreAndManagers(){var e;if(this.sdkState.isInitialised){(e=this.notificationManager)==null||e.setListener(this.listener),this.audioSinkManager.setListener(this.listener),this.interactivityCenter.setListener(this.listener);return}this.sdkState.isInitialised=!0,this.store=new wt,this.eventBus=new et,this.pluginUsageTracker=new Li(this.eventBus),this.wakeLockManager=new Hi,this.networkTestManager=new Ri(this.eventBus,this.listener),this.playlistManager=new Pt(this,this.eventBus),this.deviceManager=new Nt(this.store,this.eventBus),this.audioSinkManager=new _t(this.store,this.deviceManager,this.eventBus),this.audioOutput=new Di(this.deviceManager,this.audioSinkManager),this.audioSinkManager.setListener(this.listener),this.eventBus.autoplayError.subscribe(this.handleAutoplayError),this.localTrackManager=new ge(this.store,this.observer,this.deviceManager,this.eventBus,this.analyticsTimer),this.analyticsEventsService=new Ci(this.store),this.transport=new jt(this.observer,this.deviceManager,this.store,this.eventBus,this.analyticsEventsService,this.analyticsTimer,this.pluginUsageTracker),this.sessionStore=new Ji(this.transport),this.interactivityCenter=new xt(this.transport,this.store,this.listener),this.eventBus.analytics.subscribe(this.sendAnalyticsEvent),this.eventBus.deviceChange.subscribe(this.handleDeviceChange),this.eventBus.audioPluginFailed.subscribe(this.handleAudioPluginError)}validateJoined(e){if(!this.localPeer)throw m.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()}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}getTemplateAppData(){return this.store.getTemplateAppData()}getInteractivityCenter(){return this.interactivityCenter}getPeerListIterator(e){return new Si(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(Lr(),Cr(),this.sdkState.isPreviewInProgress)return Promise.reject(m.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),e.alwaysRequestPermissions&&this.localTrackManager.requestPermissions().then(()=>c(this,null,function*(){yield this.initDeviceManagers()}));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 l=()=>c(this,null,function*(){var g;if(this.localPeer){let T=e.asRole&&this.store.getPolicyForRole(e.asRole);this.localPeer.asRole=T||this.localPeer.role}let p=yield this.localTrackManager.getTracksToPublish(e.settings);p.forEach(T=>this.setLocalPeerTrack(T)),(g=this.localPeer)!=null&&g.audioTrack&&this.initPreviewTrackAudioLevelMonitor(),yield this.initDeviceManagers(),this.sdkState.isPreviewInProgress=!1,this.analyticsTimer.end("preview_time");let h=this.store.getRoom();h&&t.onPreview(h,p),this.sendPreviewAnalyticsEvent(),o()}),u=p=>{var h;this.analyticsTimer.end("preview_time"),p&&((h=this.errorListener)==null||h.onError(p)),this.sendPreviewAnalyticsEvent(p),this.sdkState.isPreviewInProgress=!1,n(p)};this.eventBus.policyChange.subscribeOnce(l),this.eventBus.leave.subscribeOnce(u),this.transport.preview(e.authToken,e.initEndpoint,this.localPeer.peerId,{name:e.userName,metaData:e.metaData||""},e.autoVideoSubscribe).then(p=>{var h;i=!0,clearTimeout(s),p&&e.captureNetworkQualityInPreview&&this.networkTestManager.start((h=p.config)==null?void 0:h.networkHealth).then(()=>{r=!0})}).catch(u)})})}midCallPreview(e,t){return c(this,null,function*(){var s,o;if(!this.localPeer||this.transportState!=="Joined")throw m.GenericErrors.NotConnected("VALIDATION","Not connected - midCallPreview");let i=e&&this.store.getPolicyForRole(e);if(!i)throw m.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())&&d.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 l,u,p,h,g,T;if(Lr(),Cr(),this.sdkState.isPreviewInProgress)throw m.GenericErrors.NotReady("JOIN","Preview is in progress, can't join");this.analyticsTimer.start("join_time"),this.sdkState.isJoinInProgress=!0;let{roomId:i,userId:r,role:s}=nr(e.authToken),o=((u=(l=this.localPeer)==null?void 0:l.asRole)==null?void 0:u.name)||((h=(p=this.localPeer)==null?void 0:p.role)==null?void 0:h.name);(g=this.networkTestManager)==null||g.stop(),this.listener=t,this.commonSetup(e,i,t),this.removeDevicesFromConfig(e),this.store.setConfig(e),this.store.createAndSetUserAgent(this.frameworkInfo),Ee.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 Dt(this.store,this.transport,this.deviceManager,this.getAndPublishTracks.bind(this),this.removeTrack.bind(this),this.listener),this.eventBus.localRoleUpdate.subscribe(this.handleLocalRoleUpdate),d.d(this.TAG,`\u23F3 Joining room ${i}`),d.time(`join-room-${i}`);try{yield this.transport.join(e.authToken,this.localPeer.peerId,{name:e.userName,metaData:e.metaData},e.initEndpoint,e.autoVideoSubscribe),d.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)}catch(I){throw this.analyticsTimer.end("join_time"),this.sdkState.isJoinInProgress=!1,(T=this.listener)==null||T.onError(I),this.sendJoinAnalyticsEvent(this.sdkState.isPreviewCalled,I),d.e(this.TAG,"Unable to join room",I),I}d.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.analyticsTimer.cleanup(),Q.cleanup(),this.playlistManager.cleanup(),(e=this.wakeLockManager)==null||e.cleanup(),ge.cleanup(),this.notificationManager=void 0,d.cleanup(),this.sdkState=S({},ja),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;let i=(r=this.store)==null?void 0:r.getRoom();if(i){for(;(this.sdkState.isPreviewInProgress||this.sdkState.isJoinInProgress)&&!(t!=null&&t.isTerminal);)yield Ae(100);let n=i.id;(s=this.networkTestManager)==null||s.stop(),this.eventBus.leave.publish(t),d.d(this.TAG,`\u23F3 Leaving room ${n}`),yield(o=this.transport)==null?void 0:o.leave(e),this.cleanup(),d.d(this.TAG,`\u2705 Left room ${n}`)}})}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 qa(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 m.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 m.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 m.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{peers:l}=yield this.transport.signal.findPeers({peers:[t],limit:1});if(l.length===0)throw m.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);s=Re(l[0],this.store)}else throw m.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);return yield this.sendMessageInternal({message:e,recipientPeer:s,type:i})})}sendMessageInternal(s){return c(this,arguments,function*({recipientRoles:e,recipientPeer:t,type:i="chat",message:r}){if(r.replace(/\u200b/g," ").trim()==="")throw d.w(this.TAG,"sendMessage","Ignoring empty message send"),m.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),d.d(this.TAG,"Sending Message: ",o),yield this.transport.signal.broadcast(o)})}startScreenShare(e,t){return c(this,null,function*(){var n,l,u;let i=this.store.getPublishParams();if(!i)return;let{allowed:r}=i;if(!(r&&r.includes("screen"))){d.e(this.TAG,`Role ${(n=this.localPeer)==null?void 0:n.role} cannot share screen`);return}if((u=(l=this.localPeer)==null?void 0:l.auxiliaryTracks)!=null&&u.find(p=>p.source==="screen"))throw Error("Cannot share multiple screens");let o=yield this.getScreenshareTracks(e,t);if(!this.localPeer){d.d(this.TAG,"Screenshared when not connected"),o.forEach(p=>{p.cleanup()});return}yield this.transport.publish(o),o.forEach(p=>{var h,g,T;p.peerId=(h=this.localPeer)==null?void 0:h.peerId,(g=this.localPeer)==null||g.auxiliaryTracks.push(p),(T=this.listener)==null||T.onTrackUpdate(0,p,this.localPeer)})})}stopEndedScreenshare(e){return c(this,null,function*(){d.d(this.TAG,"\u2705 Screenshare ended natively"),yield this.stopScreenShare(),e()})}stopScreenShare(){return c(this,null,function*(){var t;d.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,h,g;if(!e){d.w(this.TAG,"Please pass a valid MediaStreamTrack");return}if(!this.localPeer)throw m.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot addTrack");if(this.localPeer.auxiliaryTracks.find(T=>T.trackId===e.id))return;let r=e.kind,s=new MediaStream([e]),o=new Oe(s),n=r==="audio"?ne:B,l=new n(o,e,t,this.eventBus);this.setPlaylistSettings({track:e,hmsTrack:l,source:t}),yield(u=this.transport)==null?void 0:u.publish([l]),l.peerId=(p=this.localPeer)==null?void 0:p.peerId,(h=this.localPeer)==null||h.auxiliaryTracks.push(l),(g=this.listener)==null||g.onTrackUpdate(0,l,this.localPeer)})}removeTrack(e,t=!1){return c(this,null,function*(){var r;if(!this.localPeer)throw m.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 d.w(this.TAG,`No track found for ${e}`)})}setAnalyticsLevel(e){this.analyticsEventsService.level=e}setLogLevel(e){d.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)}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 m.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 m.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 m.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 m.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 m.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 m.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()})}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"){d.w(this.TAG,"Muting non-regular video tracks is currently not supported");return}if(e.enabled===t){d.w(this.TAG,`Aborting change track state, track already has enabled - ${t}`,e);return}if(!this.store.getTrackById(e.trackId))throw m.GenericErrors.ValidationFailed("No track found for change track state",e);let i=this.store.getPeerByTrackId(e.trackId);if(!i)throw m.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 m.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(Te)})}lowerLocalPeerHand(){return c(this,null,function*(){var e;this.validateJoined("lowerLocalPeerHand"),yield(e=this.transport)==null?void 0:e.signal.leaveGroup(Te)})}raiseRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.addToGroup(e,Te)})}lowerRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.removeFromGroup(e,Te)})}setFrameworkInfo(e){this.frameworkInfo=S(S({},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,!De].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 l;d.e(this.TAG,"Error in publish",n),(l=this.listener)==null||l.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;for(let i of e)yield this.transport.publish([i]),this.setLocalPeerTrack(i),(t=this.listener)==null||t.onTrackUpdate(0,i,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=Q.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){d.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.listener=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)||Wr;else{n.maxBitrate=((o=this.playlistSettings.video)==null?void 0:o.bitrate)||$r;let{width:l,height:u}=e.getSettings();n.width=l,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 yt({name:e.userName||"",customerUserId:i,metadata:e.metaData||"",role:s,asRole:o||s});this.store.addPeer(n)}commonSetup(e,t,i){this.stringifyMetadata(e),e.initEndpoint||(e.initEndpoint="https://prod-init.100ms.live"),this.errorListener=i,this.deviceChangeListener=i,this.initStoreAndManagers(),this.store.setErrorListener(this.errorListener),this.store.getRoom()||this.store.setRoom(new Lt(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,r]=yield this.localTrackManager.getLocalScreen(t),s=()=>{this.stopEndedScreenshare(e)},o=[];if(t!=null&&t.audioOnly){if(i.nativeTrack.stop(),!r)throw m.TracksErrors.NothingToReturn("TRACK","Select share audio when sharing screen","No audio found");o.push(r),r.nativeTrack.addEventListener("ended",s)}else o.push(i),i.nativeTrack.addEventListener("ended",s),r&&o.push(r);return o})}stopPlaylist(e){e.source==="audioplaylist"?this.playlistManager.stop("audio"):e.source==="videoplaylist"&&this.playlistManager.stop("video")}};var Be=class a{constructor(e,t,i){this.getStats=()=>(this.stats||(this.stats=new st(this.store,this.sdk)),this.stats);e?this.store=e:this.store=a.createNewHMSStore(Ii("HMSStore"),ot),i?this.notifications=i:this.notifications=new yi(this.store),t?this.actions=t:(this.sdk=new cr,this.actions=new Ai(this.store,this.sdk,this.notifications)),this.actions.setFrameworkInfo({type:"js",sdkVersion:Dr().version}),this.initialTriggerOnSubscribe=!1,w&&(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,za.default)(()=>t()),r=i.setState;i.setState=n=>{let l=typeof n=="function"?(0,Ja.produce)(n):n;r(l)};let s=i.getState;i.getState=n=>n?n(s()):s(),a.compareWithShallowCheckInSubscribe(i);let o=a.setUpDevtools(i,e);return v(S({},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||Qa.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 l=n||`${r.prefix}action`;r.send(l,e.getState())}}static devtoolsOptions(e){return{name:e,actionsBlacklist:["audioLevel","playlistProgress","connectionQuality"]}}static devtoolsSubscribe(e,t,i){return r=>{var s,o,n,l;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;(((l=r.payload.nextLiftedState)==null?void 0:l.computedStates)||[]).forEach(({state:h},g)=>{let T=u[g]||`${e.prefix}setState`;g===0?e.init(h):(i(h),e.send(T,t.getState()))})}}}};var Xa=(a,e,t)=>{let i;t.getState(J)==="Connected"&&(i=Ya(a,e,t)),t.subscribe(r=>{["Connected","Reconnecting"].includes(r)?i||(i=Ya(a,e,t)):["Disconnected","Failed"].includes(r)&&i&&(Hc(e,r),i(),i=void 0)},J)},Ya=(a,e,t)=>{var s,o;let i=Ic(t,e);(s=a.getWebrtcInternals())==null||s.start();let r=(o=a.getWebrtcInternals())==null?void 0:o.onStatsChange(n=>Rc(e,n,t,a));return()=>{i(),r&&r()}},Ic=(a,e)=>{let t,i,r;return a.getState(ce)?e.namedSetState(s=>{s.localPeer.id=a.getState(ce)},"localpeer-id"):t=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.id=s},"localpeer-id")},ce),a.getState($)?e.namedSetState(s=>{s.localPeer.videoTrack=a.getState($)},"localpeer-videotrack-id"):i=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.videoTrack=s},"localpeer-videotrack-id")},$),a.getState(X)?e.namedSetState(s=>{s.localPeer.audioTrack=a.getState(X)},"localpeer-audiotrack-id"):r=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.audioTrack=s},"localpeer-audiotrack-id")},X),()=>{t==null||t(),i==null||i(),r==null||r()}},Rc=(a,e,t,i)=>{let r=t.getState(D);a.namedSetState(s=>{let o=t.getState(ce),n={},l=Object.keys(r).filter(p=>r[p].peerId!==o);for(let p of l){let h=e.getRemoteTrackStats(p);h&&(n[p]=h)}as(s.remoteTrackStats,n);let u={[o]:e.getLocalPeerStats()};as(s.peerStats,u),wa(s.localTrackStats,e.getLocalTrackStats(),i.store.getLocalPeerTracks())},"webrtc-stats")},Hc=(a,e="resetState")=>{a.namedSetState(t=>{Object.assign(t,nt())},e)};var st=class{constructor(e,t){this.hmsStore=e;this.sdk=t;this.store=Be.createNewHMSStore(Ii("HMSStatsStore"),nt),this.getState=this.store.getState,this.subscribe=this.store.subscribe,this.getPublishPeerConnection=()=>new Promise(i=>{var r,s;this.hmsStore.getState(J)==="Connected"?i((s=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:s.getPublishPeerConnection()):this.hmsStore.subscribe(o=>{var n,l;o==="Connected"&&i((l=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:l.getPublishPeerConnection())},J)}),this.getSubscribePeerConnection=()=>new Promise(i=>{var r,s;this.hmsStore.getState(J)==="Connected"?i((s=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:s.getSubscribePeerConnection()):this.hmsStore.subscribe(o=>{var n,l;o==="Connected"&&i((l=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:l.getSubscribePeerConnection())},J)}),this.sdk&&Xa(this.sdk,this.store,this.hmsStore)}};var F=require("reselect");var Cc=a=>a.localPeer.id,Lc=a=>a.localPeer.audioTrack,Dc=a=>a.localPeer.videoTrack,wc=(a,e)=>e,Za=(a,e)=>e,_c=a=>a.remoteTrackStats,eo=a=>a.peerStats,hs=a=>a.localTrackStats,Me=(0,F.createSelector)([eo,Cc],(a,e)=>a[e]),Nc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.packetsLost}),Oc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.jitter}),xc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.bitrate}),Uc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.bitrate}),Bc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.availableOutgoingBitrate}),Vc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.availableIncomingBitrate}),Fc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.bytesSent}),Gc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.bytesReceived}),$c=(0,F.createSelector)([eo,wc],(a,e)=>e?a[e]:void 0),Wc=(0,F.createSelector)([_c,Za],(a,e)=>e?a[e]:void 0),ms=(0,F.createSelector)([hs,Za],(a,e)=>e?a[e]:void 0),Kc=b($c),qc=b(Wc),jc=(0,F.createSelector)([hs,Lc],(a,e)=>{var t;return e?(t=a[e])==null?void 0:t[0]:void 0}),Jc=b((0,F.createSelector)(ms,a=>a==null?void 0:a[0])),Qc=(0,F.createSelector)([hs,Dc],(a,e)=>{var t;return e?(t=a[e])==null?void 0:t[0]:void 0}),zc=b((0,F.createSelector)(ms,a=>a)),Yc=a=>b((0,F.createSelector)(ms,e=>{let t=Object.keys(Ie).find(i=>Ie[i]===a);return a&&(e==null?void 0:e.find(i=>i.rid===t))||(e==null?void 0:e[0])})),to={localPeerStats:Me,packetsLost:Nc,jitter:Oc,publishBitrate:xc,subscribeBitrate:Uc,availablePublishBitrate:Bc,availableSubscribeBitrate:Vc,totalBytesSent:Fc,totalBytesReceived:Gc,peerStatsByID:Kc,trackStatsByID:qc,localAudioTrackStatsByID:Jc,localVideoTrackStatsByID:zc,localVideoTrackStatsByLayer:Yc,localAudioTrackStats:jc,localVideoTrackStats:Qc};
|
|
82
|
+
}`}};var kt=class extends Ye{constructor(t){super(v(S({},t),{isLocal:!1}));this.isLocal=!1;this.auxiliaryTracks=[];this.fromRoomState=!1;this.fromRoomState=!!t.fromRoomState}};var Re=(a,e)=>new kt({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});var Si=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(v(S({},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=Re(i,this.store);t.push(r)}),t}updateState(e){this.isEnd=e.eof,this.total=e.total,e.iterator&&(this.iterator=e.iterator)}};var Ze=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(),d.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=>{d.d(this.TAG,"AudioContext close error",e.message)})}};var va=require("eventemitter2"),He=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 gi=class extends He{constructor(){super(...arguments);this.audioElement=null;this.TAG="[PlaylistAudioManager]";this.seeked=!1}play(t){return c(this,null,function*(){return this.audioElement=this.getAudioElement(),new Promise((i,r)=>{this.audioElement=this.getAudioElement(),this.audioElement.src=t,this.seeked=!1,this.audioElement.onerror=()=>{let s=`Error loading ${t}`;d.e(this.TAG,s),this.stop(),r(s)},this.audioElement.oncanplaythrough=()=>c(this,null,function*(){try{if(!this.audioElement)return;if(this.audioContextManager.resumeContext(),this.track)this.seeked?this.seeked=!1:(yield this.audioElement.play(),i([this.track]));else{yield this.audioElement.play();let s=this.audioContextManager.getAudioTrack();this.track=s,i([s])}}catch(s){d.e(this.TAG,"Error playing audio",t,s.message),r(s)}}),this.audioElement.onseeked=()=>{this.seeked=!0}})})}getTracks(){return this.track?[this.track.id]:[]}getElement(){return this.audioElement||(this.audioElement=this.getAudioElement()),this.audioElement}stop(){var t,i,r;(t=this.audioElement)==null||t.pause(),(i=this.audioElement)==null||i.removeAttribute("src"),this.audioElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.track=void 0}getAudioElement(){if(this.audioElement)return this.audioElement;let t=document.createElement("audio");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new Ze(t),t}};var Ti=class extends He{constructor(){super(...arguments);this.TAG="[PlaylistVideoManager]";this.videoElement=null;this.canvasContext=null;this.tracks=[];this.DEFAUL_FPS=24;this.seeked=!1;this.drawImage=()=>{var t,i,r;this.videoElement&&!this.videoElement.paused&&!this.videoElement.ended&&((r=this.canvasContext)==null||r.drawImage(this.videoElement,0,0,(t=this.canvas)==null?void 0:t.width,(i=this.canvas)==null?void 0:i.height),this.timer=setTimeout(()=>{this.drawImage()},1e3/this.DEFAUL_FPS))}}play(t){return this.videoElement=this.getVideoElement(),this.createCanvas(),new Promise((i,r)=>{this.videoElement=this.getVideoElement(),this.videoElement.src=t,this.seeked=!1,this.videoElement.onerror=()=>{let s=`Error loading ${t}`;d.e(this.TAG,s),this.stop(),r(s)},this.videoElement.oncanplaythrough=()=>c(this,null,function*(){var s,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 l=this.canvas.captureStream();if(!l){d.e(this.TAG,"Browser does not support captureStream");return}this.videoElement.onplay=this.drawImage,yield this.audioContextManager.resumeContext(),yield this.videoElement.play();let u=this.audioContextManager.getAudioTrack();l.addTrack(u),l.getTracks().forEach(p=>{this.tracks.push(p)}),i(this.tracks)}else this.seeked?(this.seeked=!1,(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(l){d.e(this.TAG,"Error playing video",t,l.message),r(l)}}),this.videoElement.onseeked=()=>{this.seeked=!0}})}getTracks(){return this.tracks.map(t=>t.id)}getElement(){return this.videoElement||(this.videoElement=this.getVideoElement()),this.videoElement}stop(){var t,i,r;(t=this.videoElement)==null||t.pause(),(i=this.videoElement)==null||i.removeAttribute("src"),this.videoElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.clearCanvasAndTracks()}clearCanvasAndTracks(){var t;this.tracks=[],(t=this.canvasContext)==null||t.clearRect(0,0,this.canvas.width,this.canvas.height),clearTimeout(this.timer)}getVideoElement(){if(this.videoElement)return this.videoElement;let t=document.createElement("video");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new Ze(t),t}createCanvas(){this.canvas||(this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"))}};var fi={audio:{list:[],currentIndex:-1,isAutoplayOn:!0},video:{list:[],currentIndex:-1,isAutoplayOn:!0}},Pt=class extends He{constructor(t,i){super();this.sdk=t;this.eventBus=i;this.state={audio:S({},fi.audio),video:S({},fi.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),d.d(this.TAG,"Playlist track added",ti(t))});this.removeTrack=t=>c(this,null,function*(){yield this.sdk.removeTrack(t,!0),d.d(this.TAG,"Playlist track removed",t)});this.audioManager=new gi,this.videoManager=new Ti,this.addListeners()}getList(t="audio"){return this.state[t].list}setList(t){if(!t||t.length===0){d.w(this.TAG,"Please pass in a list of HMSPlaylistItem's");return}t.forEach(i=>{this.state[i.type].list.find(r=>r.id===i.id)||this.state[i.type].list.push(i)})}clearList(t){return c(this,null,function*(){this.isPlaying(t)&&(yield this.stop(t)),this.state[t].list=[]})}removeItem(t,i){return c(this,null,function*(){let{list:r,currentIndex:s}=this.state[i],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 m.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 m.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 l=this.state[r].list.findIndex(p=>p.id===i);if(!i||l===-1){d.w(this.TAG,"Pass a valid id");return}let u=this.state[r].list[l].url;t?yield this.play(u,r):yield this.pause(u,r),this.state[r].currentIndex=l,this.setDuration(r)})}playNext(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r>=i.length-1)throw m.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 m.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:S({},fi.audio),video:S({},fi.video)},this.eventBus.localAudioEnabled.unsubscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.unsubscribe(this.handlePausePlaylist),this.audioManager.stop(),this.videoManager.stop()}onProgress(t){this.videoManager.on("progress",()=>{try{t({type:"video",progress:this.getCurrentProgress("video")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}}),this.audioManager.on("progress",()=>{try{t({type:"audio",progress:this.getCurrentProgress("audio")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}})}onNewTrackStart(t){this.on("newTrackStart",t)}onPlaylistEnded(t){this.on("playlistEnded",t)}onCurrentTrackEnded(t){this.on("currentTrackEnded",t)}getElement(t="audio"){return t==="audio"?this.audioManager.getElement():this.videoManager.getElement()}removeTracks(){return c(this,arguments,function*(t="audio"){let r=(t==="audio"?this.audioManager:this.videoManager).getTracks();for(let s of r)yield this.removeTrack(s)})}play(r){return c(this,arguments,function*(t,i="audio"){let s=i==="audio"?this.audioManager:this.videoManager,o=s.getElement();if(this.isItemCurrentlyPlaying(t,i)){d.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 l of n)yield this.addTrack(l,i==="audio"?"audioplaylist":"videoplaylist")}})}isItemCurrentlyPlaying(t,i){let r=this.getElement(i);return!!(r&&!r.paused&&r.src.includes(t))}setDuration(t="audio"){let i=this.getElement(t),{list:r,currentIndex:s}=this.state[t];r[s]&&(r[s].duration=(i==null?void 0:i.duration)||0),this.emit("newTrackStart",r[s])}pause(r){return c(this,arguments,function*(t,i="audio"){let s=this.getElement(i);s&&!s.paused&&s.src.includes(t)?(s.pause(),d.d(this.TAG,"paused url",t)):d.w(this.TAG,"The passed in url is not currently playing")})}addListeners(){this.audioManager.on("ended",()=>this.handleEnded("audio")),this.videoManager.on("ended",()=>this.handleEnded("video")),this.eventBus.localAudioEnabled.subscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.subscribe(this.handlePausePlaylist)}handleEnded(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r,isAutoplayOn:s}=this.state[t];r===i.length-1?(yield this.stop(t),this.emit("playlistEnded",t)):s?this.playNext(t):yield this.pause(i[r].url,t),this.emit("currentTrackEnded",i[r])})}};var Et="HMS-Store:",k=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(Et,...t);break}case 1:{console.debug(Et,...t);break}case 2:{console.info(Et,...t);break}case 3:{console.warn(Et,...t);break}case 6:{console.error(Et,...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}}}};k.level=0;var zr=(a,e)=>e,bt=(a,e)=>e,Ma=(a,e)=>e,gn=(a,e)=>e,Tn=(a,e)=>e,Y=(0,H.createSelector)([G,zr],(a,e)=>e?a[e]:null),Yr=(0,H.createSelector)([w,bt],(a,e)=>e?a[e]:null),fn=(0,H.createSelector)([w,bt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="video"?t:null}),vn=(0,H.createSelector)([w,bt],(a,e)=>{if(!e)return null;let t=a[e];return(t==null?void 0:t.type)==="audio"?t:null}),Mn=(0,H.createSelector)([w,bt],(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}),yn=(0,H.createSelector)([w,bt],(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}),kn=(0,H.createSelector)([Mr,Tn],(a,e)=>e?a[e]:null),$=I(Y),Pn=I((0,H.createSelector)([Xt,gn],(a,e)=>{if(a)return e?a[e]:a}));function En(a){return e=>{if(e.sessionStore)return a?e.sessionStore[a]:e.sessionStore}}var bn=(...a)=>(0,H.createSelector)([Xt],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}}),An=I((0,H.createSelector)(Y,a=>a==null?void 0:a.name)),At=I(Yr),Xr=I(fn),In=I(vn),Rn=I(Mn),Hn=I(yn),ya=I((a,e)=>{let t=Y(a,e);if(t&&t.videoTrack&&t.videoTrack!=="")return a.tracks[t.videoTrack]}),ka=I((a,e)=>{let t=Y(a,e);if(t&&t.audioTrack&&t.audioTrack!=="")return a.tracks[t.audioTrack]}),Cn=ya,Ln=I((a,e)=>{let t=Y(a,e);return(t==null?void 0:t.auxiliaryTracks.map(i=>a.tracks[i]))||[]}),Pa=(a,e)=>e?a.speakers[e]:null,wn=I((0,H.createSelector)(Pa,a=>(a==null?void 0:a.audioLevel)||0)),Dn=(a,e)=>{let t=ka(e)(a);return Pa(a,t==null?void 0:t.id)},_n=I((0,H.createSelector)(Dn,a=>(a==null?void 0:a.audioLevel)||0)),Nn=I((a,e)=>{if(e)return a.connectionQualities[e]}),On=I((a,e)=>{let t=Y(a,e);if(t){let i=t==null?void 0:t.auxiliaryTracks.find(r=>ct(a.tracks[r]));return i?a.tracks[i]:void 0}}),xn=I((0,H.createSelector)(w,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return lt(r)&&dt(r)});return t?a[t]:void 0})),Un=I((0,H.createSelector)(w,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return lt(r)&&ct(r)});return t?a[t]:void 0})),Bn=I((0,H.createSelector)(w,Y,(a,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=a[i];return Yt(r)&&ct(r)});return t?a[t]:void 0})),Zr=I((0,H.createSelector)(w,Y,(a,e)=>Le(a,e))),Vn=a=>(0,H.createSelector)(Zr(a),e=>e.video),es=a=>(0,H.createSelector)(Zr(a),e=>e.audio),Fn=I((a,e)=>{let t=Y(a,e);return Ve(a,t==null?void 0:t.audioTrack)}),Gn=I((a,e)=>{let t=Y(a,e);return Ve(a,t==null?void 0:t.videoTrack)}),ts=I((a,e)=>{if(e&&a.tracks[e])return a.tracks[e].volume===0}),Wn=I((a,e)=>{let t=Y(a,e);return ts(t==null?void 0:t.audioTrack)(a)}),$n=I((a,e)=>{let t=es(e)(a);return ts(t==null?void 0:t.id)(a)}),is=I((a,e)=>{let t=Yr(a,e);if(t){if(t.type!=="audio"){k.w("Please pass audio track here");return}return t.volume}}),Kn=I((a,e)=>{let t=Y(a,e);return is(t==null?void 0:t.audioTrack)(a)}),qn=I((a,e)=>{let t=es(e)(a);return is(t==null?void 0:t.id)(a)}),jn=I((a,e)=>{let t=Yr(a,e);if(t){if(t.type!=="video"){k.w("Please pass video track here");return}return t.layer}}),Ea=(0,H.createSelector)([Fe,ce,zr],(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)})}),ba=(0,H.createSelector)([Fe,Ma],(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})}),Aa=(0,H.createSelector)(Fe,a=>a.filter(e=>{var t;return!e.recipientPeer&&!((t=e.recipientRoles)!=null&&t.length)})),Jn=(0,H.createSelector)([ba,Ma],a=>a?a.filter(e=>!e.read).length:0),Qn=(0,H.createSelector)([Ea,zr],a=>a?a.filter(e=>!e.read).length:0),zn=(0,H.createSelector)(Aa,a=>a.filter(e=>!e.read).length),Yn=I(Ea),Xn=I(ba),Zn=I(Jn),ec=I(Qn),tc=a=>(0,H.createSelector)([ie],e=>e.filter(t=>t.roleName===a)),ic=a=>(0,H.createSelector)([ie],e=>e.filter(t=>t.roleName?a.includes(t.roleName):!1)),rc=a=>(0,H.createSelector)($(a),e=>{try{return e!=null&&e.metadata&&e.metadata!==""?JSON.parse(e.metadata):{}}catch(t){return console.error("cannot parse peer metadata",t),{}}}),sc=a=>(0,H.createSelector)($(a),e=>!!(e!=null&&e.isHandRaised)),ac=a=>(0,H.createSelector)($(a),e=>e==null?void 0:e.name),rs=I(kn),oc=a=>(0,H.createSelector)(pt,e=>e[a]);var It=require("reselect");var nc=(0,It.createSelector)([G,w],(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}})),cc=a=>a.roleChangeRequests[0]||null,dc=(0,It.createSelector)([cc,G,re],(a,e,t)=>a?{requestedBy:a.requestedBy?e[a.requestedBy]:void 0,role:t[a.roleName],token:a.token}:null),lc=(0,It.createSelector)([ht],a=>ut(a)),uc=(0,It.createSelector)([fr],a=>ut(a));var he=require("reselect");var Ia=a=>(0,he.createSelector)([re],e=>e[a]),pc=a=>(0,he.createSelector)(Ia(a),e=>ut(e)),hc=(0,he.createSelector)([W,w],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),mc=(0,he.createSelector)([X,w],(a,e)=>{let t=null;return a&&(t=e[a]),(t==null?void 0:t.plugins)||[]}),Sc=a=>(0,he.createSelector)([hc],e=>e.includes(a)),gc=a=>(0,he.createSelector)([mc],e=>e.includes(a)),Tc=a=>(0,he.createSelector)(ie,e=>e.find(a)),fc=a=>(0,he.createSelector)(ie,e=>e.filter(a)),vc=a=>(0,he.createSelector)(U,e=>e.joinedAt&&Date.now()-e.joinedAt.getTime()<=a);var Ja=require("immer"),Qa=Ce(require("zustand/shallow")),za=Ce(require("zustand/vanilla"));var Ra=require("eventemitter2");var vi={0:"PEER_JOINED",1:"PEER_LEFT",8:"ROLE_UPDATED",10:"NAME_UPDATED",11:"METADATA_UPDATED",12:"HAND_RAISE_CHANGED"},Rt={0:"TRACK_ADDED",1:"TRACK_REMOVED",2:"TRACK_MUTED",3:"TRACK_UNMUTED",5:"TRACK_DEGRADED",6:"TRACK_RESTORED",4:"TRACK_DESCRIPTION_CHANGED"},Mi={0:"POLL_CREATED",1:"POLL_STARTED",2:"POLL_STOPPED",4:"POLL_VOTES_UPDATED",3:"POLLS_LIST"};var ss="hmsNotification",yi=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(ss,i),()=>{this.eventEmitter.removeListener(ss,i)}};this.store=e,this.eventEmitter=new Ra.EventEmitter2({maxListeners:Object.keys(zt).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($(t==null?void 0:t.id))||t,r=vi[e];if(r&&i){let s=this.createNotification(r,i,"info");this.emitEvent(s)}}sendTrackUpdate(e,t){let i=this.store.getState(At(t)),r=Rt[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=Mi[e],r=this.store.getState(rs(t));if(i){let s=this.createNotification(i,r,"info");this.emitEvent(s)}}emitEvent(e){this.eventEmitter.emit(ss,e)}createNotification(e,t,i,r=""){return this.id++,{id:this.id,type:e,message:r,data:t,severity:i}}};var ki=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){k.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 Ha(a){return a instanceof te||a instanceof O}var Ca=(a,e)=>{let t=Ht(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];xe(r,s)?(Z(r.auxiliaryTracks,s.auxiliaryTracks)&&(s.auxiliaryTracks=r.auxiliaryTracks),r.groups&&Z(r.groups,s.groups)&&(s.groups=r.groups),Object.assign(r,s)):ns(r,s)?delete a[i]:Pi(r,s)&&(a[i]=s)}},La=(a,e)=>{let t=Ht(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];xe(r,s)?(os(r,s),Object.assign(r,s)):ns(r,s)?delete a[i]:Pi(r,s)&&(a[i]=s)}},wa=(a,e)=>{let t=Ht(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];xe(r,s)?(r.questions&&Z(r.questions,s.questions)&&(s.questions=r.questions),Object.assign(r,s)):Pi(r,s)&&(a[i]=s)}},as=(a,e)=>{let t=Ht(Object.keys(a),Object.keys(e));for(let i of t){let r=a[i],s=e[i];xe(r,s)?Object.assign(r,s):ns(r,s)?delete a[i]:Pi(r,s)&&(a[i]=s)}},Da=(a,e,t)=>{let i=t.reduce((s,o)=>(s[o.firstTrackId]=Object.values(e[o.getTrackIDBeingSent()]||{}).sort((n,l)=>!n.rid||!l.rid?0:n.rid<l.rid?-1:1),s),{}),r=Ht(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&&Z(a.plugins,e.plugins)&&(e.plugins=a.plugins),a.type==="video"&&a.layerDefinitions&&Z(a.layerDefinitions,e.layerDefinitions)&&(e.layerDefinitions=a.layerDefinitions)},xe=(a,e)=>a&&e,ns=(a,e)=>a&&!e,Pi=(a,e)=>!a&&e,Z=(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},Ht=(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}}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 te&&(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 B||t instanceof ne)&&(e.isPublished=t.isPublished)}static updateDeviceID(e,t){var i;t instanceof B||t instanceof ne?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 B)&&(Z(t.getSimulcastDefinitions(),e.layerDefinitions)||(e.layerDefinitions=t.getSimulcastDefinitions()))}static enrichScreenTrack(e,t){var i,r;if(t instanceof B){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 B||t instanceof ne)&&(Z(t.getPlugins(),e.plugins)||(e.plugins=t.getPlugins()))}static convertRoom(e,t){let{recording:i,rtmp:r,hls:s}=a.convertRecordingStreamingState(e==null?void 0:e.recording,e==null?void 0:e.rtmp,e==null?void 0:e.hls);return{id:e.id,name:e.name,localPeer:t,recording:i,rtmp:r,hls:s,sessionId:e.sessionId,startedAt:e.startedAt,joinedAt:e.joinedAt,peerCount:e.peerCount,isLargeRoom:e.large_room_optimization,isEffectsEnabled:e.isEffectsEnabled,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){return{code:e.code,action:e.action,name:e.name,message:e.message,description:e.description,isTerminal:e.isTerminal,nativeError:e.nativeError,timestamp:new Date}}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 v(S({},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),l=e.getCurrentIndex(t);return e.getList(t).forEach(u=>{i[u.id]=a.convertPlaylistItem(e,u)}),{list:i,selection:{id:r==null?void 0:r.id,hasPrevious:l>0,hasNext:l<n.length-1},progress:s,volume:o,currentTime:e.getCurrentTime(t),playbackRate:e.getPlaybackRate(t)}}static convertRecordingStreamingState(e,t,i){var r;return{recording:{browser:S({running:!1},e==null?void 0:e.browser),server:S({running:!1},e==null?void 0:e.server),hls:S({running:!1},e==null?void 0:e.hls)},rtmp:S({running:!1},t),hls:{variants:((r=i==null?void 0:i.variants)==null?void 0:r.map(s=>s))||[],running:!!(i!=null&&i.running),error:i==null?void 0:i.error}}}};var Ct=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){k.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"?Pr:Er,t=this.store.getState(e.selection);if(!t.id){k.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 Ei=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 bi=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,k.d("starting audio level monitor for remote peers",this.store);let e=this.store.getState(me);k.d("starting audio levels is connected to room",e),e&&(yield this.monitorAudioLevels());let t=this.store.subscribe(this.monitorAudioLevels.bind(this),me);this.unsubs.push(t)})}stop(){return c(this,null,function*(){this.hasStarted&&(this.hasStarted=!1,this.shouldMonitor=!1,this.unsubs.forEach(e=>e()),k.d("stopped audio level monitor for remote peers"))})}monitorAudioLevels(){return c(this,null,function*(){if(!this.store.getState(me)){this.shouldMonitor&&(k.i("room no longer connected, stopping audio level monitoring for remote"),this.shouldMonitor=!1);return}if(this.shouldMonitor)return;k.i("monitoring audio levels"),this.shouldMonitor=!0;let t=()=>{this.shouldMonitor?(this.logAllPeersAudioLevels(),setTimeout(t,this.intervalMs)):k.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(ie).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 l=yield this.getAudioLevel(s,n);l.level>0&&i.push(l)}}if(i.length>0){let s={event:"app-audio-level",data:i};k.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 Ai=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($(t.peerId)),r=vi[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($(t.peerId)));else if([12,13,14].includes(e))this.syncRoomState(r),i||(i=this.store.getState($(t.peerId)));else{let s=N.convertPeer(t);this.setState(o=>{let n=o.peers[s.id];xe(n,s)&&(Z(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 Ei(this.sdk,this.setSessionStoreValueLocally.bind(this)),this.actionBatcher=new ki(e)}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"){k.d("layer none will be ignored");return}if(((r=this.store.getState(Xr(e)))==null?void 0:r.preferredLayer)===t){k.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 k.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(J);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 k.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,k.e("Failed to connect to room - ",t),t}})}leave(){return c(this,null,function*(){let e=this.store.getState(me),t=!0;e||(t=!1,this.logPossibleInconsistency("room leave is called when no room is connected"));let i=this.store.getState(J);return this.setState(r=>{r.room.roomState="Disconnecting"},"leaving"),this.sdk.leave(t).then(()=>{this.resetState("leave"),this.beamSpeakerLabelsLogger&&this.beamSpeakerLabelsLogger.stop().catch(k.e),k.i("left room")}).catch(r=>{k.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(X);t&&(yield this.setEnabledTrack(t,e))})}setLocalVideoEnabled(e){return c(this,null,function*(){let t=this.store.getState(W);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(X);t&&(yield this.setSDKLocalAudioTrackSettings(t,e),this.syncRoomState("setAudioSettings"))})}setVideoSettings(e){return c(this,null,function*(){let t=this.store.getState(W);t&&(yield this.setSDKLocalVideoTrackSettings(t,e),this.syncRoomState("setVideoSettings"))})}switchCamera(){return c(this,null,function*(){let e=this.store.getState(W);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(re),s=t.map(l=>r[l]),{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 r;if(!e.message)throw k.w("sendMessage","Failed to send message",e),Error(`sendMessage Failed - ${JSON.stringify(e)}`);let t=this.sdk.getLocalPeer(),i={read:!0,id:e.id,time:new Date(e.time),message:e.message,type:e.type||"chat",recipientPeer:e.recipientPeer,recipientRoles:e.recipientRoles,senderName:t==null?void 0:t.name,sender:t==null?void 0:t.peerId,senderRole:(r=t==null?void 0:t.role)==null?void 0:r.name,ignored:!!e.type&&this.ignoredMessageTypes.includes(e.type)};this.putMessageInStore(i)}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())}),Zt)});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),k.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 k.w("no plugin passed in for checking support"),t.errMsg="no plugin passed in for checking support",t;let i=this.store.getState(W);if(!i)return k.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):(k.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 k.w('no plugin passed in for checking support"'),t.errMsg='no plugin passed in for checking support"',t;let i=this.store.getState(X);if(!i)return k.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):(k.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||k.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)})}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(vr);if(!(i!=null&&i.endRoom)){k.w("You are not allowed to perform this action - endRoom");return}let r=this.store.getState(J);this.setState(s=>{s.room.roomState="Disconnecting"},"endingRoom");try{yield this.sdk.endRoom(e,t),this.resetState("endRoom")}catch(s){k.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)})}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&&Ha(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(re);t.roles=e.roles.map(r=>i[r])}yield this.sdk.changeMultiTrackState(t)})}setLogLevel(e){k.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||(k.i("enabling beam speaker labels logging"),this.beamSpeakerLabelsLogger=new bi(this.store,this),yield this.beamSpeakerLabelsLogger.start())})}resetState(e="resetState"){this.isRoomJoinCalled=!1,k.cleanup(),this.setState(t=>{Object.assign(t,ot())},e)}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)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)}),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:this.onConnectionQualityUpdate.bind(this)})})}onRemovedFromRoom(e){var r;let t=this.store.getState($((r=e.requestedBy)==null?void 0:r.peerId));this.hmsNotifications.sendLeaveRoom(v(S({},e),{requestedBy:t||void 0}));let i=e.roomEnded||!t?"roomEnded":"removedFromRoom";k.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(j);if(this.setState(r=>{Z(r.devices.audioInput,t.audioInput)||(r.devices.audioInput=t.audioInput),Z(r.devices.videoInput,t.videoInput)||(r.devices.videoInput=t.videoInput),Z(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)}),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=Mi[e];this.setState(r=>{let s=t.reduce((o,n)=>{var l;return o[n.id]=v(S({},n),{questions:(l=n.questions)==null?void 0:l.map(u=>{var p,h;return v(S({},u),{answer:u.answer?S({},u.answer):void 0,options:(p=u.options)==null?void 0:p.map(g=>S({},g)),responses:(h=u.responses)==null?void 0:h.map(g=>S({},g))})})}),o},{});wa(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(ei)?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(ei)?(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`,k.time(`store-sync-${e}`);let t={},i=[],r={},s={},o={},n,l=this.sdk.getPeers();for(let g of l){let T=N.convertPeer(g);t[T.id]=T,i.push(T.id),o[T.id]={peerID:T.id,downlinkQuality:g.networkQuality||-1};let P=[g.audioTrack,g.videoTrack,...g.auxiliaryTracks];for(let A of P){if(!A)continue;let D=N.convertTrack(A);r[D.id]=D}if(g.isLocal){let A=g;n=this.getPreviewFields(A),Object.assign(s,this.getMediaSettings(A))}}let u=this.sdk.getRecordingState(),p=this.sdk.getRTMPState(),h=this.sdk.getHLSState();this.setState(g=>{var A;g.room.peers=i;let T=g.peers,P=g.tracks;Ca(T,t),La(P,r),Object.assign(g.settings,s),g.room.isConnected&&Object.assign(g.connectionQualities,o),(A=g.preview)!=null&&A.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,h)),Object.assign(g.templateAppData,this.sdk.getTemplateAppData())},e),k.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 Ct(t,"audio",this.syncPlaylistState.bind(this),this.store),this.videoPlaylist=new Ct(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)}onPeerUpdate(e,t){if(![4,5].includes(e)){if(Array.isArray(t)){let i=this.store.getState(G),r=t.filter(o=>!i[o.peerId]);if(this.syncRoomState("peersJoined"),this.store.getState(me)){let o=[];for(let n of t){let l=this.store.getState($(n.peerId));l&&o.push(l)}this.hmsNotifications.sendPeerList(o)}else r.forEach(o=>{let n=this.store.getState($(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=Rt[e];this.syncRoomState(r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}else{let r=Rt[e]||"trackUpdate",s=N.convertTrack(t);this.setState(o=>{let n=o.tracks[s.id];xe(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(ce));t.read=!1,t.ignored=this.ignoredMessageTypes.includes(t.type),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($((s=e.requestedBy)==null?void 0:s.peerId)),i=this.getStoreLocalTrackIDfromSDKTrack(e.track),r=this.store.getState(At(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($((s=e.requestedBy)==null?void 0:s.peerId));e.enabled||this.syncRoomState("changeMultiTrackStateRequest");let i=[],r=this.store.getState(w);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);k.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(()=>k.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),k.e("received error from sdk",t instanceof f?`${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(mr),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}}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 Pe?(yield i.setVolume(e),this.setState(r=>{let s=r.tracks[t];s&&s.type==="audio"&&(s.volume=e)},"trackVolume")):k.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(j);if((t==null?void 0:t.videoTrack)!==e)return!1;let i=this.store.getState(gr),r=this.store.getState(Zt);return i&&!r}logPossibleInconsistency(e){k.w("possible inconsistency detected - ",e)}addRemoveVideoPlugin(e,t,i){return c(this,null,function*(){if(!e){k.w("Invalid plugin received in store");return}let r=this.store.getState(W);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){k.w("Invalid plugin received in store");return}let i=this.store.getState(W);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*(){if(!e){k.w("Invalid plugin received in store");return}let i=this.store.getState(X);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`)}})}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(Sr).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(Tr)&&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)}};var Ii=a=>_?`${a} ${document.title}`:a;var Lt=class{constructor(e){this.recording={server:{running:!1},browser:{running:!1},hls:{running:!1}};this.rtmp={running:!1};this.hls={running:!1,variants:[]};this.id=e}};var Ri=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,l=z(i).then(()=>{this.controller.abort()});try{let h=(u=(yield fetch(`${t}?${Date.now()}`,{signal:s})).body)==null?void 0:u.getReader();if(!h)throw Error("unable to process request");let g=()=>c(this,null,function*(){if(h)try{let T=!1;for(;!T;){let{value:P,done:A}=yield h.read();T=A,P&&(n+=P.byteLength,this.sendScore({scoreMap:r,downloadedSize:n,startTime:o}))}}catch(T){T.name!=="AbortError"&&d.d(this.TAG,T)}});return Promise.race([g(),l]).then(()=>{this.sendScore({scoreMap:r,downloadedSize:n,startTime:o,finished:!0})}).catch(T=>{d.d(this.TAG,T),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:T.message}))})}catch(p){p.name!=="AbortError"?(d.d(this.TAG,p),this.updateScoreToListener(0),this.eventBus.analytics.publish(y.previewNetworkQuality({error:p.message}))):d.d(this.TAG,p)}});this.stop=()=>{this.controller.signal.aborted||this.controller.abort()};this.sendScore=({scoreMap:e,downloadedSize:t,startTime:i,finished:r=!1})=>{let s=(Date.now()-i)/1e3,n=t/1024/s*8,l=-1;for(let u in e){let p=e[u];n>=p.low&&(!p.high||n<=p.high)&&(l=Number(u))}this.updateScoreToListener(l),r&&this.eventBus.analytics.publish(y.previewNetworkQuality({score:l,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 wt=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 T,P,A,D,ye,Ss;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"),l=this.removeTrack(r,s,"screen"),u=this.hasSimulcastDifference((T=e.publishParams.simulcast)==null?void 0:T.video,(P=t.publishParams.simulcast)==null?void 0:P.video),p=this.hasSimulcastDifference((A=e.publishParams.simulcast)==null?void 0:A.screen,(D=t.publishParams.simulcast)==null?void 0:D.screen),h=(Ss=(ye=this.store.getLocalPeer())==null?void 0:ye.videoTrack)==null?void 0:Ss.enabled;yield this.removeAudioTrack(n),yield this.removeVideoTracks(o||u),yield this.removeScreenTracks(l||p);let g=this.getSettings();u&&(g.isVideoMuted=!h),yield this.publish(g),yield this.syncDevices(g,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 l;let n=(l=t==null?void 0:t.layers)==null?void 0:l.find(u=>u.rid===o.rid);return(n==null?void 0:n.maxBitrate)!==o.maxBitrate||(n==null?void 0:n.maxFramerate)!==o.maxFramerate}))}getSettings(){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,audioInputDeviceId:(e==null?void 0:e.audioInputDeviceId)||"default",audioOutputDeviceId:(e==null?void 0:e.audioOutputDeviceId)||"default",videoDeviceId:(e==null?void 0:e.videoDeviceId)||"default"}}};var cs=class{constructor(){this.TAG="[HTTPAnalyticsTransport]";this.failedEvents=new le("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"?la:ua;fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.metadata.token}`,user_agent_v2:e.metadata.userAgent},body:JSON.stringify(t)}).then(r=>{if(r.status===401){this.removeFromStorage(e);return}if(r.status!==200)throw Error(r.statusText);this.removeFromStorage(e)}).catch(r=>{d.v(this.TAG,"Failed to send event",r,e),this.addEventToStorage(e)})}flushFailedEvents(){let e=this.failedEvents.get();e==null||e.forEach(t=>this.sendEvent(t))}addEventToStorage(e){let t=this.failedEvents.get()||[];t.find(i=>i.timestamp===e.timestamp)||(t.length===100&&t.shift(),t.push(e),this.failedEvents.set(t))}removeFromStorage(e){let t=this.failedEvents.get()||[],i=t.findIndex(r=>r.timestamp===e.timestamp);i>-1&&(t.splice(i,1),this.failedEvents.set(t))}},fe=new cs;var Dt=class{constructor(){this.knownRoles={};this.peers={};this.tracks=new Map;this.peerTrackStates={};this.speakers=[];this.roleDetailsArrived=!1;this.env="prod";this.simulcastEnabled=!1;this.userAgent=mt(this.env);this.polls=new Map;this.whiteboards=new Map}getConfig(){return this.config}setSimulcastEnabled(e){this.simulcastEnabled=e}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=mt(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(Q.rememberDevices(!!e.rememberDeviceSelection),e.rememberDeviceSelection){let s=Q.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}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 te&&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 v(S({},e),{layers:(e.layers||[]).map(t=>v(S({},t),{maxBitrate:t.maxBitrate*1e3}))})}getSimulcastDefinitionsForPeer(e,t){var n,l,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=(l=i.simulcast)==null?void 0:l.screen,s=i.screen.width,o=i.screen.height),((u=r==null?void 0:r.layers)==null?void 0:u.map(p=>{let h=Ie[p.rid],g={width:Math.floor(s/p.scaleResolutionDownBy),height:Math.floor(o/p.scaleResolutionDownBy)};return{layer:h,resolution:g}}))||[]}setPoll(e){this.polls.set(e.id,e)}getPoll(e){return this.polls.get(e)}setWhiteboard(e){this.whiteboards.set(e.id,e)}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(m.GenericErrors.InvalidRole("VALIDATION",""));return}e.role=this.getPolicyForRole(e.role.name)})}addPluginsToRoles(e){if(!e)return;let t=(i,r,s)=>{var n;let o=this.knownRoles[i].permissions;o[r]||(o[r]=[]),(n=o[r])==null||n.push(s)};Object.keys(e).forEach(i=>{var o,n,l;let r=i;if(!e[r])return;let s=e[r].permissions;(o=s==null?void 0:s.admin)==null||o.forEach(u=>t(u,r,"admin")),(n=s==null?void 0:s.reader)==null||n.forEach(u=>t(u,r,"read")),(l=s==null?void 0:s.writer)==null||l.forEach(u=>t(u,r,"write"))})}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,fe.setEnv(i)}};var Hi=class{constructor(){this.TAG="[WakeLockManager]";this.wakeLock=null;this.acquireLock=()=>c(this,null,function*(){yield this.requestWakeLock(),document==null||document.addEventListener("visibilitychange",this.visibilityHandler)});this.cleanup=()=>c(this,null,function*(){if(this.wakeLock&&!this.wakeLock.released)try{yield this.wakeLock.release(),d.d(this.TAG,"Wake lock released")}catch(e){let t=e;d.w(this.TAG,"Error while releasing wake lock",`name=${t.name}, message=${t.message}`)}this.wakeLock=null});this.visibilityHandler=()=>c(this,null,function*(){(document==null?void 0:document.visibilityState)==="visible"&&(!this.wakeLock||this.wakeLock.released)&&(d.d(this.TAG,"Re-acquiring wake lock due to visibility change"),yield this.requestWakeLock())});this.requestWakeLock=()=>c(this,null,function*(){try{if(!("wakeLock"in navigator)){d.d(this.TAG,"Wake lock feature not supported");return}this.wakeLock=yield navigator.wakeLock.request("screen"),d.d(this.TAG,"Wake lock acquired")}catch(e){let t=e;d.w(this.TAG,"Error acquiring wake lock",`name=${t.name}, message=${t.message}`)}})}};var Ci=class{constructor(e){this.store=e;this.bufferSize=100;this.TAG="[AnalyticsEventsService]";this.transport=null;this.pendingEvents=[];this.level=1}setTransport(e){this.transport=e}reset(){this.transport=null,this.pendingEvents=[]}queue(e){if(e.level>=this.level&&(this.pendingEvents.push(e),this.pendingEvents.length>this.bufferSize)){let t=this.pendingEvents.shift();d.d(this.TAG,"Max buffer size reached","Removed event to accommodate new events",t)}return this}flushFailedClientEvents(){fe.flushFailedEvents()}flush(){var e;try{for(;this.pendingEvents.length>0;){let t=this.pendingEvents.shift();t&&(t.metadata.peer.peer_id=(e=this.store.getLocalPeer())==null?void 0:e.peerId,t.metadata.userAgent=this.store.getUserAgent(),this.transport&&this.transport.transportProvider.isConnected?this.transport.sendEvent(t):this.sendClientEventOnHTTP(t))}}catch(t){d.w(this.TAG,"Flush Failed",t)}}sendClientEventOnHTTP(e){var r,s,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},fe.sendEvent(e)}};var Na=require("uuid");var _a={autoplayFailed:void 0,initialized:!1,autoplayCheckPromise:void 0},_t=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=S({},_a);this.timer=null;this.handleAudioPaused=e=>c(this,null,function*(){var s;let i=(s=e.target.srcObject)==null?void 0:s.getAudioTracks()[0];if(!(i!=null&&i.enabled))return;d.d(this.TAG,"Audio Paused",e.target.id);let r=this.store.getTrackById(e.target.id);r&&(De()?(yield z(500),this.playAudioFor(r)):this.autoPausedTracks.add(r))});this.handleTrackUpdate=({track:e})=>{d.d(this.TAG,"Track updated",`${e}`)};this.handleTrackAdd=r=>c(this,[r],function*({track:e,peer:t,callListener:i=!0}){var o,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;d.e(this.TAG,"error on audio element",s.error);let l=m.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(l)),((p=s==null?void 0:s.error)==null?void 0:p.code)===MediaError.MEDIA_ERR_DECODE&&(this.removeAudioElement(s,e),yield z(500),yield this.handleTrackAdd({track:e,peer:t,callListener:!1}))}),e.setAudioElement(s),e.setVolume(this.volume),d.d(this.TAG,"Audio track added",`${e}`),this.init(),yield this.autoSelectAudioOutput(),(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=>{e.isUserSelection||e.error||!e.selection||e.type==="video"||this.unpauseAudioTracks()};this.handleTrackRemove=e=>{this.autoPausedTracks.delete(e);let t=document.getElementById(e.trackId);t&&this.removeAudioElement(t,e),this.audioSink&&this.audioSink.childElementCount===0&&(this.state.autoplayCheckPromise=void 0,this.state.autoplayFailed=void 0),d.d(this.TAG,"Audio track removed",`${e}`)};this.unpauseAudioTracks=()=>c(this,null,function*(){let e=[];this.autoPausedTracks.forEach(t=>{e.push(this.playAudioFor(t))}),yield Promise.all(e)});this.removeAudioElement=(e,t)=>{e&&(d.d(this.TAG,"removing audio element",`${t}`),e.removeEventListener("pause",this.handleAudioPaused),e.srcObject=null,e.remove(),t.setAudioElement(null))};this.startPollingForDevices=()=>{"ondevicechange"in navigator.mediaDevices||(this.timer=setInterval(()=>{c(this,null,function*(){yield this.deviceManager.init(!0,!1),yield this.autoSelectAudioOutput()})},5e3))};this.autoSelectAudioOutput=()=>c(this,null,function*(){var e,t;if(((e=this.audioSink)==null?void 0:e.children.length)===0){let i=null,r=null,s=null,o=null;for(let l of this.deviceManager.audioInput)l.label.toLowerCase().includes("speakerphone")&&(r=l),l.label.toLowerCase().includes("wired")&&(s=l),l.label.toLowerCase().includes("bluetooth")&&(i=l),l.label.toLowerCase().includes("earpiece")&&(o=l);let n=(t=this.store.getLocalPeer())==null?void 0:t.audioTrack;if(n&&o){let l=(i==null?void 0:i.deviceId)||(s==null?void 0:s.deviceId)||(r==null?void 0:r.deviceId);if(d.d(this.TAG,"externalDeviceID",l),n.settings.deviceId===l)return;yield n.setSettings({deviceId:o==null?void 0:o.deviceId},!0),yield n.setSettings({deviceId:l},!0)}}});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.startPollingForDevices()}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&&this.unpauseAudioTracks()})}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,Na.v4)()}`,(e&&document.getElementById(e)||document.body).append(t),this.audioSink=t,d.d(this.TAG,"audio sink created",this.audioSink)}cleanup(){var e;(e=this.audioSink)==null||e.remove(),this.audioSink=void 0,this.timer&&(clearInterval(this.timer),this.timer=null),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.autoPausedTracks=new Set,this.state=S({},_a)}playAudioFor(e){return c(this,null,function*(){let t=e.getAudioElement();if(!t){d.w(this.TAG,"No audio element found on track",e.trackId);return}try{yield t.play(),this.state.autoplayFailed=!1,this.autoPausedTracks.delete(e),d.d(this.TAG,"Played track",`${e}`)}catch(i){this.autoPausedTracks.add(e),d.w(this.TAG,"Failed to play track",`${e}`,i);let r=i;if(!this.state.autoplayFailed&&r.name==="NotAllowedError"){this.state.autoplayFailed=!0;let s=m.TracksErrors.AutoplayBlocked("AUTOPLAY","");s.addNativeError(r),this.eventBus.analytics.publish(y.autoplayError()),this.eventBus.autoplayError.publish(s)}}})}};var Li=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 Nt=class{constructor(e,t){this.store=e;this.eventBus=t;this.audioInput=[];this.audioOutput=[];this.videoInput=[];this.hasWebcamPermission=!1;this.hasMicrophonePermission=!1;this.TAG="[Device Manager]:";this.initialized=!1;this.videoInputChanged=!1;this.audioInputChanged=!1;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"})),Q.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(l=>this.createIdentifier(l)===t),s=this.videoInput.find(l=>this.createIdentifier(l)===i);return{audioInput:r,videoInput:s,audioOutput:this.outputDevice}};this.computeChange=(e,t)=>e.length!==t.length?!0:t.some(i=>!e.includes(this.createIdentifier(i)));this.enumerateDevices=()=>c(this,null,function*(){try{let e=yield navigator.mediaDevices.enumerateDevices(),t=this.videoInput.map(this.createIdentifier),i=this.audioInput.map(this.createIdentifier);this.audioInput=[],this.audioOutput=[],this.videoInput=[],e.forEach(r=>{r.kind==="audioinput"&&r.label?(this.hasMicrophonePermission=!0,this.audioInput.push(r)):r.kind==="audiooutput"?this.audioOutput.push(r):r.kind==="videoinput"&&r.label&&(this.hasWebcamPermission=!0,this.videoInput.push(r))}),this.videoInputChanged=this.computeChange(t,this.videoInput),this.audioInputChanged=this.computeChange(i,this.audioInput),Q.setDevices({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput]}),this.logDevices("Enumerate Devices")}catch(e){d.e(this.TAG,"Failed enumerating devices",e)}});this.handleDeviceChange=ai(()=>c(this,null,function*(){yield this.enumerateDevices(),this.logDevices("After Device Change");let e=this.store.getLocalPeer();yield this.setOutputDevice(!0),yield this.handleAudioInputDeviceChange(e==null?void 0:e.audioTrack),yield this.handleVideoInputDeviceChange(e==null?void 0:e.videoTrack),this.eventBus.analytics.publish(y.deviceChange({selection:this.getCurrentSelection(),type:"change",devices:this.getDevices()}))}),500).bind(this);this.handleAudioInputDeviceChange=e=>c(this,null,function*(){if(!e){d.d(this.TAG,"No Audio track on local peer");return}if(!this.audioInputChanged){d.d(this.TAG,"No Change in AudioInput Device");return}let t=this.getNewAudioInputDevice();if(!t||!t.deviceId){this.eventBus.analytics.publish(y.deviceChange({selection:{audioInput:t},error:m.TracksErrors.SelectedDeviceMissing("audio"),devices:this.getDevices(),type:"audioInput"})),d.e(this.TAG,"Audio device not found");return}let{settings:i}=e,r=new oe().codec(i.codec).maxBitrate(i.maxBitrate).deviceId(t.deviceId).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"audioInput"}),this.logDevices("Audio Device Change Success")}catch(s){d.e(this.TAG,"[Audio Device Change]",s),this.eventBus.analytics.publish(y.deviceChange({selection:{audioInput:t},devices:this.getDevices(),type:"audioInput",error:s})),this.eventBus.deviceChange.publish({error:s,selection:t,type:"audioInput",devices:this.getDevices()})}});this.handleVideoInputDeviceChange=e=>c(this,null,function*(){if(!e){d.d(this.TAG,"No video track on local peer");return}if(!this.videoInputChanged){d.d(this.TAG,"No Change in VideoInput Device");return}let t=this.videoInput[0];if(!t||!t.deviceId){this.eventBus.analytics.publish(y.deviceChange({selection:{videoInput:t},error:m.TracksErrors.SelectedDeviceMissing("video"),devices:this.getDevices(),type:"video"})),d.e(this.TAG,"Video device not found");return}let{settings:i}=e,r=new ee().codec(i.codec).maxBitrate(i.maxBitrate).maxFramerate(i.maxFramerate).setWidth(i.width).setHeight(i.height).deviceId(t.deviceId).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"video"}),this.logDevices("Video Device Change Success")}catch(s){d.e(this.TAG,"[Video Device Change]",s),this.eventBus.analytics.publish(y.deviceChange({selection:{videoInput:t},devices:this.getDevices(),type:"video",error:s})),this.eventBus.deviceChange.publish({error:s,type:"video",selection:t,devices:this.getDevices()})}});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,l=this[n].find(u=>this.createIdentifier(u)===this.createIdentifier(o));this.eventBus.analytics.publish(y.deviceChange({selection:{[n]:l},devices:this.getDevices(),type:r,isUserSelection:s}))}})}init(e=!1,t=!0){return c(this,null,function*(){this.initialized&&!e||(!this.initialized&&navigator.mediaDevices.addEventListener("devicechange",this.handleDeviceChange),this.initialized=!0,yield this.enumerateDevices(),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.initialized=!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(){let e=this.store.getLocalPeer(),t=e==null?void 0:e.audioTrack,i=this.audioInput.find(s=>s.deviceId===(t==null?void 0:t.getManuallySelectedDeviceId()));if(i)return i;t==null||t.resetManuallySelectedDeviceId();let r=this.audioInput.find(s=>s.deviceId==="default");return r?this.audioInput.find(o=>o.deviceId!=="default"&&r.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()}))})}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(l=>i.includes(l.toLowerCase())))return;let r=this.audioOutput.find(l=>e.deviceId!=="default"&&l.label===e.label);if(r)return r;let s=this.audioOutput.find(l=>l.groupId===e.groupId);if(s&&this.audioOutput[0].deviceId==="default"&&s.groupId===this.audioOutput[0].groupId)return s}logDevices(e=""){d.d(this.TAG,e,JSON.stringify({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput],selected:this.getCurrentSelection()},null,4))}};var wi=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 Ee.resumeContext()})}};var Oa=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 et=class{constructor(){this.eventEmitter=new Oa.EventEmitter2;this.deviceChange=new x(V.DEVICE_CHANGE,this.eventEmitter);this.localAudioEnabled=new x(V.LOCAL_AUDIO_ENABLED,this.eventEmitter);this.localVideoEnabled=new x(V.LOCAL_VIDEO_ENABLED,this.eventEmitter);this.statsUpdate=new x(V.STATS_UPDATE,this.eventEmitter);this.trackDegraded=new x(V.TRACK_DEGRADED,this.eventEmitter);this.trackRestored=new x(V.TRACK_RESTORED,this.eventEmitter);this.trackAudioLevelUpdate=new x(V.TRACK_AUDIO_LEVEL_UPDATE,this.eventEmitter);this.audioPluginFailed=new x(V.AUDIO_PLUGIN_FAILED,this.eventEmitter);this.localAudioSilence=new x(V.LOCAL_AUDIO_SILENCE,this.eventEmitter);this.analytics=new x(V.ANALYTICS,this.eventEmitter);this.policyChange=new x(V.POLICY_CHANGE,this.eventEmitter);this.localRoleUpdate=new x(V.LOCAL_ROLE_UPDATE,this.eventEmitter);this.audioTrackUpdate=new x(V.AUDIO_TRACK_UPDATE,this.eventEmitter);this.audioTrackAdded=new x(V.AUDIO_TRACK_ADDED,this.eventEmitter);this.audioTrackRemoved=new x(V.AUDIO_TRACK_REMOVED,this.eventEmitter);this.autoplayError=new x(V.AUTOPLAY_ERROR,this.eventEmitter);this.leave=new x(V.LEAVE,this.eventEmitter)}};var Ot=class{constructor(e){this.type=e.type,this.source=e.source||"regular",this.description="",e instanceof ke?(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 Di=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(l=>({audioLevel:l.level,peer:this.store.getPeerById(l.peer_id),track:this.store.getTrackById(l.track_id)}));(s=this.audioListener)==null||s.onAudioLevelUpdate(i),this.store.updateSpeakers(i);let r=t[0];if(r){let l=this.store.getPeerById(r.peer_id);(o=this.listener)==null||o.onPeerUpdate(4,l)}else(n=this.listener)==null||n.onPeerUpdate(5,null)}};var _i=class{constructor(e){this.listener=e;this.TAG="[BroadcastManager]"}handleNotification(e,t){e==="on-broadcast"&&this.handleBroadcast(t)}handleBroadcast(e){var t,i;d.d(this.TAG,`Received Message from sender=${(t=e==null?void 0:e.peer)==null?void 0:t.peer_id}: ${e}`),(i=this.listener)==null||i.onMessageReceived(e)}};var Ni=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 tt=class{constructor(e,t,i){this.store=e;this.eventBus=t;this.listener=i;this.TAG="[TrackManager]";this.tracksToProcess=new Map;this.handleTrackAdd=e=>{d.d(this.TAG,"ONTRACKADD",`${e}`),this.tracksToProcess.set(e.trackId,e),this.processPendingTracks()};this.handleTrackRemovedPermanently=e=>{d.d(this.TAG,"ONTRACKREMOVE",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){d.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){d.d(this.TAG,"Track Update ignored - Peer not added to store");return}i||(i=Re(r,this.store),this.store.addPeer(i));for(let n in e.tracks){let l=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:S(S({},l),u)}),!p||this.tracksToProcess.has(n))this.processTrackInfo(u,e.peer.peer_id,t),this.processPendingTracks();else{p.setEnabled(!u.mute);let h=this.processTrackUpdate(p,l,u);h&&((o=this.listener)==null||o.onTrackUpdate(h,p,i))}}};this.processTrackInfo=(e,t,i)=>{};this.processPendingTracks=()=>{new Map(this.tracksToProcess).forEach(t=>{var s;let i=this.store.getTrackState(t.trackId);if(!i){d.d(this.TAG,"TrackState not added to store",`peerId - ${t.peerId}`,`trackId -${t.trackId}`);return}let r=this.store.getPeerById(i.peerId);if(!r){d.d(this.TAG,"Peer not added to store, peerId",i.peerId);return}t.source=i.trackInfo.source,t.peerId=r.peerId,t.logIdentifier=r.name,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){d.d(this.TAG,"TRACK_METADATA_ADD",JSON.stringify(e,null,2));for(let t in e.tracks){let i=e.tracks[t];this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:i})}this.processPendingTracks()}handleTrackRemove(e,t=!0){var s;d.d(this.TAG,"ONTRACKREMOVE",`${e}`);let i=this.store.getTrackState(e.trackId);if(!i)return;if(!this.store.hasTrack(e)){d.d(this.TAG,"Track not found in store");return}if(t){this.store.removeTrack(e);let 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),d.d(this.TAG,"auxiliary track removed",`${t}`)):t.type==="audio"&&e.audioTrack===t?(e.audioTrack=void 0,d.d(this.TAG,"audio track removed",`${t}`)):t.type==="video"&&e.videoTrack===t&&(e.videoTrack=void 0,d.d(this.TAG,"video track removed",`${t}`))}addAudioTrack(e,t){var i;t.type==="audio"&&(t.source==="regular"&&(!e.audioTrack||((i=e.audioTrack)==null?void 0:i.trackId)===t.trackId)?e.audioTrack=t:e.auxiliaryTracks.push(t),this.store.addTrack(t),d.d(this.TAG,"audio track added",`${t}`))}addVideoTrack(e,t){if(t.type!=="video")return;let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);if(i.setSimulcastDefinitons(r),this.addAsPrimaryVideoTrack(e,i))e.videoTrack?e.videoTrack.replaceTrack(i):e.videoTrack=i,this.store.addTrack(e.videoTrack);else{let s=e.auxiliaryTracks.findIndex(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]))}d.d(this.TAG,"video track added",`${t}`)}addAsPrimaryVideoTrack(e,t){var i;return t.source==="regular"&&(!e.videoTrack||((i=e.videoTrack)==null?void 0:i.trackId)===t.trackId)}processTrackUpdate(e,t,i){let r;return t.mute!==i.mute?(r=i.mute?2:3,e.type==="audio"&&this.eventBus.audioTrackUpdate.publish({track:e,enabled:!i.mute})):t.description!==i.description&&(r=4),r}};var Oi=class extends tt{constructor(t,i,r,s){super(t,i,s);this.transport=r;this.TAG="[OnDemandTrackManager]";this.processTrackInfo=(t,i,r=!0)=>{var u;if(t.type!=="video")return;let s=this.store.getPeerById(i);if(!s||!this.isPeerRoleSubscribed(i)){d.d(this.TAG,`no peer in store for peerId: ${i}`);return}let o=new Se(new MediaStream,this.transport.getSubscribeConnection()),n=ge.getEmptyVideoTrack();n.enabled=!t.mute;let l=new O(o,n,t.source);l.setTrackId(t.track_id),l.peerId=s.peerId,l.logIdentifier=s.name,this.addVideoTrack(s,l),r&&((u=this.listener)==null||u.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&&ue(t.videoTrack.nativeTrack)}isPeerRoleSubscribed(t){var s,o,n,l;if(!t)return!0;let i=this.store.getLocalPeer(),r=this.store.getPeerById(t);return r&&((l=(o=(s=i==null?void 0:i.role)==null?void 0:s.subscribeParams)==null?void 0:o.subscribeToRoles)==null?void 0:l.includes((n=r.role)==null?void 0:n.name))}};var xi=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&&d.d(this.TAG,`${r}`),r.forEach(o=>{var l;let n={peer_id:o.peerId,role:((l=o.role)==null?void 0:l.name)||"",info:{name:o.name,data:o.metadata||"",user_id:o.customerUserId||""},tracks:{},groups:[],realtime:o.realtime};this.peerManager.handlePeerLeave(n)});let s=[];i.forEach(o=>{let n=this.store.getPeerById(o.peer_id),l=Object.values(o.tracks);n&&(this.store.getPeerTracks(n.peerId).forEach(p=>{var h;o.tracks[p.trackId]||(this.removePeerTrack(n,p.trackId),(h=this.listener)==null||h.onTrackUpdate(1,p,n))}),l.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?(d.d(this.TAG,"RECONNECT_PEER_LIST event",JSON.stringify(r,null,2)),this.handleReconnectPeerList(r)):(d.d(this.TAG,"PEER_LIST event",JSON.stringify(r,null,2)),this.handleInitialPeerList(r))}else if(e==="room-state"){let r=t;this.handlePreviewRoomState(r)}}removePeerTrack(e,t){var i,r;if(d.d(this.TAG,`removing track - ${t} from ${e}`),((i=e.audioTrack)==null?void 0:i.trackId)===t)e.audioTrack=void 0;else if(((r=e.videoTrack)==null?void 0:r.trackId)===t)e.videoTrack=void 0;else{let s=e.auxiliaryTracks.findIndex(o=>o.trackId===t);s>=0&&e.auxiliaryTracks.splice(s,1)}}};var L=a=>a?new Date(a):void 0;var Ui=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),d.d(this.TAG,"PEER_LEAVE",e.peer_id,`remainingPeers=${this.store.getPeers().length}`),t&&(t.audioTrack&&((i=this.listener)==null||i.onTrackUpdate(1,t.audioTrack,t)),t.videoTrack&&((r=this.listener)==null||r.onTrackUpdate(1,t.videoTrack,t)),(s=t.auxiliaryTracks)==null||s.forEach(n=>{var l;(l=this.listener)==null||l.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,l,u;let t=this.store.getPeerById(e.peer_id);if(!t&&e.realtime){t=this.makePeer(e),(s=this.listener)==null||s.onPeerUpdate(t.isHandRaised?12:14,t);return}if(t&&!t.isLocal&&!e.realtime){this.store.removePeer(t.peerId),(o=this.listener)==null||o.onPeerUpdate(13,t);return}if(!t){d.d(this.TAG,`peer ${e.peer_id} not found`);return}if(t.role&&t.role.name!==e.role){let p=this.store.getPolicyForRole(e.role);t.updateRole(p),this.updateSimulcastLayersForPeer(t),(n=this.listener)==null||n.onPeerUpdate(8,t)}let i=t.isHandRaised;t.updateGroups(e.groups);let r=(l=e.groups)==null?void 0:l.includes(Te);i!==r&&((u=this.listener)==null||u.onPeerUpdate(12,t)),this.handlePeerInfoUpdate(S({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=Re(e,this.store),t.realtime=e.realtime,t.joinedAt=L(e.joined_at),t.fromRoomState=!!e.is_from_room_state,this.store.addPeer(t),d.d(this.TAG,"adding to the peerList",`${t}`));for(let i in e.tracks){let r=e.tracks[i];this.store.setTrackState({peerId:e.peer_id,trackInfo:r}),r.type==="video"&&this.trackManager.processTrackInfo(r,e.peer_id,!1)}return t}updateSimulcastLayersForPeer(e){this.store.getPeerTracks(e.peerId).forEach(t=>{if(t.type==="video"&&["regular","screen"].includes(t.source)){let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);i.setSimulcastDefinitons(r)}})}};var Bi=class{constructor(e,t){this.store=e;this.eventBus=t}handlePolicyChange(e){let t=this.store.getLocalPeer();if(t&&!t.role){let r=e.known_roles[e.name];t.updateRole(r)}this.store.setKnownRoles(e);let i=this.store.getRoom();i?i.templateId=e.template_id:d.w("[PolicyChangeManager]","on policy change - room not present"),this.updateLocalPeerRole(e),this.eventBus.policyChange.publish(e)}updateLocalPeerRole(e){var i;let t=this.store.getLocalPeer();if(t!=null&&t.role&&t.role.name!==e.name){let r=this.store.getPolicyForRole(e.name),s=t.role;t.updateRole(r),r.name===((i=t.asRole)==null?void 0:i.name)&&delete t.asRole,this.eventBus.localRoleUpdate.publish({oldRole:s,newRole:r})}}};var Vi=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 d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e==null?void 0:e.id),i=t==null?void 0:t.id;if(t||(i=(yield this.transport.signal.createWhiteboard(this.getCreateOptionsWithDefaults(e))).id),!i)throw new Error(`Whiteboard ID: ${i} not found`);let r=yield this.transport.signal.getWhiteboard({id:i}),s=v(S({},t),{title:e==null?void 0:e.title,attributes:e==null?void 0:e.attributes,id:r.id,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 d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e);if(!t)throw new Error(`Whiteboard ID: ${e} not found`);let i={id:t.id,title:t.title,open:!1};this.store.setWhiteboard(i),(r=this.listener)==null||r.onWhiteboardUpdate(i)})}setListener(e){this.listener=e}getCreateOptionsWithDefaults(e){var o;let t=Object.values(this.store.getKnownRoles()),i=[],r=[],s=[];return t.forEach(n=>{var l,u,p;(l=n.permissions.whiteboard)!=null&&l.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 xt=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.whiteboard=new Vi(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(v(S({},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=Fi(v(S({},e),{poll_id:e.id,state:"created",created_by:(o=this.store.getLocalPeer())==null?void 0:o.peerId}));s.questions=r.questions.map(({question:l,options:u,answer:p})=>v(S({},l),{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,l;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"?((l=s.options)==null||l.sort(),delete s.text,delete s.option):(delete s.option,delete s.options),s.skipped&&(delete s.option,delete s.options,delete s.text),S({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 u,p;let r=this.store.getPoll(e);if(!r)throw new Error("Invalid poll ID - Poll not found");let s=((p=(u=this.store.getLocalPeer())==null?void 0:u.role)==null?void 0:p.permissions.pollRead)||!1;if(r.anonymous||r.state!=="stopped"||!s)return{entries:[],hasNext:!1};let o=yield this.transport.signal.fetchPollLeaderboard({poll_id:r.id,count:i,offset:t}),n={avgScore:o.avg_score,avgTime:o.avg_time,votedUsers:o.voted_users,totalUsers:o.total_users,correctUsers:o.correct_users};return{entries:o.questions.map(h=>({position:h.position,totalResponses:h.total_responses,correctResponses:h.correct_responses,duration:h.duration,peer:h.peer,score:h.score})),hasNext:!o.last,summary:n}})}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 l=yield this.transport.signal.getPollsList({count:50,state:"created"}),u=yield this.transport.signal.getPollsList({count:50,state:"stopped"});r=[...l.polls,...r,...u.polls]}for(let l of r){let u=yield this.transport.signal.getPollQuestions({poll_id:l.poll_id,index:0,count:50}),p=Fi(l),h=this.store.getPoll(l.poll_id);p.questions=u.questions.map(({question:g,options:T,answer:P},A)=>{var D,ye;return v(S({},g),{options:T,answer:P,responses:(ye=(D=h==null?void 0:h.questions)==null?void 0:D[A])==null?void 0:ye.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 l=(o=e.options)==null?void 0:o.map((u,p)=>v(S({},u),{index:p+1}));return{question:v(S({},e),{index:t+1}),options:l,answer:e.answer}}let i=v(S({},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((l,u)=>({index:u+1,text:l.text,weight:l.weight})),e.type==="single-choice"?s.option=e.options.findIndex(l=>l.isCorrectAnswer)+1||void 0:s.options=e.options.map((l,u)=>l.isCorrectAnswer?u+1:void 0).filter(l=>!!l)):(s==null||delete s.options,s==null||delete s.option),{question:i,options:r,answer:s}}getQuestionInPoll(e,t){var r;let i=(r=e==null?void 0:e.questions)==null?void 0:r.find(s=>s.index===t);if(!i)throw new Error("Invalid question index - Question not found in poll");return i}},Fi=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 Gi=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}),l=Fi(s);l.questions=n.questions.map(({question:u,options:p,answer:h})=>v(S({},u),{options:p,answer:h})),yield this.updatePollResponses(l,!0),t.push(l),this.store.setPoll(l)}(r=this.listener)==null||r.onPollsUpdate(1,t)})}handlePollStop(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let s=this.store.getPoll(r.poll_id);if(s){s.state="stopped",s.stoppedAt=L(r.stopped_at),s.stoppedBy=r.stopped_by;let 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),yield this.updatePollResponses(s,!1),t.push(s)}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(4,t))})}updatePollResult(e,t){var i;e.result=S({},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(l=>l.index===r.question);s&&(s.result=S({},s.result),s.result.correctResponses=r.correct,s.result.skippedCount=r.skipped,s.result.totalResponses=r.total,(n=r.options)==null||n.forEach((l,u)=>{var h;let p=(h=s.options)==null?void 0:h[u];p&&p.voteCount!==l&&(p.voteCount=l)}))})}updatePollResponses(e,t){return c(this,null,function*(){var r;(r=(yield this.transport.signal.getPollResponses({poll_id:e.id,index:0,count:50,self:t})).responses)==null||r.forEach(({response:s,peer:o,final:n})=>{var p;let l=(p=e==null?void 0:e.questions)==null?void 0:p.find(h=>h.index===s.question);if(!l)return;let u={id:s.response_id,questionIndex:s.question,option:s.option,options:s.options,text:s.text,responseFinal: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(l.responses)&&l.responses.length>0?l.responses.find(({id:h})=>h===u.id)||l.responses.push(u):l.responses=[u]})})}};var Wi=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(l=>l.publishedTrackId===i);if(!o)return;let n=()=>{var l;(l=this.listener)==null||l.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,l=this.getTracksToBeUpdated({type:t,source:i,enabled:n});if(l.length!==0)if(n)(u=this.listener)==null||u.onChangeMultiTrackStateRequest({requestedBy:o,tracks:l,type:t,source:i,enabled:!0});else{let p=[];for(let h of l)p.push(h.setEnabled(!1));Promise.all(p).then(()=>{var h;(h=this.listener)==null||h.onChangeMultiTrackStateRequest({requestedBy:o,tracks:l,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 $i=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;default:break}}handleRoomInfo(e){let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.description=e.description,t.large_room_optimization=e.large_room_optimization,t.max_size=e.max_size,t.name=e.name}handleSessionInfo(e){var i;let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.sessionId=e.session_id,t.peerCount!==e.peer_count&&(t.peerCount=e.peer_count,(i=this.listener)==null||i.onRoomUpdate("ROOM_PEER_COUNT_UPDATED",t))}handlePreviewRoomState(e){let{room:t}=e;this.onRoomState(t)}onRoomState(e){var l,u,p,h;let{recording:t,streaming:i,session_id:r,started_at:s,name:o}=e,n=this.store.getRoom();if(!n){d.w(this.TAG,"on room state - room not present");return}n.name=o,n.rtmp.running=this.isStreamingRunning((l=i==null?void 0:i.rtmp)==null?void 0:l.state),n.rtmp.startedAt=L((u=i==null?void 0:i.rtmp)==null?void 0:u.started_at),n.rtmp.state=(p=i==null?void 0:i.rtmp)==null?void 0:p.state,n.recording.server=this.getPeerListSFURecording(t),n.recording.browser=this.getPeerListBrowserRecording(t),n.recording.hls=this.getPeerListHLSRecording(t),n.hls=this.convertHls(i==null?void 0:i.hls),n.sessionId=r,n.startedAt=L(s),(h=this.listener)==null||h.onRoomUpdate("RECORDING_STATE_UPDATED",n)}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;i.variants.push({initialisedAt:L((o=e==null?void 0:e.variants)==null?void 0:o[s].initialised_at),url:""})}),i):(d.w(this.TAG,"on hls - room not present"),i)}updateHLSStatus(e){var r;let t=this.store.getRoom(),i=e.variants&&e.variants.length>0?this.isStreamingRunning(e.variants[0].state):!1;if(!t){d.w(this.TAG,"on hls - room not present");return}e.enabled=i,t.hls=this.convertHls(e),(r=this.listener)==null||r.onRoomUpdate("HLS_STREAMING_STATE_UPDATED",t)}convertHls(e){var r;if(e!=null&&e.variants&&e.variants.length>0?e.variants[0].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})}),i}getHLSRecording(e){var r,s;let t={running:!1},i=this.isRecordingRunning(e==null?void 0:e.state);return(i||(e==null?void 0:e.state)==="paused")&&(t={running:i,singleFilePerLayer:!!((r=e==null?void 0:e.hls_recording)!=null&&r.single_file_per_layer),hlsVod:!!((s=e==null?void 0:e.hls_recording)!=null&&s.hls_vod),startedAt:L(e==null?void 0:e.started_at),initialisedAt:L(e==null?void 0:e.initialised_at),state:e==null?void 0:e.state,error:this.toSdkError(e==null?void 0:e.error)}),t}getPeerListHLSRecording(e){var r,s;let t=e==null?void 0:e.hls;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),initialisedAt:L(t==null?void 0:t.initialised_at),state:t==null?void 0:t.state,singleFilePerLayer:(r=t==null?void 0:t.config)==null?void 0:r.single_file_per_layer,hlsVod:(s=t==null?void 0:t.config)==null?void 0:s.hls_vod}}getPeerListBrowserRecording(e){let t=e==null?void 0:e.browser;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}getPeerListSFURecording(e){let t=e==null?void 0:e.sfu;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}updateRecordingStatus(e){var s;let t=this.store.getRoom(),i=this.isRecordingRunning(e.state);if(!t){d.w(this.TAG,`set recording status running=${i} - room not present`);return}let r;e.type==="sfu"?(t.recording.server={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e.state},r="SERVER_RECORDING_STATE_UPDATED"):e.type==="HLS"?(t.recording.hls=this.getHLSRecording(e),r="RECORDING_STATE_UPDATED"):(t.recording.browser={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e==null?void 0:e.state},r="BROWSER_RECORDING_STATE_UPDATED"),(s=this.listener)==null||s.onRoomUpdate(r,t)}updateRTMPStatus(e){var r,s;let t=this.store.getRoom(),i=this.isStreamingRunning(e.state);if(!t){d.w(this.TAG,"on policy change - room not present");return}if(!i){t.rtmp={running:i,state:e.state,error:this.toSdkError(e.error)},(r=this.listener)==null||r.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t);return}t.rtmp={running:i,startedAt:i?L(e.started_at):void 0,state:e.state,error:this.toSdkError(e.error)},(s=this.listener)==null||s.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t)}toSdkError(e){if(!(e!=null&&e.code))return;let t=e.message||"error in streaming/recording",i=new f(e.code,"ServerErrors","NONE",t,t);return d.e(this.TAG,"error in streaming/recording",i),i}};var Ki=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 qi=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,!r&&o.open){let l=yield this.transport.signal.getWhiteboard({id:e.id});o.token=l.token,o.addr=l.addr,o.permissions=l.permissions}this.store.setWhiteboard(o),(n=this.listener)==null||n.onWhiteboardUpdate(o)})}};var ji=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 Oi(this.store,t,this.transport,this.listener):new tt(this.store,t,this.listener),this.peerManager=new Ui(this.store,this.trackManager,this.listener),this.peerListManager=new xi(this.store,this.peerManager,this.trackManager,this.listener),this.broadcastManager=new _i(this.listener),this.policyChangeManager=new Bi(this.store,t),this.requestManager=new Wi(this.store,this.listener),this.activeSpeakerManager=new Di(this.store,this.listener,this.audioListener),this.connectionQualityManager=new Ni(this.store,this.connectionQualityListener),this.roomUpdateManager=new $i(this.store,this.listener),this.sessionMetadataManager=new Ki(this.store,this.listener),this.pollsManager=new Gi(this.store,this.transport,this.listener),this.whiteboardManager=new qi(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)||d.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){d.d(this.TAG,`Ignoring sfu notification - ${e}`,{notification:t});return}this.trackManager.handleTrackRemovedPermanently(t);break}case"on-track-layer-update":{this.trackManager.handleTrackLayerUpdate(t);break}case"active-speakers":this.activeSpeakerManager.handleActiveSpeakers(t);break;case"on-connection-quality-update":this.connectionQualityManager.handleQualityUpdate(t);break;case"on-policy-change":this.policyChangeManager.handlePolicyChange(t);break;default:break}}};var Ji=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 Qi=class{constructor(e,t,i="",r="",s="https://prod-init.100ms.live/init",o=!1){this.authToken=e;this.peerId=t;this.peerName=i;this.data=r;this.endpoint=s;this.autoSubscribeVideo=o}};var K=(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))(K||{}),xa={0:[],1:[],2:[1],3:[1],4:[1]};var zi=(n=>(n.Disconnected="Disconnected",n.Connecting="Connecting",n.Joined="Joined",n.Preview="Preview",n.Failed="Failed",n.Reconnecting="Reconnecting",n.Leaving="Leaving",n))(zi||{});var Yi=class{constructor(e){this.promise=new Promise((t,i)=>{this.resolve=t,this.reject=i,e(t,i)})}};var Xi=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,maxFailedRetries:s=5,changeState:o=!0}){yield this.scheduleTask({category:e,error:t,changeState:o,task:i,originalState:r,maxFailedRetries:s})})}reset(){this.retryTaskIds.forEach(e=>clearTimeout(e)),this.retryTaskIds=[],this.inProgress.clear()}isTaskInProgress(e){return!!this.inProgress.get(e)}scheduleTask(l){return c(this,arguments,function*({category:e,error:t,changeState:i,task:r,originalState:s,maxFailedRetries:o=5,failedRetryCount:n=0}){if(d.d(this.TAG,"schedule: ",{category:K[e],error:t}),n===0){let T=this.inProgress.get(e);if(T){d.d(this.TAG,`schedule: Already a task for ${K[e]} scheduled, waiting for its completion`),yield T.promise;return}let P=new Yi((A,D)=>{});this.inProgress.set(e,P),this.sendEvent(t,e)}let u=!1,p=xa[e];for(let T in p){let P=p[parseInt(T)];try{let A=this.inProgress.get(P);A&&(d.d(this.TAG,`schedule: Suspending retry task of ${K[e]}, waiting for ${K[P]} to recover`),yield A.promise,d.d(this.TAG,`schedule: Resuming retry task ${K[e]} as it's dependency ${K[P]} is recovered`))}catch(A){d.d(this.TAG,`schedule: Stopping retry task of ${K[e]} as it's dependency ${K[P]} failed to recover`),u=!0;break}}if(n>=o||u){if(t.description+=`. [${K[e]}] Could not recover after ${n} tries`,u&&(t.description+=` Could not recover all of it's required dependencies - [${p.map(T=>K[T]).toString()}]`),t.isTerminal=!0,this.inProgress.delete(e),this.sendEvent(t,e),this.reset(),i)this.onStateChange("Failed",t);else throw t;return}i&&this.onStateChange("Reconnecting",t);let h=this.getDelayForRetryCount(e,n);d.d(this.TAG,`schedule: [${K[e]}] [failedRetryCount=${n}] Scheduling retry task in ${h}ms`);let g;try{g=yield this.setTimeoutPromise(r,h)}catch(T){g=!1,d.w(this.TAG,`[${K[e]}] Un-caught exception ${T.name} in retry-task, initiating retry`,T)}if(g){let T=this.inProgress.get(e);this.inProgress.delete(e),T==null||T.resolve(n),i&&this.inProgress.size===0&&this.onStateChange(s),d.d(this.TAG,`schedule: [${K[e]}] [failedRetryCount=${n}] Recovered \u267B\uFE0F`)}else yield this.scheduleTask({category:e,error:t,changeState:i,task:r,originalState:s,maxFailedRetries:o,failedRetryCount:n+1})})}getBaseDelayForTask(e,t){return e===2?2:Math.pow(2,t)}getDelayForRetryCount(e,t){let i=this.getBaseDelayForTask(e,t),r=e===2?Math.random()*2:Math.random();return Math.round(Math.min(i+r,60)*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 Zi=class extends be{constructor(){super(100);this.localStorage=new le("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 R(i);super.enqueue(r)})}};var er=class{constructor(){this.TAG="[AnalyticsTransport]"}sendEvent(e){try{this.sendSingleEvent(e),this.flushFailedEvents()}catch(t){d.w(this.TAG,"sendEvent failed",t)}}flushFailedEvents(e){var t;try{for(d.d(this.TAG,"Flushing failed events",this.failedEvents);this.failedEvents.size()>0;){let i=this.failedEvents.dequeue();i&&(((t=i.metadata)==null?void 0:t.peer.peer_id)===e||!i.metadata.peer.peer_id?this.sendSingleEvent(i):fe.sendEvent(i))}}catch(i){d.w(this.TAG,"flushFailedEvents failed",i)}}sendSingleEvent(e){try{this.transportProvider.sendEvent(e),d.d(this.TAG,"Sent event",e.name,e)}catch(t){throw d.w(this.TAG,`${this.transportProvider.TAG}.sendEvent failed, adding to local storage events`,{event:e,error:t}),this.failedEvents.enqueue(e),t}}};var tr=class extends er{constructor(t){super();this.transportProvider=t;this.failedEvents=new Zi}};var it=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=>d.e("[StatsAnanlytics]",e.message)))}startLoop(){return c(this,null,function*(){for(;this.shouldSendEvent;)yield z(this.pushInterval*1e3),this.sendEvent()})}sendEvent(){this.trackAnalytics.forEach(e=>{e.clearSamples()})}},rt=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)}},ir=(a,e)=>a&&e&&(a.frameWidth!==e.frameWidth||a.frameHeight!==e.frameHeight),rr=(a,e)=>a&&e&&a.enabled!==e.enabled,Ut=a=>Object.entries(a).filter(([,e])=>e!==void 0).reduce((e,[t,i])=>(e[t]=i,e),{});var Bt=class extends it{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(l=>l.getTrackIDBeingSent()===s);Object.keys(o).forEach(l=>{var T,P,A;let u=o[l];if(!n)return;let p=this.getTrackIdentifier(n.trackId,u),h=v(S({},u),{availableOutgoingBitrate:(P=(T=t.getLocalPeerStats())==null?void 0:T.publish)==null?void 0:P.availableOutgoingBitrate});if(p&&this.trackAnalytics.has(p))(A=this.trackAnalytics.get(p))==null||A.pushTempStat(h);else if(n){let D=new ls({track:n,sampleWindowSize:this.sampleWindowSize,rid:u.rid,ssrc:u.ssrc.toString(),kind:u.kind});D.pushTempStat(h),this.trackAnalytics.set(this.getTrackIdentifier(n.trackId,u),D)}let g=this.trackAnalytics.get(p);g!=null&&g.shouldCreateSample()&&(i=!0)})}),this.trackAnalytics.forEach(s=>{!this.store.hasTrack(s.track)&&!(s.samples.length>0)&&this.trackAnalytics.delete(s.track_id)}),i&&this.trackAnalytics.forEach(s=>{s.createSample()})}getTrackIdentifier(t,i){return i.rid?`${t}:${i.rid}`:t}},ls=class extends rt{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,l=this.calculateAverage("roundTripTime",!1),u=l?Math.round(l*1e3):void 0;return Ut({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.calculateDifferenceForSample("packetsLost"),total_packets_sent:this.calculateDifferenceForSample("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||rr(i,r)||i.kind==="video"&&ir(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}};var Vt=class extends it{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 h;let o=i[s],n=this.store.getTrackById(s),l=o.jitterBufferDelay&&o.jitterBufferEmittedCount&&o.jitterBufferDelay/o.jitterBufferEmittedCount,u=this.calculateAvSyncForStat(o,t);if(this.trackAnalytics.has(s))(h=this.trackAnalytics.get(s))==null||h.pushTempStat(v(S({},o),{calculatedJitterBufferDelay:l,avSync:u}));else if(n){let g=new ps({track:n,sampleWindowSize:this.sampleWindowSize,ssrc:o.ssrc.toString(),kind:o.kind});g.pushTempStat(v(S({},o),{calculatedJitterBufferDelay:l,avSync:u})),this.trackAnalytics.set(s,g)}let p=this.trackAnalytics.get(s);p!=null&&p.shouldCreateSample()&&(r=!0)}),this.trackAnalytics.forEach(s=>{!this.store.hasTrack(s.track)&&!(s.samples.length>0)&&this.trackAnalytics.delete(s.track_id)}),r&&this.trackAnalytics.forEach(s=>{s.createSample()})}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 Mt;let l=i.getRemoteTrackStats(s.trackId);if(!l)return Mt;if(l.estimatedPlayoutTimestamp)return l.estimatedPlayoutTimestamp-t.estimatedPlayoutTimestamp}},ps=class extends rt{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 Ut(v(S({},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"),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 Ut(v(S({},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||rr(i,r)||i.kind==="video"&&ir(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!==Mt);return i.length===0?Mt:i.reduce((r,s)=>r+s,0)/i.length}};var ar=(t=>(t[t.Publish=0]="Publish",t[t.Subscribe=1]="Subscribe",t))(ar||{});var Ft=Ce(require("sdp-transform"));function Ua(a,e){var r;let t=Ft.parse(a.sdp);if(!((r=t.origin)!=null&&r.username.startsWith("mozilla")))return a;let i=e?Array.from(e.values()):[];return t.media.forEach(s=>{var l,u,p;let o=(l=s.msid)==null?void 0:l.split(" ")[0],n=(u=i.find(h=>h.type===s.type&&h.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:Ft.write(t)}}function Ba(a,e){var s;if(!(a!=null&&a.sdp)||!e)return;let i=Ft.parse(a.sdp).media.find(o=>se(o.mid)&&parseInt(o.mid)===parseInt(e));return(s=i==null?void 0:i.msid)==null?void 0:s.split(" ")[1]}function Va(a){return a.sdp.includes("usedtx=1")?a:{type:a.type,sdp:a.sdp.replace("useinbandfec=1","useinbandfec=1;usedtx=1")}}var ve="[HMSConnection]",Ue=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"}addTransceiver(e,t){return this.nativeConnection.addTransceiver(e,t)}createOffer(e,t){return c(this,null,function*(){try{let i=yield this.nativeConnection.createOffer(t);return d.d(ve,`[role=${this.role}] createOffer offer=${JSON.stringify(i,null,1)}`),Va(Ua(i,e))}catch(i){throw m.WebrtcErrors.CreateOfferFailed(this.action,i.message)}})}createAnswer(e=void 0){return c(this,null,function*(){try{let t=yield this.nativeConnection.createAnswer(e);return d.d(ve,`[role=${this.role}] createAnswer answer=${JSON.stringify(t,null,1)}`),t}catch(t){throw m.WebrtcErrors.CreateAnswerFailed(this.action,t.message)}})}setLocalDescription(e){return c(this,null,function*(){try{d.d(ve,`[role=${this.role}] setLocalDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setLocalDescription(e)}catch(t){throw m.WebrtcErrors.SetLocalDescriptionFailed(this.action,t.message)}})}setRemoteDescription(e){return c(this,null,function*(){try{d.d(ve,`[role=${this.role}] setRemoteDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setRemoteDescription(e)}catch(t){throw m.WebrtcErrors.SetRemoteDescriptionFailed(this.action,t.message)}})}addIceCandidate(e){return c(this,null,function*(){if(this.nativeConnection.signalingState==="closed"){d.d(ve,`[role=${this.role}] addIceCandidate signalling state closed`);return}d.d(ve,`[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()}logSelectedIceCandidatePairs(){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(),d.d(ve,`${ar[this.role]} connection`,`selected ${i||"unknown"} candidate pair`,JSON.stringify(this.selectedCandidatePair,null,2)))};typeof s.onselectedcandidatepairchange=="function"&&(s.onselectedcandidatepairchange=o),o()}})}catch(e){d.w(ve,`Error in logging selected ice candidate pair for ${ar[this.role]} connection`,e)}}removeTrack(e){this.nativeConnection.signalingState!=="closed"&&this.nativeConnection.removeTrack(e)}setMaxBitrateAndFramerate(e){return c(this,null,function*(){let t=e.settings.maxBitrate,i=e instanceof B&&e.settings.maxFramerate,r=this.getSenders().find(s=>{var o;return((o=s==null?void 0:s.track)==null?void 0:o.id)===e.getTrackIDBeingSent()});if(r){let s=r.getParameters();s.encodings.length===1&&(t&&(s.encodings[0].maxBitrate=t*1e3),i&&(s.encodings[0].maxFramerate=i)),yield r.setParameters(s)}else d.w(ve,`no sender found to setMaxBitrate for track - ${e.trackId}, sentTrackId - ${e.getTrackIDBeingSent()}`)})}getStats(){return c(this,null,function*(){return yield this.nativeConnection.getStats()})}close(){return c(this,null,function*(){this.nativeConnection.close()})}getReceivers(){return this.nativeConnection.getReceivers()}};var Gt=class extends Ue{constructor(t,i,r){super(0,t);this.TAG="[HMSPublishConnection]";this.observer=r,this.nativeConnection=new RTCPeerConnection(i),this.channel=this.nativeConnection.createDataChannel(pi,{protocol:"SCTP"}),this.channel.onerror=s=>d.e(this.TAG,`publish data channel onerror ${s}`,s),this.nativeConnection.onicecandidate=({candidate:s})=>{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")})}}initAfterJoin(){this.nativeConnection.onnegotiationneeded=()=>c(this,null,function*(){d.d(this.TAG,"onnegotiationneeded"),yield this.observer.onRenegotiationNeeded()})}};var Fa=Ce(require("eventemitter2")),Ga=require("uuid");var Wt=class{constructor(e,t,i=""){this.TAG="[HMSDataChannel]";this.nativeChannel=e,this.observer=t,this.metadata=i,e.onmessage=r=>{this.observer.onMessage(r.data)}}get id(){return this.nativeChannel.id}get label(){return this.nativeChannel.label}get readyState(){return this.nativeChannel.readyState}send(e){d.d(this.TAG,`[${this.metadata}] Sending [size=${e.length}] message=${e}`),this.nativeChannel.send(e)}close(){this.nativeChannel.close()}};var $t=class a extends Ue{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 Fa.default({maxListeners:60});this.handlePendingApiMessages=()=>{this.eventEmitter.emit("open",!0),this.pendingMessageQueue.length>0&&(d.d(this.TAG,"Found pending message queue, sending messages"),this.pendingMessageQueue.forEach(t=>this.sendOverApiDataChannel(t)),this.pendingMessageQueue.length=0)};this.sendMessage=(t,i)=>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){d.d(this.TAG,`Track not found ${i}`,{request:t,try:o+1,error:n});break}if(d.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 Ae(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 d.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===pi&&(this.apiChannel=new Wt(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.signal.trickle(this.role,t.candidate)},this.nativeConnection.ontrack=t=>{var u;let i=t.streams[0],r=i.id;if(!this.remoteStreams.has(r)){let p=new Se(i,this);this.remoteStreams.set(r,p)}i.addEventListener("removetrack",p=>{if(p.track.id!==t.track.id)return;let h=s.tracks.findIndex(g=>{var T;return g.nativeTrack.id===p.track.id&&t.transceiver.mid===((T=g.transceiver)==null?void 0:T.mid)});if(h>=0){let g=s.tracks[h];this.observer.onTrackRemove(g),s.tracks.splice(h,1),s.tracks.length===0&&this.remoteStreams.delete(r)}});let s=this.remoteStreams.get(r),o=t.track.kind==="audio"?te:O,n=new o(s,t.track);t.track.kind==="video"&&s.setVideoLayerLocally("none","addTrack","subscribeConnection"),n.transceiver=t.transceiver;let l=Ba(this.remoteDescription,(u=t.transceiver)==null?void 0:u.mid);l&&n.setSdpTrackId(l),s.tracks.push(n),this.observer.onTrackAdd(n)}}sendOverApiDataChannel(t){this.apiChannel&&this.apiChannel.readyState==="open"?this.apiChannel.send(t):(d.w(this.TAG,`API Data channel not ${this.apiChannel?"open":"present"}, queueing`,t),this.pendingMessageQueue.push(t))}sendOverApiDataChannelWithResponse(t,i){return c(this,null,function*(){let r=(0,Ga.v4)();if(t.method==="prefer-video-track-state"&&this.isFlagEnabled("disableVideoTrackAutoUnsubscribe")&&t.params.max_spatial_layer==="none")return d.d(this.TAG,"video auto unsubscribe is disabled, request is ignored"),{id:r};let s=JSON.stringify(S({id:i||r,jsonrpc:"2.0"},t));return this.sendMessage(s,r)})}close(){return c(this,null,function*(){var t;yield q(a.prototype,this,"close").call(this),(t=this.apiChannel)==null||t.close()})}};var or="[InitService]",Kt=class{static handleError(e,t){switch(e.status){case 404:throw m.APIErrors.EndpointUnreachable("INIT",t.message||e.statusText);case 200:break;default:throw m.APIErrors.ServerErrors(t.code||e.status,"INIT",t.message||(e==null?void 0:e.statusText))}}static fetchInitConfig(o){return c(this,arguments,function*({token:e,peerId:t,userAgent:i,initEndpoint:r="https://prod-init.100ms.live",region:s=""}){d.d(or,`fetchInitConfig: initEndpoint=${r} token=${e} peerId=${t} region=${s} `);let n=kc(r,t,i,s);try{let l=yield fetch(n,{headers:{Authorization:`Bearer ${e}`}});try{let u=yield l.clone().json();return this.handleError(l,u),d.d(or,`config is ${JSON.stringify(u,null,2)}`),Pc(u)}catch(u){let p=yield l.text();throw d.e(or,"json error",u.message,p),m.APIErrors.ServerErrors(l.status,"INIT",p)}}catch(l){let u=l;throw["Failed to fetch","NetworkError","ECONNRESET"].some(p=>u.message.includes(p))?m.APIErrors.EndpointUnreachable("INIT",u.message):u}})}};function kc(a,e,t,i){try{let r=new URL("/init",a);return i&&i.trim().length>0&&r.searchParams.set("region",i.trim()),r.searchParams.set("peer_id",e),r.searchParams.set("user_agent_v2",t),r.toString()}catch(r){let s=r;throw d.e(or,s.name,s.message),s}}function Pc(a){var e;return v(S({},a),{rtcConfiguration:v(S({},a.rtcConfiguration),{iceServers:(e=a.rtcConfiguration)==null?void 0:e.ice_servers})})}var Wa=require("uuid");var qt=class{constructor(e){this.TAG="[SIGNAL]: ";this.pongResponseTimes=new be(5);this.isJoinCompleted=!1;this.pendingTrickle=[];this.socket=null;this.callbacks=new Map;this._isConnected=!1;this.id=0;this.onCloseHandler=()=>{};this.resolvePingOnAnyResponse=()=>{this.callbacks.forEach((e,t)=>{var i;((i=e.metadata)==null?void 0:i.method)==="ping"&&(e.resolve({timestamp:Date.now()}),this.callbacks.delete(t))})};this.offlineListener=()=>{d.d(this.TAG,"Window network offline"),this.setIsConnected(!1,"Window network offline")};this.onlineListener=()=>{d.d(this.TAG,"Window network online"),this.observer.onNetworkOnline()};this.observer=e,window.addEventListener("offline",this.offlineListener),window.addEventListener("online",this.onlineListener),this.onMessageHandler=this.onMessageHandler.bind(this)}get isConnected(){return this._isConnected}setIsConnected(e,t=""){d.d(this.TAG,`isConnected set id: ${this.id}, oldValue: ${this._isConnected}, newValue: ${e}`),this._isConnected!==e&&(this._isConnected&&!e?(this._isConnected=e,this.rejectPendingCalls(t),this.observer.onOffline(t)):!this._isConnected&&e&&(this._isConnected=e,this.observer.onOnline()))}getPongResponseTimes(){return this.pongResponseTimes.toList()}internalCall(e,t){return c(this,null,function*(){var s;let i=(0,Wa.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,l)=>{this.callbacks.set(i,{resolve:n,reject:l,metadata:{method:e}})})}catch(o){if(o instanceof f)throw o;let n=o;throw m.WebsocketMethodErrors.ServerErrors(Number(n.code),Rr(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=()=>{d.e(this.TAG,"Error from websocket"),r=!0,i(m.WebSocketConnectionErrors.FailedToConnect("JOIN","Error opening websocket connection"))};this.onCloseHandler=n=>{d.w(`Websocket closed code=${n.code}`),r?this.setIsConnected(!1,`code: ${n.code}${n.code!==1e3?", unexpected websocket close":""}`):(r=!0,i(m.WebSocketConnectionErrors.AbnormalClose("JOIN",`Error opening websocket connection - websocket closed unexpectedly with code=${n.code}`)))},this.socket.addEventListener("error",s);let o=()=>{var n,l;r=!0,t(),this.setIsConnected(!0),this.id++,(n=this.socket)==null||n.removeEventListener("open",o),(l=this.socket)==null||l.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 m.WebSocketConnectionErrors.WebSocketConnectionLost("JOIN","Failed to send join over WS connection");let l={name:e,disableVidAutoSub:i,data:t,offer:n,server_sub_degrade:r,simulcast:s,onDemandTracks:o},u=yield this.internalCall("join",l);return this.isJoinCompleted=!0,this.pendingTrickle.forEach(({target:p,candidate:h})=>this.trickle(p,h)),this.pendingTrickle.length=0,d.d(this.TAG,`join: response=${JSON.stringify(u,null,1)}`),u})}trickle(e,t){this.isJoinCompleted?this.notify("trickle",{target:e,candidate:t}):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)})})}answer(e){this.notify("answer",{desc:e})}trackUpdate(e){this.notify("track-update",{tracks:Object.fromEntries(e)})}broadcast(e){return c(this,null,function*(){return yield this.call("broadcast",e)})}leave(){this.notify("leave",{})}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",S({},e))})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.call("rtmp-stop",{})})}startHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-start",S({},e))})}stopHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-stop",S({},e))})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.call("hls-timed-metadata",S({},e))})}updatePeer(e){return c(this,null,function*(){yield this.call("peer-update",S({},e))})}getPeer(e){return c(this,null,function*(){yield this.call("get-peer",S({},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)})}setSessionMetadata(e){if(!this.isConnected)throw m.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("set-metadata",S({},e))}listenMetadataChange(e){if(!this.isConnected)throw m.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 m.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",S({},e))}getPollInfo(e){return this.call("poll-info-get",S({},e))}setPollQuestions(e){return this.call("poll-questions-set",S({},e))}startPoll(e){return this.call("poll-start",S({},e))}stopPoll(e){return this.call("poll-stop",S({},e))}getPollQuestions(e){return this.call("poll-questions-get",S({},e))}setPollResponses(e){return this.call("poll-response",S({},e))}getPollResponses(e){return this.call("poll-responses",S({},e))}getPollsList(e){return this.call("poll-list",S({},e))}getPollResult(e){return this.call("poll-result",S({},e))}createWhiteboard(e){return this.validateConnection(),this.call("whiteboard-create",S({},e))}getWhiteboard(e){return this.validateConnection(),this.call("whiteboard-get",S({},e))}fetchPollLeaderboard(e){return this.call("poll-leaderboard",S({},e))}validateConnection(){if(!this.isConnected)throw m.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(m.WebsocketMethodErrors.ServerErrors(Number(e.params.code),"on-error",e.params.message));break;case"on-warning":d.w(this.TAG,e.params);break;default:this.observer.onNotification(e);break}}rejectPendingCalls(e=""){this.callbacks.forEach((t,i)=>{var r,s,o,n;((r=t.metadata)==null?void 0:r.method)!=="ping"&&(d.e(this.TAG,`rejecting pending callback ${(s=t.metadata)==null?void 0:s.method}, id=${i}`),t.reject(m.WebSocketConnectionErrors.WebSocketConnectionLost((o=t.metadata)!=null&&o.method?Rr((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?(d.d(this.TAG,`Pong timeout ${e}, pageHidden=${Vs()}`),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=m.WebsocketMethodErrors.ServerErrors(500,e,`Default ${e} error`);this.validateConnection();let s;for(s=1;s<=3;s++)try{return d.d(this.TAG,`Try number ${s} sending ${e}`,t),yield this.internalCall(e,t)}catch(o){if(r=o,d.e(this.TAG,`Failed sending ${e} try: ${s}`,{method:e,params:t,error:r}),!(parseInt(`${r.code/100}`)===5||r.code===429))break;let l=(2+Math.random()*2)*1e3;yield Ae(l)}throw d.e(`Sending ${e} over WS failed after ${Math.min(s,3)} retries`,{method:e,params:t,error:r}),r})}};var $a=()=>{if(!_||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 b="[HMSTransport]:",jt=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.callbacks=new Map;this.signalObserver={onOffer:e=>c(this,null,function*(){try{if(!this.subscribeConnection)return;yield this.subscribeConnection.setRemoteDescription(e),d.d(b,`[SUBSCRIBE] Adding ${this.subscribeConnection.candidates.length} ice-candidates`,this.subscribeConnection.candidates);for(let i of this.subscribeConnection.candidates)yield this.subscribeConnection.addIceCandidate(i);this.subscribeConnection.candidates.length=0;let t=yield this.subscribeConnection.createAnswer();yield this.subscribeConnection.setLocalDescription(t),this.signal.answer(t),d.d(b,"[role=SUBSCRIBE] onOffer renegotiation DONE \u2705")}catch(t){d.d(b,"[role=SUBSCRIBE] onOffer renegotiation FAILED \u274C",t),this.state="Failed";let i;t instanceof f?i=t:i=m.GenericErrors.Unknown("PUBLISH",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*(){d.d(b,"socket offline",zi[this.state]);try{this.state!=="Leaving"&&this.joinParameters&&this.retryScheduler.schedule({category:1,error:m.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL",e),task:this.retrySignalDisconnectTask,originalState:this.state})}catch(t){console.error(t)}}),onOnline:()=>{var e;d.d(b,"socket online",zi[this.state]),this.analyticsSignalTransport.flushFailedEvents((e=this.store.getLocalPeer())==null?void 0:e.peerId)},onNetworkOnline:()=>{this.analyticsEventsService.flushFailedClientEvents()}};this.signal=new qt(this.signalObserver);this.analyticsSignalTransport=new tr(this.signal);this.publishDtlsStateTimer=0;this.lastPublishDtlsState="new";this.publishConnectionObserver={onRenegotiationNeeded:()=>c(this,null,function*(){yield this.performPublishRenegotiation()}),onDTLSTransportStateChange:e=>{var r,s,o;if((e==="failed"?d.w.bind(d):d.d.bind(d))(b,`Publisher on dtls transport state change: ${e}`),!e||this.lastPublishDtlsState===e||(this.lastPublishDtlsState=e,this.publishDtlsStateTimer!==0&&(clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0),e!=="connecting"&&e!=="failed"))return;let i=(o=(s=(r=this.initConfig)==null?void 0:r.config)==null?void 0:s.dtlsStateTimeouts)==null?void 0:o[e];!i||i<=0||(this.publishDtlsStateTimer=window.setTimeout(()=>{var l;let n=(l=this.publishConnection)==null?void 0:l.nativeConnection.connectionState;if(n&&e&&n===e){let u=m.WebrtcErrors.ICEFailure("PUBLISH",`DTLS transport state ${e} timeout:${i}ms`,!0);this.eventBus.analytics.publish(y.disconnect(u)),this.observer.onFailure(u)}},i))},onDTLSTransportError:e=>{d.e(b,`onDTLSTransportError ${e.name} ${e.message}`,e),this.eventBus.analytics.publish(y.disconnect(e))},onIceConnectionChange:e=>c(this,null,function*(){(e==="disconnected"?d.w.bind(d):d.d.bind(d))(b,`Publish ice connection state change: ${e}`)}),onConnectionStateChange:e=>c(this,null,function*(){var i,r,s,o,n;(e==="disconnected"?d.w.bind(d):d.d.bind(d))(b,`Publish connection state change: ${e}`),e==="connected"&&((i=this.publishConnection)==null||i.logSelectedIceCandidatePairs()),e==="disconnected"&&setTimeout(()=>{var l,u,p,h,g;((l=this.publishConnection)==null?void 0:l.connectionState)==="disconnected"&&this.handleIceConnectionFailure(0,m.WebrtcErrors.ICEDisconnected("PUBLISH",`local candidate - ${(p=(u=this.publishConnection)==null?void 0:u.selectedCandidatePair)==null?void 0:p.local.candidate}; remote candidate - ${(g=(h=this.publishConnection)==null?void 0:h.selectedCandidatePair)==null?void 0:g.remote.candidate}`))},5e3),e==="failed"&&(yield this.handleIceConnectionFailure(0,m.WebrtcErrors.ICEFailure("PUBLISH",`local candidate - ${(s=(r=this.publishConnection)==null?void 0:r.selectedCandidatePair)==null?void 0:s.local.candidate}; remote candidate - ${(n=(o=this.publishConnection)==null?void 0:o.selectedCandidatePair)==null?void 0:n.remote.candidate}`)))})};this.subscribeConnectionObserver={onApiChannelMessage:e=>{this.observer.onNotification(JSON.parse(e))},onTrackAdd:e=>{d.d(b,"[Subscribe] onTrackAdd",`${e}`),this.observer.onTrackAdd(e)},onTrackRemove:e=>{d.d(b,"[Subscribe] onTrackRemove",`${e}`),this.observer.onTrackRemove(e)},onIceConnectionChange:e=>c(this,null,function*(){if((e==="disconnected"?d.w.bind(d):d.d.bind(d))(b,`Subscribe ice connection state change: ${e}`),e==="connected"){let i=this.callbacks.get(ze);this.callbacks.delete(ze),i&&i.promise.resolve(!0)}}),onConnectionStateChange:e=>c(this,null,function*(){var i,r,s,o;(e==="disconnected"?d.w.bind(d):d.d.bind(d))(b,`Subscribe connection state change: ${e}`),e==="failed"&&(yield this.handleIceConnectionFailure(1,m.WebrtcErrors.ICEFailure("SUBSCRIBE",`local candidate - ${(r=(i=this.subscribeConnection)==null?void 0:i.selectedCandidatePair)==null?void 0:r.local.candidate}; remote candidate - ${(o=(s=this.subscribeConnection)==null?void 0:s.selectedCandidatePair)==null?void 0:o.remote.candidate}`))),e==="disconnected"&&setTimeout(()=>{var n,l,u,p,h;((n=this.subscribeConnection)==null?void 0:n.connectionState)==="disconnected"&&this.handleIceConnectionFailure(1,m.WebrtcErrors.ICEDisconnected("SUBSCRIBE",`local candidate - ${(u=(l=this.subscribeConnection)==null?void 0:l.selectedCandidatePair)==null?void 0:u.local.candidate}; remote candidate - ${(h=(p=this.subscribeConnection)==null?void 0:p.selectedCandidatePair)==null?void 0:h.remote.candidate}`))},5e3),e==="connected"&&this.handleSubscribeConnectionConnected()})};this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){!this.doesRoleNeedWebRTC(e)&&this.doesRoleNeedWebRTC(t)&&(d.d(b,"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(Qe,{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(ze,{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;d.d(b,"retrySignalDisconnectTask",{signalConnected:this.signal.isConnected}),this.signal.isConnected||(yield this.internalConnect(this.joinParameters.authToken,this.joinParameters.endpoint,this.joinParameters.peerId));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});var u,p;this.webrtcInternals=new mi(this.store,this.eventBus,(u=this.publishConnection)==null?void 0:u.nativeConnection,(p=this.subscribeConnection)==null?void 0:p.nativeConnection);let l=(h,g)=>c(this,null,function*(){h!==this.state&&(this.state=h,yield this.observer.onStateChange(this.state,g))});this.retryScheduler=new Xi(l,this.sendErrorAnalyticsEvent.bind(this)),this.eventBus.statsUpdate.subscribe(h=>{var T,P;let g=((P=(T=h.getLocalPeerStats())==null?void 0:T.subscribe)==null?void 0:P.bitrate)||0;this.maxSubscribeBitrate=Math.max(this.maxSubscribeBitrate,g)}),this.eventBus.localAudioEnabled.subscribe(({track:h})=>this.trackUpdate(h)),this.eventBus.localVideoEnabled.subscribe(({track:h})=>this.trackUpdate(h))}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)}preview(e,t,i,r,s=!1){return c(this,null,function*(){let o=yield this.connect(e,t,i,r,s);return this.state="Preview",this.observer.onStateChange(this.state),o})}join(e,t,i,r,s=!1){return c(this,null,function*(){d.d(b,"join: started \u23F0");try{(!this.signal.isConnected||!this.initConfig)&&(yield this.connect(e,r,t,i,s)),this.validateNotDisconnected("connect"),this.initConfig&&(yield this.waitForLocalRoleAvailability(),yield this.createConnectionsAndNegotiateJoin(i,s),yield this.initRtcStatsMonitor(),d.d(b,"\u2705 join: Negotiated over PUBLISH connection"))}catch(o){d.e(b,`join: failed \u274C [token=${e}]`,o),this.state="Failed";let n=o;throw n.isTerminal=n.isTerminal||n.code===500,yield this.observer.onStateChange(this.state,n),n}d.d(b,"\u2705 join: successful"),this.state="Joined",this.observer.onStateChange(this.state)})}connect(e,t,i,r,s=!1){return c(this,null,function*(){this.setTransportStateForConnect(),this.joinParameters=new Qi(e,i,r.name,r.metaData,t,s);try{return yield this.internalConnect(e,t,i)}catch(o){if(o instanceof f&&([M.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,M.WebSocketConnectionErrors.FAILED_TO_CONNECT,M.WebSocketConnectionErrors.ABNORMAL_CLOSE,M.APIErrors.ENDPOINT_UNREACHABLE].includes(o.code)||o.code.toString().startsWith("5")||o.code.toString().startsWith("429"))){let l=()=>c(this,null,function*(){return yield this.internalConnect(e,t,i),!!(this.initConfig&&this.initConfig.endpoint)});yield this.retryScheduler.schedule({category:0,error:o,task:l,originalState:this.state,maxFailedRetries:5,changeState:!1})}else throw o}})}leave(e){return c(this,null,function*(){var t,i,r,s,o;this.retryScheduler.reset(),this.joinParameters=void 0,d.d(b,"leaving in transport");try{let n=this.pluginUsageTracker.getPluginUsage("HMSKrispPlugin");if(n&&this.eventBus.analytics.publish(y.getKrispUsage(n)),this.state="Leaving",(t=this.publishStatsAnalytics)==null||t.stop(),(i=this.subscribeStatsAnalytics)==null||i.stop(),(r=this.webrtcInternals)==null||r.cleanup(),yield(s=this.publishConnection)==null?void 0:s.close(),yield(o=this.subscribeConnection)==null?void 0:o.close(),e)try{this.signal.leave(),d.d(b,"signal leave done")}catch(l){d.w(b,"failed to send leave on websocket to server",l)}this.analyticsEventsService.flushFailedClientEvents(),this.analyticsEventsService.reset(),yield this.signal.close()}catch(n){this.eventBus.analytics.publish(y.disconnect(n)),d.e(b,"leave: FAILED \u274C",n)}finally{this.state="Disconnected",this.observer.onStateChange(this.state)}})}publish(e){return c(this,null,function*(){for(let t of e)try{yield this.publishTrack(t)}catch(i){this.eventBus.analytics.publish(y.publish({devices:this.deviceManager.getDevices(),error:i}))}})}unpublish(e){return c(this,null,function*(){for(let t of e)yield this.unpublishTrack(t)})}trackUpdate(e){let i=Array.from(this.trackStates.values()).find(r=>e.type===r.type&&e.source===r.source);if(i){let r=new Ot(v(S({},i),{mute:!e.enabled}));this.trackStates.set(i.track_id,r),d.d(b,"Track Update",this.trackStates,e),this.signal.trackUpdate(new Map([[i.track_id,r]]))}}publishTrack(e){return c(this,null,function*(){e.publishedTrackId=e.getTrackIDBeingSent(),d.d(b,`\u23F3 publishTrack: trackId=${e.trackId}, toPublishTrackId=${e.publishedTrackId}`,`${e}`),this.trackStates.set(e.publishedTrackId,new Ot(e));let t=new Promise((s,o)=>{this.callbacks.set(Qe,{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),d.time(`publish-${e.trackId}-${e.type}`),yield t,d.timeEnd(`publish-${e.trackId}-${e.type}`),this.store.addTrack(e),yield i.setMaxBitrateAndFramerate(e).then(()=>{d.d(b,`Setting maxBitrate=${e.settings.maxBitrate} kpbs${e instanceof B?` and maxFramerate=${e.settings.maxFramerate}`:""} for ${e.source} ${e.type} ${e.trackId}`)}).catch(s=>d.w(b,"Failed setting maxBitrate and maxFramerate",s)),e.isPublished=!0,d.d(b,`\u2705 publishTrack: trackId=${e.trackId}`,`${e}`,this.callbacks)})}unpublishTrack(e){return c(this,null,function*(){if(d.d(b,`\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(Qe,{promise:{resolve:r,reject:s},action:"UNPUBLISH",extra:{}})});e.stream.removeSender(e),yield t,yield e.cleanup(),this.store.removeTrack(e),d.d(b,`\u2705 unpublishTrack: trackId=${e.trackId}`,this.callbacks)})}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(){this.initConfig&&(this.publishConnection||(this.publishConnection=new Gt(this.signal,this.initConfig.rtcConfiguration,this.publishConnectionObserver)),this.subscribeConnection||(this.subscribeConnection=new $t(this.signal,this.initConfig.rtcConfiguration,this.isFlagEnabled.bind(this),this.subscribeConnectionObserver)))}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){d.e(b,"Join negotiation failed \u274C",o);let n=o instanceof f?o:m.WebsocketMethodErrors.ServerErrors(500,"JOIN",`Websocket join error - ${o.message}`),l=parseInt(`${n.code/100}`)===5||[M.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,429].includes(n.code);if(n.code===410&&(n.isTerminal=!0),l){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",maxFailedRetries:3,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(d.d(b,"\u23F3 join: Negotiating over PUBLISH connection"),!this.publishConnection)return d.e(b,"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"),l=this.isFlagEnabled("onDemandTracks"),u=yield this.signal.join(e,t,!i,o,n,l,s);yield this.publishConnection.setRemoteDescription(u);for(let p of this.publishConnection.candidates)yield this.publishConnection.addIceCandidate(p);return this.publishConnection.initAfterJoin(),!!u})}negotiateJoinNonWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){d.d(b,"\u23F3 join: Negotiating Non-WebRTC");let s=this.isFlagEnabled("subscribeDegradation"),o=this.isFlagEnabled("simulcast"),n=this.isFlagEnabled("onDemandTracks");return!!(yield this.signal.join(e,t,!i,s,o,n))})}negotiateOnFirstPublish(){return c(this,null,function*(){if(d.d(b,"\u23F3 Negotiating offer over PUBLISH connection"),!this.publishConnection)return d.e(b,"Publish peer connection not found, cannot negotiate"),!1;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})}performPublishRenegotiation(e){return c(this,null,function*(){d.d(b,"\u23F3 [role=PUBLISH] onRenegotiationNeeded START",this.trackStates);let t=this.callbacks.get(Qe);if(t){if(!this.publishConnection){d.e(b,"Publish peer connection not found, cannot renegotiate");return}try{let i=yield this.publishConnection.createOffer(this.trackStates,e);yield this.publishConnection.setLocalDescription(i),d.time("renegotiation-offer-exchange");let r=yield this.signal.offer(i,this.trackStates);this.callbacks.delete(Qe),d.timeEnd("renegotiation-offer-exchange"),yield this.publishConnection.setRemoteDescription(r),t.promise.resolve(!0),d.d(b,"[role=PUBLISH] onRenegotiationNeeded DONE \u2705")}catch(i){let r;i instanceof f?r=i:r=m.GenericErrors.Unknown("PUBLISH",i.message),t.promise.reject(r),d.d(b,"[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",maxFailedRetries:1}))})}internalConnect(e,t,i){return c(this,null,function*(){var s;d.d(b,"connect: started \u23F0");let r=new Date;try{this.analyticsTimer.start("init_response_time"),this.initConfig=yield Kt.fetchInitConfig({token:e,peerId:i,userAgent:this.store.getUserAgent(),initEndpoint:t});let o=this.store.getRoom();return o&&(o.effectsKey=(s=this.initConfig.config.vb)==null?void 0:s.effectsKey,o.isEffectsEnabled=this.isFlagEnabled("effectsSDKEnabled"),o.isHipaaEnabled=this.isFlagEnabled("hipaa"),o.isNoiseCancellationEnabled=this.isFlagEnabled("noiseCancellation")),this.analyticsTimer.end("init_response_time"),fe.setWebsocketEndpoint(this.initConfig.endpoint),this.validateNotDisconnected("post init"),yield this.openSignal(e,i),this.observer.onConnected(),this.store.setSimulcastEnabled(this.isFlagEnabled("simulcast")),d.d(b,"Adding Analytics Transport: JsonRpcSignal"),this.analyticsEventsService.setTransport(this.analyticsSignalTransport),this.analyticsEventsService.flush(),this.initConfig}catch(o){throw this.state!=="Reconnecting"&&this.eventBus.analytics.publish(y.connect(o,this.getAdditionalAnalyticsProperties(),r,new Date,t)),d.e(b,"\u274C internal connect: failed",o),o}})}validateNotDisconnected(e){if(this.state==="Disconnected")throw d.w(b,"aborting join as transport state is disconnected"),m.GenericErrors.ValidationFailed(`leave called before join could complete - stage=${e}`)}openSignal(e,t){return c(this,null,function*(){if(!this.initConfig)throw m.APIErrors.InitConfigNotAvailable("INIT","Init Config not found");d.d(b,"\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",pa),i.searchParams.set("protocol_spec",ha),this.endpoint=i.toString(),this.analyticsTimer.start("ws_connect_time"),yield this.signal.open(this.endpoint),this.analyticsTimer.end("ws_connect_time"),this.analyticsTimer.start("on_policy_change_time"),this.analyticsTimer.start("room_state_time"),d.d(b,"\u2705 internal connect: connected to ws endpoint")})}initRtcStatsMonitor(){return c(this,null,function*(){var e,t,i;(i=this.webrtcInternals)==null||i.setPeerConnections({publish:(e=this.publishConnection)==null?void 0:e.nativeConnection,subscribe:(t=this.subscribeConnection)==null?void 0:t.nativeConnection}),this.initStatsAnalytics()})}initStatsAnalytics(){var e,t;this.isFlagEnabled("publishStats")&&(this.publishStatsAnalytics=new Bt(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 Vt(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}handleSubscribeConnectionConnected(){var t;(t=this.subscribeConnection)==null||t.logSelectedIceCandidatePairs();let e=this.callbacks.get(ze);this.callbacks.delete(ze),e&&e.promise.resolve(!0)}setTransportStateForConnect(){if(this.state==="Failed"&&(this.state="Disconnected"),this.state!=="Disconnected"&&this.state!=="Reconnecting")throw m.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,l,u,p,h,g,T;let e=$a(),t=typeof document!="undefined"&&document.hidden,i=this.store.getRemoteVideoTracks().filter(P=>P.degraded).length,r=(u=(l=(n=(o=this.getWebrtcInternals())==null?void 0:o.getCurrentStats())==null?void 0:n.getLocalPeerStats())==null?void 0:l.publish)==null?void 0:u.bitrate,s=(T=(g=(h=(p=this.getWebrtcInternals())==null?void 0:p.getCurrentStats())==null?void 0:h.getLocalPeerStats())==null?void 0:g.subscribe)==null?void 0:T.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}}};var qa=(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 m.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))?m.APIErrors.EndpointUnreachable("GET_TOKEN",r.message):r});function nr(a){if(!a||a.length===0)throw m.APIErrors.InvalidTokenFormat("INIT","Token cannot be an empty string or undefined or null");let e=a.split(".");if(e.length!==3)throw m.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 m.APIErrors.InvalidTokenFormat("INIT",`couldn't parse to json - ${i.message}`)}}var ja={published:!1,isInitialised:!1,isReconnecting:!1,isPreviewInProgress:!1,isPreviewCalled:!1,isJoinInProgress:!1,deviceManagersInitialised:!1},cr=class{constructor(){this.TAG="[HMSSdk]:";this.transportState="Disconnected";this.analyticsTimer=new li;this.sdkState=S({},ja);this.playlistSettings={video:{bitrate:Wr},audio:{bitrate:$r}};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,l;yield this.internalLeave(!0,o),!this.sdkState.isPreviewInProgress&&!this.sdkState.isJoinInProgress&&((l=(n=this.errorListener)==null?void 0:n.onError)==null||l.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,d.d(this.TAG,"Transport State Change",this.transportState)})};this.handlePeerLeaveRequest=e=>{var r;let t=e.requested_by?this.store.getPeerById(e.requested_by):void 0,i={roomEnded:e.room_end,reason:e.reason,requestedBy:t};(r=this.listener)==null||r.onRemovedFromRoom(i),this.internalLeave(!1)};this.handleDeviceChange=e=>{var i,r;if(e.isUserSelection)return;d.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,l;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),[M.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,M.TracksErrors.DEVICE_IN_USE,M.TracksErrors.DEVICE_NOT_AVAILABLE].includes(e.error.code)&&u&&(u.setEnabled(!1),(l=this.listener)==null||l.onTrackUpdate(2,u,this.localPeer))}})()};this.handleAudioPluginError=e=>{var t;d.e(this.TAG,"Audio Plugin Error event",e),(t=this.errorListener)==null||t.onError(e)};this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){var r;yield this.transport.handleLocalRoleUpdate({oldRole:e,newRole:t}),yield(r=this.roleChangeManager)==null?void 0:r.handleLocalPeerRoleUpdate({oldRole:e,newRole:t})});this.sendAudioPresenceFailed=()=>{let e=m.TracksErrors.NoAudioDetected("PREVIEW");d.w(this.TAG,"Audio Presence Failure",this.transportState,e)};this.sendJoinAnalyticsEvent=(e=!1,t)=>{this.eventBus.analytics.publish(y.join(v(S({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(v(S({error:e},this.analyticsTimer.getTimes()),{time:this.analyticsTimer.getTimeTaken("preview_time")})))};this.sendAnalyticsEvent=e=>{this.analyticsEventsService.queue(e).flush()}}initNotificationManager(){this.notificationManager||(this.notificationManager=new ji(this.store,this.eventBus,this.transport,this.listener,this.audioListener))}initStoreAndManagers(){var e;if(this.sdkState.isInitialised){(e=this.notificationManager)==null||e.setListener(this.listener),this.audioSinkManager.setListener(this.listener),this.interactivityCenter.setListener(this.listener);return}this.sdkState.isInitialised=!0,this.store=new Dt,this.eventBus=new et,this.pluginUsageTracker=new Li(this.eventBus),this.wakeLockManager=new Hi,this.networkTestManager=new Ri(this.eventBus,this.listener),this.playlistManager=new Pt(this,this.eventBus),this.deviceManager=new Nt(this.store,this.eventBus),this.audioSinkManager=new _t(this.store,this.deviceManager,this.eventBus),this.audioOutput=new wi(this.deviceManager,this.audioSinkManager),this.audioSinkManager.setListener(this.listener),this.eventBus.autoplayError.subscribe(this.handleAutoplayError),this.localTrackManager=new ge(this.store,this.observer,this.deviceManager,this.eventBus,this.analyticsTimer),this.analyticsEventsService=new Ci(this.store),this.transport=new jt(this.observer,this.deviceManager,this.store,this.eventBus,this.analyticsEventsService,this.analyticsTimer,this.pluginUsageTracker),this.sessionStore=new Ji(this.transport),this.interactivityCenter=new xt(this.transport,this.store,this.listener),this.eventBus.analytics.subscribe(this.sendAnalyticsEvent),this.eventBus.deviceChange.subscribe(this.handleDeviceChange),this.eventBus.audioPluginFailed.subscribe(this.handleAudioPluginError)}validateJoined(e){if(!this.localPeer)throw m.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()}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}getTemplateAppData(){return this.store.getTemplateAppData()}getInteractivityCenter(){return this.interactivityCenter}getPeerListIterator(e){return new Si(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(Lr(),Cr(),this.sdkState.isPreviewInProgress)return Promise.reject(m.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),e.alwaysRequestPermissions&&this.localTrackManager.requestPermissions().then(()=>c(this,null,function*(){yield this.initDeviceManagers()}));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 l=()=>c(this,null,function*(){var g;if(this.localPeer){let T=e.asRole&&this.store.getPolicyForRole(e.asRole);this.localPeer.asRole=T||this.localPeer.role}let p=yield this.localTrackManager.getTracksToPublish(e.settings);p.forEach(T=>this.setLocalPeerTrack(T)),(g=this.localPeer)!=null&&g.audioTrack&&this.initPreviewTrackAudioLevelMonitor(),yield this.initDeviceManagers(),this.sdkState.isPreviewInProgress=!1,this.analyticsTimer.end("preview_time");let h=this.store.getRoom();h&&t.onPreview(h,p),this.sendPreviewAnalyticsEvent(),o()}),u=p=>{var h;this.analyticsTimer.end("preview_time"),p&&((h=this.errorListener)==null||h.onError(p)),this.sendPreviewAnalyticsEvent(p),this.sdkState.isPreviewInProgress=!1,n(p)};this.eventBus.policyChange.subscribeOnce(l),this.eventBus.leave.subscribeOnce(u),this.transport.preview(e.authToken,e.initEndpoint,this.localPeer.peerId,{name:e.userName,metaData:e.metaData||""},e.autoVideoSubscribe).then(p=>{var h;i=!0,clearTimeout(s),p&&e.captureNetworkQualityInPreview&&this.networkTestManager.start((h=p.config)==null?void 0:h.networkHealth).then(()=>{r=!0})}).catch(u)})})}midCallPreview(e,t){return c(this,null,function*(){var s,o;if(!this.localPeer||this.transportState!=="Joined")throw m.GenericErrors.NotConnected("VALIDATION","Not connected - midCallPreview");let i=e&&this.store.getPolicyForRole(e);if(!i)throw m.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())&&d.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 l,u,p,h,g,T;if(Lr(),Cr(),this.sdkState.isPreviewInProgress)throw m.GenericErrors.NotReady("JOIN","Preview is in progress, can't join");this.analyticsTimer.start("join_time"),this.sdkState.isJoinInProgress=!0;let{roomId:i,userId:r,role:s}=nr(e.authToken),o=((u=(l=this.localPeer)==null?void 0:l.asRole)==null?void 0:u.name)||((h=(p=this.localPeer)==null?void 0:p.role)==null?void 0:h.name);(g=this.networkTestManager)==null||g.stop(),this.listener=t,this.commonSetup(e,i,t),this.removeDevicesFromConfig(e),this.store.setConfig(e),this.store.createAndSetUserAgent(this.frameworkInfo),Ee.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 wt(this.store,this.transport,this.deviceManager,this.getAndPublishTracks.bind(this),this.removeTrack.bind(this),this.listener),this.eventBus.localRoleUpdate.subscribe(this.handleLocalRoleUpdate),d.d(this.TAG,`\u23F3 Joining room ${i}`),d.time(`join-room-${i}`);try{yield this.transport.join(e.authToken,this.localPeer.peerId,{name:e.userName,metaData:e.metaData},e.initEndpoint,e.autoVideoSubscribe),d.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)}catch(P){throw this.analyticsTimer.end("join_time"),this.sdkState.isJoinInProgress=!1,(T=this.listener)==null||T.onError(P),this.sendJoinAnalyticsEvent(this.sdkState.isPreviewCalled,P),d.e(this.TAG,"Unable to join room",P),P}d.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.analyticsTimer.cleanup(),Q.cleanup(),this.playlistManager.cleanup(),(e=this.wakeLockManager)==null||e.cleanup(),ge.cleanup(),this.notificationManager=void 0,d.cleanup(),this.sdkState=S({},ja),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;let i=(r=this.store)==null?void 0:r.getRoom();if(i){for(;(this.sdkState.isPreviewInProgress||this.sdkState.isJoinInProgress)&&!(t!=null&&t.isTerminal);)yield Ae(100);let n=i.id;(s=this.networkTestManager)==null||s.stop(),this.eventBus.leave.publish(t),d.d(this.TAG,`\u23F3 Leaving room ${n}`),yield(o=this.transport)==null?void 0:o.leave(e),this.cleanup(),d.d(this.TAG,`\u2705 Left room ${n}`)}})}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 qa(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 m.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 m.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 m.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{peers:l}=yield this.transport.signal.findPeers({peers:[t],limit:1});if(l.length===0)throw m.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);s=Re(l[0],this.store)}else throw m.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);return yield this.sendMessageInternal({message:e,recipientPeer:s,type:i})})}sendMessageInternal(s){return c(this,arguments,function*({recipientRoles:e,recipientPeer:t,type:i="chat",message:r}){if(r.replace(/\u200b/g," ").trim()==="")throw d.w(this.TAG,"sendMessage","Ignoring empty message send"),m.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),d.d(this.TAG,"Sending Message: ",o),yield this.transport.signal.broadcast(o)})}startScreenShare(e,t){return c(this,null,function*(){var n,l,u;let i=this.store.getPublishParams();if(!i)return;let{allowed:r}=i;if(!(r&&r.includes("screen"))){d.e(this.TAG,`Role ${(n=this.localPeer)==null?void 0:n.role} cannot share screen`);return}if((u=(l=this.localPeer)==null?void 0:l.auxiliaryTracks)!=null&&u.find(p=>p.source==="screen"))throw Error("Cannot share multiple screens");let o=yield this.getScreenshareTracks(e,t);if(!this.localPeer){d.d(this.TAG,"Screenshared when not connected"),o.forEach(p=>{p.cleanup()});return}yield this.transport.publish(o),o.forEach(p=>{var h,g,T;p.peerId=(h=this.localPeer)==null?void 0:h.peerId,(g=this.localPeer)==null||g.auxiliaryTracks.push(p),(T=this.listener)==null||T.onTrackUpdate(0,p,this.localPeer)})})}stopEndedScreenshare(e){return c(this,null,function*(){d.d(this.TAG,"\u2705 Screenshare ended natively"),yield this.stopScreenShare(),e()})}stopScreenShare(){return c(this,null,function*(){var t;d.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,h,g;if(!e){d.w(this.TAG,"Please pass a valid MediaStreamTrack");return}if(!this.localPeer)throw m.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot addTrack");if(this.localPeer.auxiliaryTracks.find(T=>T.trackId===e.id))return;let r=e.kind,s=new MediaStream([e]),o=new Oe(s),n=r==="audio"?ne:B,l=new n(o,e,t,this.eventBus);this.setPlaylistSettings({track:e,hmsTrack:l,source:t}),yield(u=this.transport)==null?void 0:u.publish([l]),l.peerId=(p=this.localPeer)==null?void 0:p.peerId,(h=this.localPeer)==null||h.auxiliaryTracks.push(l),(g=this.listener)==null||g.onTrackUpdate(0,l,this.localPeer)})}removeTrack(e,t=!1){return c(this,null,function*(){var r;if(!this.localPeer)throw m.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 d.w(this.TAG,`No track found for ${e}`)})}setAnalyticsLevel(e){this.analyticsEventsService.level=e}setLogLevel(e){d.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)}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 m.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 m.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 m.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 m.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 m.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 m.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()})}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"){d.w(this.TAG,"Muting non-regular video tracks is currently not supported");return}if(e.enabled===t){d.w(this.TAG,`Aborting change track state, track already has enabled - ${t}`,e);return}if(!this.store.getTrackById(e.trackId))throw m.GenericErrors.ValidationFailed("No track found for change track state",e);let i=this.store.getPeerByTrackId(e.trackId);if(!i)throw m.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 m.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(Te)})}lowerLocalPeerHand(){return c(this,null,function*(){var e;this.validateJoined("lowerLocalPeerHand"),yield(e=this.transport)==null?void 0:e.signal.leaveGroup(Te)})}raiseRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.addToGroup(e,Te)})}lowerRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.removeFromGroup(e,Te)})}setFrameworkInfo(e){this.frameworkInfo=S(S({},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,!we].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 l;d.e(this.TAG,"Error in publish",n),(l=this.listener)==null||l.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;for(let i of e)yield this.transport.publish([i]),this.setLocalPeerTrack(i),(t=this.listener)==null||t.onTrackUpdate(0,i,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=Q.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){d.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.listener=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)||$r;else{n.maxBitrate=((o=this.playlistSettings.video)==null?void 0:o.bitrate)||Wr;let{width:l,height:u}=e.getSettings();n.width=l,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 yt({name:e.userName||"",customerUserId:i,metadata:e.metaData||"",role:s,asRole:o||s});this.store.addPeer(n)}commonSetup(e,t,i){this.stringifyMetadata(e),e.initEndpoint||(e.initEndpoint="https://prod-init.100ms.live"),this.errorListener=i,this.deviceChangeListener=i,this.initStoreAndManagers(),this.store.setErrorListener(this.errorListener),this.store.getRoom()||this.store.setRoom(new Lt(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 m.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")}};var Be=class a{constructor(e,t,i){this.getStats=()=>(this.stats||(this.stats=new st(this.store,this.sdk)),this.stats);e?this.store=e:this.store=a.createNewHMSStore(Ii("HMSStore"),ot),i?this.notifications=i:this.notifications=new yi(this.store),t?this.actions=t:(this.sdk=new cr,this.actions=new Ai(this.store,this.sdk,this.notifications)),this.actions.setFrameworkInfo({type:"js",sdkVersion:wr().version}),this.initialTriggerOnSubscribe=!1,_&&(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,za.default)(()=>t()),r=i.setState;i.setState=n=>{let l=typeof n=="function"?(0,Ja.produce)(n):n;r(l)};let s=i.getState;i.getState=n=>n?n(s()):s(),a.compareWithShallowCheckInSubscribe(i);let o=a.setUpDevtools(i,e);return v(S({},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||Qa.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 l=n||`${r.prefix}action`;r.send(l,e.getState())}}static devtoolsOptions(e){return{name:e,actionsBlacklist:["audioLevel","playlistProgress","connectionQuality"]}}static devtoolsSubscribe(e,t,i){return r=>{var s,o,n,l;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;(((l=r.payload.nextLiftedState)==null?void 0:l.computedStates)||[]).forEach(({state:h},g)=>{let T=u[g]||`${e.prefix}setState`;g===0?e.init(h):(i(h),e.send(T,t.getState()))})}}}};var Xa=(a,e,t)=>{let i;t.getState(J)==="Connected"&&(i=Ya(a,e,t)),t.subscribe(r=>{["Connected","Reconnecting"].includes(r)?i||(i=Ya(a,e,t)):["Disconnected","Failed"].includes(r)&&i&&(Hc(e,r),i(),i=void 0)},J)},Ya=(a,e,t)=>{var s,o;let i=Ic(t,e);(s=a.getWebrtcInternals())==null||s.start();let r=(o=a.getWebrtcInternals())==null?void 0:o.onStatsChange(n=>Rc(e,n,t,a));return()=>{i(),r&&r()}},Ic=(a,e)=>{let t,i,r;return a.getState(ce)?e.namedSetState(s=>{s.localPeer.id=a.getState(ce)},"localpeer-id"):t=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.id=s},"localpeer-id")},ce),a.getState(W)?e.namedSetState(s=>{s.localPeer.videoTrack=a.getState(W)},"localpeer-videotrack-id"):i=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.videoTrack=s},"localpeer-videotrack-id")},W),a.getState(X)?e.namedSetState(s=>{s.localPeer.audioTrack=a.getState(X)},"localpeer-audiotrack-id"):r=a.subscribe(s=>{s&&e.namedSetState(o=>{o.localPeer.audioTrack=s},"localpeer-audiotrack-id")},X),()=>{t==null||t(),i==null||i(),r==null||r()}},Rc=(a,e,t,i)=>{let r=t.getState(w);a.namedSetState(s=>{let o=t.getState(ce),n={},l=Object.keys(r).filter(p=>r[p].peerId!==o);for(let p of l){let h=e.getRemoteTrackStats(p);h&&(n[p]=h)}as(s.remoteTrackStats,n);let u={[o]:e.getLocalPeerStats()};as(s.peerStats,u),Da(s.localTrackStats,e.getLocalTrackStats(),i.store.getLocalPeerTracks())},"webrtc-stats")},Hc=(a,e="resetState")=>{a.namedSetState(t=>{Object.assign(t,nt())},e)};var st=class{constructor(e,t){this.hmsStore=e;this.sdk=t;this.store=Be.createNewHMSStore(Ii("HMSStatsStore"),nt),this.getState=this.store.getState,this.subscribe=this.store.subscribe,this.getPublishPeerConnection=()=>new Promise(i=>{var r,s;this.hmsStore.getState(J)==="Connected"?i((s=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:s.getPublishPeerConnection()):this.hmsStore.subscribe(o=>{var n,l;o==="Connected"&&i((l=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:l.getPublishPeerConnection())},J)}),this.getSubscribePeerConnection=()=>new Promise(i=>{var r,s;this.hmsStore.getState(J)==="Connected"?i((s=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:s.getSubscribePeerConnection()):this.hmsStore.subscribe(o=>{var n,l;o==="Connected"&&i((l=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:l.getSubscribePeerConnection())},J)}),this.sdk&&Xa(this.sdk,this.store,this.hmsStore)}};var F=require("reselect");var Cc=a=>a.localPeer.id,Lc=a=>a.localPeer.audioTrack,wc=a=>a.localPeer.videoTrack,Dc=(a,e)=>e,Za=(a,e)=>e,_c=a=>a.remoteTrackStats,eo=a=>a.peerStats,hs=a=>a.localTrackStats,Me=(0,F.createSelector)([eo,Cc],(a,e)=>a[e]),Nc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.packetsLost}),Oc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.jitter}),xc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.bitrate}),Uc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.bitrate}),Bc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.availableOutgoingBitrate}),Vc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.availableIncomingBitrate}),Fc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.publish)==null?void 0:e.bytesSent}),Gc=(0,F.createSelector)(Me,a=>{var e;return(e=a==null?void 0:a.subscribe)==null?void 0:e.bytesReceived}),Wc=(0,F.createSelector)([eo,Dc],(a,e)=>e?a[e]:void 0),$c=(0,F.createSelector)([_c,Za],(a,e)=>e?a[e]:void 0),ms=(0,F.createSelector)([hs,Za],(a,e)=>e?a[e]:void 0),Kc=I(Wc),qc=I($c),jc=(0,F.createSelector)([hs,Lc],(a,e)=>{var t;return e?(t=a[e])==null?void 0:t[0]:void 0}),Jc=I((0,F.createSelector)(ms,a=>a==null?void 0:a[0])),Qc=(0,F.createSelector)([hs,wc],(a,e)=>{var t;return e?(t=a[e])==null?void 0:t[0]:void 0}),zc=I((0,F.createSelector)(ms,a=>a)),Yc=a=>I((0,F.createSelector)(ms,e=>{let t=Object.keys(Ie).find(i=>Ie[i]===a);return a&&(e==null?void 0:e.find(i=>i.rid===t))||(e==null?void 0:e[0])})),to={localPeerStats:Me,packetsLost:Nc,jitter:Oc,publishBitrate:xc,subscribeBitrate:Uc,availablePublishBitrate:Bc,availableSubscribeBitrate:Vc,totalBytesSent:Fc,totalBytesReceived:Gc,peerStatsByID:Kc,trackStatsByID:qc,localAudioTrackStatsByID:Jc,localVideoTrackStatsByID:zc,localVideoTrackStatsByLayer:Yc,localAudioTrackStats:jc,localVideoTrackStats:Qc};
|
|
83
83
|
//# sourceMappingURL=index.cjs.js.map
|