1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1463],{78155:function(e,t,i){let s,n,a,r;i.d(t,{Bl:function(){return M},Dt:function(){return nh},GR:function(){return ri},I4:function(){return nu},JM:function(){return nE},Jq:function(){return ta},Mz:function(){return nv},OX:function(){return nA},Oy:function(){return np},PP:function(){return em},Uq:function(){return F},VJ:function(){return nn},WV:function(){return aR},Wt:function(){return nI},_J:function(){return sk},go:function(){return nl},jl:function(){return sm},sy:function(){return sO},u2:function(){return nT},wf:function(){return nd},xp:function(){return n_},zE:function(){return no}}),i(95051);var o,c,l,d,h,u,p,g,m,v,S,b,f,C,T,k,y,w,E,I,_,R,D,A,O,P,N,U,L,j,M,V,F,x=i(5435),H=i(82044),B=i(42741),W=i(29829),q=i(80735),$=i(44716),J=i(73107),G=i(80894),K=i(95053),X=i(66554),Y=i(88137),z=i(4620),Q=i(31379),Z=i(33627),ee=i(53105),et=i(45698),ei=i(99299),es=i(81571),en=i(86962),ea=i(24451),er=i(5899),eo=i(8866),ec=i(35448),el=i(22038),ed=i(74294),eh=i(78238),eu=i(37808),ep=i(25049);let eg={DISABLED:"disabled",AUTO_ON:"auto-on"},em={BLOCK_USERS:"block-users",CHANGE_MAX_DURATION:"change-max-duration",CREATE_CALL:"create-call",CREATE_REACTION:"create-reaction",ENABLE_NOISE_CANCELLATION:"enable-noise-cancellation",END_CALL:"end-call",JOIN_BACKSTAGE:"join-backstage",JOIN_CALL:"join-call",JOIN_ENDED_CALL:"join-ended-call",MUTE_USERS:"mute-users",PIN_FOR_EVERYONE:"pin-for-everyone",READ_CALL:"read-call",REMOVE_CALL_MEMBER:"remove-call-member",SCREENSHARE:"screenshare",SEND_AUDIO:"send-audio",SEND_VIDEO:"send-video",START_BROADCAST_CALL:"start-broadcast-call",START_CLOSED_CAPTIONS_CALL:"start-closed-captions-call",START_RECORD_CALL:"start-record-call",START_TRANSCRIPTION_CALL:"start-transcription-call",STOP_BROADCAST_CALL:"stop-broadcast-call",STOP_CLOSED_CAPTIONS_CALL:"stop-closed-captions-call",STOP_RECORD_CALL:"stop-record-call",STOP_TRANSCRIPTION_CALL:"stop-transcription-call",UPDATE_CALL:"update-call",UPDATE_CALL_MEMBER:"update-call-member",UPDATE_CALL_PERMISSIONS:"update-call-permissions",UPDATE_CALL_SETTINGS:"update-call-settings"};class ev extends Error{}(o=w||(w={}))[o.NULL_VALUE=0]="NULL_VALUE";class eS extends x.C{internalJsonWrite(e,t){let i={};for(let[t,s]of Object.entries(e.fields))i[t]=eC.toJson(s);return i}internalJsonRead(e,t,i){if(!(0,H.b)(e))throw new globalThis.Error("Unable to parse message "+this.typeName+" from JSON "+(0,H.Z)(e)+".");for(let[t,s]of(i||(i=this.create()),globalThis.Object.entries(e)))i.fields[t]=eC.fromJson(s);return i}constructor(){super("google.protobuf.Struct",[{no:1,name:"fields",kind:"map",K:9,V:{kind:"message",T:()=>eC}}])}}let eb=new eS;class ef extends x.C{internalJsonWrite(e,t){if(void 0===e.kind.oneofKind)throw new globalThis.Error;switch(e.kind.oneofKind){case void 0:throw new globalThis.Error;case"boolValue":return e.kind.boolValue;case"nullValue":return null;case"numberValue":let i=e.kind.numberValue;if("number"==typeof i&&!Number.isFinite(i))throw new globalThis.Error;return i;case"stringValue":return e.kind.stringValue;case"listValue":let s=this.fields.find(e=>6===e.no);if((null==s?void 0:s.kind)!=="message")throw new globalThis.Error;return s.T().toJson(e.kind.listValue);case"structValue":let n=this.fields.find(e=>5===e.no);if((null==n?void 0:n.kind)!=="message")throw new globalThis.Error;return n.T().toJson(e.kind.structValue)}}internalJsonRead(e,t,i){switch(i||(i=this.create()),typeof e){case"number":i.kind={oneofKind:"numberValue",numberValue:e};break;case"string":i.kind={oneofKind:"stringValue",stringValue:e};break;case"boolean":i.kind={oneofKind:"boolValue",boolValue:e};break;case"object":null===e?i.kind={oneofKind:"nullValue",nullValue:w.NULL_VALUE}:globalThis.Array.isArray(e)?i.kind={oneofKind:"listValue",listValue:ek.fromJson(e)}:i.kind={oneofKind:"structValue",structValue:eb.fromJson(e)};break;default:throw new globalThis.Error("Unable to parse "+this.typeName+" from JSON "+(0,H.Z)(e))}return i}constructor(){super("google.protobuf.Value",[{no:1,name:"null_value",kind:"enum",oneof:"kind",T:()=>["google.protobuf.NullValue",w]},{no:2,name:"number_value",kind:"scalar",oneof:"kind",T:1},{no:3,name:"string_value",kind:"scalar",oneof:"kind",T:9},{no:4,name:"bool_value",kind:"scalar",oneof:"kind",T:8},{no:5,name:"struct_value",kind:"message",oneof:"kind",T:()=>eb},{no:6,name:"list_value",kind:"message",oneof:"kind",T:()=>ek}])}}let eC=new ef;class eT extends x.C{internalJsonWrite(e,t){return e.values.map(e=>eC.toJson(e))}internalJsonRead(e,t,i){if(!globalThis.Array.isArray(e))throw new globalThis.Error("Unable to parse "+this.typeName+" from JSON "+(0,H.Z)(e));i||(i=this.create());let s=e.map(e=>eC.fromJson(e));return i.values.push(...s),i}constructor(){super("google.protobuf.ListValue",[{no:1,name:"values",kind:"message",repeat:1,T:()=>eC}])}}let ek=new eT;
1class ey extends x.C{now(){let e=this.create(),t=Date.now();return e.seconds=B.MJ.from(Math.floor(t/1e3)).toString(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*B.MJ.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){let t=this.create(),i=e.getTime();return t.seconds=B.MJ.from(Math.floor(i/1e3)).toString(),t.nanos=i%1e3*1e6,t}internalJsonWrite(e,t){let i=1e3*B.MJ.from(e.seconds).toNumber();if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let s="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);s="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(i).toISOString().replace(".000Z",s)}internalJsonRead(e,t,i){if("string"!=typeof e)throw Error("Unable to parse Timestamp from JSON "+(0,H.Z)(e)+".");let s=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!s)throw Error("Unable to parse Timestamp from JSON. Invalid format.");let n=Date.parse(s[1]+"-"+s[2]+"-"+s[3]+"T"+s[4]+":"+s[5]+":"+s[6]+(s[8]?s[8]:"Z"));if(Number.isNaN(n))throw Error("Unable to parse Timestamp from JSON. Invalid value.");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return i||(i=this.create()),i.seconds=B.MJ.from(n/1e3).toString(),i.nanos=0,s[7]&&(i.nanos=parseInt("1"+s[7]+"0".repeat(9-s[7].length))-1e9),i}constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}])}}let ew=new ey;(c=E||(E={}))[c.PUBLISHER_UNSPECIFIED=0]="PUBLISHER_UNSPECIFIED",c[c.SUBSCRIBER=1]="SUBSCRIBER",(l=I||(I={}))[l.UNSPECIFIED=0]="UNSPECIFIED",l[l.POOR=1]="POOR",l[l.GOOD=2]="GOOD",l[l.EXCELLENT=3]="EXCELLENT",(d=_||(_={}))[d.LOW_UNSPECIFIED=0]="LOW_UNSPECIFIED",d[d.MID=1]="MID",d[d.HIGH=2]="HIGH",d[d.OFF=3]="OFF",(h=R||(R={}))[h.UNSPECIFIED=0]="UNSPECIFIED",h[h.AUDIO=1]="AUDIO",h[h.VIDEO=2]="VIDEO",h[h.SCREEN_SHARE=3]="SCREEN_SHARE",h[h.SCREEN_SHARE_AUDIO=4]="SCREEN_SHARE_AUDIO",(u=D||(D={}))[u.UNSPECIFIED=0]="UNSPECIFIED",u[u.PUBLISH_TRACK_NOT_FOUND=100]="PUBLISH_TRACK_NOT_FOUND",u[u.PUBLISH_TRACKS_MISMATCH=101]="PUBLISH_TRACKS_MISMATCH",u[u.PUBLISH_TRACK_OUT_OF_ORDER=102]="PUBLISH_TRACK_OUT_OF_ORDER",u[u.PUBLISH_TRACK_VIDEO_LAYER_NOT_FOUND=103]="PUBLISH_TRACK_VIDEO_LAYER_NOT_FOUND",u[u.LIVE_ENDED=104]="LIVE_ENDED",u[u.PARTICIPANT_NOT_FOUND=200]="PARTICIPANT_NOT_FOUND",u[u.PARTICIPANT_MIGRATING_OUT=201]="PARTICIPANT_MIGRATING_OUT",u[u.PARTICIPANT_MIGRATION_FAILED=202]="PARTICIPANT_MIGRATION_FAILED",u[u.PARTICIPANT_MIGRATING=203]="PARTICIPANT_MIGRATING",u[u.PARTICIPANT_RECONNECT_FAILED=204]="PARTICIPANT_RECONNECT_FAILED",u[u.PARTICIPANT_MEDIA_TRANSPORT_FAILURE=205]="PARTICIPANT_MEDIA_TRANSPORT_FAILURE",u[u.CALL_NOT_FOUND=300]="CALL_NOT_FOUND",u[u.REQUEST_VALIDATION_FAILED=400]="REQUEST_VALIDATION_FAILED",u[u.UNAUTHENTICATED=401]="UNAUTHENTICATED",u[u.PERMISSION_DENIED=403]="PERMISSION_DENIED",u[u.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",u[u.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",u[u.SFU_SHUTTING_DOWN=600]="SFU_SHUTTING_DOWN",u[u.SFU_FULL=700]="SFU_FULL",(p=A||(A={}))[p.UNSPECIFIED=0]="UNSPECIFIED",p[p.REACT=1]="REACT",p[p.ANGULAR=2]="ANGULAR",p[p.ANDROID=3]="ANDROID",p[p.IOS=4]="IOS",p[p.FLUTTER=5]="FLUTTER",p[p.REACT_NATIVE=6]="REACT_NATIVE",p[p.UNITY=7]="UNITY",p[p.GO=8]="GO",p[p.PLAIN_JAVASCRIPT=9]="PLAIN_JAVASCRIPT",(g=O||(O={}))[g.UNSPECIFIED=0]="UNSPECIFIED",g[g.USER_MUTED=1]="USER_MUTED",g[g.PERMISSION_REVOKED=2]="PERMISSION_REVOKED",g[g.MODERATION=3]="MODERATION",(m=P||(P={}))[m.UNSPECIFIED=0]="UNSPECIFIED",m[m.SHUTTING_DOWN=1]="SHUTTING_DOWN",m[m.REBALANCE=2]="REBALANCE",(v=N||(N={}))[v.UNSPECIFIED=0]="UNSPECIFIED",v[v.ENDED=1]="ENDED",v[v.LIVE_ENDED=2]="LIVE_ENDED",v[v.KICKED=3]="KICKED",v[v.SESSION_ENDED=4]="SESSION_ENDED",(S=U||(U={}))[S.UNSPECIFIED=0]="UNSPECIFIED",S[S.DISCONNECT=1]="DISCONNECT",S[S.FAST=2]="FAST",S[S.REJOIN=3]="REJOIN",S[S.MIGRATE=4]="MIGRATE",(b=L||(L={}))[b.UNSPECIFIED=0]="UNSPECIFIED",b[b.NONE=1]="NONE",b[b.LIGHT=2]="LIGHT",b[b.MODERATE=3]="MODERATE",b[b.SEVERE=4]="SEVERE",b[b.CRITICAL=5]="CRITICAL",b[b.EMERGENCY=6]="EMERGENCY",b[b.SHUTDOWN=7]="SHUTDOWN",(f=j||(j={}))[f.UNSPECIFIED=0]="UNSPECIFIED",f[f.NOMINAL=1]="NOMINAL",f[f.FAIR=2]="FAIR",f[f.SERIOUS=3]="SERIOUS",f[f.CRITICAL=4]="CRITICAL";class eE extends x.C{constructor(){super("stream.video.sfu.models.CallState",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>eP},{no:2,name:"started_at",kind:"message",T:()=>ew},{no:3,name:"participant_count",kind:"message",T:()=>eR},{no:4,name:"pins",kind:"message",repeat:1,T:()=>eA}])}}let eI=new eE;class e_ extends x.C{constructor(){super("stream.video.sfu.models.ParticipantCount",[{no:1,name:"total",kind:"scalar",T:13},{no:2,name:"anonymous",kind:"scalar",T:13}])}}let eR=new e_;class eD extends x.C{constructor(){super("stream.video.sfu.models.Pin",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"session_id",kind:"scalar",T:9}])}}let eA=new eD;class eO extends x.C{constructor(){super("stream.video.sfu.models.Participant",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"session_id",kind:"scalar",T:9},{no:3,name:"published_tracks",kind:"enum",repeat:1,T:()=>["stream.video.sfu.models.TrackType",R,"TRACK_TYPE_"]},{no:4,name:"joined_at",kind:"message",T:()=>ew},{no:5,name:"track_lookup_prefix",kind:"scalar",T:9},{no:6,name:"connection_quality",kind:"enum",T:()=>["stream.video.sfu.models.ConnectionQuality",I,"CONNECTION_QUALITY_"]},{no:7,name:"is_speaking",kind:"scalar",T:8},{no:8,name:"is_dominant_speaker",kind:"scalar",T:8},{no:9,name:"audio_level",kind:"scalar",T:2},{no:10,name:"name",kind:"scalar",T:9},{no:11,name:"image",kind:"scalar",T:9},{no:12,name:"custom",kind:"message",T:()=>eb},{no:13,name:"roles",kind:"scalar",repeat:2,T:9}])}}let eP=new eO;class eN extends x.C{constructor(){super("stream.video.sfu.models.StreamQuality",[{no:1,name:"video_quality",kind:"enum",T:()=>["stream.video.sfu.models.VideoQuality",_,"VIDEO_QUALITY_"]},{no:2,name:"user_id",kind:"scalar",T:9}])}}let eU=new eN;class eL extends x.C{constructor(){super("stream.video.sfu.models.VideoDimension",[{no:1,name:"width",kind:"scalar",T:13},{no:2,name:"height",kind:"scalar",T:13}])}}let ej=new eL;class eM extends x.C{constructor(){super("stream.video.sfu.models.VideoLayer",[{no:1,name:"rid",kind:"scalar",T:9},{no:2,name:"video_dimension",kind:"message",T:()=>ej},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"fps",kind:"scalar",T:13},{no:6,name:"quality",kind:"enum",T:()=>["stream.video.sfu.models.VideoQuality",_,"VIDEO_QUALITY_"]}])}}let eV=new eM;class eF extends x.C{constructor(){super("stream.video.sfu.models.PublishOptions",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>eB}])}}let ex=new eF;class eH extends x.C{constructor(){super("stream.video.sfu.models.PublishOption",[{no:1,name:"track_type",kind:"enum",T:()=>["stream.video.sfu.models.TrackType",R,"TRACK_TYPE_"]},{no:2,name:"codec",kind:"message",T:()=>eq},{no:3,name:"bitrate",kind:"scalar",T:5},{no:4,name:"fps",kind:"scalar",T:5},{no:5,name:"max_spatial_layers",kind:"scalar",T:5},{no:6,name:"max_temporal_layers",kind:"scalar",T:5}])}}let eB=new eH;class eW extends x.C{constructor(){super("stream.video.sfu.models.Codec",[{no:11,name:"payload_type",kind:"scalar",T:13},{no:10,name:"name",kind:"scalar",T:9},{no:14,name:"clock_rate",kind:"scalar",T:13},{no:13,name:"encoding_parameters",kind:"scalar",T:9},{no:12,name:"fmtp",kind:"scalar",T:9}])}}let eq=new eW,e$=new class extends x.C{constructor(){super("stream.video.sfu.models.ICETrickle",[{no:1,name:"peer_type",kind:"enum",T:()=>["stream.video.sfu.models.PeerType",E,"PEER_TYPE_"]},{no:2,name:"ice_candidate",kind:"scalar",T:9},{no:3,name:"session_id",kind:"scalar",T:9}])}};class eJ extends x.C{constructor(){super("stream.video.sfu.models.TrackInfo",[{no:1,name:"track_id",kind:"scalar",T:9},{no:2,name:"track_type",kind:"enum",T:()=>["stream.video.sfu.models.TrackType",R,"TRACK_TYPE_"]},{no:5,name:"layers",kind:"message",repeat:1,T:()=>eV},{no:6,name:"mid",kind:"scalar",T:9},{no:7,name:"dtx",kind:"scalar",T:8},{no:8,name:"stereo",kind:"scalar",T:8},{no:9,name:"red",kind:"scalar",T:8},{no:10,name:"muted",kind:"scalar",T:8}])}}let eG=new eJ,eK=new class extends x.C{constructor(){super("stream.video.sfu.models.Error",[{no:1,name:"code",kind:"enum",T:()=>["stream.video.sfu.models.ErrorCode",D,"ERROR_CODE_"]},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"should_retry",kind:"scalar",T:8}])}};class eX extends x.C{constructor(){super("stream.video.sfu.models.ClientDetails",[{no:1,name:"sdk",kind:"message",T:()=>eQ},{no:2,name:"os",kind:"message",T:()=>e0},{no:3,name:"browser",kind:"message",T:()=>e2},{no:4,name:"device",kind:"message",T:()=>e9}])}}let eY=new eX;class ez extends x.C{constructor(){super("stream.video.sfu.models.Sdk",[{no:1,name:"type",kind:"enum",T:()=>["stream.video.sfu.models.SdkType",A,"SDK_TYPE_"]},{no:2,name:"major",kind:"scalar",T:9},{no:3,name:"minor",kind:"scalar",T:9},{no:4,name:"patch",kind:"scalar",T:9}])}}let eQ=new ez;class eZ extends x.C{constructor(){super("stream.video.sfu.models.OS",[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"architecture",kind:"scalar",T:9}])}}let e0=new eZ;class e1 extends x.C{constructor(){super("stream.video.sfu.models.Browser",[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"version",kind:"scalar",T:9}])}}let e2=new e1;class e3 extends x.C{constructor(){super("stream.video.sfu.models.Device",[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"version",kind:"scalar",T:9}])}}
1let e9=new e3;class e5 extends x.C{constructor(){super("stream.video.sfu.models.Call",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"created_by_user_id",kind:"scalar",T:9},{no:4,name:"host_user_id",kind:"scalar",T:9},{no:5,name:"custom",kind:"message",T:()=>eb},{no:6,name:"created_at",kind:"message",T:()=>ew},{no:7,name:"updated_at",kind:"message",T:()=>ew}])}}let e4=new e5;class e8 extends x.C{constructor(){super("stream.video.sfu.models.CallGrants",[{no:1,name:"can_publish_audio",kind:"scalar",T:8},{no:2,name:"can_publish_video",kind:"scalar",T:8},{no:3,name:"can_screenshare",kind:"scalar",T:8}])}}let e6=new e8;class e7 extends x.C{constructor(){super("stream.video.sfu.models.InputDevices",[{no:1,name:"available_devices",kind:"scalar",repeat:2,T:9},{no:2,name:"current_device",kind:"scalar",T:9},{no:3,name:"is_permitted",kind:"scalar",T:8}])}}let te=new e7;class tt extends x.C{constructor(){super("stream.video.sfu.models.AndroidState",[{no:1,name:"thermal_state",kind:"enum",T:()=>["stream.video.sfu.models.AndroidThermalState",L,"ANDROID_THERMAL_STATE_"]},{no:2,name:"is_power_saver_mode",kind:"scalar",T:8}])}}let ti=new tt;class ts extends x.C{constructor(){super("stream.video.sfu.models.AppleState",[{no:1,name:"thermal_state",kind:"enum",T:()=>["stream.video.sfu.models.AppleThermalState",j,"APPLE_THERMAL_STATE_"]},{no:2,name:"is_low_power_mode_enabled",kind:"scalar",T:8}])}}let tn=new ts;var ta=Object.freeze({__proto__:null,AndroidState:ti,get AndroidThermalState(){return L},AppleState:tn,get AppleThermalState(){return j},Browser:e2,Call:e4,get CallEndedReason(){return N},CallGrants:e6,CallState:eI,ClientDetails:eY,Codec:eq,get ConnectionQuality(){return I},Device:e9,Error:eK,get ErrorCode(){return D},get GoAwayReason(){return P},ICETrickle:e$,InputDevices:te,OS:e0,Participant:eP,ParticipantCount:eR,get PeerType(){return E},Pin:eA,PublishOption:eB,PublishOptions:ex,Sdk:eQ,get SdkType(){return A},StreamQuality:eU,TrackInfo:eG,get TrackType(){return R},get TrackUnpublishReason(){return O},VideoDimension:ej,VideoLayer:eV,get VideoQuality(){return _},get WebsocketReconnectStrategy(){return U}});class tr extends x.C{constructor(){super("stream.video.sfu.signal.StartNoiseCancellationRequest",[{no:1,name:"session_id",kind:"scalar",T:9}])}}let to=new tr;class tc extends x.C{constructor(){super("stream.video.sfu.signal.StartNoiseCancellationResponse",[{no:1,name:"error",kind:"message",T:()=>eK}])}}let tl=new tc;class td extends x.C{constructor(){super("stream.video.sfu.signal.StopNoiseCancellationRequest",[{no:1,name:"session_id",kind:"scalar",T:9}])}}let th=new td;class tu extends x.C{constructor(){super("stream.video.sfu.signal.StopNoiseCancellationResponse",[{no:1,name:"error",kind:"message",T:()=>eK}])}}let tp=new tu;class tg extends x.C{constructor(){super("stream.video.sfu.signal.Reconnection",[{no:1,name:"time_seconds",kind:"scalar",T:2},{no:2,name:"strategy",kind:"enum",T:()=>["stream.video.sfu.models.WebsocketReconnectStrategy",U,"WEBSOCKET_RECONNECT_STRATEGY_"]}])}}let tm=new tg;class tv extends x.C{constructor(){super("stream.video.sfu.signal.Telemetry",[{no:1,name:"connection_time_seconds",kind:"scalar",oneof:"data",T:2},{no:2,name:"reconnection",kind:"message",oneof:"data",T:()=>tm}])}}let tS=new tv;class tb extends x.C{constructor(){super("stream.video.sfu.signal.SendStatsRequest",[{no:1,name:"session_id",kind:"scalar",T:9},{no:2,name:"subscriber_stats",kind:"scalar",T:9},{no:3,name:"publisher_stats",kind:"scalar",T:9},{no:4,name:"webrtc_version",kind:"scalar",T:9},{no:5,name:"sdk",kind:"scalar",T:9},{no:6,name:"sdk_version",kind:"scalar",T:9},{no:7,name:"audio_devices",kind:"message",T:()=>te},{no:8,name:"video_devices",kind:"message",T:()=>te},{no:9,name:"android",kind:"message",oneof:"deviceState",T:()=>ti},{no:10,name:"apple",kind:"message",oneof:"deviceState",T:()=>tn},{no:11,name:"telemetry",kind:"message",T:()=>tS}])}}let tf=new tb;class tC extends x.C{constructor(){super("stream.video.sfu.signal.SendStatsResponse",[{no:1,name:"error",kind:"message",T:()=>eK}])}}let tT=new tC;class tk extends x.C{constructor(){super("stream.video.sfu.signal.ICERestartRequest",[{no:1,name:"session_id",kind:"scalar",T:9},{no:2,name:"peer_type",kind:"enum",T:()=>["stream.video.sfu.models.PeerType",E,"PEER_TYPE_"]}])}}let ty=new tk;class tw extends x.C{constructor(){super("stream.video.sfu.signal.ICERestartResponse",[{no:1,name:"error",kind:"message",T:()=>eK}])}}let tE=new tw;class tI extends x.C{constructor(){super("stream.video.sfu.signal.UpdateMuteStatesRequest",[{no:1,name:"session_id",kind:"scalar",T:9},{no:3,name:"mute_states",kind:"message",repeat:1,T:()=>tO}])}}let t_=new tI;class tR extends x.C{constructor(){super("stream.video.sfu.signal.UpdateMuteStatesResponse",[{no:4,name:"error",kind:"message",T:()=>eK}])}}let tD=new tR;class tA extends x.C{constructor(){super("stream.video.sfu.signal.TrackMuteState",[{no:1,name:"track_type",kind:"enum",T:()=>["stream.video.sfu.models.TrackType",R,"TRACK_TYPE_"]},{no:2,name:"muted",kind:"scalar",T:8}])}}let tO=new tA;class tP extends x.C{constructor(){super("stream.video.sfu.signal.AudioMuteChanged",[{no:1,name:"muted",kind:"scalar",T:8}])}}new tP;class tN extends x.C{constructor(){super("stream.video.sfu.signal.VideoMuteChanged",[{no:2,name:"muted",kind:"scalar",T:8}])}}new tN;class tU extends x.C{constructor(){super("stream.video.sfu.signal.UpdateSubscriptionsRequest",[{no:2,name:"session_id",kind:"scalar",T:9},{no:3,name:"tracks",kind:"message",repeat:1,T:()=>tF}])}}let tL=new tU;class tj extends x.C{constructor(){super("stream.video.sfu.signal.UpdateSubscriptionsResponse",[{no:4,name:"error",kind:"message",T:()=>eK}])}}let tM=new tj;class tV extends x.C{constructor(){super("stream.video.sfu.signal.TrackSubscriptionDetail
1s",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"session_id",kind:"scalar",T:9},{no:3,name:"track_type",kind:"enum",T:()=>["stream.video.sfu.models.TrackType",R,"TRACK_TYPE_"]},{no:4,name:"dimension",kind:"message",T:()=>ej}])}}let tF=new tV;class tx extends x.C{constructor(){super("stream.video.sfu.signal.SendAnswerRequest",[{no:1,name:"peer_type",kind:"enum",T:()=>["stream.video.sfu.models.PeerType",E,"PEER_TYPE_"]},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"session_id",kind:"scalar",T:9}])}}let tH=new tx;class tB extends x.C{constructor(){super("stream.video.sfu.signal.SendAnswerResponse",[{no:4,name:"error",kind:"message",T:()=>eK}])}}let tW=new tB;class tq extends x.C{constructor(){super("stream.video.sfu.signal.ICETrickleResponse",[{no:4,name:"error",kind:"message",T:()=>eK}])}}let t$=new tq;class tJ extends x.C{constructor(){super("stream.video.sfu.signal.SetPublisherRequest",[{no:1,name:"sdp",kind:"scalar",T:9},{no:2,name:"session_id",kind:"scalar",T:9},{no:3,name:"tracks",kind:"message",repeat:1,T:()=>eG}])}}let tG=new tJ;class tK extends x.C{constructor(){super("stream.video.sfu.signal.SetPublisherResponse",[{no:1,name:"sdp",kind:"scalar",T:9},{no:2,name:"session_id",kind:"scalar",T:9},{no:3,name:"ice_restart",kind:"scalar",T:8},{no:4,name:"error",kind:"message",T:()=>eK}])}}let tX=new tK,tY=new W.U("stream.video.sfu.signal.SignalServer",[{name:"SetPublisher",options:{},I:tG,O:tX},{name:"SendAnswer",options:{},I:tH,O:tW},{name:"IceTrickle",options:{},I:e$,O:t$},{name:"UpdateSubscriptions",options:{},I:tL,O:tM},{name:"UpdateMuteStates",options:{},I:t_,O:tD},{name:"IceRestart",options:{},I:ty,O:tE},{name:"SendStats",options:{},I:tf,O:tT},{name:"StartNoiseCancellation",options:{},I:to,O:tl},{name:"StopNoiseCancellation",options:{},I:th,O:tp}]);class tz extends x.C{constructor(){super("stream.video.sfu.event.SfuEvent",[{no:1,name:"subscriber_offer",kind:"message",oneof:"eventPayload",T:()=>iO},{no:2,name:"publisher_answer",kind:"message",oneof:"eventPayload",T:()=>iN},{no:3,name:"connection_quality_changed",kind:"message",oneof:"eventPayload",T:()=>iL},{no:4,name:"audio_level_changed",kind:"message",oneof:"eventPayload",T:()=>iW},{no:5,name:"ice_trickle",kind:"message",oneof:"eventPayload",T:()=>e$},{no:6,name:"change_publish_quality",kind:"message",oneof:"eventPayload",T:()=>iz},{no:10,name:"participant_joined",kind:"message",oneof:"eventPayload",T:()=>iE},{no:11,name:"participant_left",kind:"message",oneof:"eventPayload",T:()=>i_},{no:12,name:"dominant_speaker_changed",kind:"message",oneof:"eventPayload",T:()=>iF},{no:13,name:"join_response",kind:"message",oneof:"eventPayload",T:()=>iy},{no:14,name:"health_check_response",kind:"message",oneof:"eventPayload",T:()=>id},{no:16,name:"track_published",kind:"message",oneof:"eventPayload",T:()=>iu},{no:17,name:"track_unpublished",kind:"message",oneof:"eventPayload",T:()=>ig},{no:18,name:"error",kind:"message",oneof:"eventPayload",T:()=>t6},{no:19,name:"call_grants_updated",kind:"message",oneof:"eventPayload",T:()=>iZ},{no:20,name:"go_away",kind:"message",oneof:"eventPayload",T:()=>i1},{no:21,name:"ice_restart",kind:"message",oneof:"eventPayload",T:()=>it},{no:22,name:"pins_updated",kind:"message",oneof:"eventPayload",T:()=>t4},{no:23,name:"call_ended",kind:"message",oneof:"eventPayload",T:()=>i3},{no:24,name:"participant_updated",kind:"message",oneof:"eventPayload",T:()=>iD},{no:25,name:"participant_migration_complete",kind:"message",oneof:"eventPayload",T:()=>t9},{no:26,name:"codec_negotiation_complete",kind:"message",oneof:"eventPayload",T:()=>t2},{no:27,name:"change_publish_options",kind:"message",oneof:"eventPayload",T:()=>t0}])}}let tQ=new tz;class tZ extends x.C{constructor(){super("stream.video.sfu.event.ChangePublishOptions",[{no:1,name:"publish_option",kind:"message",T:()=>eB}])}}let t0=new tZ;class t1 extends x.C{constructor(){super("stream.video.sfu.event.CodecNegotiationComplete",[])}}let t2=new t1;class t3 extends x.C{constructor(){super("stream.video.sfu.event.ParticipantMigrationComplete",[])}}let t9=new t3;class t5 extends x.C{constructor(){super("stream.video.sfu.event.PinsChanged",[{no:1,name:"pins",kind:"message",repeat:1,T:()=>eA}])}}let t4=new t5;class t8 extends x.C{constructor(){super("stream.video.sfu.event.Error",[{no:4,name:"error",kind:"message",T:()=>eK},{no:5,name:"reconnect_strategy",kind:"enum",T:()=>["stream.video.sfu.models.WebsocketReconnectStrategy",U,"WEBSOCKET_RECONNECT_STRATEGY_"]}])}}let t6=new t8;class t7 extends x.C{constructor(){super("stream.video.sfu.event.ICETrickle",[{no:1,name:"peer_type",kind:"enum",T:()=>["stream.video.sfu.models.PeerType",E,"PEER_TYPE_"]},{no:2,name:"ice_candidate",kind:"scalar",T:9}])}}new t7;class ie extends x.C{constructor(){super("stream.video.sfu.event.ICERestart",[{no:1,name:"peer_type",kind:"enum",T:()=>["stream.video.sfu.models.PeerType",E,"PEER_TYPE_"]}])}}let it=new ie;class ii extends x.C{constructor(){super("stream.video.sfu.event.SfuRequest",[{no:1,name:"join_request",kind:"message",oneof:"requestPayload",T:()=>iv},{no:2,name:"health_check_request",kind:"message",oneof:"requestPayload",T:()=>ic},{no:3,name:"leave_call_request",kind:"message",oneof:"requestPayload",T:()=>ir}])}}let is=new ii;class ia extends x.C{constructor(){super("stream.video.sfu.event.LeaveCallRequest",[{no:1,name:"session_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9}])}}let ir=new ia;class io extends x.C{constructor(){super("stream.video.sfu.event.HealthCheckRequest",[])}}let ic=new io;class il extends x.C{constructor(){super("stream.video.sfu.event.HealthCheckResponse",[{no:1,name:"participant_count",kind:"message",T:()=>eR}])}}let id=new il;class ih extends x.C{constructor(){super("stream.video.sfu.event.TrackPublished",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"session_id",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:()=>["stream.video.sfu.models.TrackType",R,"TRACK_TYPE_"]},{no:4,name:"participant",kind:"message",T:()=>eP}])}}let iu=new ih;class ip extends x.C{constructor(){super("stream.video.sfu.event.TrackUnpublished",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"session_id",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:()=>["stream.video.sfu.models.TrackType",R,"TRACK_TYPE_"]},{no:4,name:"cause",kind:"enum",T:()=>["stream.video.sfu.models.TrackUnpublishReason",O,"TRACK_UNPUBLISH_REASON_"]},{no:5,name:"participant",kind:"message",T:()=>eP}])}}let ig=new ip;class im extends x.C{constructor(){super("stream.video.sfu.event.JoinRequest",[{no:1,name:"token",kind:"scalar",T:9},{no:2,name:"session_id",kind:"scalar",T:9},{no:3,name:"subscriber_sdp",kind:"scalar",T:9},{no:8,name:"publisher_sdp",kind:"scalar",T:9},{no:4,name:"client_details",kind:"message",T:()=>eY},{no:5,name:"migration",kind:"message",T:()=>iT},{no:6,name:"fast_reconnect",kind:"scalar",T:8},{no:7,name:"reconnect_details",kind:"message",T:()=>ib}])}}let iv=new im;class iS extends x.C{constructor(){super("stream.video.sfu.event.ReconnectDetails",[{no:1,name:"strategy",kind:"enum",T:()=>["stream.video.sfu.models.WebsocketReconnectStrategy",U,"WEBSOCKET_RECONNECT_STRATEGY_"]},{no:3,name:"announced_tracks",kind:"message",repeat:1,T:()=>eG},{no:4,name:"subscriptions",kind:"message",repeat:1,T:()=>tF},{no:5,name:"reconnect_attempt",kind:"scalar",T:13},{no:6,name:"from_sfu_id",kind:"scalar",T:9},{no:7,name:"previous_session_id",kind:"scalar",T:9}])}}let ib=new iS;class iC extends x.C{constructor(){super("stream.video.sfu.event.Migration",[{no:1,name:"from_sfu_id",kind:"scalar",T:9},{no:2,name:"announced_tracks",kind:"message",repeat:1,T:()=>eG},{no:3,name:"subscriptions",kind:"message",repeat:1,T:()=>tF}])}}let iT=new iC;class ik extends x.C{constructor(){super("stream.video.sfu.event.JoinResponse",[{no:1,name:"call_state",kind:"message",T:()=>eI},{no:2,name:"reconnected",kind:"scalar",T:8},{no:3,name:"fast_reconnect_deadline_seconds",kind:"scalar",T:5},{no:4,name:"publish_options",kind:"message",T:()=>ex}])}}let iy=new ik;class iw extends x.C{constructor(){super("stream.video.sfu.event.ParticipantJoined",[{no:1,name:"call_cid",kind:"scalar",T:9},{no:2,name:"participant",kind:"message",T:()=>eP}])}}let iE=new iw;class iI extends x.C{constructor(){super("stream.video.sfu.event.ParticipantLeft",[{no:1,name:"call_cid",kind:"scalar",T:9},{no:2,name:"participant",kind:"message",T:()=>eP}])}}let i_=new iI;class iR extends x.C{constructor(){super("stream.video.sfu.event.ParticipantUpdated",[{no:1,name:"call_cid",kind:"scalar",T:9},{no:2,name:"participant",kind:"message",T:()=>eP}])}}let iD=new iR;class iA extends x.C{constructor(){super("stream.video.sfu.event.SubscriberOffer",[{no:1,name:"ice_restart",kind:"scalar",T:8},{no:2,name:"sdp",kind:"scalar",T:9}])}}let iO=new iA;class iP extends x.C{constructor(){super("stream.video.sfu.event.PublisherAnswer",[{no:1,name:"sdp",kind:"scalar",T:9}])}}let iN=new iP;class iU extends x.C{constructor(){super("stream.video.sfu.event.ConnectionQualityChanged",[{no:1,name:"connection_quality_updates",kind:"message",repeat:1,T:()=>iM}])}}let iL=new iU;class ij extends x.C{constructor(){super("stream.video.sfu.event.ConnectionQualityInfo",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"session_id",kind:"scalar",T:9},{no:3,name:"connection_quality",kind:"enum",T:()=>["stream.video.sfu.models.ConnectionQuality",I,"CONNECTION_QUALITY_"]}])}}let iM=new ij;class iV extends x.C{constructor(){super("stream.video.sfu.event.DominantSpeakerChanged",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"session_id",kind:"scalar",T:9}])}}let iF=new iV;class ix extends x.C{constructor(){super("stream.video.sfu.event.AudioLevel",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"session_id",kind:"scalar",T:9},{no:3,name:"level",kind:"scalar",T:2},{no:4,name:"is_speaking",kind:"scalar",T:8}])}}let iH=new ix;class iB extends x.C{constructor(){super("stream.video.sfu.event.AudioLevelChanged",[{no:1,name:"audio_levels",kind:"message",repeat:1,T:()=>iH}])}}let iW=new iB;class iq extends x.C{constructor(){super("stream.video.sfu.event.AudioSender",[{no:2,name:"codec",kind:"message",T:()=>eq}])}}let i$=new iq;class iJ extends x.C{constructor(){super("stream.video.sfu.event.VideoLayerSetting",[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"active",kind:"scalar",T:8},{no:3,name:"max_bitrate",kind:"scalar",T:5},{no:4,name:"scale_resolution_down_by",kind:"scalar",T:2},{no:6,name:"codec",kind:"message",T:()=>eq},{no:7,name:"max_framerate",kind:"scalar",T:13},{no:8,name:"scalability_mode",kind:"scalar",T:9}])}}let iG=new iJ;class iK extends x.C{constructor(){super("stream.video.sfu.event.VideoSender",[{no:2,name:"codec",kind:"message",T:()=>eq},{no:3,name:"layers",kind:"message",repeat:1,T:()=>iG}])}}let iX=new iK;class iY extends x.C{constructor(){super("stream.video.sfu.event.ChangePublishQuality",[{no:1,name:"audio_senders",kind:"message",repeat:1,T:()=>i$},{no:2,name:"video_senders",kind:"message",repeat:1,T:()=>iX}])}}let iz=new iY;class iQ extends x.C{constructor(){super("stream.video.sfu.event.CallGrantsUpdated",[{no:1,name:"current_grants",kind:"message",T:()=>e6},{no:2,name:"message",kind:"scalar",T:9}])}}let iZ=new iQ;class i0 extends x.C{constructor(){super("stream.video.sfu.event.GoAway",[{no:1,name:"reason",kind:"enum",T:()=>
1["stream.video.sfu.models.GoAwayReason",P,"GO_AWAY_REASON_"]}])}}let i1=new i0;class i2 extends x.C{constructor(){super("stream.video.sfu.event.CallEnded",[{no:1,name:"reason",kind:"enum",T:()=>["stream.video.sfu.models.CallEndedReason",N,"CALL_ENDED_REASON_"]}])}}let i3=new i2;(C=M||(M={})).UNKNOWN="UNKNOWN",C.VISIBLE="VISIBLE",C.INVISIBLE="INVISIBLE",(T=V||(V={}))[T.IMMEDIATE=20]="IMMEDIATE",T[T.FAST=100]="FAST",T[T.MEDIUM=600]="MEDIUM",T[T.SLOW=1200]="SLOW";class i9{setPublisher(e,t){let i=this.methods[0],s=this._transport.mergeOptions(t);return(0,q.xA)("unary",this._transport,i,s,e)}sendAnswer(e,t){let i=this.methods[1],s=this._transport.mergeOptions(t);return(0,q.xA)("unary",this._transport,i,s,e)}iceTrickle(e,t){let i=this.methods[2],s=this._transport.mergeOptions(t);return(0,q.xA)("unary",this._transport,i,s,e)}updateSubscriptions(e,t){let i=this.methods[3],s=this._transport.mergeOptions(t);return(0,q.xA)("unary",this._transport,i,s,e)}updateMuteStates(e,t){let i=this.methods[4],s=this._transport.mergeOptions(t);return(0,q.xA)("unary",this._transport,i,s,e)}iceRestart(e,t){let i=this.methods[5],s=this._transport.mergeOptions(t);return(0,q.xA)("unary",this._transport,i,s,e)}sendStats(e,t){let i=this.methods[6],s=this._transport.mergeOptions(t);return(0,q.xA)("unary",this._transport,i,s,e)}startNoiseCancellation(e,t){let i=this.methods[7],s=this._transport.mergeOptions(t);return(0,q.xA)("unary",this._transport,i,s,e)}stopNoiseCancellation(e,t){let i=this.methods[8],s=this._transport.mergeOptions(t);return(0,q.xA)("unary",this._transport,i,s,e)}constructor(e){this._transport=e,this.typeName=tY.typeName,this.methods=tY.methods,this.options=tY.options}}let i5={baseUrl:"",sendJson:!0,timeout:5e3,jsonOptions:{ignoreUnknownFields:!0}},i4=e=>({interceptUnary:(t,i,s,n)=>(n.meta={...n.meta,...e},t(i,s,n))}),i8=(e,t)=>({interceptUnary:(i,s,n,a)=>(e(t,"Calling SFU RPC method ".concat(s.name),{input:n,options:a}),i(s,n,a))}),i6=e=>new i9(new G.M({...i5,...e})),i7=e=>new Promise(t=>setTimeout(t,e));function se(e){return e&&("[object Function]"===Object.prototype.toString.call(e)||"function"==typeof e||e instanceof Function)}let st={TOKEN_EXPIRED:40,WS_CLOSED_SUCCESS:1e3};function si(e){let t=Math.min(Math.max(250,(e-1)*2e3),5e3);return Math.floor(Math.random()*(Math.min(500+2e3*e,5e3)-t)+t)}function ss(e){let t="";for(let i=0;i<e.length;i++)t+=e[i].toString(16).padStart(2,"0");return t}function sn(){let e=function(e){let t=new Uint8Array(16);return sa(t),t}(0);return e[6]=15&e[6]|64,e[8]=191&e[8]|128,ss(e.subarray(0,4))+"-"+ss(e.subarray(4,6))+"-"+ss(e.subarray(6,8))+"-"+ss(e.subarray(8,10))+"-"+ss(e.subarray(10,16))}let sa="undefined"!=typeof crypto&&void 0!==(null===(k=crypto)||void 0===k?void 0:k.getRandomValues)?crypto.getRandomValues.bind(crypto):"undefined"!=typeof msCrypto?msCrypto.getRandomValues.bind(msCrypto):function(e){let t=Math.pow(2,8*e.byteLength/e.length);for(let i=0;i<e.length;i++)e[i]=Math.random()*t};function sr(e){window.addEventListener&&(window.addEventListener("offline",e),window.addEventListener("online",e))}function so(e){window.removeEventListener&&(window.removeEventListener("offline",e),window.removeEventListener("online",e))}let sc=()=>{var e;return"undefined"!=typeof navigator&&(null===(e=navigator.product)||void 0===e?void 0:e.toLowerCase())==="reactnative"},sl=Object.freeze({trace:0,debug:1,info:2,warn:3,error:4}),sd="info",sh=function(e,t){let i;for(var s=arguments.length,n=Array(s>2?s-2:0),a=2;a<s;a++)n[a-2]=arguments[a];switch(e){case"error":if(sc()){t="ERROR: ".concat(t),i=console.info;break}i=console.error;break;case"warn":if(sc()){t="WARN: ".concat(t),i=console.info;break}i=console.warn;break;case"info":i=console.info;break;case"trace":i=console.trace;break;default:i=console.log}i(t,...n)},su=(e,t)=>{s=e,t&&sp(t)},sp=e=>{sd=e},sg=()=>sd,sm=e=>{let t=s||sh,i=(e||[]).filter(Boolean).join(":");return function(e,s){for(var n=arguments.length,a=Array(n>2?n-2:0),r=2;r<n;r++)a[r-2]=arguments[r];sl[e]>=sl[sd]&&t(e,"[".concat(i,"]: ").concat(s),...a)}},sv=async(e,t)=>{var i,s;let n;let a=0;do{a>0&&await i7(si(a));try{n=await e()}catch(n){let e=n instanceof $.l&&n.code===K.b[K.b.cancelled],i=null!==(s=null==t?void 0:t.aborted)&&void 0!==s&&s;if(e||i)throw n;sm(["sfu-client","rpc"])("debug","rpc failed (".concat(a,")"),n),a++}}while(!n||(null===(i=n.response.error)||void 0===i?void 0:i.shouldRetry));return n},[sS,sb,sf]="1.14.0".split("."),sC={type:A.PLAIN_JAVASCRIPT,major:sS,minor:sb,patch:sf},sT={oneofKind:void 0},sk=e=>{sC=e},sy=()=>sC,sw=()=>n,sE=()=>a,sI=()=>r,s_=()=>sT,sR=()=>
1{if(sc())return{sdk:sy(),os:sw(),device:sE()};let{browser:e,os:t,device:i,cpu:s}=new X.UAParser(navigator.userAgent).getResult();return{sdk:sy(),browser:{name:e.name||navigator.userAgent,version:e.version||""},os:{name:t.name||"",version:t.version||"",architecture:s.architecture||""},device:{name:[i.vendor,i.model,i.type].filter(Boolean).join(" "),version:""}}},sD=()=>"undefined"!=typeof navigator&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent||""),sA=()=>{var e;return"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Firefox"))};var sO=Object.freeze({__proto__:null,isChrome:()=>{var e;return"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Chrome"))},isFirefox:sA,isSafari:sD});let sP=(e,t,i,s)=>{let n="receiver"===s?RTCRtpReceiver:RTCRtpSender;if(!("getCapabilities"in n))return;let a=n.getCapabilities(e);if(!a)return;let r=[],o=[],c=[],l="".concat(e,"/").concat(t.toLowerCase()),d=i&&"".concat(e,"/").concat(i.toLowerCase());for(let e of a.codecs){let t=e.mimeType.toLowerCase();if(t===d)continue;if(t!==l){c.push(e);continue}if("video/h264"!==t){r.push(e);continue}let i=e.sdpFmtpLine;if(!i||!i.includes("profile-level-id=42")){o.push(e);continue}i.includes("packetization-mode=1")?r.unshift(e):r.push(e)}return[...r,...o,...c]},sN=async e=>{var t;let i=new RTCPeerConnection;i.addTransceiver("video",{direction:e}),i.addTransceiver("audio",{direction:e});let s=null!==(t=(await i.createOffer()).sdp)&&void 0!==t?t:"";return i.getTransceivers().forEach(e=>{var t;null===(t=e.stop)||void 0===t||t.call(e)}),i.close(),s},sU=e=>{if(sc()){var t;let i=null===(t=sw())||void 0===t?void 0:t.name.toLowerCase();return"android"===i?sL(e,"vp8"):"ios"===i||"ipados"===i?sj()?"h264":"vp8":sL(e,"h264")}return sD()?"h264":sA()?"vp8":sL(e,"vp8")},sL=(e,t)=>{if(!e||!("getCapabilities"in RTCRtpSender))return t;let i=RTCRtpSender.getCapabilities("video");if(!i||sM(e)&&(sD()||sA()))return t;let{codecs:s}=i,n="video/".concat(e).toLowerCase();return s.some(e=>e.mimeType.toLowerCase()===n)?e:t},sj=()=>{if(!("getCapabilities"in RTCRtpSender))return!1;let e=RTCRtpSender.getCapabilities("video");return!!e&&e.codecs.some(e=>{var t;return"video/h264"===e.mimeType.toLowerCase()&&(null===(t=e.sdpFmtpLine)||void 0===t?void 0:t.includes("profile-level-id=42e01f"))})},sM=e=>!!e&&("vp9"===(e=e.toLowerCase())||"av1"===e||"video/vp9"===e||"video/av1"===e),sV={subscriberOffer:void 0,publisherAnswer:void 0,connectionQualityChanged:void 0,audioLevelChanged:void 0,iceTrickle:void 0,changePublishQuality:void 0,participantJoined:void 0,participantLeft:void 0,dominantSpeakerChanged:void 0,joinResponse:void 0,healthCheckResponse:void 0,trackPublished:void 0,trackUnpublished:void 0,error:void 0,callGrantsUpdated:void 0,goAway:void 0,iceRestart:void 0,pinsUpdated:void 0,callEnded:void 0,participantUpdated:void 0,participantMigrationComplete:void 0,codecNegotiationComplete:void 0,changePublishOptions:void 0},sF=e=>Object.prototype.hasOwnProperty.call(sV,e);class sx{constructor(){var e=this;this.logger=sm(["Dispatcher"]),this.subscribers={},this.dispatch=function(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"0",s=t.eventPayload.oneofKind;if(!s)return;let n=t.eventPayload[s];e.logger("debug","Dispatching ".concat(s,", tag=").concat(i),n);let a=e.subscribers[s];if(a)for(let t of a)try{t(n)}catch(t){e.logger("warn","Listener failed with error",t)}},this.on=(e,t)=>{var i,s;return(null!==(s=(i=this.subscribers)[e])&&void 0!==s?s:i[e]=[]).push(t),()=>{this.off(e,t)}},this.off=(e,t)=>{this.subscribers[e]=(this.subscribers[e]||[]).filter(e=>e!==t)},this.offAll=e=>{e?this.subscribers[e]=[]:this.subscribers={}}}}class sH{constructor(){this.subscriberCandidates=new Y.t,this.publisherCandidates=new Y.t,this.push=e=>{e.peerType===E.SUBSCRIBER?this.subscriberCandidates.next(e):e.peerType===E.PUBLISHER_UNSPECIFIED?this.publisherCandidates.next(e):sm(["sfu-client"])("warn","ICETrickle, Unknown peer type",e)}}}function sB(e){if(e.usernameFragment)return JSON.stringify(e.toJSON());{let t=e.candidate.split(" "),i=t.findIndex(e=>"ufrag"===e)+1,s=t[i];return JSON.stringify({...e,usernameFragment:s})}}let sW={h264:{2160:5e6,1440:3e6,1080:2e6,720:125e4,540:75e4,360:4e5,default:125e4},vp8:{2160:5e6,1440:275e4,1080:2e6,720:125e4,540:6e5,360:35e4,default:125e4},vp9:{2160:3e6,1440:2e6,1080:15e5,720:125e4,540:5e5,360:275e3,default:125e4},av1:{2160:2e6,1440:155e4,1080:1e6,720:6e5,540:35e4,360:2e5,default:6e5}},sq=(e,t)=>{let i=sW[e];if(!i)throw Error("Unknown codec: ".concat(e));let s=i[t];if(!s){let e=Object.keys(i).map(Number).reduce((e,i)=>Math.abs(i-t)<Math.abs(e-t)?i:e);s=i[e]}return null!=s?s:i.default},s$={bitrate:125e4,width:1280,height:720},sJ={q:3e5,h:75e4,f:125e4},sG=e=>null==e?void 0:e.filter(e=>"f"===e.rid).map(e=>({...e,rid:"q"})),sK=e=>"q"===e?_.LOW_UNSPECIFIED:"h"===e?_.MID:_.HIGH,sX=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s$,i=arguments.length>2?arguments[2]:void 0,s=arguments.length>3?arguments[3]:void 0,n=[],a=e.getSettings(),{width:r=0,height:o=0}=a,{scalabilityMode:c,bitrateDownscaleFactor:l=2,maxSimulcastLayers:d=3}=s||{},h=sY(t,r,o,i,s),u=1,p=1,g=sM(i);for(let e of["f","h","q"].slice(0,g?3:Math.min(3,d))){let t={active:!0,rid:e,width:Math.round(r/u),height:Math.round(o/u),maxBitrate:Math.round(h/p)||sJ[e],maxFramerate:30};g?t.scalabilityMode=c||"L3T2_KEY":t.scaleResolutionDownBy=u,u*=2,p*=l,n.unshift(t)}return sz(a,n)},sY=(e,t,i,s,n)=>{let{width:a,height:r,bitrate:o}=e,{preferredBitrate:c}=n||{},l=c||(s?sq(s,t>i?i:t):o);return t<a||i<r?Math.round(t*i/(a*r)*l):l},sz=(e,t)=>
1{let i;let s=Math.max(e.width||0,e.height||0);i=s<=320?t.filter(e=>"f"===e.rid):s<=640?t.filter(e=>"h"!==e.rid):t;let n=["q","h","f"];return i.map((e,t)=>({...e,rid:n[t]}))},sQ=function(e,t){var i,s;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3e6,{screenShareSettings:a}=t||{},r=e.getSettings();return[{active:!0,rid:"q",width:r.width||0,height:r.height||0,scaleResolutionDownBy:1,maxBitrate:null!==(i=null==a?void 0:a.maxBitrate)&&void 0!==i?i:n,maxFramerate:null!==(s=null==a?void 0:a.maxFramerate)&&void 0!==s?s:30}]},sZ=(e,t)=>{sm(["helpers"])("warn",t,e)},s0=e=>{switch(e){case R.SCREEN_SHARE:return"screenShareStream";case R.SCREEN_SHARE_AUDIO:return"screenShareAudioStream";case R.VIDEO:return"videoStream";case R.AUDIO:return"audioStream";case R.UNSPECIFIED:throw Error("Track type is unspecified");default:sZ(e,"Unknown track type")}},s1=e=>{switch(e){case"audio":return R.AUDIO;case"video":return R.VIDEO;case"screenshare":return R.SCREEN_SHARE;case"screenshare_audio":return R.SCREEN_SHARE_AUDIO;default:sZ(e,"Unknown mute type")}},s2=e=>{switch(e){case"TRACK_TYPE_AUDIO":return R.AUDIO;case"TRACK_TYPE_VIDEO":return R.VIDEO;case"TRACK_TYPE_SCREEN_SHARE":return R.SCREEN_SHARE;case"TRACK_TYPE_SCREEN_SHARE_AUDIO":return R.SCREEN_SHARE_AUDIO;default:return}},s3=s8(function(e,t){let i=!1;return{cb:()=>t().finally(()=>{i||s5.delete(e)}),onContinued:()=>i=!0}}),s9=s8(function(e,t){let i=new AbortController;return{cb:()=>i.signal.aborted?Promise.resolve("canceled"):t(i.signal).finally(()=>{i.signal.aborted||s5.delete(e)}),onContinued:()=>i.abort()}}),s5=new Map;async function s4(e){var t;await (null===(t=s5.get(e))||void 0===t?void 0:t.promise)}function s8(e){return function(t,i){let{cb:s,onContinued:n}=e(t,i),a=s5.get(t);null==a||a.onContinued();let r=a?a.promise.then(s,s):s();return s5.set(t,{promise:r,onContinued:n}),r}}let s6=e=>"function"==typeof e,s7=e=>{let t,i;if((0,z.a)([e]).subscribe({next:e=>{let[i]=e;t=i},error:e=>{i=e}}).unsubscribe(),i)throw i;return t},ne=(e,t)=>{let i=s6(t)?t(s7(e)):t;return e.next(i),i},nt=(e,t)=>{let i=e.getValue();return{lastValue:i,value:ne(e,t),rollback:()=>ne(e,i)}},ni=function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e=>sm(["RxUtils"])("warn","An observable emitted an error",e),s=e.subscribe({next:t,error:i});return()=>{s.unsubscribe()}},ns=(e,t)=>{let i=Symbol();return ni(e,e=>{s3(i,()=>t(e))})};var nn=Object.freeze({__proto__:null,createSafeAsyncSubscription:ns,createSubscription:ni,getCurrentValue:s7,setCurrentValue:ne,updateValue:nt});(y=F||(F={})).UNKNOWN="unknown",y.IDLE="idle",y.RINGING="ringing",y.JOINING="joining",y.JOINED="joined",y.LEFT="left",y.RECONNECTING="reconnecting",y.MIGRATING="migrating",y.RECONNECTING_FAILED="reconnecting-failed",y.OFFLINE="offline";class na{get connectedUser(){return s7(this.connectedUserSubject)}get calls(){return s7(this.callsSubject)}constructor(){this.connectedUserSubject=new Q.X(void 0),this.callsSubject=new Q.X([]),this.setConnectedUser=e=>ne(this.connectedUserSubject,e),this.setCalls=e=>ne(this.callsSubject,e),this.registerCall=e=>{this.calls.find(t=>t.cid===e.cid)||this.setCalls(t=>[...t,e])},this.unregisterCall=e=>this.setCalls(t=>t.filter(t=>t!==e)),this.findCall=(e,t)=>this.calls.find(i=>i.type===e&&i.id===t),this.connectedUserSubject.subscribe(async e=>{if(!e){let e=sm(["client-state"]);for(let t of this.calls)t.state.callingState!==F.LEFT&&(e("info","User disconnected, leaving call: ".concat(t.cid)),await t.leave({reason:"client.disconnectUser() called"}).catch(i=>{e("error","Error leaving call: ".concat(t.cid),i)}))}})}}class nr{get connectedUser(){return s7(this.connectedUser$)}get calls(){return s7(this.calls$)}constructor(e){this.getCurrentValue=s7,this.connectedUser$=e.connectedUserSubject.asObservable(),this.calls$=e.callsSubject.asObservable()}}let no=function(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];return(e,i)=>{for(let s of t){let t=s(e,i);if(0!==t)return t}return 0}},nc=e=>t=>(i,s)=>e(i,s)?t(i,s):0,nl=e=>e.publishedTracks.includes(R.VIDEO),nd=e=>e.publishedTracks.includes(R.AUDIO),nh=e=>e.publishedTracks.includes(R.SCREEN_SHARE),nu=e=>e.publishedTracks.includes(R.SCREEN_SHARE_AUDIO),np=e=>!!e.pin&&(e.pin.isLocalPin||e.pin.pinnedAt>0),ng=(e,t)=>
1e.isDominantSpeaker&&!t.isDominantSpeaker?-1:!e.isDominantSpeaker&&t.isDominantSpeaker?1:0,nm=(e,t)=>e.isSpeaking&&!t.isSpeaking?-1:!e.isSpeaking&&t.isSpeaking?1:0,nv=(e,t)=>nh(e)&&!nh(t)?-1:!nh(e)&&nh(t)?1:0,nS=(e,t)=>nl(e)&&!nl(t)?-1:!nl(e)&&nl(t)?1:0,nb=(e,t)=>nd(e)&&!nd(t)?-1:!nd(e)&&nd(t)?1:0,nf=(e,t)=>{if(e.pin&&t.pin){if(!e.pin.isLocalPin&&t.pin.isLocalPin)return -1;if(e.pin.isLocalPin&&!t.pin.isLocalPin)return 1;if(e.pin.pinnedAt>t.pin.pinnedAt)return -1;if(e.pin.pinnedAt<t.pin.pinnedAt)return 1}return e.pin&&!t.pin?-1:!e.pin&&t.pin?1:0},nC=e=>(t,i)=>{var s,n,a,r;return(null===(s=t.reaction)||void 0===s?void 0:s.type)===e&&(null===(n=i.reaction)||void 0===n?void 0:n.type)!==e?-1:(null===(a=t.reaction)||void 0===a?void 0:a.type)!==e&&(null===(r=i.reaction)||void 0===r?void 0:r.type)===e?1:0},nT=(e,t)=>e.name<t.name?-1:e.name>t.name?1:0,nk=(e,t)=>(e.roles||[]).some(e=>t.includes(e)),ny=nc((e,t)=>{var i,s;return(null===(i=e.viewportVisibilityState)||void 0===i?void 0:i.videoTrack)===M.INVISIBLE||(null===(s=t.viewportVisibilityState)||void 0===s?void 0:s.videoTrack)===M.INVISIBLE}),nw=nc((e,t)=>{var i,s,n,a;return(null===(i=e.viewportVisibilityState)||void 0===i?void 0:i.videoTrack)===M.INVISIBLE||(null===(s=e.viewportVisibilityState)||void 0===s?void 0:s.videoTrack)===M.UNKNOWN||(null===(n=t.viewportVisibilityState)||void 0===n?void 0:n.videoTrack)===M.INVISIBLE||(null===(a=t.viewportVisibilityState)||void 0===a?void 0:a.videoTrack)===M.UNKNOWN}),nE=no(nf,nv,ny(no(ng,nm,nC("raised-hand"),nS,nb))),nI=no(nf,nv,ng,ny(no(nm,nC("raised-hand"),nS,nb))),n_=no(nf,nw(no(ng,nm,nC("raised-hand"),nS,nb))),nR=no(ny(no(ng,nm,nC("raised-hand"),nS,nb)),function(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];return(e,i)=>nk(e,t)&&!nk(i,t)?-1:!nk(e,t)&&nk(i,t)?1:0}("admin","host","speaker")),nD={broadcasting:!1,hls:{playlist_url:""},rtmps:[]};class nA{get participantCount(){return this.getCurrentValue(this.participantCount$)}get startedAt(){return this.getCurrentValue(this.startedAt$)}get captioning(){return this.getCurrentValue(this.captioning$)}get anonymousParticipantCount(){return this.getCurrentValue(this.anonymousParticipantCount$)}get participants(){return this.getCurrentValue(this.participants$)}get localParticipant(){return this.getCurrentValue(this.localParticipant$)}get remoteParticipants(){return this.getCurrentValue(this.remoteParticipants$)}get dominantSpeaker(){return this.getCurrentValue(this.dominantSpeaker$)}get pinnedParticipants(){return this.getCurrentValue(this.pinnedParticipants$)}get hasOngoingScreenShare(){return this.getCurrentValue(this.hasOngoingScreenShare$)}get callingState(){return this.getCurrentValue(this.callingState$)}get callStatsReport(){return this.getCurrentValue(this.callStatsReport$)}get members(){return this.getCurrentValue(this.members$)}get ownCapabilities(){return this.getCurrentValue(this.ownCapabilities$)}get backstage(){return this.getCurrentValue(this.backstage$)}get blockedUserIds(){return this.getCurrentValue(this.blockedUserIds$)}get createdAt(){return this.getCurrentValue(this.createdAt$)}get endedAt(){return this.getCurrentValue(this.endedAt$)}get startsAt(){return this.getCurrentValue(this.startsAt$)}get updatedAt(){return this.getCurrentValue(this.updatedAt$)}get createdBy(){return this.getCurrentValue(this.createdBy$)}get custom(){return this.getCurrentValue(this.custom$)}get egress(){return this.getCurrentValue(this.egress$)}get ingress(){return this.getCurrentValue(this.ingress$)}get recording(){return this.getCurrentValue(this.recording$)}get session(){return this.getCurrentValue(this.session$)}get settings(){return this.getCurrentValue(this.settings$)}get transcribing(){return this.getCurrentValue(this.transcribing$)}get endedBy(){return this.getCurrentValue(this.endedBy$)}get thumbnails(){return this.getCurrentValue(this.thumbnails$)}get closedCaptions(){return this.getCurrentValue(this.closedCaptions$)}constructor(){this.backstageSubject=new Q.X(!0),this.blockedUserIdsSubject=ne
1w Q.X([]),this.createdAtSubject=new Q.X(new Date),this.endedAtSubject=new Q.X(void 0),this.startsAtSubject=new Q.X(void 0),this.updatedAtSubject=new Q.X(new Date),this.createdBySubject=new Q.X(void 0),this.customSubject=new Q.X({}),this.egressSubject=new Q.X(void 0),this.ingressSubject=new Q.X(void 0),this.recordingSubject=new Q.X(!1),this.sessionSubject=new Q.X(void 0),this.settingsSubject=new Q.X(void 0),this.transcribingSubject=new Q.X(!1),this.captioningSubject=new Q.X(!1),this.endedBySubject=new Q.X(void 0),this.thumbnailsSubject=new Q.X(void 0),this.membersSubject=new Q.X([]),this.ownCapabilitiesSubject=new Q.X([]),this.callingStateSubject=new Q.X(F.UNKNOWN),this.startedAtSubject=new Q.X(void 0),this.participantCountSubject=new Q.X(0),this.anonymousParticipantCountSubject=new Q.X(0),this.participantsSubject=new Q.X([]),this.callStatsReportSubject=new Q.X(void 0),this.closedCaptionsSubject=new Q.X([]),this.orphanedTracks=[],this.logger=sm(["CallState"]),this.sortParticipantsBy=nE,this.closedCaptionsTasks=new Map,this.dispose=()=>{for(let[e,t]of this.closedCaptionsTasks.entries())clearTimeout(t),this.closedCaptionsTasks.delete(e)},this.setSortParticipantsBy=e=>{this.sortParticipantsBy=e,this.setCurrentValue(this.participantsSubject,e=>e)},this.getCurrentValue=s7,this.setCurrentValue=ne,this.setParticipantCount=e=>this.setCurrentValue(this.participantCountSubject,e),this.setStartedAt=e=>this.setCurrentValue(this.startedAtSubject,e),this.setCaptioning=e=>nt(this.captioningSubject,e),this.setAnonymousParticipantCount=e=>this.setCurrentValue(this.anonymousParticipantCountSubject,e),this.setParticipants=e=>this.setCurrentValue(this.participantsSubject,e),this.setCallingState=e=>this.setCurrentValue(this.callingStateSubject,e),this.setCallStatsReport=e=>this.setCurrentValue(this.callStatsReportSubject,e),this.setMembers=e=>{this.setCurrentValue(this.membersSubject,e)},this.setOwnCapabilities=e=>this.setCurrentValue(this.ownCapabilitiesSubject,e),this.setEndedAt=e=>this.setCurrentValue(this.endedAtSubject,e),this.findParticipantBySessionId=e=>this.participants.find(t=>t.sessionId===e),this.getParticipantLookupBySessionId=()=>this.participants.reduce((e,t)=>(e[t.sessionId]=t,e),{}),this.updateParticipant=(e,t)=>
1{let i=this.findParticipantBySessionId(e);if(!i){this.logger("warn","Participant with sessionId ".concat(e," not found"));return}let s="function"==typeof t?t(i):t,n={...i,...s};return this.setParticipants(t=>t.map(t=>t.sessionId===e?n:t))},this.updateOrAddParticipant=(e,t)=>this.setParticipants(i=>{let s=!0,n=i.map(i=>i.sessionId===e?(s=!1,{...i,...t}):i);return s&&n.push(t),n}),this.updateParticipants=e=>0===Object.keys(e).length?this.participants:this.setParticipants(t=>t.map(t=>{let i=e[t.sessionId];return i?{...t,...i}:t})),this.updateParticipantTracks=(e,t)=>this.updateParticipants(Object.entries(t).reduce((t,i)=>{let[s,n]=i;n.dimension&&(n.dimension.height=Math.ceil(n.dimension.height),n.dimension.width=Math.ceil(n.dimension.width));let a="videoTrack"===e?"videoDimension":"screenShareTrack"===e?"screenShareDimension":void 0;return a&&(t[s]={[a]:n.dimension}),t},{})),this.updateFromEvent=e=>{let t=this.eventHandlers[e.type];t&&t(e)},this.setServerSidePins=e=>{let t=e.reduce((e,t)=>(e[t.sessionId]=Date.now(),e),{});return this.setParticipants(e=>e.map(e=>{let i=t[e.sessionId];return i?{...e,pin:{isLocalPin:!1,pinnedAt:i}}:e.pin&&!e.pin.isLocalPin?{...e,pin:void 0}:e}))},this.registerOrphanedTrack=e=>{this.orphanedTracks.push(e)},this.removeOrphanedTrack=e=>{this.orphanedTracks=this.orphanedTracks.filter(t=>t.id!==e)},this.takeOrphanedTracks=e=>{let t=this.orphanedTracks.filter(t=>t.trackLookupPrefix===e);return t.length>0&&(this.orphanedTracks=this.orphanedTracks.filter(t=>t.trackLookupPrefix!==e)),t},this.updateClosedCaptionSettings=e=>{this.closedCaptionsSettings={...this.closedCaptionsSettings,...e}},this.updateFromCallResponse=e=>{this.setCurrentValue(this.backstageSubject,e.backstage),this.setCurrentValue(this.blockedUserIdsSubject,e.blocked_user_ids),this.setCurrentValue(this.createdAtSubject,new Date(e.created_at)),this.setCurrentValue(this.updatedAtSubject,new Date(e.updated_at)),this.setCurrentValue(this.startsAtSubject,e.
1starts_at?new Date(e.starts_at):void 0),this.setEndedAt(e.ended_at?new Date(e.ended_at):void 0),this.setCurrentValue(this.createdBySubject,e.created_by),this.setCurrentValue(this.customSubject,e.custom),this.setCurrentValue(this.egressSubject,e.egress),this.setCurrentValue(this.ingressSubject,e.ingress),this.setCurrentValue(this.recordingSubject,e.recording);let t=this.setCurrentValue(this.sessionSubject,e.session);this.updateParticipantCountFromSession(t),this.setCurrentValue(this.settingsSubject,e.settings),this.setCurrentValue(this.transcribingSubject,e.transcribing),this.setCurrentValue(this.captioningSubject,e.captioning),this.setCurrentValue(this.thumbnailsSubject,e.thumbnails)},this.updateFromSfuCallState=(e,t,i)=>{var s;let{participants:n,participantCount:a,startedAt:r,pins:o}=e,c=null!==(s=null==i?void 0:i.announcedTracks.map(e=>e.trackType))&&void 0!==s?s:[];this.setParticipants(()=>{let e=this.getParticipantLookupBySessionId();return n.map(i=>{var s;let n=e[i.sessionId],a=i.sessionId===t;return Object.assign({},n,i,{isLocalParticipant:a,publishedTracks:a?c:i.publishedTracks,viewportVisibilityState:null!==(s=null==n?void 0:n.viewportVisibilityState)&&void 0!==s?s:{videoTrack:M.UNKNOWN,screenShareTrack:M.UNKNOWN}})})}),this.setParticipantCount((null==a?void 0:a.total)||0),this.setAnonymousParticipantCount((null==a?void 0:a.anonymous)||0),this.setStartedAt(r?ew.toDate(r):new Date),this.setServerSidePins(o)},this.updateFromMemberRemoved=e=>{this.updateFromCallResponse(e.call),this.setCurrentValue(this.membersSubject,t=>t.filter(t=>-1===e.members.indexOf(t.user_id)))},this.updateFromMemberAdded=e=>{this.updateFromCallResponse(e.call),this.setCurrentValue(this.membersSubject,t=>[...t,...e.members])},this.updateFromHLSBroadcastStopped=()=>{this.setCurrentValue(this.egressSubject,function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nD;return{...e,broadcasting:!1}})},this.updateFromHLSBroadcastingFailed=()=>{this.setCurrentValue(this.egressSubject,function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nD;return{...e,broadcasting:!1}})},this.updateFromHLSBroadcastStarted=e=>{this.setCurrentValue(this.egressSubject,function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nD;return{...t,broadcasting:!0,hls:{...t.hls,playlist_url:e.hls_playlist_url}}})},this.updateParticipantCountFromSession=e=>{if(!e||this.callingState===F.JOINED)return;let t=Math.max(Object.values(e.participants_count_by_role).reduce((e,t)=>e+t,0),e.participants.length);this.setParticipantCount(t),this.setAnonymousParticipantCount(e.anonymous_participant_count||0)},this.updateFromSessionParticipantCountUpdate=e=>{let t=this.setCurrentValue(this.sessionSubject,t=>t?{...t,anonymous_participant_count:e.anonymous_participant_count,participants_count_by_role:e.participants_count_by_role}:t);this.updateParticipantCountFromSession(t)},this.updateFromSessionParticipantLeft=e=>{let t=this.setCurrentValue(this.sessionSubject,t=>{if(!t)return t;let{participants:i,participants_count_by_role:s}=t,{user:n,user_session_id:a}=e.participant;return{...t,participants:i.filter(e=>e.user_session_id!==a),participants_count_by_role:{...s,[n.role]:Math.max(0,(s[n.role]||0)-1)}}});this.updateParticipantCountFromSession(t)},this.updateFromSessionParticipantJoined=e=>{let t=this.setCurrentValue(this.sessionSubject,t=>{if(!t)return t;let{participants:i,participants_count_by_role:s}=t,{user:n,user_session_id:a}=e.participant,r=!0,o=i.map(t=>t.user_session_id===a?(r=!1,e.participant):t);r&&o.push(e.participant);let c=r?1:0;return{...t,participants:o,participants_count_by_role:{...s,[n.role]:(s[n.role]||0)+c}}});this.updateParticipantCountFromSession(t)},this.updateMembers=e=>{this.updateFromCallResponse(e.call),this.setCurrentValue(this.membersSubject,t=>t.map(t=>e.members.find(e=>e.user_id===t.user_id)||t))},this.updateParticipantReaction=e=>{let{user:t,custom:i,type:s,emoji_code:n}=e.reaction;this.setParticipants(e=>e.map(e=>e.userId!==t.id?e:{...e,reaction:{type:s,emoji_code:n,custom:i}}))},this.unblockUser=e=>{this.setCurrentValue(this.blockedUserIdsSubject,t=>t?t.filter(t=>t!==e.user.id):t)},this.blockUser=e=>{this.setCurrentValue(this.blockedUserIdsSubject,t=>[...t||[],e.user.id])},this.updateOwnCapabilities=e=>{var t;e.user.id===(null===(t=this.localParticipant)||void 0===t?void 0:t.userId)&&this.setCurrentValue(this.ownCapabilitiesSubject,e.own_capabilities)},this.updateFromClosedCaptions=e=>{this.setCurrentValue(this.closedCaptionsSubject,t=>{let{closed_caption:i}=e,s=e=>"".concat(e.speaker_id,"/").concat(e.start_time),n=s(i);if(t.some(e=>s(e)===n))return t;let a=[...t,i],{visibilityDurationMs:r=2700,maxVisibleCaptions:o=2}=this.closedCaptionsSettings||{};if(r>0){let e=setTimeout(()=>{this.setCurrentValue(this.closedCaptionsSubject,e=>e.filter(e=>e!==i)),this.closedCaptionsTasks.delete(n)},r);this.closedCaptionsTasks.set(n,e);for(let e=0;e<a.length-o;e++){let t=s(a[e]);clearTimeout(this.closedCaptionsTasks.get(t)),this.closedCaptionsTasks.delete(t)}}return a.slice(-o)})},this.participants$=this.participantsSubject.asObservable().pipe((0,Z.U)(e=>e.sort(this.sortParticipantsBy)),(0,ee.d)({bufferSize:1,refCount:!0})),this.localParticipant$=this.participants$.pipe((0,Z.U)(e=>e.find(e=>e.isLocalParticipant)),(0,ee.d)({bufferSize:1,refCount:!0})),this.remoteParticipants$=this.participants$.pipe((0,Z.U)(e=>e.filter(e=>!e.isLocalParticipant)),(0,ee.d)({bufferSize:1,refCount:!0})),this.pinnedParticipants$=this.participants$.pipe((0,Z.U)(e=>e.filter(e=>!!e.pin)),(0,ee.d)({bufferSize:1,refCount:!0})),this.dominantSpeaker$=this.participants$.pipe((0,Z.U)(e=>e.find(e=>e.isDominantSpeaker)),(0,ee.d)({bufferSize:1,refCount:!0})),this.hasOngoingScreenShare$=this.participants$.pipe((0,Z.U)(e=>e.some(e=>nh(e))),(0,et.x)(),(0,ee.d)({bufferSize:1,refCount:!0})),this.createdAt$=this.createdAtSubject.asObservable(),this.endedAt$=this.endedAtSubject.asObservable(),this.startsAt$=this.startsAtSubject.asObservable(),this.startedAt$=this.startedAtSubject.asObservable(),this.updatedAt$=this.updatedAtSubject.asObservable(),this.callStatsReport$=this.callStatsReportSubject.asObservable(),this.members$=this.membersSubject.asObservable(),this.createdBy$=this.createdBySubject.asObservable(),this.custom$=this.customSubject.asObservable(),this.egress$=this.egressSubject.asObservable(),this.ingress$=this.ingressSubject.asObservable(),this.session$=this.sessionSubject.asObservable(),this.settings$=this.settingsSubject.asObservable(),this.endedBy$=this.endedBySubject.asObservable(),this.thumbnails$=this.thumbnailsSubject.asObservable(),this.closedCaptions$=this.closedCaptionsSubject.asObservable();let e=(e,t)=>
1{if(e.length!==t.length)return!1;for(let i of e)if(!t.includes(i))return!1;for(let i of t)if(!e.includes(i))return!1;return!0},t=(e,t)=>e.asObservable().pipe((0,et.x)(t));this.anonymousParticipantCount$=t(this.anonymousParticipantCountSubject),this.blockedUserIds$=t(this.blockedUserIdsSubject,e),this.backstage$=t(this.backstageSubject),this.callingState$=t(this.callingStateSubject),this.ownCapabilities$=t(this.ownCapabilitiesSubject,e),this.participantCount$=t(this.participantCountSubject),this.recording$=t(this.recordingSubject),this.transcribing$=t(this.transcribingSubject),this.captioning$=t(this.captioningSubject),this.eventHandlers={"call.deleted":void 0,"call.permission_request":void 0,"call.recording_ready":void 0,"call.transcription_ready":void 0,"call.user_muted":void 0,"connection.error":void 0,"connection.ok":void 0,"health.check":void 0,"user.banned":void 0,"user.deactivated":void 0,"user.deleted":void 0,"user.muted":void 0,"user.presence.changed":void 0,"user.reactivated":void 0,"user.unbanned":void 0,"user.updated":void 0,custom:void 0,"call.accepted":e=>this.updateFromCallResponse(e.call),"call.blocked_user":this.blockUser,"call.closed_caption":this.updateFromClosedCaptions,"call.closed_captions_failed":()=>{this.setCurrentValue(this.captioningSubject,!1)},"call.closed_captions_started":()=>{this.setCurrentValue(this.captioningSubject,!0)},"call.closed_captions_stopped":()=>{this.setCurrentValue(this.captioningSubject,!1)},"call.created":e=>this.updateFromCallResponse(e.call),"call.ended":e=>{this.updateFromCallResponse(e.call),this.setCurrentValue(this.endedBySubject,e.user)},"call.hls_broadcasting_failed":this.updateFromHLSBroadcastingFailed,"call.hls_broadcasting_started":this.updateFromHLSBroadcastStarted,"call.hls_broadcasting_stopped":this.updateFromHLSBroadcastStopped,"call.live_started":e=>this.updateFromCallResponse(e.call),"call.member_added":this.updateFromMemberAdded,"call.member_removed":this.updateFromMemberRemoved,"call.member_updated_permission":this.updateMembers,"call.member_updated":this.updateMembers,"call.notification":e=>{this.updateFromCallResponse(e.call),this.setMembers(e.members)},"call.permissions_updated":this.updateOwnCapabilities,"call.reaction_new":this.updateParticipantReaction,"call.recording_started":()=>this.setCurrentValue(this.recordingSubject,!0),"call.recording_stopped":()=>this.setCurrentValue(this.recordingSubject,!1),"call.recording_failed":()=>this.setCurrentValue(this.recordingSubject,!1),"call.rejected":e=>this.updateFromCallResponse(e.call),"call.ring":e=>this.updateFromCallResponse(e.call),"call.missed":e=>this.updateFromCallResponse(e.call),"call.session_ended":e=>this.updateFromCallResponse(e.call),"call.session_participant_count_updated":this.updateFromSessionParticipantCountUpdate,"call.session_participant_joined":this.updateFromSessionParticipantJoined,"call.session_participant_left":this.updateFromSessionParticipantLeft,"call.session_started":e=>this.updateFromCallResponse(e.call),"call.transcription_started":()=>{this.setCurrentValue(this.transcribingSubject,!0)},"call.transcription_stopped":()=>{this.setCurrentValue(this.transcribingSubject,!1)},"call.transcription_failed":()=>{this.setCurrentValue(this.transcribingSubject,!1)},"call.unblocked_user":this.unblockUser,"call.updated":e=>this.updateFromCallResponse(e.call)}}}let nO=e=>{let t=/^a=rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/.exec(e);if(t)return{original:t[0],payload:t[1],codec:t[2]}},nP=e=>{let t=/^a=fmtp:(\d*) (.*)/.exec(e);if(t)return{original:t[0],payload:t[1],config:t[2]}},nN=(e,t)=>{let i=new RegExp("(m=".concat(t," \\d+ [\\w/]+) ([\\d\\s]+)")).exec(e);if(i)return{original:i[0],mediaWithPorts:i[1],codecOrder:i[2]}},nU=(e,t)=>{let i;let s=[],n=[],a=!1;if(e.split(/(\r\n|\r|\n)/).forEach(e=>{if(!/^([a-z])=(.*)/.test(e))return;let r=e[0];if("m"===r){let s=nN(e,t);a=!!s,s&&(i=s)}else if(a&&"a"===r){let t=nO(e),i=nP(e);t?s.push(t):i&&n.push(i)}}),i)return{media:i,rtpMap:s,fmtp:n}},nL=e=>{let t=nU(e,"audio"),i=null==t?void 0:t.rtpMap.find(e=>"opus"===e.codec.toLowerCase()),s=null==i?void 0:i.payload;if(s)return null==t?void 0:t.fmtp.find(e=>e.payload===s)},nj=(e,t)=>{let i=nL(e);if(!i)return e;let s=/usedtx=(\d)/.exec(i.config),n="usedtx=".concat(t?"1":"0"),a=s?i.original.replace(/usedtx=(\d)/,n):"".concat(i.original,";").concat(n);return e.replace(i.original,a)},nM=(e,t,i)=>{let[s,n]=i.mimeType.toLowerCase().split("/"),a=e=>new Set(e.split(";").map(e=>e.trim().toLowerCase())),r=(e,t)=>{if(e.size!==t.size)return!1;for(let i of e)if(!t.has(i))return!1;return!0},o=a(i.sdpFmtpLine||""),c=ep.Qc(e);for(let e of c.media){var l;if(e.type!==s||String(e.mid)!==t)continue;let i=new Set;for(let t of e.rtp)t.codec.toLowerCase()===n&&("vp8"===n||e.fmtp.some(e=>e.payload===t.payload&&r(a(e.config),o)))&&i.add(t.payload);for(let t of e.fmtp){let e=t.config.match(/(apt)=(\d+)/);if(!e)continue;let[,,s]=e;i.has(Number(s))&&i.add(t.payload)}e.rtp=e.rtp.filter(e=>i.has(e.payload)),e.fmtp=e.fmtp.filter(e=>i.has(e.payload)),e.rtcpFb=null===(l=e.rtcpFb)||void 0===l?void 0:l.filter(e=>i.has(e.payload)),e.payloads=Array.from(i).join(" ")}return ep.cW(c)},nV=function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:51e4;i=Math.max(Math.min(i,51e4),96e3);let s=ep.Qc(e),n=s.media.find(e=>"audio"===e.type&&String(e.mid)===t);if(!n)return e;let a=n.rtp.find(e=>"opus"===e.codec);if(!a)return e;let r=n.fmtp.find(e=>e.payload===a.payload);return r?(r.config.match(/stereo=(\d)/)?r.config=r.config.replace(/stereo=(\d)/,"stereo=1"):r.config="".concat(r.config,";stereo=1"),r.config.match(/maxaveragebitrate=(\d*)/)?r.config=r.config.replace(/maxaveragebitrate=(\d*)/,"maxaveragebitrate=".concat(i)):r.config="".concat(r.config,";maxaveragebitrate=").concat(i),ep.cW(s)):e},nF=(e,t,i)=>{if(e.mid)return e.mid;if(!i)return"";let s=e.sender.track,n=ep.Qc(i).media.find(e=>{var t,i;return e.type===s.kind&&(null===(i=null===(t=e.msid)||void 0===t?void 0:t.includes(s.id
1))||void 0===i||i)});return void 0!==(null==n?void 0:n.mid)?String(n.mid):-1===t?"":String(t)};class nx{removeUnpreferredCodecs(e,t){let i=this.publishOptsForTrack.get(t),s=!!(null==i?void 0:i.forceSingleCodec)||sc()||sA();if(!i||!s)return e;let n=i.forceCodec||sU(i.preferredCodec),a=this.getCodecPreferences(t,n,"sender");if(!a||0===a.length)return e;let r=this.transceiverCache.get(t);if(!r)return e;let o=nF(r,this.transceiverInitOrder.indexOf(t),e),[c]=a;return nM(e,o,c)}constructor({connectionConfig:e,sfuClient:t,dispatcher:i,state:s,isDtxEnabled:n,isRedEnabled:a,onUnrecoverableError:r,logTag:o}){var c=this;this.transceiverCache=new Map,this.trackLayersCache=new Map,this.publishOptsForTrack=new Map,this.transceiverInitOrder=[],this.isIceRestarting=!1,this.createPeerConnection=e=>{let t=new RTCPeerConnection(e);return t.addEventListener("icecandidate",this.onIceCandidate),t.addEventListener("negotiationneeded",this.onNegotiationNeeded),t.addEventListener("icecandidateerror",this.onIceCandidateError),t.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),t.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),t.addEventListener("signalingstatechange",this.onSignalingStateChange),t},this.close=e=>{let{stopTracks:t}=e;t&&(this.stopPublishing(),this.transceiverCache.clear(),this.trackLayersCache.clear()),this.detachEventHandlers(),this.pc.close()},this.detachEventHandlers=()=>{this.unsubscribeOnIceRestart(),this.unsubscribeChangePublishQuality(),this.pc.removeEventListener("icecandidate",this.onIceCandidate),this.pc.removeEventListener("negotiationneeded",this.onNegotiationNeeded),this.pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this.pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this.pc.removeEventListener("signalingstatechange",this.onSignalingStateChange)},this.publishStream=async function(e,t,i){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if("ended"===t.readyState)throw Error("Can't publish a track that has ended already.");t.enabled||(t.enabled=!0);let n=c.transceiverCache.get(i);if(n&&n.sender.track)await c.updateTransceiver(n,t);else{let n=()=>{c.logger("info","Track ".concat(R[i]," has ended abruptly")),t.removeEventListener("ended",n),c.notifyTrackMuteStateChanged(e,i,!0).catch(e=>c.logger("warn","Couldn't notify track mute state",e))};t.addEventListener("ended",n),c.addTransceiver(i,t,s,e)}await c.notifyTrackMuteStateChanged(e,i,!1)},this.addTransceiver=(e,t,i,s)=>{let{forceCodec:n,preferredCodec:a}=i,r=n||sU(a),o=this.computeLayers(e,t,i),c=this.pc.addTransceiver(t,{direction:"sendonly",streams:e===R.VIDEO||e===R.SCREEN_SHARE?[s]:void 0,sendEncodings:sM(r)?sG(o):o});if(this.logger("debug","Added ".concat(R[e]," transceiver")),this.transceiverInitOrder.push(e),this.transceiverCache.set(e,c),this.publishOptsForTrack.set(e,i),!("setCodecPreferences"in c))return;let l=this.getCodecPreferences(e,e===R.VIDEO?r:void 0,"receiver");if(l)try{this.logger("info","Setting ".concat(R[e]," codec preferences"),l),c.setCodecPreferences(l)}catch(e){this.logger("warn","Couldn't set codec preferences",e)}},this.updateTransceiver=async(e,t)=>{let i=e.sender.track;i&&i!==t&&i.stop(),await e.sender.replaceTrack(t)},this.unpublishStream=async(e,t)=>{let i=this.transceiverCache.get(e);if(i&&i.sender.track&&(t?"live"===i.sender.track.readyState:i.sender.track.enabled)){var s;t?i.sender.track.stop():i.sender.track.enabled=!1,(null===(s=this.state.localParticipant)||void 0===s?void 0:s.publishedTracks.includes(e))&&await this.notifyTrackMuteStateChanged(void 0,e,!0)}},this.isPublishing=e=>{let t=this.transceiverCache.get(e);if(!t||!t.sender)return!1;let i=t.sender.track;return!!i&&"live"===i.readyState&&i.enabled},this.notifyTrackMuteStateChanged=async(e,t,i)=>{await this.sfuClient.updateMuteState(t,i);let s=s0(t);s&&(i?this.state.updateParticipant(this.sfuClient.sessionId,e=>({publishedTracks:e.publishedTracks.filter(e=>e!==t),[s]:void 0})):this.state.updateParticipant(this.sfuClient.sessionId,i=>
1({publishedTracks:i.publishedTracks.includes(t)?i.publishedTracks:[...i.publishedTracks,t],[s]:e})))},this.stopPublishing=()=>{this.logger("debug","Stopping publishing all tracks"),this.pc.getSenders().forEach(e=>{var t;null===(t=e.track)||void 0===t||t.stop(),"closed"!==this.pc.signalingState&&this.pc.removeTrack(e)})},this.changePublishQuality=async e=>{var t,i;this.logger("info","Update publish quality, requested layers by SFU:",e);let s=null===(t=this.transceiverCache.get(R.VIDEO))||void 0===t?void 0:t.sender;if(!s){this.logger("warn","Update publish quality, no video sender found.");return}let n=s.getParameters();if(0===n.encodings.length){this.logger("warn","Update publish quality, No suitable video encoding quality found");return}let[a]=n.codecs,r=a&&sM(a.mimeType),o=!1;for(let t of n.encodings){let s=r?e[0]:null!==(i=e.find(e=>e.name===t.rid))&&void 0!==i?i:1===n.encodings.length?e[0]:void 0,a=!!(null==s?void 0:s.active);if(a!==t.active&&(t.active=a,o=!0),!s)continue;let{maxFramerate:c,scaleResolutionDownBy:l,maxBitrate:d,scalabilityMode:h}=s;l>=1&&l!==t.scaleResolutionDownBy&&(t.scaleResolutionDownBy=l,o=!0),d>0&&d!==t.maxBitrate&&(t.maxBitrate=d,o=!0),c>0&&c!==t.maxFramerate&&(t.maxFramerate=c,o=!0),h&&h!==t.scalabilityMode&&(t.scalabilityMode=h,o=!0)}let c=n.encodings.filter(e=>e.active);if(!o){this.logger("info","Update publish quality, no change:",c);return}await s.setParameters(n),this.logger("info","Update publish quality, enabled rids:",c)},this.getStats=e=>this.pc.getStats(e),this.getCodecPreferences=(e,t,i)=>{if(e===R.VIDEO)return sP("video",t||"vp8",void 0,i);if(e===R.AUDIO){let e=this.isRedEnabled?"red":"opus";return sP("audio",null!=t?t:e,this.isRedEnabled?void 0:"red",i)}},this.onIceCandidate=e=>{let{candidate:t}=e;if(!t){this.logger("debug","null ice candidate");return}this.sfuClient.iceTrickle({iceCandidate:sB(t),peerType:E.PUBLISHER_UNSPECIFIED}).catch(e=>{this.logger("warn","ICETrickle failed",e)})},this.setSfuClient=e=>{this.sfuClient=e},this.restartIce=async()=>{this.logger("debug","Restarting ICE connection");let e=this.pc.signalingState;if(this.isIceRestarting||"have-local-offer"===e){this.logger("debug","ICE restart is already in progress");return}await this.negotiate({iceRestart:!0})},this.onNegotiationNeeded=()=>{this.negotiate().catch(e=>{var t;this.logger("error","Negotiation failed.",e),null===(t=this.onUnrecoverableError)||void 0===t||t.call(this)})},this.negotiate=async e=>{let t=await this.pc.createOffer(e);t.sdp&&(t.sdp=nj(t.sdp,this.isDtxEnabled),this.isPublishing(R.SCREEN_SHARE_AUDIO)&&(t.sdp=this.enableHighQualityAudio(t.sdp)),this.isPublishing(R.VIDEO)&&(t.sdp=this.removeUnpreferredCodecs(t.sdp,R.VIDEO)));let i=this.getAnnouncedTracks(t.sdp);if(0===i.length)throw Error("Can't negotiate without announcing any tracks");try{var s;this.isIceRestarting=null!==(s=null==e?void 0:e.iceRestart)&&void 0!==s&&s,await this.pc.setLocalDescription(t);let{response:n}=await this.sfuClient.setPublisher({sdp:t.sdp||"",tracks:i});if(n.error)throw Error(n.error.message);await this.pc.setRemoteDescription({type:"answer",sdp:n.sdp})}finally{this.isIceRestarting=!1}this.sfuClient.iceTrickleBuffer.publisherCandidates.subscribe(async e=>{try{let t=JSON.parse(e.iceCandidate);await this.pc.addIceCandidate(t)}catch(t){this.logger("warn","ICE candidate error",t,e)}})},this.enableHighQualityAudio=e=>{let t=this.transceiverCache.get(R.SCREEN_SHARE_AUDIO);if(!t)return e;let i=nF(t,this.transceiverInitOrder.indexOf(R.SCREEN_SHARE_AUDIO),e);return nV(e,i)},this.getAnnouncedTracks=e=>{var t;return e=e||(null===(t=this.pc.localDescription)||void 0===t?void 0:t.sdp),this.pc.getTransceivers().filter(e=>"sendonly"===e.direction&&e.sender.track).map(t=>{let i,s;this.transceiverCache.forEach((e,s)=>{e===t&&(i=s)});let n=t.sender.track,a="live"===n.readyState;a?(s=this.computeLayers(i,n)||[],this.trackLayersCache.set(i,s)):(s=this.trackLayersCache.get(i)||[],this.logger("debug","Track ".concat(R[i]," is ended. Announcing last known optimal layers"),s));let r=s.map(e=>({rid:e.rid||"",bitrate:e.maxBitrate||0,fps:e.maxFramerate||0,quality:sK(e.rid||""),videoDimension:{width:e.width,height:e.height}})),o=[R.AUDIO,R.SCREEN_SHARE_AUDIO].includes(i),c=n.getSettings(),l=o&&2===c.channelCount,d=this.transceiverInitOrder.indexOf(i);return{trackId:n.id,layers:r,trackType:i,mid:nF(t,d,e),stereo:l,dtx:o&&this.isDtxEnabled,red:o&&this.isRedEnabled,muted:!a}})},this.computeLayers=(e,t,i)=>{var s;let{settings:n}=this.state,a=null==n?void 0:n.video.target_resolution,r=null==n?void 0:null===(s=n.screensharing.target_resolution)||void 0===s?void 0:s.bitrate,o=i||this.publishOptsForTrack.get(e),c=(null==i?void 0:i.forceCodec)||sU(null==i?void 0:i.preferredCodec);return e===R.VIDEO?sX(t,a,c,o):e===R.SCREEN_SHARE?sQ(t,o,r):void 0},this.onIceCandidateError=e=>{let t=e instanceof RTCPeerConnectionIceErrorEvent&&"".concat(e.errorCode,": ").concat(e.errorText),i=this.pc.iceConnectionState;this.logger("connected"===i||"checking"===i?"debug":"warn","ICE Candidate error",t)},this.onIceConnectionStateChange=()=>{let e=this.pc.iceConnectionState;this.logger("debug","ICE Connection state changed to",e),this.state.callingState!==F.RECONNECTING&&("failed"===e||"disconnected"===e)&&(this.logger("debug","Attempting to restart ICE"),this.restartIce().catch(e=>{var t;this.logger("error","ICE restart error",e),null===(t=this.onUnrecoverableError)||void 0===t||t.call(this)}))},this.onIceGatheringStateChange=()=>{this.logger("debug","ICE Gathering State",this.pc.iceGatheringState)},this.onSignalingStateChange=()=>{this.logger("debug","Signaling state changed",this.pc.signalingState)},this.logger=sm(["Publisher",o]),this.pc=this.createPeerConnection(e),this.sfuClient=t,this.state=s,this.isDtxEnabled=n,this.isRedEnabled=a,this.onUnrecoverableError=r,this.unsubscribeOnIceRestart=i.on("iceRestart",e=>{e.peerType===E.PUBLISHER_UNSPECIFIED&&this.restartIce().catch(e=>{var t;this.logger("warn","ICERestart failed",e),null===(t=this.onUnrecoverableError)||void 0===t||t.call(this)})}),this.unsubscribeChangePublishQuality=i.on("changePublishQuality",e=>{let{videoSenders:t}=e;s3("publisher.changePublishQuality",async()=>{for(let e of t){let{layers:t}=e,i=t.filter(e=>e.active);await this.changePublishQuality(i)}}).catch(e=>{this.logger("warn","Failed to change publish quality",e)})})}}class nH{constructor({sfuClient:e,dispatcher:t,state:i,connectionConfig:s,onUnrecoverableError:n,logTag:a}){this.isIceRestarting=!1,this.createPeerConnection=e=>{let t=new RTCPeerConnection(e);return t.addEventListener("icecandidate",this.onIceCandidate),t.addEventListener("track",this.handleOnTrack),t.addEventListener("icecandidateerror",this.onIceCandidateError),t.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),t.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),t},this.close=()=>{this.detachEventHandlers(),this.pc.close()},this.detachEventHandlers=()=>{this.unregisterOnSubscriberOffer(),this.unregisterOnIceRestart(),this.pc.removeEventListener("icecandidate",this.onIceCandidate),this.pc.removeEventListener("track",this.handleOnTrack),this.pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this.pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange)}
1,this.getStats=e=>this.pc.getStats(e),this.setSfuClient=e=>{this.sfuClient=e},this.restartIce=async()=>{if(this.logger("debug","Restarting ICE connection"),"have-remote-offer"===this.pc.signalingState){this.logger("debug","ICE restart is already in progress");return}if("new"===this.pc.connectionState){this.logger("debug","ICE connection is not yet established, skipping restart.");return}let e=this.isIceRestarting;try{this.isIceRestarting=!0,await this.sfuClient.iceRestart({peerType:E.SUBSCRIBER})}catch(t){throw this.isIceRestarting=e,t}},this.handleOnTrack=e=>{let[t]=e.streams,[i,s]=t.id.split(":"),n=this.state.participants.find(e=>e.trackLookupPrefix===i);this.logger("debug","[onTrack]: Got remote ".concat(s," track for userId: ").concat(null==n?void 0:n.userId),e.track.id,e.track);let a="".concat(null==n?void 0:n.userId," ").concat(s,":").concat(i);e.track.addEventListener("mute",()=>{this.logger("info","[onTrack]: Track muted: ".concat(a))}),e.track.addEventListener("unmute",()=>{this.logger("info","[onTrack]: Track unmuted: ".concat(a))}),e.track.addEventListener("ended",()=>{this.logger("info","[onTrack]: Track ended: ".concat(a)),this.state.removeOrphanedTrack(t.id)});let r=s2(s);if(!r)return this.logger("error","Unknown track type: ".concat(s));if(!n){this.logger("warn","[onTrack]: Received track for unknown participant: ".concat(i),e),this.state.registerOrphanedTrack({id:t.id,trackLookupPrefix:i,track:t,trackType:r});return}let o=s0(r);if(!o){this.logger("error","Unknown track type: ".concat(s));return}let c=n[o];c&&(this.logger("info","[onTrack]: Cleaning up previous remote ".concat(e.track.kind," tracks for userId: ").concat(n.userId)),c.getTracks().forEach(e=>{e.stop(),c.removeTrack(e)})),this.state.updateParticipant(n.sessionId,{[o]:t})},this.onIceCandidate=e=>{let{candidate:t}=e;if(!t){this.logger("debug","null ice candidate");return}this.sfuClient.iceTrickle({iceCandidate:sB(t),peerType:E.SUBSCRIBER}).catch(e=>{this.logger("warn","ICETrickle failed",e)})},this.negotiate=async e=>{this.logger("info","Received subscriberOffer",e),await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp}),this.sfuClient.iceTrickleBuffer.subscriberCandidates.subscribe(async e=>{try{let t=JSON.parse(e.iceCandidate);await this.pc.addIceCandidate(t)}catch(t){this.logger("warn","ICE candidate error",[t,e])}});let t=await this.pc.createAnswer();await this.pc.setLocalDescription(t),await this.sfuClient.sendAnswer({peerType:E.SUBSCRIBER,sdp:t.sdp||""}),this.isIceRestarting=!1},this.onIceConnectionStateChange=()=>{let e=this.pc.iceConnectionState;this.logger("debug","ICE connection state changed",e),this.state.callingState!==F.RECONNECTING&&(this.isIceRestarting||"failed"!==e&&"disconnected"!==e||(this.logger("debug","Attempting to restart ICE"),this.restartIce().catch(e=>{var t;this.logger("error","ICE restart failed",e),null===(t=this.onUnrecoverableError)||void 0===t||t.call(this)})))},this.onIceGatheringStateChange=()=>{this.logger("debug","ICE gathering state changed",this.pc.iceGatheringState)},this.onIceCandidateError=e=>{let t=e instanceof RTCPeerConnectionIceErrorEvent&&"".concat(e.errorCode,": ").concat(e.errorText),i=this.pc.iceConnectionState;this.logger("connected"===i||"checking"===i?"debug":"warn","ICE Candidate error",t)},this.logger=sm(["Subscriber",a]),this.sfuClient=e,this.state=i,this.onUnrecoverableError=n,this.pc=this.createPeerConnection(s);let r=Symbol("subscriberOffer");this.unregisterOnSubscriberOffer=t.on("subscriberOffer",e=>{s3(r,()=>this.negotiate(e)).catch(e=>{this.logger("error","Negotiation failed.",e)})});let o=Symbol("iceRestart");this.unregisterOnIceRestart=t.on("iceRestart",e=>{s3(o,async()=>{e.peerType===E.SUBSCRIBER&&await this.restartIce()}).catch(e=>{var t;this.logger("error","ICERestart failed",e),null===(t=this.onUnrecoverableError)||void 0===t||t.call(this)})})}}let nB=e=>{let{endpoint:t,onMessage:i,logTag:s}=e,n=sm(["SfuClientWS",s]),a=new WebSocket(t);return a.binaryType="arraybuffer",a.addEventListener("error",e=>{n("error","Signaling WS channel error",e)}),a.addEventListener("close",e=>{n("info","Signaling WS channel is closed",e)}),a.addEventListener("open",e=>{n("info","Signaling WS channel is open",e)}),a.addEventListener("message",e=>{try{let t=e.data instanceof ArrayBuffer?tQ.fromBinary(new Uint8Array(e.data)):tQ.fromJsonString(e.data.toString());i(t)}catch(t){n("error","Failed to decode a message. Check whether the Proto models match.",{event:e,error:t})}}),a};function nW(e){let t=!0,i=e.then(e=>({status:"resolved",result:e}),e=>({status:"rejected",error:e})).finally(()=>t=!1),s=()=>i.then(e=>{if("rejected"===e.status)throw e.error;return e.result});return s.checkPending=()=>t,s}let nq=()=>{let e,t;let i=new Promise((i,s)=>{e=i,t=s}),s=!1,n=!1;return{promise:i,resolve:t=>{e(t)},reject:e=>{t(e)},isResolved:!1,isRejected:!1}},n$=Symbol("uninitialized");function nJ(e){let t=n$;return()=>(t===n$&&(t=e()),t)}let nG={src:"const timerIdMapping = new Map();\nself.addEventListener('message', (event) => {\n const request = event.data;\n switch (request.type) {\n case 'setTimeout':\n case 'setInterval':\n timerIdMapping.set(request.id, (request.type === 'setTimeout' ? setTimeout : setInterval)(() =>
1 {\n tick(request.id);\n if (request.type === 'setTimeout') {\n timerIdMapping.delete(request.id);\n }\n }, request.timeout));\n break;\n case 'clearTimeout':\n case 'clearInterval':\n (request.type === 'clearTimeout' ? clearTimeout : clearInterval)(timerIdMapping.get(request.id));\n timerIdMapping.delete(request.id);\n break;\n }\n});\nfunction tick(id) {\n const message = { type: 'tick', id };\n self.postMessage(message);\n}"};class nK{setup(){let{useTimerWorker:e=!0}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!e){this.fallback=!0;return}try{let e=nG.src,t=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(t);this.worker=new Worker(i,{name:"str-timer-worker"}),this.worker.addEventListener("message",e=>{let{type:t,id:i}=e.data;if("tick"===t){var s;null===(s=this.callbacks.get(i))||void 0===s||s()}})}catch(e){sm(["timer-worker"])("error",e),this.fallback=!0}}destroy(){var e;this.callbacks.clear(),null===(e=this.worker)||void 0===e||e.terminate(),this.worker=void 0,this.fallback=!1}get ready(){return this.fallback||!!this.worker}setInterval(e,t){return this.setTimer("setInterval",e,t)}clearInterval(e){this.clearTimer("clearInterval",e)}setTimeout(e,t){return this.setTimer("setTimeout",e,t)}clearTimeout(e){this.clearTimer("clearTimeout",e)}setTimer(e,t,i){if(this.ready||this.setup(),this.fallback)return("setTimeout"===e?setTimeout:setInterval)(t,i);let s=this.getTimerId();return this.callbacks.set(s,()=>{t(),"setTimeout"===e&&this.callbacks.delete(s)}),this.sendMessage({type:e,id:s,timeout:i}),s}clearTimer(e,t){if(t){if(this.ready||this.setup(),this.fallback){("clearTimeout"===e?clearTimeout:clearInterval)(t);return}this.callbacks.delete(t),this.sendMessage({type:e,id:t})}}getTimerId(){return this.currentTimerId++}sendMessage(e){if(!this.worker)throw Error("Cannot use timer worker before it's set up");this.worker.postMessage(e)}constructor(){this.currentTimerId=1,this.callbacks=new Map,this.fallback=!1}}let nX=!1,nY=()=>{nX=!0},nz=nJ(()=>{let e=new nK;return e.setup({useTimerWorker:nX}),e});class nQ{get isHealthy(){return this.signalWs.readyState===WebSocket.OPEN}get joinTask(){return this.joinResponseTask.promise}constructor({dispatcher:e,credentials:t,sessionId:i,logTag:s,joinResponseTimeout:n=5e3,onSignalClose:a,streamClient:r}){var o=this;this.iceTrickleBuffer=new sH,this.isLeaving=!1,this.pingIntervalInMs=1e4,this.unhealthyTimeoutInMs=this.pingIntervalInMs+5e3,this.joinResponseTask=nq(),this.abortController=new AbortController,this.createWebSocket=()=>{this.signalWs=nB({logTag:this.logTag,endpoint:"".concat(this.credentials.server.ws_endpoint,"?tag=").concat(this.logTag),onMessage:e=>{this.lastMessageTimestamp=new Date,this.scheduleConnectionCheck(),this.dispatcher.dispatch(e,this.logTag)}}),this.signalWs.addEventListener("close",this.handleWebSocketClose),this.signalReady=nW(Promise.race([new Promise(e=>{let t=()=>{this.signalWs.removeEventListener("open",t),e(this.signalWs)};this.signalWs.addEventListener("open",t)}),new Promise((e,t)=>{setTimeout(()=>t(Error("SFU WS connection timed out")),this.joinResponseTimeout)})]))},this.cleanUpWebSocket=()=>{this.signalWs.removeEventListener("close",this.handleWebSocketClose)},this.handleWebSocketClose=()=>{var e;this.signalWs.removeEventListener("close",this.handleWebSocketClose),nz().clearInterval(this.keepAliveInterval),clearTimeout(this.connectionCheckTimeout),null===(e=this.onSignalClose)||void 0===e||e.call(this)},this.close=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nQ.NORMAL_CLOSURE,t=arguments.length>1?arguments[1]:void 0;o.signalWs.readyState===WebSocket.OPEN&&(o.logger("debug","Closing SFU WS connection: ".concat(e," - ").concat(t)),o.signalWs.close(e,"js-client: ".concat(t)),o.cleanUpWebSocket()),o.dispose()},this.dispose=()=>{var e;this.logger("debug","Disposing SFU client"),this.unsubscribeIceTrickle(),this.unsubscribeNetworkChanged(),clearInterval(this.keepAliveInterval),clearTimeout(this.connectionCheckTimeout),clearTimeout(this.migrateAwayTimeout),this.abortController.abort(),null===(e=this.migrationTask)||void 0===e||e.resolve()},this.leaveAndClose=async e=>{await this.joinTask;try{this.isLeaving=!0,await this.notifyLeave(e)}catch(e){this.logger("debug","Error notifying SFU about leaving call",e)}
1this.close(nQ.NORMAL_CLOSURE,e.substring(0,115))},this.updateSubscriptions=async e=>(await this.joinTask,sv(()=>this.rpc.updateSubscriptions({sessionId:this.sessionId,tracks:e}),this.abortController.signal)),this.setPublisher=async e=>(await this.joinTask,sv(()=>this.rpc.setPublisher({...e,sessionId:this.sessionId}),this.abortController.signal)),this.sendAnswer=async e=>(await this.joinTask,sv(()=>this.rpc.sendAnswer({...e,sessionId:this.sessionId}),this.abortController.signal)),this.iceTrickle=async e=>(await this.joinTask,sv(()=>this.rpc.iceTrickle({...e,sessionId:this.sessionId}),this.abortController.signal)),this.iceRestart=async e=>(await this.joinTask,sv(()=>this.rpc.iceRestart({...e,sessionId:this.sessionId}),this.abortController.signal)),this.updateMuteState=async(e,t)=>(await this.joinTask,this.updateMuteStates({muteStates:[{trackType:e,muted:t}]})),this.updateMuteStates=async e=>(await this.joinTask,sv(()=>this.rpc.updateMuteStates({...e,sessionId:this.sessionId}),this.abortController.signal)),this.sendStats=async e=>(await this.joinTask,sv(()=>this.rpc.sendStats({...e,sessionId:this.sessionId}),this.abortController.signal)),this.startNoiseCancellation=async()=>(await this.joinTask,sv(()=>this.rpc.startNoiseCancellation({sessionId:this.sessionId}),this.abortController.signal)),this.stopNoiseCancellation=async()=>(await this.joinTask,sv(()=>this.rpc.stopNoiseCancellation({sessionId:this.sessionId}),this.abortController.signal)),this.enterMigration=async function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};o.isLeaving=!0;let{timeout:i=7e3}=t;null===(e=o.migrationTask)||void 0===e||e.reject(Error("Cancelled previous migration"));let s=o.migrationTask=nq(),n=o.dispatcher.on("participantMigrationComplete",()=>{n(),clearTimeout(o.migrateAwayTimeout),s.resolve()});return o.migrateAwayTimeout=setTimeout(()=>{n(),s.reject(Error("Migration (".concat(o.logTag,") failed to complete in ").concat(i,"ms")))},i),s.promise},this.join=async e=>{let t;await this.signalReady(),(this.joinResponseTask.isResolved||this.joinResponseTask.isRejected)&&(this.joinResponseTask=nq());let i=this.joinResponseTask,s=this.dispatcher.on("joinResponse",e=>{this.logger("debug","Received joinResponse",e),clearTimeout(t),s(),this.keepAlive(),i.resolve(e)});return t=setTimeout(()=>{s(),i.reject(Error('Waiting for "joinResponse" has timed out'))},this.joinResponseTimeout),await this.send(is.create({requestPayload:{oneofKind:"joinRequest",joinRequest:iv.create({...e,sessionId:this.sessionId,token:this.credentials.token})}})),i.promise},this.ping=async()=>this.send(is.create({requestPayload:{oneofKind:"healthCheckRequest",healthCheckRequest:{}}})),this.notifyLeave=async e=>this.send(is.create({requestPayload:{oneofKind:"leaveCallRequest",leaveCallRequest:{sessionId:this.sessionId,reason:e}}})),this.send=async e=>{await this.signalReady();let t=is.toJson(e);if(this.signalWs.readyState!==WebSocket.OPEN){this.logger("debug","Signal WS is not open. Skipping message",t);return}this.logger("debug","Sending message to: ".concat(this.edgeName),t),this.signalWs.send(is.toBinary(e))},this.keepAlive=()=>{let e=nz();e.clearInterval(this.keepAliveInterval),this.keepAliveInterval=e.setInterval(()=>{this.ping().catch(e=>{this.logger("error","Error sending healthCheckRequest to SFU",e)})},this.pingIntervalInMs)},this.scheduleConnectionCheck=()=>{clearTimeout(this.connectionCheckTimeout),this.connectionCheckTimeout=setTimeout(()=>{this.lastMessageTimestamp&&new Date().getTime()-this.lastMessageTimestamp.getTime()>this.unhealthyTimeoutInMs&&this.close(nQ.ERROR_CONNECTION_UNHEALTHY,"SFU connection unhealthy. Didn't receive any message for ".concat(this.unhealthyTimeoutInMs,"ms"))},this.unhealthyTimeoutInMs)},this.dispatcher=e,this.sessionId=i||sn(),this.onSignalClose=a,this.credentials=t;let{server:c,token:l}=t;this.edgeName=c.edge_name,this.joinResponseTimeout=n,this.logTag=s,this.logger=sm(["SfuClient",s]),this.rpc=i6({baseUrl:c.url,interceptors:[i4({Authorization:"Bearer ".concat(l)}),"trace"===sg()&&i8(this.logger,"trace")].filter(e=>!!e)}),this.unsubscribeIceTrickle=e.on("iceTrickle",e=>{this.iceTrickleBuffer.push(e)}),this.unsubscribeNetworkChanged=r.on("network.changed",e=>{if(e.online){var t;null===(t=this.networkAvailableTask)||void 0===t||t.resolve()}else this.networkAvailableTask=nq()}),this.createWebSocket()}}nQ.NORMAL_CLOSURE=1e3,nQ.ERROR_CONNECTION_UNHEALTHY=4001,nQ.DISPOSE_OLD_SOCKET=4002;let nZ=e=>({iceServers:e.map(e=>({urls:e.urls,username:e.username,credential:e.password}))}),n0=e=>async function(t){if(t.user.id===e.currentUserId)return;let{state:i}=e;t.call.created_by.id===e.currentUserId&&i.callingState===F.RINGING&&await e.join()},n1=e=>async function(t){if(t.user.id===e.currentUserId)return;let{call:i}=t,{session:s}=i;
1if(!s){e.logger("warn","No call session provided. Ignoring call.rejected event.",t);return}let n=s.rejected_by,{members:a,callingState:r}=e.state;if(r!==F.RINGING){e.logger("info","Call is not in ringing mode (it is either accepted or rejected already). Ignoring call.rejected event.",t);return}e.isCreatedByMe?a.filter(t=>t.user_id!==e.currentUserId).every(e=>n[e.user_id])&&(e.logger("info","everyone rejected, leaving the call"),await e.leave({reason:"ring: everyone rejected"})):n[i.created_by.id]&&(e.logger("info","call creator rejected, leaving call"),await e.leave({reason:"ring: creator rejected"}))},n2=e=>function(){let{callingState:t}=e.state;t!==F.IDLE&&t!==F.LEFT&&e.leave({reason:"call.ended event received",reject:!1}).catch(t=>{e.logger("error","Failed to leave call after call.ended ",t)})},n3=e=>e.on("callEnded",async t=>{if(e.state.callingState!==F.LEFT)try{e.state.setEndedAt(new Date);let i=N[t.reason];await e.leave({reason:"callEnded received: ".concat(i)})}catch(t){e.logger("error","Failed to leave call after being ended by the SFU",t)}}),n9=e=>function(t){let{currentGrants:i}=t;if(i){let{canPublishAudio:t,canPublishVideo:s,canScreenshare:n}=i,a={[em.SEND_AUDIO]:t,[em.SEND_VIDEO]:s,[em.SCREENSHARE]:n},r=e.ownCapabilities.filter(e=>!1!==a[e]);Object.entries(a).forEach(e=>{let[t,i]=e;i&&!r.includes(t)&&r.push(t)}),e.setOwnCapabilities(r)}},n5=(e,t)=>e.on("connectionQualityChanged",e=>{let{connectionQualityUpdates:i}=e;i&&t.updateParticipants(i.reduce((e,t)=>{let{sessionId:i,connectionQuality:s}=t;return e[i]={connectionQuality:s},e},{}))}),n4=(e,t)=>e.on("healthCheckResponse",e=>{let{participantCount:i}=e;i&&(t.setParticipantCount(i.total),t.setAnonymousParticipantCount(i.anonymous))}),n8=(e,t)=>e.on("error",e=>{e.error&&e.error.code!==D.LIVE_ENDED||t.permissionsContext.hasPermission(em.JOIN_BACKSTAGE)||t.leave({reason:"live ended"}).catch(e=>{t.logger("error","Failed to leave call after live ended",e)})}),n6=e=>e.on("error",e=>{if(!e.error)return;let t=sm(["SfuClient"]),{error:i,reconnectStrategy:s}=e;t("error","SFU reported error",{code:D[i.code],reconnectStrategy:U[s],message:i.message,shouldRetry:i.shouldRetry})}),n7=e=>function(t){let{pins:i}=t;e.setServerSidePins(i)},ae=e=>e.on("trackUnpublished",async t=>{let{cause:i,type:s,sessionId:n}=t,{localParticipant:a}=e.state;if(i===O.MODERATION&&n===(null==a?void 0:a.sessionId)){let t=e.logger;t("info","Local participant's ".concat(R[s]," track is muted remotely"));try{s===R.VIDEO?await e.camera.disable():s===R.AUDIO?await e.microphone.disable():s===R.SCREEN_SHARE||s===R.SCREEN_SHARE_AUDIO?await e.screenShare.disable():t("warn","Unsupported track type to soft mute",R[s])}catch(e){t("error","Failed to stop publishing",e)}}}),at=e=>function(t){let{participant:i}=t;if(!i)return;let s=ao(e,i);e.updateOrAddParticipant(i.sessionId,Object.assign(i,s,{viewportVisibilityState:{videoTrack:M.UNKNOWN,screenShareTrack:M.UNKNOWN}}))},ai=e=>function(t){let{participant:i}=t;i&&e.setParticipants(e=>e.filter(e=>e.sessionId!==i.sessionId))},as=e=>function(t){let{participant:i}=t;i&&e.updateParticipant(i.sessionId,i)},an=e=>function(t){let{type:i,sessionId:s}=t;if(t.participant){let i=ao(e,t.participant),n=Object.assign(t.participant,i);e.updateOrAddParticipant(s,n)}else e.updateParticipant(s,e=>({publishedTracks:[...e.publishedTracks,i].filter(ar)}))},aa=e=>function(t){let{type:i,sessionId:s}=t;if(t.participant){let i=ao(e,t.participant),n=Object.assign(t.participant,i);e.updateOrAddParticipant(s,n)}else e.updateParticipant(s,e=>({publishedTracks:e.publishedTracks.filter(e=>e!==i)}))},ar=(e,t,i)=>i.indexOf(e)===t,ao=(e,t)=>{let i=e.takeOrphanedTracks(t.trackLookupPrefix);if(!i.length)return;let s={};for(let e of i){let t=s0(e.trackType);t&&(s[t]=e.track)}return s},ac=(e,t)=>e.on("dominantSpeakerChanged",e=>{var i;let{sessionId:s}=e;s!==(null===(i=t.dominantSpeaker)||void 0===i?void 0:i.sessionId)&&t.setParticipants(e=>e.map(e=>e.sessionId===s?{...e,isDominantSpeaker:!0}:e.isDominantSpeaker?{...e,isDominantSpeaker:!1}:e))}),al=(e,t)=>e.on("audioLevelChanged",e=>{let{audioLevels:i}=e;t.updateParticipants(i.reduce((e,t)=>
1(e[t.sessionId]={audioLevel:t.level,isSpeaking:t.isSpeaking},e),{}))}),ad=(e,t)=>{let i=e.state,s=[e.on("call.ended",n2(e)),n3(e),n8(t,e),n6(t),n5(t,i),n4(t,i),e.on("participantJoined",at(i)),e.on("participantLeft",ai(i)),e.on("participantUpdated",as(i)),e.on("trackPublished",an(i)),e.on("trackUnpublished",aa(i)),al(t,i),ac(t,i),e.on("callGrantsUpdated",n9(i)),e.on("pinsUpdated",n7(i)),ae(e)];return e.ringing&&s.push(ah(e)),()=>{s.forEach(e=>e())}},ah=e=>{let t={"call.accepted":n0(e),"call.rejected":n1(e)},i=Object.keys(t).map(i=>e.on(i,t[i]));return()=>{i.forEach(e=>e())}},au=e=>{let t=[];return e.forEach(e=>{t.push(e)}),t},ap=e=>{let{sdk:t,...i}=e;return{sdkName:ag(t),sdkVersion:am(t),...i}},ag=e=>e&&e.type===A.REACT?"stream-react":e&&e.type===A.REACT_NATIVE?"stream-react-native":"stream-js",am=e=>e?"".concat(e.major,".").concat(e.minor,".").concat(e.patch):"0.0.0-development",av=e=>{let t,{subscriber:i,publisher:s,state:n,datacenter:a,pollingIntervalInMs:r=2e3}=e,o=sm(["stats"]),c=async(e,t)=>"subscriber"===e&&i?i.getStats(t):"publisher"===e&&s?s.getStats(t):void 0,l=async(e,t)=>{let n="subscriber"===e?i:s;if(!n)return[];let a=[];for(let i of t.getTracks()){let t=aS(await n.getStats(i),{trackKind:i.kind,kind:e});a.push(t)}return a},d=new Set,h=async()=>{let e={},t=new Set(d);if(t.size>0)for(let i of n.participants){if(!t.has(i.sessionId))continue;let s=i.isLocalParticipant?"publisher":"subscriber";try{var r,h;let t=new MediaStream([...(null===(r=i.videoStream)||void 0===r?void 0:r.getVideoTracks())||[],...(null===(h=i.audioStream)||void 0===h?void 0:h.getAudioTracks())||[]]);e[i.sessionId]=await l(s,t),t.getTracks().forEach(e=>{t.removeTrack(e)})}catch(e){o("error","Failed to collect stats for ".concat(s," of ").concat(i.userId),e)}}let[u,p]=await Promise.all([i.getStats().then(e=>aS(e,{kind:"subscriber",trackKind:"video"})).then(af),s?s.getStats().then(e=>aS(e,{kind:"publisher",trackKind:"video"})).then(af):ab()]),[g,m]=await Promise.all([c("subscriber"),s?c("publisher"):void 0]);n.setCallStatsReport({datacenter:a,publisherStats:p,subscriberStats:u,subscriberRawStats:g,publisherRawStats:m,participants:e,timestamp:Date.now()})};if(r>0){let e=async()=>{await h().catch(e=>{o("debug","Failed to collect stats",e)}),t=setTimeout(e,r)};e()}return{getRawStatsForTrack:c,getStatsForStream:l,startReportingStatsFor:e=>{d.add(e),h()},stopReportingStatsFor:e=>{d.delete(e),h()},stop:()=>{t&&clearTimeout(t)}}},aS=(e,t)=>{let{trackKind:i,kind:s}=t,n="subscriber"===s?"inbound-rtp":"outbound-rtp",a=au(e);return{rawStats:e,streams:a.filter(e=>e.type===n&&e.kind===i).map(e=>{let t;let i=a.find(t=>"codec"===t.type&&t.id===e.codecId),s=a.find(t=>"transport"===t.type&&t.id===e.transportId);if(s&&"connected"===s.dtlsState){let e=a.find(e=>"candidate-pair"===e.type&&e.id===s.selectedCandidatePairId);t=null==e?void 0:e.currentRoundTripTime}return{bytesSent:e.bytesSent,bytesReceived:e.bytesReceived,codec:null==i?void 0:i.mimeType,currentRoundTripTime:t,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,jitter:e.jitter,kind:e.kind,qualityLimitationReason:e.qualityLimitationReason,rid:e.rid,ssrc:e.ssrc}}),timestamp:Date.now()}},ab=e=>({rawReport:null!=e?e:{streams:[],timestamp:Date.now()},totalBytesSent:0,totalBytesReceived:0,averageJitterInMs:0,averageRoundTripTimeInMs:0,qualityLimitationReasons:"none",highestFrameWidth:0,highestFrameHeight:0,highestFramesPerSecond:0,codec:"",timestamp:Date.now()}),af=e=>{let t=ab(e),i=-1,s=(e,t)=>e*t,n=new Set,a=e.streams,r=a.reduce((e,t)=>{e.totalBytesSent+=t.bytesSent||0,e.totalBytesReceived+=t.bytesReceived||0,e.averageJitterInMs+=t.jitter||0,e.averageRoundTripTimeInMs+=t.currentRoundTripTime||0;let a=s(t.frameWidth||0,t.frameHeight||0);return a>i&&(e.highestFrameWidth=t.frameWidth||0,e.highestFrameHeight=t.frameHeight||0,e.highestFramesPerSecond=t.framesPerSecond||0,i=a),n.add(t.qualityLimitationReason||""),e},t);a.length>0&&(r.averageJitterInMs=Math.round(r.averageJitterInMs/a.length*1e3),r.averageRoundTripTimeInMs=Math.round(r.averageRoundTripTimeInMs/a.length*1e3),r.codec=a[0].codec||"");let o=[n.has("cpu")&&"cpu",n.has("bandwidth")&&"bandwidth",n.has("other")&&"other"].filter(
1Boolean).join(", ");return o&&(r.qualityLimitationReasons=o),r};class aC{constructor(e,{options:t,clientDetails:i,subscriber:s,publisher:n,microphone:a,camera:r,state:o}){this.logger=sm(["SfuStatsReporter"]),this.inputDevices=new Map,this.observeDevice=(e,t)=>{var i;let{hasBrowserPermission$:s}=e.state;null===(i=this.unsubscribeDevicePermissionsSubscription)||void 0===i||i.call(this),this.unsubscribeDevicePermissionsSubscription=ni((0,z.a)([s,this.state.ownCapabilities$]),i=>{var s;let[n,a]=i;null===(s=this.unsubscribeListDevicesSubscription)||void 0===s||s.call(this);let r="mic"===t?a.includes(em.SEND_AUDIO):a.includes(em.SEND_VIDEO);if(!n||!r){this.inputDevices.set(t,{currentDevice:"",availableDevices:[],isPermitted:!1});return}this.unsubscribeListDevicesSubscription=ni((0,z.a)([e.listDevices(),e.state.selectedDevice$]),e=>{let[i,s]=e,n=i.find(e=>e.deviceId===s);this.inputDevices.set(t,{currentDevice:(null==n?void 0:n.label)||s||"",availableDevices:i.map(e=>e.label),isPermitted:!0})})})},this.sendTelemetryData=async e=>this.run(e),this.run=async e=>{var t,i;let[s,n]=await Promise.all([this.subscriber.getStats().then(au).then(JSON.stringify),null!==(i=null===(t=this.publisher)||void 0===t?void 0:t.getStats().then(au).then(JSON.stringify))&&void 0!==i?i:"[]"]);await this.sfuClient.sendStats({sdk:this.sdkName,sdkVersion:this.sdkVersion,webrtcVersion:this.webRTCVersion,subscriberStats:s,publisherStats:n,audioDevices:this.inputDevices.get("mic"),videoDevices:this.inputDevices.get("camera"),deviceState:s_(),telemetry:e})},this.start=()=>{this.options.reporting_interval_ms<=0||(this.observeDevice(this.microphone,"mic"),this.observeDevice(this.camera,"camera"),clearInterval(this.intervalId),this.intervalId=setInterval(()=>{this.run().catch(e=>{this.logger("warn","Failed to report stats",e)})},this.options.reporting_interval_ms))},this.stop=()=>{var e,t;null===(e=this.unsubscribeDevicePermissionsSubscription)||void 0===e||e.call(this),this.unsubscribeDevicePermissionsSubscription=void 0,null===(t=this.unsubscribeListDevicesSubscription)||void 0===t||t.call(this),this.unsubscribeListDevicesSubscription=void 0,this.inputDevices.clear(),clearInterval(this.intervalId),this.intervalId=void 0},this.sfuClient=e,this.options=t,this.subscriber=s,this.publisher=n,this.microphone=a,this.camera=r,this.state=o;let{sdk:c,browser:l}=i;this.sdkName=ag(c),this.sdkVersion=am(c);let d=sI();this.webRTCVersion=(null==d?void 0:d.version)||"".concat((null==l?void 0:l.name)||"","-").concat((null==l?void 0:l.version)||"")||"N/A"}}class aT{constructor(){this.elementHandlerMap=new Map,this.observer=null,this.queueSet=new Set,this.setViewport=(e,t)=>{var i;return this.observer=new IntersectionObserver(e=>{e.forEach(e=>{let t=this.elementHandlerMap.get(e.target);null==t||t(e)})},{root:e,...t,threshold:null!==(i=null==t?void 0:t.threshold)&&void 0!==i?i:.35}),this.queueSet.size&&(this.queueSet.forEach(t=>{let[i,s]=t;e.contains(i)&&(this.observer.observe(i),this.elementHandlerMap.set(i,s))}),this.queueSet.clear()),()=>{var e;null===(e=this.observer)||void 0===e||e.disconnect(),this.observer=null,this.elementHandlerMap.clear()}},this.observe=(e,t)=>{let i=[e,t];return this.elementHandlerMap.has(e)||(this.observer?this.observer.root.contains(e)&&(this.elementHandlerMap.set(e,t),this.observer.observe(e)):this.queueSet.add(i)),()=>{var t;this.elementHandlerMap.delete(e),null===(t=this.observer)||void 0===t||t.unobserve(e),this.queueSet.delete(i)}}}}let ak={videoTrack:M.UNKNOWN,screenShareTrack:M.UNKNOWN},ay=Symbol("globalOverrideKey");class aw{setSfuClient(e){this.sfuClient=e}get trackSubscriptions(){let e=[];for(let s of this.callState.remoteParticipants){if(s.videoDimension&&nl(s)){var t,i;let n=null!==(t=this.videoTrackSubscriptionOverrides[s.sessionId])&&void 0!==t?t:this.videoTrackSubscriptionOverrides[ay];(null==n?void 0:n.enabled)!==!1&&e.push({userId:s.userId,sessionId:s.sessionId,trackType:R.VIDEO,dimension:null!==(i=null==n?void 0:n.dimension)&&void 0!==i?i:s.videoDimension})}s.screenShareDimension&&nh(s)&&e.push({userId:s.userId,sessionId:s.sessionId,trackType:R.SCREEN_SHARE,dimension:s.screenShareDimension}),nu(s)&&e.push({userId:s.userId,sessionId:s.sessionId,trackType:R.SCREEN_SHARE_AUDIO})}return e}get videoTrackSubscriptionOverrides(){return s7(this.videoTrackSubscriptionOverrides$)}constructor(e,t){var i=this;this.viewportTracker=new aT,this.logger=sm(["DynascaleManager"]),this.pendingSubscriptionsUpdate=null,this.videoTrackSubscriptionOverridesSubject=ne
1w Q.X({}),this.videoTrackSubscriptionOverrides$=this.videoTrackSubscriptionOverridesSubject.asObservable(),this.incomingVideoSettings$=this.videoTrackSubscriptionOverrides$.pipe((0,Z.U)(e=>{let{[ay]:t,...i}=e;return{enabled:(null==t?void 0:t.enabled)!==!1,preferredResolution:(null==t?void 0:t.enabled)?t.dimension:void 0,participants:Object.fromEntries(Object.entries(i).map(e=>{let[t,i]=e;return[t,{enabled:(null==i?void 0:i.enabled)!==!1,preferredResolution:(null==i?void 0:i.enabled)?i.dimension:void 0}]})),isParticipantVideoEnabled:t=>{var i,s,n,a;return null===(a=null!==(n=null===(i=e[t])||void 0===i?void 0:i.enabled)&&void 0!==n?n:null===(s=e[ay])||void 0===s?void 0:s.enabled)||void 0===a||a}}}),(0,ee.d)(1)),this.setVideoTrackSubscriptionOverrides=(e,t)=>t?ne(this.videoTrackSubscriptionOverridesSubject,i=>({...i,...Object.fromEntries(t.map(t=>[t,e]))})):ne(this.videoTrackSubscriptionOverridesSubject,e?{[ay]:e}:{}),this.applyTrackSubscriptions=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:V.SLOW;i.pendingSubscriptionsUpdate&&clearTimeout(i.pendingSubscriptionsUpdate);let t=()=>{var e;i.pendingSubscriptionsUpdate=null,null===(e=i.sfuClient)||void 0===e||e.updateSubscriptions(i.trackSubscriptions).catch(e=>{i.logger("debug","Failed to update track subscriptions",e)})};e?i.pendingSubscriptionsUpdate=setTimeout(t,e):t()},this.trackElementVisibility=(e,t,i)=>{let s=this.viewportTracker.observe(e,s=>{this.callState.updateParticipant(t,t=>{var n;let a=null!==(n=t.viewportVisibilityState)&&void 0!==n?n:ak,r=s.isIntersecting||document.fullscreenElement===e?M.VISIBLE:M.INVISIBLE;return{...t,viewportVisibilityState:{...a,[i]:r}}})});return()=>{s(),this.callState.updateParticipant(t,e=>{var t;let s=null!==(t=e.viewportVisibilityState)&&void 0!==t?t:ak;return{...e,viewportVisibilityState:{...s,[i]:M.UNKNOWN}}})}},this.setViewport=e=>this.viewportTracker.setViewport(e),this.bindVideoElement=(e,t,i)=>{let s,n;let a=this.callState.findParticipantBySessionId(t);if(!a)return;let r=(e,s)=>{s&&(0===s.width||0===s.height)&&(this.logger("debug","Ignoring 0x0 dimension",a),s=void 0),this.callState.updateParticipantTracks(i,{[t]:{dimension:s}}),this.applyTrackSubscriptions(e)},o=this.callState.participants$.pipe((0,Z.U)(e=>e.find(e=>e.sessionId===t)),(0,ei.o)(e=>!!e),(0,et.x)(),(0,ee.d)({bufferSize:1,refCount:!0})),c=a.isLocalParticipant?null:o.pipe((0,Z.U)(e=>{var t;return null===(t=e.viewportVisibilityState)||void 0===t?void 0:t[i]}),(0,et.x)()).subscribe(t=>{if(!s){s=null!=t?t:M.UNKNOWN;return}if(s=null!=t?t:M.UNKNOWN,t===M.INVISIBLE)return r(V.MEDIUM,void 0);r(V.MEDIUM,{width:e.clientWidth,height:e.clientHeight})}),l=a.isLocalParticipant?null:new ResizeObserver(()=>{let t={width:e.clientWidth,height:e.clientHeight};if(!n){n=t;return}(n.width!==t.width||n.height!==t.height)&&s!==M.INVISIBLE&&(r(Math.max(t.width/n.width,t.height/n.height)>1.2?V.IMMEDIATE:V.MEDIUM,{width:e.clientWidth,height:e.clientHeight}),n=t)});null==l||l.observe(e);let d=a.isLocalParticipant?null:o.pipe((0,es.g)("publishedTracks"),(0,Z.U)(e=>"videoTrack"===i?nl(e):nh(e)),(0,et.x)()).subscribe(t=>{t?r(V.IMMEDIATE,{width:e.clientWidth,height:e.clientHeight}):r(V.FAST,void 0)});e.autoplay=!0,e.playsInline=!0,e.muted=!0;let h=o.pipe((0,es.g)("videoTrack"===i?"videoStream":"screenShareStream")).subscribe(t=>{let s="videoTrack"===i?t.videoStream:t.screenShareStream;e.srcObject!==s&&(e.srcObject=null!=s?s:null,(sD()||sA())&&setTimeout(()=>{e.srcObject=null!=s?s:null,e.play().catch(e=>{this.logger("warn","Failed to play stream",e)})},25))});return()=>{r(V.FAST,void 0),null==c||c.unsubscribe(),null==d||d.unsubscribe(),h.unsubscribe(),null==l||l.disconnect()}},this.bindAudioElement=(e,t,i)=>{let s=this.callState.findParticipantBySessionId(t);if(!s||s.isLocalParticipant)return;let n=this.callState.participants$.pipe((0,Z.U)(e=>e.find(e=>e.sessionId===t)),(0,ei.o)(e=>!!e),(0,et.x)(),(0,ee.d)({bufferSize:1,refCount:!0})),a=n.pipe((0,es.g)("screenShareAudioTrack"===i?"screenShareAudioStream":"audioStream")).subscribe(t=>{let s="screenShareAudioTrack"===i?t.screenShareAudioStream:t.audioStream;e.srcObject!==s&&setTimeout(()=>{if(e.srcObject=null!=s?s:null,e.srcObject){e.play().catch(e=>{this.logger("warn","Failed to play stream",e)});let{selectedDevice:t}=this.speaker.state;t&&"setSinkId"in e&&e.setSinkId(t)}})}),r="setSinkId"in e?this.speaker.state.selectedDevice$.subscribe(t=>{t&&e.setSinkId(t)}):null,o=(0,z.a)([this.speaker.state.volume$,n.pipe((0,es.g)("audioVolume"))]).subscribe(t=>{var i;let[s,n]=t;e.volume=null!==(i=n.audioVolume)&&void 0!==i?i:s});
1return e.autoplay=!0,()=>{null==r||r.unsubscribe(),o.unsubscribe(),a.unsubscribe()}},this.callState=e,this.speaker=t}}class aE{constructor(){var e=this;this.permissions=[],this.setPermissions=e=>{this.permissions=e||[]},this.setCallSettings=e=>{this.settings=e},this.hasPermission=e=>this.permissions.includes(e),this.canRequest=function(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.settings;if(!i)return!1;let{audio:s,video:n,screensharing:a}=i;switch(t){case em.SEND_AUDIO:return s.access_request_enabled;case em.SEND_VIDEO:return n.access_request_enabled;case em.SCREENSHARE:return a.access_request_enabled;default:return!1}}}}class aI{constructor(e,t={sortParticipantsBy:nE}){this.name=e,this.options=t}}class a_{constructor(e){this.register=e=>{this.callTypes[e.name]=e},this.unregister=e=>{delete this.callTypes[e]},this.get=e=>(this.callTypes[e]||this.register(new aI(e)),this.callTypes[e]),this.callTypes=e.reduce((e,t)=>(e[t.name]=t,e),{})}}let aR=new a_([new aI("default",{sortParticipantsBy:nE}),new aI("development",{sortParticipantsBy:nE}),new aI("livestream",{sortParticipantsBy:nR}),new aI("audio_room",{sortParticipantsBy:nR})]);class aD{dispose(){this.state=void 0,this.disposeController.abort()}async getState(){if(await this.ready,!this.state)throw Error("BrowserPermission instance possibly disposed");return this.state}async prompt(){let{forcePrompt:e=!1,throwOnNotAllowed:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return await s3("permission-prompt-".concat(this.permission.queryName),async()=>
1{if(await this.getState()!=="prompt"||this.wasPrompted&&!e){let e="granted"===this.state;if(!e&&t)throw Error("Permission was not granted previously, and prompting again is not allowed");return e}try{this.wasPrompted=!0;let e=await navigator.mediaDevices.getUserMedia(this.permission.constraints);return aJ(e),this.setState("granted"),!0}catch(e){if(e&&"object"==typeof e&&"name"in e&&("NotAllowedError"===e.name||"SecurityError"===e.name)){if(this.logger("info","Browser permission was not granted",{permission:this.permission}),this.setState("denied"),t)throw e;return!1}throw this.logger("error","Failed to getUserMedia",{error:e,permission:this.permission}),e}})}listen(e){return this.listeners.add(e),this.state&&e(this.state),()=>this.listeners.delete(e)}asObservable(){return(0,en.R)(e=>this.listen(e),(e,t)=>t()).pipe((0,Z.U)(e=>"denied"!==e))}setState(e){this.state!==e&&(this.state=e,this.listeners.forEach(t=>t(e)))}constructor(e){this.permission=e,this.disposeController=new AbortController,this.wasPrompted=!1,this.listeners=new Set,this.logger=sm(["permissions"]);let t=this.disposeController.signal;this.ready=(async()=>{var i;let s=e=>{this.setState("prompt")};if(!(!sc()&&"undefined"!=typeof navigator&&(null===(i=navigator.permissions)||void 0===i?void 0:i.query)))return s();try{let i=await navigator.permissions.query({name:e.queryName});t.aborted||(this.setState(i.state),i.addEventListener("change",()=>this.setState(i.state),{signal:t}))}catch(e){s()}})()}}let aA=(e,t)=>(0,ea.D)((async()=>{let i=await navigator.mediaDevices.enumerateDevices();return i.some(e=>e.kind===t&&""===e.label)&&await e.prompt()&&(i=await navigator.mediaDevices.enumerateDevices()),i.filter(e=>e.kind===t&&""!==e.label&&"default"!==e.deviceId)})()),aO=()=>"undefined"!=typeof document&&"setSinkId"in document.createElement("audio"),aP={audio:{autoGainControl:!0,noiseSuppression:!0,echoCancellation:!0}},aN={video:{width:1280,height:720}},aU=nJ(()=>new aD({constraints:aP,queryName:"microphone"})),aL=nJ(()=>new aD({constraints:aN,queryName:"camera"})),aj=nJ(()=>navigator.mediaDevices.addEventListener?(0,er.R)(navigator.mediaDevices,"devicechange").pipe((0,Z.U)(()=>void 0),(0,eo.b)(500)):(0,ea.D)([])),aM=nJ(()=>(0,ec.T)(aj(),aU().asObservable()).pipe((0,el.O)(void 0),(0,ed.b)(()=>aA(aU(),"audioinput")),(0,ee.d)(1))),aV=nJ(()=>(0,ec.T)(aj(),aL().asObservable()).pipe((0,el.O)(void 0),(0,ed.b)(()=>aA(aL(),"videoinput")),(0,ee.d)(1))),aF=nJ(()=>(0,ec.T)(aj(),aU().asObservable()).pipe((0,el.O)(void 0),(0,ed.b)(()=>aA(aU(),"audiooutput")),(0,ee.d)(1))),ax=async e=>{let t=await navigator.mediaDevices.getUserMedia(e);return sA()&&navigator.mediaDevices.dispatchEvent(new Event("devicechange")),t};function aH(e){return e&&"object"==typeof e&&("name"in e&&"OverconstrainedError"===e.name||"message"in e&&"string"==typeof e.message&&e.message.startsWith("OverconstrainedError"))}let aB=async e=>{let t={audio:{...aP.audio,...e}};try{return await aU().prompt({throwOnNotAllowed:!0,forcePrompt:!0}),await ax(t)}catch(i){if(aH(i)&&(null==e?void 0:e.deviceId)){let{deviceId:s,...n}=e;return sm(["devices"])("warn","Failed to get audio stream, will try again with relaxed constraints",{error:i,constraints:t,relaxedConstraints:n}),aB(n)}throw sm(["devices"])("error","Failed to get audio stream",{error:i,constraints:t}),i}},aW=async e=>{let t={video:{...aN.video,...e}};try{return await aL().prompt({throwOnNotAllowed:!0,forcePrompt:!0}),await ax(t)}catch(i){if(aH(i)&&(null==e?void 0:e.deviceId)){let{deviceId:s,...n}=e;return sm(["devices"])("warn","Failed to get video stream, will try again with relaxed constraints",{error:i,constraints:t,relaxedConstraints:n}),aW(n)}throw sm(["devices"])("error","Failed to get video stream",{error:i,constraints:t}),i}},aq=async e=>{try{return await navigator.mediaDevices.getDisplayMedia({video:!0,audio:{channelCount:{ideal:2},echoCancellation:!1,autoGainControl:!1,noiseSuppression:!1},systemAudio:"include",...e})}catch(e){throw sm(["devices"])("error","Failed to get screen share stream",e),e}},a$="undefined"!=typeof navigator&&void 0!==navigator.mediaDevices?aj().pipe((0,el.O)(void 0),(0,ed.b)(()=>navigator.mediaDevices.enumerateDevices()),(0,ee.d)(1)):void 0,aJ=e=>
1{e.active&&(e.getTracks().forEach(e=>{e.stop()}),"function"==typeof e.release&&e.release())};class aG{listDevices(){return this.getDevices()}get enabled(){return"enabled"===this.state.status}async enable(){this.state.prevStatus=this.state.optimisticStatus,"enabled"!==this.state.optimisticStatus&&(this.state.setPendingStatus("enabled"),await s9(this.statusChangeConcurrencyTag,async e=>{try{await this.unmuteStream(),this.state.setStatus("enabled")}finally{e.aborted||this.state.setPendingStatus(this.state.status)}}))}async disable(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.state.prevStatus=this.state.optimisticStatus,(e||"disabled"!==this.state.optimisticStatus)&&(this.state.setPendingStatus("disabled"),await s9(this.statusChangeConcurrencyTag,async t=>{try{let t=e||"stop-tracks"===this.state.disableMode;await this.muteStream(t),this.state.setStatus("disabled")}finally{t.aborted||this.state.setPendingStatus(this.state.status)}}))}async statusChangeSettled(){await s4(this.statusChangeConcurrencyTag)}async resume(){"enabled"===this.state.prevStatus&&"enabled"!==this.state.status&&await this.enable()}async toggle(){return"enabled"===this.state.optimisticStatus?await this.disable():await this.enable()}registerFilter(e){let t={start:e,stop:void 0};return{registered:s3(this.filterRegistrationConcurrencyTag,async()=>{this.filters.push(t),await this.applySettingsToStream()}),unregister:()=>s3(this.filterRegistrationConcurrencyTag,async()=>{var e;null===(e=t.stop)||void 0===e||e.call(t),this.filters=this.filters.filter(e=>e!==t),await this.applySettingsToStream()})}}setDefaultConstraints(e){this.state.setDefaultConstraints(e)}async select(e){if(sc())throw Error("This method is not supported in React Native. Please visit https://getstream.io/video/docs/reactnative/core/camera-and-microphone/#speaker-management for reference.");let t=this.state.selectedDevice;if(e!==t)try{this.state.setDevice(e),await this.applySettingsToStream()}catch(e){throw this.state.setDevice(t),e}}async applySettingsToStream(){await s9(this.statusChangeConcurrencyTag,async()=>{this.enabled&&(await this.muteStream(),await this.unmuteStream())})}getTracks(){var e,t;return null!==(t=null===(e=this.state.mediaStream)||void 0===e?void 0:e.getTracks())&&void 0!==t?t:[]}async muteStream(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];this.state.mediaStream&&(this.logger("debug","".concat(e?"Stopping":"Disabling"," stream")),this.call.state.callingState===F.JOINED&&await this.stopPublishStream(e),this.muteLocalStream(e),this.getTracks().every(e=>"ended"===e.readyState)&&(this.state.mediaStream&&"function"==typeof this.state.mediaStream.release&&this.state.mediaStream.release(),this.state.setMediaStream(void 0,void 0),this.filters.forEach(e=>{var t;return null===(t=e.stop)||void 0===t?void 0:t.call(e)})))}muteTracks(){this.getTracks().forEach(e=>{e.enabled&&(e.enabled=!1)})}unmuteTracks(){this.getTracks().forEach(e=>{e.enabled||(e.enabled=!0)})}stopTracks(){this.getTracks().forEach(e=>{"live"===e.readyState&&e.stop()})}muteLocalStream(e){this.state.mediaStream&&(e?this.stopTracks():this.muteTracks())}async unmuteStream(){let e,t;if(this.logger("debug","Starting stream"),this.state.mediaStream&&this.getTracks().every(e=>"live"===e.readyState))e=this.state.mediaStream,this.unmuteTracks();else{let i={...this.state.defaultConstraints,deviceId:this.state.selectedDevice?{exact:this.state.selectedDevice}:void 0},s=e=>async t=>{if(!e)return t;let i=await e;return t.getTracks().forEach(e=>{let t=e.stop;e.stop=function(){t.call(e),i.getTracks().forEach(t=>{t.kind===e.kind&&t.stop()})}}),i.getTracks().forEach(e=>{let i=()=>{t.getTracks().forEach(t=>{e.kind===t.kind&&(t.stop(),t.dispatchEvent(new Event("ended")))})};e.addEventListener("ended",i),this.subscriptions.push(()=>{e.removeEventListener("ended",i)})}),t};t=this.getStream(i),e=await this.filters.reduce((e,t)=>e.then(e=>{let{stop:i,output:s}=t.start(e);return t.stop=i,s}).then(s(e),t=>(this.logger("warn","Filter failed to start and will be ignored",t),e)),t)}if(this.call.state.callingState===F.JOINED&&await this.publishStream(e),this.state.mediaStream!==e){this.state.setMediaStream(e,await t);let i=async()=>{await this.statusChangeSettled(),this.enabled&&(this.isTrackStoppedDueToTrackEnd=!0,setTimeout(()=>{this.isTrackStoppedDueToTrackEnd=!1},2e3),await this.disable())};
1this.getTracks().forEach(e=>{e.addEventListener("ended",i),this.subscriptions.push(()=>e.removeEventListener("ended",i))})}}get mediaDeviceKind(){return this.trackType===R.AUDIO?"audioinput":this.trackType===R.VIDEO?"videoinput":""}handleDisconnectedOrReplacedDevices(){this.subscriptions.push(ni((0,z.a)([a$.pipe((0,eh.G)()),this.state.selectedDevice$]),async e=>{let[[t,i],s]=e;try{if(!s)return;await this.statusChangeSettled();let e=!1,n=!1,a=this.findDeviceInList(i,s),r=this.findDeviceInList(t,s);!a&&r?e=!0:a&&r&&a.deviceId===r.deviceId&&a.groupId!==r.groupId&&(n=!0),e&&(await this.disable(),await this.select(void 0)),n&&(this.isTrackStoppedDueToTrackEnd&&"disabled"===this.state.status?(await this.enable(),this.isTrackStoppedDueToTrackEnd=!1):await this.applySettingsToStream())}catch(e){this.logger("warn","Unexpected error while handling disconnected or replaced device",e)}}))}findDeviceInList(e,t){return e.find(e=>e.deviceId===t&&e.kind===this.mediaDeviceKind)}constructor(e,t,i){this.call=e,this.state=t,this.trackType=i,this.stopOnLeave=!0,this.subscriptions=[],this.isTrackStoppedDueToTrackEnd=!1,this.filters=[],this.statusChangeConcurrencyTag=Symbol("statusChangeConcurrencyTag"),this.filterRegistrationConcurrencyTag=Symbol("filterRegistrationConcurrencyTag"),this.dispose=()=>{this.subscriptions.forEach(e=>e())},this.logger=sm(["".concat(R[i].toLowerCase()," manager")]),a$&&!sc()&&(this.trackType===R.AUDIO||this.trackType===R.VIDEO)&&this.handleDisconnectedOrReplacedDevices()}}class aK{get status(){return this.getCurrentValue(this.status$)}get optimisticStatus(){return this.getCurrentValue(this.optimisticStatus$)}get selectedDevice(){return this.getCurrentValue(this.selectedDevice$)}get mediaStream(){return this.getCurrentValue(this.mediaStream$)}setStatus(e){this.setCurrentValue(this.statusSubject,e)}setPendingStatus(e){this.setCurrentValue(this.optimisticStatusSubject,e)}setMediaStream(e,t){this.setCurrentValue(this.mediaStreamSubject,e),t&&this.setDevice(this.getDeviceIdFromStream(t))}setDevice(e){this.setCurrentValue(this.selectedDeviceSubject,e)}get defaultConstraints(){return this.getCurrentValue(this.defaultConstraints$)}setDefaultConstraints(e){this.setCurrentValue(this.defaultConstraintsSubject,e)}constructor(e="stop-tracks",t){this.disableMode=e,this.statusSubject=new Q.X(void 0),this.optimisticStatusSubject=new Q.X(void 0),this.mediaStreamSubject=new Q.X(void 0),this.selectedDeviceSubject=new Q.X(void 0),this.defaultConstraintsSubject=new Q.X(void 0),this.mediaStream$=this.mediaStreamSubject.asObservable(),this.selectedDevice$=this.selectedDeviceSubject.asObservable().pipe((0,et.x)()),this.status$=this.statusSubject.asObservable().pipe((0,et.x)()),this.optimisticStatus$=this.optimisticStatusSubject.asObservable().pipe((0,et.x)()),this.defaultConstraints$=this.defaultConstraintsSubject.asObservable(),this.getCurrentValue=s7,this.setCurrentValue=ne,this.hasBrowserPermission$=t?t.asObservable().pipe((0,ee.d)(1)):(0,eu.of)(!0)}}class aX extends aK{get direction(){return this.getCurrentValue(this.direction$)}setDirection(e){this.setCurrentValue(this.directionSubject,e)}setMediaStream(e,t){if(super.setMediaStream(e,t),e){var i;let t=sc()?this.direction:(null===(i=e.getVideoTracks()[0])||void 0===i?void 0:i.getSettings().facingMode)==="environment"?"back":"front";this.setDirection(t)}}getDeviceIdFromStream(e){let[t]=e.getVideoTracks();return null==t?void 0:t.getSettings().deviceId}constructor(){super("stop-tracks",aL()),this.directionSubject=ne
1w Q.X(void 0),this.direction$=this.directionSubject.asObservable().pipe((0,et.x)())}}let aY=()=>/Mobi/i.test(navigator.userAgent);class az extends aG{isDirectionSupportedByDevice(){return sc()||aY()}async selectDirection(e){this.isDirectionSupportedByDevice()?(this.state.setDirection(e),this.state.setDevice(void 0),await this.applySettingsToStream()):this.logger("warn","Camera direction ignored for desktop devices")}async flip(){let e="front"===this.state.direction?"back":"front";await this.selectDirection(e)}async selectTargetResolution(e){if(this.targetResolution.height=e.height,this.targetResolution.width=e.width,"enabled"===this.state.optimisticStatus)try{await this.statusChangeSettled()}catch(e){this.logger("warn","could not apply target resolution",e)}if(this.enabled&&this.state.mediaStream){let[e]=this.state.mediaStream.getVideoTracks();if(!e)return;let{width:t,height:i}=e.getSettings();(t!==this.targetResolution.width||i!==this.targetResolution.height)&&(await this.applySettingsToStream(),this.logger("debug","".concat(t,"x").concat(i," target resolution applied to media stream")))}}setPreferredCodec(e){this.call.updatePublishOptions({preferredCodec:e})}getDevices(){return aV()}getStream(e){return e.width=this.targetResolution.width,e.height=this.targetResolution.height,!e.deviceId&&this.state.direction&&this.isDirectionSupportedByDevice()&&(e.facingMode="front"===this.state.direction?"user":"environment"),aW(e)}publishStream(e){return this.call.publishVideoStream(e)}stopPublishStream(e){return this.call.stopPublish(R.VIDEO,e)}constructor(e){super(e,new aX,R.VIDEO),this.targetResolution={width:1280,height:720}}}class aQ extends aK{get speakingWhileMuted(){return this.getCurrentValue(this.speakingWhileMuted$)}setSpeakingWhileMuted(e){this.setCurrentValue(this.speakingWhileMutedSubject,e)}getDeviceIdFromStream(e){let[t]=e.getAudioTracks();return null==t?void 0:t.getSettings().deviceId}
1constructor(e){super(e,aU()),this.speakingWhileMutedSubject=new Q.X(!1),this.speakingWhileMuted$=this.speakingWhileMutedSubject.asObservable().pipe((0,et.x)())}}let aZ=function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{detectionFrequencyInMs:s=500,audioLevelThreshold:n=150,fftSize:a=128,destroyStreamOnStop:r=!0}=i,o=new AudioContext,c=o.createAnalyser();c.fftSize=a;let l=o.createMediaStreamSource(e);l.connect(c);let d=setInterval(()=>{var i;let s=new Uint8Array(c.frequencyBinCount);c.getByteFrequencyData(s);let a=s.some(e=>e>=n),r=s.reduce((e,t)=>e+t,0)/s.length;(null===(i=e.getAudioTracks()[0])||void 0===i?void 0:i.enabled)?t({isSoundDetected:a,audioLevel:r>n?100:Math.round(r/n*100)}):t({isSoundDetected:!1,audioLevel:0})},s);return async function(){clearInterval(d),l.disconnect(),c.disconnect(),"closed"!==o.state&&await o.close(),r&&e.getTracks().forEach(t=>{t.stop(),e.removeTrack(t)})}};class a0{async start(){try{this.cleanupAudioStream();let e=await navigator.mediaDevices.getUserMedia({audio:!0});this.audioStream=e,this.pc1.addEventListener("icecandidate",async e=>{await this.pc2.addIceCandidate(e.candidate)}),this.pc2.addEventListener("icecandidate",async e=>{await this.pc1.addIceCandidate(e.candidate)}),e.getTracks().forEach(t=>this.pc1.addTrack(t,e));let t=await this.pc1.createOffer({});await this.pc2.setRemoteDescription(t),await this.pc1.setLocalDescription(t);let i=await this.pc2.createAnswer();await this.pc1.setRemoteDescription(i),await this.pc2.setLocalDescription(i),e.getAudioTracks().forEach(e=>e.enabled=!1)}catch(e){console.error("Error connecting and negotiating between PeerConnections:",e)}}stop(){this.pc1.close(),this.pc2.close(),this.cleanupAudioStream(),this.intervalId&&clearInterval(this.intervalId)}onSpeakingDetectedStateChange(e){return this.intervalId=setInterval(async()=>{let t=au(await this.pc1.getStats()).find(e=>"media-source"===e.type&&"audio"===e.kind);if(t){let{audioLevel:i}=t;i&&(i>=.2?e({isSoundDetected:!0,audioLevel:i}):e({isSoundDetected:!1,audioLevel:0}))}},1e3),()=>{clearInterval(this.intervalId)}}cleanupAudioStream(){this.audioStream&&(this.audioStream.getTracks().forEach(e=>e.stop()),"function"==typeof this.audioStream.release&&this.audioStream.release())}constructor(){this.pc1=new RTCPeerConnection({}),this.pc2=new RTCPeerConnection({})}}class a1 extends aG{async enableNoiseCancellation(e){if(sc())throw Error("Noise cancellation is not supported in React Native");let{ownCapabilities:t,settings:i}=this.call.state;if(!t.includes(em.ENABLE_NOISE_CANCELLATION))throw Error("Noise cancellation is not available.");let s=null==i?void 0:i.audio.noise_cancellation;if(!s||s.mode===eg.DISABLED)throw Error("Noise cancellation is disabled for this call type.");try{this.noiseCancellation=e,this.noiseCancellationChangeUnsubscribe=this.noiseCancellation.on("change",e=>{e?this.call.notifyNoiseCancellationStarting().catch(e=>{this.logger("warn","notifyNoiseCancellationStart failed",e)}):this.call.notifyNoiseCancellationStopped().catch(e=>{this.logger("warn","notifyNoiseCancellationStop failed",e)})});let t=this.registerFilter(e.toFilter());this.noiseCancellationRegistration=t.registered,this.unregisterNoiseCancellation=t.unregister,await this.noiseCancellationRegistration,s.mode===eg.AUTO_ON&&this.call.state.callingState===F.JOINED&&e.enable()}catch(e){this.logger("warn","Failed to enable noise cancellation",e),await this.disableNoiseCancellation().catch(e=>{this.logger("warn","Failed to disable noise cancellation",e)})}}async disableNoiseCancellation(){var e,t;if(sc())throw Error("Noise cancellation is not supported in React Native");await (null!==(t=null===(e=this.unregisterNoiseCancellation)||void 0===e?void 0:e.call(this))&&void 0!==t?t:Promise.resolve()).then(()=>{var e;return null===(e=this.noiseCancellation)||void 0===e?void 0:e.disable()}).then(()=>{var e;return null===(e=this.noiseCancellationChangeUnsubscribe)||void 0===e?void 0:e.call(this)}).catch(e=>{this.logger("warn","Failed to unregister noise cancellation",e)}),await this.call.notifyNoiseCancellationStopped()}async enableSpeakingWhileMutedNotification(){this.speakingWhileMutedNotificationEnabled=!0,"disabled"===this.state.status&&await this.startSpeakingWhileMutedDetection(this.state.selectedDevice)}async disableSpeakingWhileMutedNotification(){this.speakingWhileMutedNotificationEnabled=!1,await this.stopSpeakingWhileMutedDetection()}getDevices(){return aM()}getStream(e){return aB(e)}publishStream(e){return this.call.publishAudioStream(e)}stopPublishStream(e){return this.call.stopPublish(R.AUDIO,e)}async startSpeakingWhileMutedDetection(e){await s3(this.soundDetectorConcurrencyTag,async()=>
1{if(await this.stopSpeakingWhileMutedDetection(),sc()){var t;this.rnSpeechDetector=new a0,await this.rnSpeechDetector.start();let e=null===(t=this.rnSpeechDetector)||void 0===t?void 0:t.onSpeakingDetectedStateChange(e=>{this.state.setSpeakingWhileMuted(e.isSoundDetected)});this.soundDetectorCleanup=()=>{var t;e(),null===(t=this.rnSpeechDetector)||void 0===t||t.stop(),this.rnSpeechDetector=void 0}}else{let t=await this.getStream({deviceId:e});this.soundDetectorCleanup=aZ(t,e=>{this.state.setSpeakingWhileMuted(e.isSoundDetected)})}})}async stopSpeakingWhileMutedDetection(){await s3(this.soundDetectorConcurrencyTag,async()=>{if(!this.soundDetectorCleanup)return;let e=this.soundDetectorCleanup;this.soundDetectorCleanup=void 0,this.state.setSpeakingWhileMuted(!1),await e()})}constructor(e,t=sc()?"disable-tracks":"stop-tracks"){super(e,new aQ(t),R.AUDIO),this.speakingWhileMutedNotificationEnabled=!0,this.soundDetectorConcurrencyTag=Symbol("soundDetectorConcurrencyTag"),this.subscriptions.push(ni((0,z.a)([this.call.state.callingState$,this.call.state.ownCapabilities$,this.state.selectedDevice$,this.state.status$]),async e=>{let[t,i,s,n]=e;try{if(t===F.LEFT&&await this.stopSpeakingWhileMutedDetection(),t!==F.JOINED||!this.speakingWhileMutedNotificationEnabled)return;i.includes(em.SEND_AUDIO)&&"disabled"===n?await this.startSpeakingWhileMutedDetection(s):await this.stopSpeakingWhileMutedDetection()}catch(e){this.logger("warn","Could not enable speaking while muted",e)}})),this.subscriptions.push(ni(this.call.state.callingState$,e=>{var t,i;this.noiseCancellationRegistration&&this.noiseCancellation&&((null===(i=this.call.state.settings)||void 0===i?void 0:null===(t=i.audio.noise_cancellation)||void 0===t?void 0:t.mode)===eg.AUTO_ON&&e===F.JOINED?this.noiseCancellationRegistration.then(()=>{var e;return null===(e=this.noiseCancellation)||void 0===e?void 0:e.enable()}).catch(e=>(this.logger("warn","Failed to enable noise cancellation",e),this.call.notifyNoiseCancellationStopped())):e===F.LEFT&&this.noiseCancellationRegistration.then(()=>{var e;return null===(e=this.noiseCancellation)||void 0===e?void 0:e.disable()}).catch(e=>{this.logger("warn","Failed to disable noise cancellation",e)}))}))}}class a2 extends aK{get audioEnabled(){return this.getCurrentValue(this.audioEnabled$)}setAudioEnabled(e){this.setCurrentValue(this.audioEnabledSubject,e)}get settings(){return this.getCurrentValue(this.settings$)}setSettings(e){this.setCurrentValue(this.settingsSubject,e)}
1constructor(){super(...arguments),this.audioEnabledSubject=new Q.X(!0),this.settingsSubject=new Q.X(void 0),this.audioEnabled$=this.audioEnabledSubject.asObservable().pipe((0,et.x)()),this.settings$=this.settingsSubject.asObservable(),this.getDeviceIdFromStream=e=>{let[t]=e.getTracks();return null==t?void 0:t.getSettings().deviceId}}}class a3 extends aG{enableScreenShareAudio(){this.state.setAudioEnabled(!0)}async disableScreenShareAudio(){var e;this.state.setAudioEnabled(!1),(null===(e=this.call.publisher)||void 0===e?void 0:e.isPublishing(R.SCREEN_SHARE_AUDIO))&&await this.call.stopPublish(R.SCREEN_SHARE_AUDIO,!0)}getSettings(){return this.state.settings}setSettings(e){this.state.setSettings(e)}getDevices(){return(0,eu.of)([])}getStream(e){return this.state.audioEnabled||(e.audio=!1),aq(e)}publishStream(e){return this.call.publishScreenShareStream(e)}async stopPublishStream(e){await this.call.stopPublish(R.SCREEN_SHARE,e),await this.call.stopPublish(R.SCREEN_SHARE_AUDIO,e)}async select(e){throw Error("This method is not supported in for Screen Share")}constructor(e){super(e,new a2,R.SCREEN_SHARE),this.subscriptions.push(ni(e.state.settings$,e=>{let t=null==e?void 0:e.screensharing.target_resolution;t&&this.setDefaultConstraints({video:{width:t.width,height:t.height}})}))}}class a9{get selectedDevice(){return this.getCurrentValue(this.selectedDevice$)}get volume(){return this.getCurrentValue(this.volume$)}setDevice(e){this.setCurrentValue(this.selectedDeviceSubject,e)}setVolume(e){this.setCurrentValue(this.volumeSubject,e)}constructor(){this.selectedDeviceSubject=new Q.X(""),this.volumeSubject=new Q.X(1),this.isDeviceSelectionSupported=aO(),this.getCurrentValue=s7,this.setCurrentValue=ne,this.selectedDevice$=this.selectedDeviceSubject.asObservable().pipe((0,et.x)()),this.volume$=this.volumeSubject.asObservable().pipe((0,et.x)())}}class a5{listDevices(){if(sc())throw Error("This feature is not supported in React Native. Please visit https://getstream.io/video/docs/reactnative/core/camera-and-microphone/#speaker-management for more details");return aF()}select(e){if(sc())throw Error("This feature is not supported in React Native. Please visit https://getstream.io/video/docs/reactnative/core/camera-and-microphone/#speaker-management for more details");this.state.setDevice(e)}setVolume(e){if(sc())throw Error("This feature is not supported in React Native. Please visit https://getstream.io/video/docs/reactnative/core/camera-and-microphone/#speaker-management for more details");if(e&&(e<0||e>1))throw Error("Volume must be between 0 and 1");this.state.setVolume(e)}setParticipantVolume(e,t){if(sc())throw Error("This feature is not supported in React Native. Please visit https://getstream.io/video/docs/reactnative/core/camera-and-microphone/#speaker-management for more details");if(t&&(t<0||t>1))throw Error("Volume must be between 0 and 1, or undefined");this.call.state.updateParticipant(e,{audioVolume:t})}constructor(e){this.state=new a9,this.subscriptions=[],this.dispose=()=>{this.subscriptions.forEach(e=>e.unsubscribe())},this.call=e,a$&&!sc()&&this.subscriptions.push((0,z.a)([a$,this.state.selectedDevice$]).subscribe(e=>{let[t,i]=e;i&&(t.find(e=>e.deviceId===i&&"audiooutput"===e.kind)||this.select(""))}))}}class a4{async setup(){await s3(this.joinLeaveConcurrencyTag,async()=>{this.initialized||(this.leaveCallHooks.add(this.on("all",e=>{this.state.updateFromEvent(e)})),this.leaveCallHooks.add(ad(this,this.dispatcher)),this.registerEffects(),this.registerReconnectHandlers(),this.state.callingState===F.LEFT&&this.state.setCallingState(F.IDLE),this.initialized=!0)})}registerEffects(){this.leaveCallHooks.add(ni(this.state.settings$,e=>{e&&this.permissionsContext.setCallSettings(e)})),this.leaveCallHooks.add(ns(this.state.ownCapabilities$,this.handleOwnCapabilitiesUpdated)),this.leaveCallHooks.add(ni(this.state.blockedUserIds$,async e=>{if(!e||0===e.length)return;let t=this.currentUserId;t&&e.includes(t)&&(this.logger("info","Leaving call because of being blocked"),await this.leave({reason:"user blocked"}).catch(e=>{this.logger("error","Error leaving call after being blocked",e)}))}
1)),this.leaveCallHooks.add(ni(this.state.session$,e=>{var t;if(!this.ringing)return;let i=null===(t=this.clientStore.connectedUser)||void 0===t?void 0:t.id;if(!i)return;let s=!!(null==e?void 0:e.accepted_by[i]),n=!!(null==e?void 0:e.rejected_by[i]);(s||n)&&this.cancelAutoDrop()})),this.leaveCallHooks.add(ni(this.ringingSubject,e=>{var t,i;if(!e)return;let s=this.state.session,n=null===(t=this.clientStore.connectedUser)||void 0===t?void 0:t.id,a=null==s?void 0:s.ended_at,r=null===(i=this.state.createdBy)||void 0===i?void 0:i.id,o=null==s?void 0:s.rejected_by,c=null==s?void 0:s.accepted_by,l=!1;a?l=!0:r&&o?o[r]&&(l=!0):n&&o?o[n]&&(l=!0):n&&c&&c[n]&&(l=!0),l?this.state.callingState!==F.IDLE&&this.state.setCallingState(F.IDLE):(this.state.callingState===F.IDLE&&this.state.setCallingState(F.RINGING),this.scheduleAutoDrop(),this.leaveCallHooks.add(ah(this)))}))}get ringing(){return s7(this.ringingSubject)}get currentUserId(){var e;return null===(e=this.clientStore.connectedUser)||void 0===e?void 0:e.id}get isCreatedByMe(){var e;return(null===(e=this.state.createdBy)||void 0===e?void 0:e.id)===this.currentUserId}updatePublishOptions(e){this.publishOptions={...this.publishOptions,...e}}constructor({type:e,id:t,streamClient:i,members:s,ownCapabilities:n,sortParticipantsBy:a,clientStore:r,ringing:o=!1,watching:c=!1}){var l=this;this.state=new nA,this.permissionsContext=new aE,this.dispatcher=new sx,this.sfuClientTag=0,this.reconnectConcurrencyTag=Symbol("reconnectConcurrencyTag"),this.reconnectAttempts=0,this.reconnectStrategy=U.UNSPECIFIED,this.fastReconnectDeadlineSeconds=0,this.disconnectionTimeoutSeconds=0,this.lastOfflineTimestamp=0,this.trackPublishOrder=[],this.hasJoinedOnce=!1,this.deviceSettingsAppliedOnce=!1,this.initialized=!1,this.joinLeaveConcurrencyTag=Symbol("joinLeaveConcurrencyTag"),this.leaveCallHooks=new Set,this.streamClientEventHandlers=new Map,this.handleOwnCapabilitiesUpdated=async e=>{if(this.permissionsContext.setPermissions(e),this.publisher){for(let[e,t]of Object.entries({[em.SEND_AUDIO]:R.AUDIO,[em.SEND_VIDEO]:R.VIDEO,[em.SCREENSHARE]:R.SCREEN_SHARE}))if(!this.permissionsContext.hasPermission(e))try{switch(t){case R.AUDIO:this.microphone.enabled&&await this.microphone.disable();break;case R.VIDEO:this.camera.enabled&&await this.camera.disable();break;case R.SCREEN_SHARE:this.screenShare.enabled&&await this.screenShare.disable()}}catch(e){this.logger("error","Can't disable mic/camera/screenshare after revoked permissions",e)}}},this.on=(e,t)=>{if(sF(e))return this.dispatcher.on(e,t);let i=this.streamClient.on(e,e=>{e.call_cid&&e.call_cid===this.cid&&t(e)});return this.streamClientEventHandlers.set(t,i),()=>{this.off(e,t)}},this.off=(e,t)=>{if(sF(e))return this.dispatcher.off(e,t);let i=this.streamClientEventHandlers.get(t);i&&i()},this.leave=async function(){let{reject:e,reason:t="user is leaving the call"}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};await s3(l.joinLeaveConcurrencyTag,async()=>{var i,s,n,a,r;let o=l.state.callingState;if(o===F.LEFT)throw Error("Cannot leave call that has already been left.");if(o===F.JOINING&&await new Promise(e=>{l.state.callingState$.pipe((0,ei.o)(e=>e!==F.JOINED,!0)).subscribe(()=>e())}),o===F.RINGING&&!1!==e){if(e)await l.reject(t);else{let e=l.state.remoteParticipants.length>0;l.isCreatedByMe&&!e&&await l.reject("cancel")}}null===(i=l.statsReporter)||void 0===i||i.stop(),l.statsReporter=void 0,null===(s=l.sfuStatsReporter)||void 0===s||s.stop(),l.sfuStatsReporter=void 0,null===(n=l.subscriber)||void 0===n||n.close(),l.subscriber=void 0,null===(a=l.publisher)||void 0===a||a.close({stopTracks:!0}),l.publisher=void 0,await (null===(r=l.sfuClient)||void 0===r?void 0:r.leaveAndClose(t)),l.sfuClient=void 0,l.dynascaleManager.setSfuClient(void 0),l.state.setCallingState(F.LEFT),l.state.dispose(),l.leaveCallHooks.forEach(e=>e()),l.initialized=!1,l.hasJoinedOnce=!1,l.clientStore.unregisterCall(l),l.camera.dispose(),l.microphone.dispose(),l.screenShare.dispose(),l.speaker.dispose();let c=[];l.camera.stopOnLeave&&c.push(l.camera.disable(!0)),l.microphone.stopOnLeave&&c.push(l.microphone.disable(!0)),l.screenShare.stopOnLeave&&c.push(l.screenShare.disable(!0)),await Promise.all(c)})},this.updateFromRingingEvent=async e=>{await this.setup();let t=this.state.members.find(t=>t.user.id===e.call.created_by.id);t?this.state.setMembers([t,...e.members]):this.state.setMembers(e.members),this.state.updateFromCallResponse(e.call),this.watching=!0,this.ringingSubject.next(!0);let i=this.clientStore.calls.filter(e=>e.cid!==this.cid);this.clientStore.setCalls([this,...i]),await this.applyDeviceConfig(!1)},this.get=async e=>{await this.setup();let t=await this.streamClient.get(this.streamClientBasePath,e);return this.state.updateFromCallResponse(t.call),this.state.setMembers(t.members),this.state.setOwnCapabilities(t.own_capabilities),((null==e?void 0:e.ring)||this.ringing)&&this.ringingSubject.next(!0),this.streamClient._hasConnectionID()&&(this.watching=!0,this.clientStore.registerCall(this)),await this.applyDeviceConfig(!1),t},this.getOrCreate=async e=>{await this.setup();let t=await this.streamClient.post(this.streamClientBasePath,e);return this.state.updateFromCallResponse(t.call),this.state.setMembers(t.members),this.state.setOwnCapabilities(t.own_capabilities),((null==e?void 0:e.ring)||this.ringing)&&this.ringingSubject.next(!0),this.streamClient._hasConnectionID()&&(this.watching=!0,this.clientStore.registerCall(this)),await this.applyDeviceConfig(!1),t},this.create=async e=>this.getOrCreate(e),this.ring=async()=>await this.get({ring:!0}),this.notify=async()=>await this.get({notify:!0}),this.accept=async()=>this.streamClient.post("".concat(this.streamClientBasePath,"/accept")),this.reject=async e=>this.streamClient.post("".concat(this.streamClientBasePath,"/reject"),{reason:e}),this.join=async e=>{var t,i,s,n;let a=Date.now();await this.setup();let r=this.state.callingState;if([F.JOINED,F.JOINING].includes(r))throw Error("Illegal State: call.join() shall be called only once");this.joinCallData=e,this.logger("debug","Starting join flow"),this.state.setCallingState(F.JOINING);let o=this.reconnectStrategy===U.MIGRATE,c=this.reconnectStrategy===U.REJOIN,l=this.reconnectStrategy===U.FAST,d=null===(t=this.sfuStatsReporter)||void 0===t?void 0:t.options;if(!this.credentials||!d||c||o)try{let t=await this.doJoinRequest(e);this.credentials=t.credentials,d=t.stats_options}catch(e){throw this.state.setCallingState(r),e}let h=this.sfuClient,u=null==h?void 0:h.sessionId,p=!!(null==h?void 0:h.isHealthy),g=c||o||!p?new nQ({logTag:String(this.sfuClientTag++),dispatcher:this.dispatcher,credentials:this.credentials,streamClient:this.streamClient,sessionId:c?void 0:u,onSignalClose:()=>this.handleSfuSignalClose(g)}
1):h;this.sfuClient=g,this.dynascaleManager.setSfuClient(g);let m=sR();if(h!==g){let t=await sN("recvonly"),i=this.reconnectStrategy!==U.UNSPECIFIED?this.getReconnectDetails(null==e?void 0:e.migrating_from,u):void 0,{callState:s,fastReconnectDeadlineSeconds:n}=await g.join({subscriberSdp:t,publisherSdp:"",clientDetails:m,fastReconnect:l,reconnectDetails:i});this.fastReconnectDeadlineSeconds=n,s&&this.state.updateFromSfuCallState(s,g.sessionId,i)}if(o||this.state.setCallingState(F.JOINED),this.hasJoinedOnce=!0,l)await this.restoreICE(g,{includeSubscriber:!1});else{let e=nZ(this.credentials.ice_servers);this.initPublisherAndSubscriber({sfuClient:g,connectionConfig:e,clientDetails:m,statsOptions:d,closePreviousInstances:!o})}if(c||l||o||null===(n=this.sfuStatsReporter)||void 0===n||n.sendTelemetryData({data:{oneofKind:"connectionTimeSeconds",connectionTimeSeconds:(Date.now()-a)/1e3}}),c){let e=U[this.reconnectStrategy];await (null==h?void 0:h.leaveAndClose("Closing previous WS after reconnect with strategy: ".concat(e)))}else p||null==h||h.close(nQ.DISPOSE_OLD_SOCKET,"Closing unhealthy WS after reconnect");this.deviceSettingsAppliedOnce||(await this.applyDeviceConfig(!0),this.deviceSettingsAppliedOnce=!0),null===(i=this.joinCallData)||void 0===i||delete i.ring,null===(s=this.joinCallData)||void 0===s||delete s.notify,this.logger("info","Joined call ".concat(this.cid))},this.getReconnectDetails=(e,t)=>{var i;let s=this.reconnectStrategy,n=s===U.REJOIN;return{strategy:s,announcedTracks:(null===(i=this.publisher)||void 0===i?void 0:i.getAnnouncedTracks())||[],subscriptions:this.dynascaleManager.trackSubscriptions,reconnectAttempt:this.reconnectAttempts,fromSfuId:e||"",previousSessionId:n&&t||""}},this.restoreICE=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{includeSubscriber:i=!0,includePublisher:s=!0}=t;l.subscriber&&(l.subscriber.setSfuClient(e),i&&await l.subscriber.restartIce()),l.publisher&&(l.publisher.setSfuClient(e),s&&await l.publisher.restartIce())},this.initPublisherAndSubscriber=e=>{var t,i,s,n;let{sfuClient:a,connectionConfig:r,clientDetails:o,statsOptions:c,closePreviousInstances:l}=e;if(l&&this.subscriber&&this.subscriber.close(),this.subscriber=new nH({sfuClient:a,dispatcher:this.dispatcher,state:this.state,connectionConfig:r,logTag:String(this.sfuClientTag),onUnrecoverableError:()=>{this.reconnect(U.REJOIN).catch(e=>{this.logger("warn","[Reconnect] Error reconnecting after a subscriber error",e)})}}),(null===(t=this.streamClient.user)||void 0===t?void 0:t.type)!=="anonymous"){l&&this.publisher&&this.publisher.close({stopTracks:!1});let e=null===(n=this.state.settings)||void 0===n?void 0:n.audio,t=!!(null==e?void 0:e.opus_dtx_enabled),i=!!(null==e?void 0:e.redundant_coding_enabled);this.publisher=new nx({sfuClient:a,dispatcher:this.dispatcher,state:this.state,connectionConfig:r,isDtxEnabled:t,isRedEnabled:i,logTag:String(this.sfuClientTag),onUnrecoverableError:()=>{this.reconnect(U.REJOIN).catch(e=>{this.logger("warn","[Reconnect] Error reconnecting after a publisher error",e)})}})}null===(i=this.statsReporter)||void 0===i||i.stop(),this.statsReporter=av({subscriber:this.subscriber,publisher:this.publisher,state:this.state,datacenter:a.edgeName}),null===(s=this.sfuStatsReporter)||void 0===s||s.stop(),(null==c?void 0:c.reporting_interval_ms)>0&&(this.sfuStatsReporter=new aC(a,{clientDetails:o,options:c,subscriber:this.subscriber,publisher:this.publisher,microphone:this.microphone,camera:this.camera,state:this.state}),this.sfuStatsReporter.start())},this.doJoinRequest=async e=>{let t=await this.streamClient.getLocationHint(),i={...e,location:t},s=await this.streamClient.post("".concat(this.streamClientBasePath,"/join"),i);return this.state.updateFromCallResponse(s.call),this.state.setMembers(s.members),this.state.setOwnCapabilities(s.own_capabilities),(null==e?void 0:e.ring)&&!this.ringing&&this.ringingSubject.next(!0),this.ringing&&!this.isCreatedByMe&&await this.accept(),this.streamClient._hasConnectionID()&&(this.watching=!0,this.clientStore.registerCall(this)),s},this.handleSfuSignalClose=e=>{this.logger("debug","[Reconnect] SFU signal connection closed"),this.state.callingState!==F.JOINING&&(e.isLeaving||this.reconnect(U.REJOIN).catch(e=>{this.logger("warn","[Reconnect] Error reconnecting",e)}))},this.reconnect=async e=>{if(this.state.callingState!==F.RECONNECTING&&this.state.callingState!==F.RECONNECTING_FAILED)return s3(this.reconnectConcurrencyTag,async()=>{this.logger("info","[Reconnect] Reconnecting with strategy ".concat(U[e]));let t=Date.now();this.reconnectStrategy=e;do{if(this.disconnectionTimeoutSeconds>0&&(Date.now()-t)/1e3>this.disconnectionTimeoutSeconds){this.logger("warn","[Reconnect] Stopping reconnection attempts after reaching disconnection timeout"),this.state.setCallingState(F.RECONNECTING_FAILED);return}this.reconnectStrategy!==U.FAST&&this.reconnectAttempts++;let e=U[this.reconnectStrategy];try{var i;switch(await (null===(i=this.networkAvailableTask)||void 0===i?void 0:i.promise),this.reconnectStrategy){case U.UNSPECIFIED:case U.DISCONNECT:this.logger("debug","[Reconnect] No-op strategy ".concat(e));break;case U.FAST:await this.reconnectFast();break;case U.REJOIN:await this.reconnectRejoin();break;case U.MIGRATE:await this.reconnectMigrate();break;
1default:sZ(this.reconnectStrategy,"Unknown reconnection strategy")}break}catch(t){if(t instanceof ev&&t.unrecoverable){this.logger("warn","[Reconnect] Can't reconnect due to coordinator unrecoverable error",t),this.state.setCallingState(F.RECONNECTING_FAILED);return}this.logger("warn","[Reconnect] ".concat(e," (").concat(this.reconnectAttempts,") failed. Attempting with REJOIN"),t),await i7(500),this.reconnectStrategy=U.REJOIN}}while(this.state.callingState!==F.JOINED&&this.state.callingState!==F.RECONNECTING_FAILED&&this.state.callingState!==F.LEFT)})},this.reconnectFast=async()=>{var e;let t=Date.now();this.reconnectStrategy=U.FAST,this.state.setCallingState(F.RECONNECTING),await this.join(this.joinCallData),null===(e=this.sfuStatsReporter)||void 0===e||e.sendTelemetryData({data:{oneofKind:"reconnection",reconnection:{timeSeconds:(Date.now()-t)/1e3,strategy:U.FAST}}})},this.reconnectRejoin=async()=>{var e;let t=Date.now();this.reconnectStrategy=U.REJOIN,this.state.setCallingState(F.RECONNECTING),await this.join(this.joinCallData),await this.restorePublishedTracks(),this.restoreSubscribedTracks(),null===(e=this.sfuStatsReporter)||void 0===e||e.sendTelemetryData({data:{oneofKind:"reconnection",reconnection:{timeSeconds:(Date.now()-t)/1e3,strategy:U.REJOIN}}})},this.reconnectMigrate=async()=>{var e,t;let i=Date.now(),s=this.sfuClient;if(!s)throw Error("Cannot migrate without an active SFU client");this.reconnectStrategy=U.MIGRATE,this.state.setCallingState(F.MIGRATING);let n=this.subscriber,a=this.publisher;null==n||n.detachEventHandlers(),null==a||a.detachEventHandlers();let r=nW(s.enterMigration());try{let e=s.edgeName;await this.join({...this.joinCallData,migrating_from:e})}finally{null===(t=this.joinCallData)||void 0===t||delete t.migrating_from}await this.restorePublishedTracks(),this.restoreSubscribedTracks();try{await r(),this.state.setCallingState(F.JOINED)}finally{null==n||n.close(),null==a||a.close({stopTracks:!1}),s.close()}null===(e=this.sfuStatsReporter)||void 0===e||e.sendTelemetryData({data:{oneofKind:"reconnection",reconnection:{timeSeconds:(Date.now()-i)/1e3,strategy:U.MIGRATE}}})},this.registerReconnectHandlers=()=>{let e=this.on("goAway",()=>{this.reconnect(U.MIGRATE).catch(e=>{this.logger("warn","[Reconnect] Error reconnecting",e)})}),t=this.on("error",e=>{let{reconnectStrategy:t}=e;t!==U.UNSPECIFIED&&(t===U.DISCONNECT?this.leave({reason:"SFU instructed to disconnect"}).catch(e=>{this.logger("warn","Can't leave call after disconnect request",e)}):this.reconnect(t).catch(e=>{this.logger("warn","[Reconnect] Error reconnecting",e)}))}),i=this.streamClient.on("network.changed",e=>{var t,i,s,n;if(e.online)this.logger("debug","[Reconnect] Going online"),null===(i=this.sfuClient)||void 0===i||i.close(nQ.DISPOSE_OLD_SOCKET,"Closing WS to reconnect after going online"),null===(s=this.networkAvailableTask)||void 0===s||s.resolve(),this.networkAvailableTask=void 0,null===(n=this.sfuStatsReporter)||void 0===n||n.start();else{if(this.logger("debug","[Reconnect] Going offline"),!this.hasJoinedOnce)return;this.lastOfflineTimestamp=Date.now();let e=nq();e.promise.then(()=>{let e=U.FAST;this.lastOfflineTimestamp&&(Date.now()-this.lastOfflineTimestamp)/1e3>this.fastReconnectDeadlineSeconds&&(e=U.REJOIN),this.reconnect(e).catch(e=>{this.logger("warn","[Reconnect] Error reconnecting after going online",e)})}),this.networkAvailableTask=e,null===(t=this.sfuStatsReporter)||void 0===t||t.stop(),this.state.setCallingState(F.OFFLINE)}});this.leaveCallHooks.add(e),this.leaveCallHooks.add(t),this.leaveCallHooks.add(i)},this.restorePublishedTracks=async()=>{for(let e of this.trackPublishOrder)switch(e){case R.AUDIO:let t=this.microphone.state.mediaStream;t&&await this.publishAudioStream(t);break;case R.VIDEO:let i=this.camera.state.mediaStream;i&&await this.publishVideoStream(i);break;case R.SCREEN_SHARE:let s=this.screenShare.state.mediaStream;s&&await this.publishScreenShareStream(s);break;case R.SCREEN_SHARE_AUDIO:case R.UNSPECIFIED:break;default:sZ(e,"Unknown track type")}},this.restoreSubscribedTracks=()=>{let{remoteParticipants:e}=this.state;e.length<=0||this.dynascaleManager.applyTrackSubscriptions(void 0)}
1,this.publishVideoStream=async e=>{if(!this.sfuClient)throw Error("Call not joined yet.");if(await this.sfuClient.joinTask,!this.permissionsContext.hasPermission(em.SEND_VIDEO))throw Error("No permission to publish video");if(!this.publisher)throw Error("Publisher is not initialized");let[t]=e.getVideoTracks();if(!t)throw Error("There is no video track in the stream");this.trackPublishOrder.includes(R.VIDEO)||this.trackPublishOrder.push(R.VIDEO),await this.publisher.publishStream(e,t,R.VIDEO,this.publishOptions)},this.publishAudioStream=async e=>{if(!this.sfuClient)throw Error("Call not joined yet.");if(await this.sfuClient.joinTask,!this.permissionsContext.hasPermission(em.SEND_AUDIO))throw Error("No permission to publish audio");if(!this.publisher)throw Error("Publisher is not initialized");let[t]=e.getAudioTracks();if(!t)throw Error("There is no audio track in the stream");this.trackPublishOrder.includes(R.AUDIO)||this.trackPublishOrder.push(R.AUDIO),await this.publisher.publishStream(e,t,R.AUDIO)},this.publishScreenShareStream=async e=>{if(!this.sfuClient)throw Error("Call not joined yet.");if(await this.sfuClient.joinTask,!this.permissionsContext.hasPermission(em.SCREENSHARE))throw Error("No permission to publish screen share");if(!this.publisher)throw Error("Publisher is not initialized");let[t]=e.getVideoTracks();if(!t)throw Error("There is no screen share track in the stream");this.trackPublishOrder.includes(R.SCREEN_SHARE)||this.trackPublishOrder.push(R.SCREEN_SHARE);let i={screenShareSettings:this.screenShare.getSettings()};await this.publisher.publishStream(e,t,R.SCREEN_SHARE,i);let[s]=e.getAudioTracks();s&&(this.trackPublishOrder.includes(R.SCREEN_SHARE_AUDIO)||this.trackPublishOrder.push(R.SCREEN_SHARE_AUDIO),await this.publisher.publishStream(e,s,R.SCREEN_SHARE_AUDIO,i))},this.stopPublish=async function(e){var t;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];l.logger("info","stopPublish ".concat(R[e],", stop tracks: ").concat(i)),await (null===(t=l.publisher)||void 0===t?void 0:t.unpublishStream(e,i))},this.notifyNoiseCancellationStarting=async()=>{var e;return null===(e=this.sfuClient)||void 0===e?void 0:e.startNoiseCancellation().catch(e=>{this.logger("warn","Failed to notify start of noise cancellation",e)})},this.notifyNoiseCancellationStopped=async()=>{var e;return null===(e=this.sfuClient)||void 0===e?void 0:e.stopNoiseCancellation().catch(e=>{this.logger("warn","Failed to notify stop of noise cancellation",e)})},this.startReportingStatsFor=e=>{var t;return null===(t=this.statsReporter)||void 0===t?void 0:t.startReportingStatsFor(e)},this.stopReportingStatsFor=e=>{var t;return null===(t=this.statsReporter)||void 0===t?void 0:t.stopReportingStatsFor(e)},this.resetReaction=e=>{this.state.updateParticipant(e,{reaction:void 0})},this.setSortParticipantsBy=e=>this.state.setSortParticipantsBy(e),this.sendReaction=async e=>this.streamClient.post("".concat(this.streamClientBasePath,"/reaction"),e),this.blockUser=async e=>this.streamClient.post("".concat(this.streamClientBasePath,"/block"),{user_id:e}),this.unblockUser=async e=>this.streamClient.post("".concat(this.streamClientBasePath,"/unblock"),{user_id:e}),this.muteSelf=e=>{let t=this.currentUserId;if(t)return this.muteUser(t,e)},this.muteOthers=e=>{let t=s1(e);if(!t)return;let i=[];for(let e of this.state.remoteParticipants)e.publishedTracks.includes(t)&&i.push(e.userId);if(i.length>0)return this.muteUser(i,e)},this.muteUser=(e,t)=>this.streamClient.post("".concat(this.streamClientBasePath,"/mute_users"),{user_ids:Array.isArray(e)?e:[e],[t]:!0}),this.muteAllUsers=e=>this.streamClient.post("".concat(this.streamClientBasePath,"/mute_users"),{mute_all_users:!0,[e]:!0}),this.startRecording=async e=>this.streamClient.post("".concat(this.streamClientBasePath,"/start_recording"),e||{}),this.stopRecording=async()=>this.streamClient.post("".concat(this.streamClientBasePath,"/stop_recording"),{}),this.startTranscription=async e=>this.streamClient.post("".concat(this.streamClientBasePath,"/start_transcription"),e),this.stopTranscription=async()=>this.streamClient.post("".concat(this.streamClientBasePath,"/stop_transcription")),this.startClosedCaptions=async e=>{let t=this.state.setCaptioning(!0);try{return await this.streamClient.post("".concat(this.streamClientBasePath,"/start_closed_captions"),e)}catch(e){throw t.rollback(),e}},this.stopClosedCaptions=async e=>{let t=this.state.setCaptioning(!1);try{return await this.streamClient.post("".concat(this.streamClientBasePath,"/stop_closed_captions"),e)}catch(e){throw t.rollback(),e}},this.updateClosedCaptionSettings=e=>{this.state.updateClosedCaptionSettings(e)},this.requestPermissions=async e=>{let{permissions:t}=e;if(!t.every(e=>this.permissionsContext.canRequest(e)))throw Error("You are not allowed to request permissions: ".concat(t.join(", ")));return this.streamClient.post("".concat(this.streamClientBasePath,"/request_permission"),e)},this.grantPermissions=async(e,t)=>this.updateUserPermissions({user_id:e,grant_permissions:t}),this.revokePermissions=async(e,t)=>this.updateUserPermissions({user_id:e,revoke_permissions:t}),this.updateUserPermissions=async e=>this.streamClient.post("".concat(this.streamClientBasePath,"/user_permissions"),e),this.goLive=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return l.streamClient.post("".concat(l.streamClientBasePath,"/go_live"),e,t)},this.stopLive=async()=>this.streamClient.post("".concat(this.streamClientBasePath,"/stop_live"),{}),this.startHLS=async()=>this.streamClient.post("".concat(this.streamClientBasePath,"/start_broadcasting"),{}),this.stopHLS=async()=>this.streamClient.post("".concat(this.streamClientBasePath,"/stop_broadcasting"),{}),this.update=async e=>{let t=await this.streamClient.patch("".concat(this.streamClientBasePath),e),{call:i,members:s,own_capabilities:n}=t;return this.state.updateFromCallResponse(i),this.state.setMembers(s),this.state.setOwnCapabilities(n),t},this.endCall=async()=>this.streamClient.post("".concat(this.streamClientBasePath,"/mark_ended")),this.pin=e
1=>{this.state.updateParticipant(e,{pin:{isLocalPin:!0,pinnedAt:Date.now()}})},this.unpin=e=>{this.state.updateParticipant(e,{pin:void 0})},this.pinForEveryone=async e=>this.streamClient.post("".concat(this.streamClientBasePath,"/pin"),e),this.unpinForEveryone=async e=>this.streamClient.post("".concat(this.streamClientBasePath,"/unpin"),e),this.queryMembers=e=>this.streamClient.post("/call/members",{...e||{},id:this.id,type:this.type}),this.updateCallMembers=async e=>this.streamClient.post("".concat(this.streamClientBasePath,"/members"),e),this.scheduleAutoDrop=()=>{this.cancelAutoDrop();let e=this.state.settings;if(!e||this.state.callingState!==F.RINGING)return;let t=this.isCreatedByMe?e.ring.auto_cancel_timeout_ms:e.ring.incoming_call_timeout_ms;t<=0||(this.dropTimeout=setTimeout(()=>{this.state.callingState===F.RINGING&&this.leave({reject:!0,reason:"timeout"}).catch(e=>{this.logger("error","Failed to drop call",e)})},t))},this.cancelAutoDrop=()=>{clearTimeout(this.dropTimeout),this.dropTimeout=void 0},this.queryRecordings=async e=>{let t=this.streamClientBasePath;return e&&(t="".concat(t,"/").concat(e)),this.streamClient.get("".concat(t,"/recordings"))},this.queryTranscriptions=async()=>this.streamClient.get("".concat(this.streamClientBasePath,"/transcriptions")),this.getCallStats=async e=>{let t="".concat(this.streamClientBasePath,"/stats/").concat(e);return this.streamClient.get(t)},this.submitFeedback=async function(e){var t,i,s;let{reason:n,custom:a}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e<1||e>5)throw Error("Rating must be between 1 and 5");let r=null===(t=l.state.session)||void 0===t?void 0:t.id;if(!r)throw Error("Feedback can be submitted only in the context of a call session");let{sdkName:o,sdkVersion:c,...d}=ap(sR()),h=null!==(s=null===(i=l.sfuClient)||void 0===i?void 0:i.sessionId)&&void 0!==s?s:"N/A",u="".concat(l.streamClientBasePath,"/feedback/").concat(r);return l.streamClient.post(u,{rating:e,reason:n,user_session_id:h,sdk:o,sdk_version:c,custom:{...a,"x-stream-platform-data":d}})},this.sendCustomEvent=async e=>this.streamClient.post("".concat(this.streamClientBasePath,"/event"),{custom:e}),this.applyDeviceConfig=async e=>{await this.initCamera({setStatus:e}).catch(e=>{this.logger("warn","Camera init failed",e)}),await this.initMic({setStatus:e}).catch(e=>{this.logger("warn","Mic init failed",e)})},this.initCamera=async e=>{var t,i,s,n,a;if(await this.camera.statusChangeSettled(),(null===(t=this.state.localParticipant)||void 0===t?void 0:t.videoStream)||!this.permissionsContext.hasPermission("send-video"))return;if(!this.camera.state.direction&&!this.camera.state.selectedDevice){let e="front",t=null===(s=this.state.settings)||void 0===s?void 0:s.video.camera_facing;t&&(e="front"===t?"front":"back"),this.camera.state.setDirection(e)}let r=null===(i=this.state.settings)||void 0===i?void 0:i.video.target_resolution;r&&await this.camera.selectTargetResolution(r),e.setStatus&&(this.camera.enabled&&this.camera.state.mediaStream&&!(null===(n=this.publisher)||void 0===n?void 0:n.isPublishing(R.VIDEO))&&await this.publishVideoStream(this.camera.state.mediaStream),void 0===this.camera.state.status&&(null===(a=this.state.settings)||void 0===a?void 0:a.video.camera_default_on)&&await this.camera.enable())},this.initMic=async e=>{var t,i,s;await this.microphone.statusChangeSettled(),(null===(t=this.state.localParticipant)||void 0===t||!t.audioStream)&&this.permissionsContext.hasPermission("send-audio")&&e.setStatus&&(this.microphone.enabled&&this.microphone.state.mediaStream&&!(null===(i=this.publisher)||void 0===i?void 0:i.isPublishing(R.AUDIO))&&await this.publishAudioStream(this.microphone.state.mediaStream),void 0===this.microphone.state.status&&(null===(s=this.state.settings)||void 0===s?void 0:s.audio.mic_default_on)&&await this.microphone.enable())},this.trackElementVisibility=(e,t,i)=>this.dynascaleManager.trackElementVisibility(e,t,i),this.setViewport=e=>this.dynascaleManager.setViewport(e),this.bindVideoElement=(e,t,i)=>{let s=this.dynascaleManager.bindVideoElement(e,t,i);if(s)return this.leaveCallHooks.add(s),()=>{this.leaveCallHooks.delete(s),s()}},this.bindAudioElement=function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"audioTrack",s=l.dynascaleManager.bindAudioElement(e,t,i);if(s)return l.leaveCallHooks.add(s),()=>{l.leaveCallHooks.delete(s),s()}}
1,this.bindCallThumbnailElement=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=()=>{e.src=t.fallbackImageSource||"https://getstream.io/random_svg/?name=x&id=x"},s=ni(l.state.thumbnails$,t=>{if(!t)return;e.addEventListener("error",i);let s=new URL(t.image_url);s.searchParams.set("w",String(e.clientWidth)),s.searchParams.set("h",String(e.clientHeight)),e.src=s.toString()});return()=>{s(),e.removeEventListener("error",i)}},this.setPreferredIncomingVideoResolution=(e,t)=>{this.dynascaleManager.setVideoTrackSubscriptionOverrides(e?{enabled:!0,dimension:e}:void 0,t),this.dynascaleManager.applyTrackSubscriptions()},this.setIncomingVideoEnabled=e=>{this.dynascaleManager.setVideoTrackSubscriptionOverrides(e?void 0:{enabled:!1}),this.dynascaleManager.applyTrackSubscriptions()},this.setDisconnectionTimeout=e=>{this.disconnectionTimeoutSeconds=e},this.type=e,this.id=t,this.cid="".concat(e,":").concat(t),this.ringingSubject=new Q.X(o),this.watching=c,this.streamClient=i,this.clientStore=r,this.streamClientBasePath="/call/".concat(this.type,"/").concat(this.id),this.logger=sm(["Call"]);let d=aR.get(e),h=a||d.options.sortParticipantsBy;h&&this.state.setSortParticipantsBy(h),this.state.setMembers(s||[]),this.state.setOwnCapabilities(n||[]),this.state.setCallingState(o?F.RINGING:F.IDLE),this.camera=new az(this),this.microphone=new a1(this),this.speaker=new a5(this),this.screenShare=new a3(this),this.dynascaleManager=new aw(this.state,this.speaker)}}class a8{async connect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15e3;if(this.isConnecting)throw Error("You've called connect twice, can only attempt 1 connection at the time");this.isDisconnected=!1;try{let e=await this._connect();this.consecutiveFailures=0,this._log("connect() - Established ws connection with healthcheck: ".concat(e))}catch(e){if(this.isHealthy=!1,this.consecutiveFailures+=1,e.code!==st.TOKEN_EXPIRED||this.client.tokenManager.isStatic()){if(!e.isWSFailure)throw Error(JSON.stringify({code:e.code,StatusCode:e.StatusCode,message:e.message,isWSFailure:e.isWSFailure}))}else this._log("connect() - WS failure due to expired token, so going to try to reload token and reconnect"),this._reconnect({refreshToken:!0})}return await this._waitForHealthy(e)}async _waitForHealthy(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15e3;return Promise.race([(async()=>{for(let t=0;t<=e;t+=50)try{return await this.connectionOpen}catch(i){if(t===e)throw Error(JSON.stringify({code:i.code,StatusCode:i.StatusCode,message:i.message,isWSFailure:i.isWSFailure}));await i7(50)}})(),(async()=>{throw await i7(e),this.isConnecting=!1,Error(JSON.stringify({code:"",StatusCode:"",message:"initial WS connection could not be established",isWSFailure:!0}))})()])}disconnect(e){let t;this._log("disconnect() - Closing the websocket connection for wsID ".concat(this.wsID)),this.wsID+=1,this.isConnecting=!1,this.isDisconnected=!0,this.healthCheckTimeoutRef&&nz().clearInterval(this.healthCheckTimeoutRef),this.connectionCheckTimeoutRef&&clearInterval(this.connectionCheckTimeoutRef),so(this.onlineStatusChanged),this.isHealthy=!1;let{ws:i}=this;return i&&i.close&&i.readyState===i.OPEN?(t=new Promise(t=>{let s=e=>{this._log("disconnect() - resolving isClosedPromise ".concat(e?"with":"without"," close frame"),{event:e}),t()};i.onclose=s,setTimeout(s,null!=e?e:1e3)}),this._log("disconnect() - Manually closed connection by calling client.disconnect()"),i.close(st.WS_CLOSED_SUCCESS,"Manually closed connection by calling client.disconnect()")):(this._log("disconnect() - ws connection doesn't exist or it is already closed."),t=Promise.resolve()),delete this.ws,t}async _connect(){var e,t,i,s,n;if(this.isConnecting)return;this.isConnecting=!0,this.requestID=sn();let a=!1;try{this._log("_connect() - waiting for token"),await this.client.tokenManager.tokenReady(),a=!0}catch(e){}try{a||(this._log("_connect() - tokenProvider failed before, so going to retry"),await this.client.tokenManager.loadToken()),this.client.isConnectionIsPromisePending||this.client._setupConnectionIdPromise(),this._setupConnectionPromise();let s=this._buildUrl();this._log("_connect() - Connecting to ".concat(s),{wsURL:s,requestID:this.requestID});let n=null!==(e=this.client.options.WebSocketImpl)&&void 0!==e?e:WebSocket;this.ws=new n(s),this.ws.onopen=this.onopen.bind(this,this.wsID),this.ws.onclose
1=this.onclose.bind(this,this.wsID),this.ws.onerror=this.onerror.bind(this,this.wsID),this.ws.onmessage=this.onmessage.bind(this,this.wsID);let r=await this.connectionOpen;if(this.isConnecting=!1,r)return this.connectionID=r.connection_id,null===(t=(i=this.client).resolveConnectionId)||void 0===t||t.call(i,this.connectionID),r}catch(e){throw await this.client._setupConnectionIdPromise(),this.isConnecting=!1,this._log("_connect() - Error - ",e),null===(s=(n=this.client).rejectConnectionId)||void 0===s||s.call(n,e),e}}async _reconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this._log("_reconnect() - Initiating the reconnect"),this.isConnecting||this.isHealthy){this._log("_reconnect() - Abort (1) since already connecting or healthy");return}let t=e.interval;if(t||(t=si(this.consecutiveFailures)),await i7(t),this.isConnecting||this.isHealthy){this._log("_reconnect() - Abort (2) since already connecting or healthy");return}if(this.isDisconnected){this._log("_reconnect() - Abort (3) since disconnect() is called");return}this._log("_reconnect() - Destroying current WS connection"),this._destroyCurrentWSConnection(),e.refreshToken&&await this.client.tokenManager.loadToken();try{await this._connect(),this._log("_reconnect() - Waiting for recoverCallBack"),this._log("_reconnect() - Finished recoverCallBack"),this.consecutiveFailures=0}catch(e){if(this.isHealthy=!1,this.consecutiveFailures+=1,e.code===st.TOKEN_EXPIRED&&!this.client.tokenManager.isStatic())return this._log("_reconnect() - WS failure due to expired token, so going to try to reload token and reconnect"),this._reconnect({refreshToken:!0});e.isWSFailure&&(this._log("_reconnect() - WS failure, so going to try to reconnect"),this._reconnect())}this._log("_reconnect() - == END ==")}_destroyCurrentWSConnection(){this.wsID+=1;try{var e;null===this||void 0===this||null===(e=this.ws)||void 0===e||e.close()}catch(e){}}get connectionOpen(){var e;return null===(e=this.connectionOpenSafe)||void 0===e?void 0:e.call(this)}constructor(e){var t=this;this._log=function(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"info";t.client.logger(s,"connection:"+e,{...i})},this.setClient=e=>{this.client=e},this._buildUrl=()=>{let e=new URLSearchParams;return e.set("api_key",this.client.key),e.set("stream-auth-type",this.client.getAuthType()),e.set("X-Stream-Client",this.client.getUserAgent()),"".concat(this.client.wsBaseURL,"/connect?").concat(e.toString())},this.onlineStatusChanged=e=>{"offline"===e.type?(this._log("onlineStatusChanged() - Status changing to offline"),this._setHealth(!1,!0)):"online"!==e.type||(this._log("onlineStatusChanged() - Status changing to online. isHealthy: ".concat(this.isHealthy)),this.isHealthy||this._reconnect({interval:10}))},this.onopen=e=>{var t;if(this.wsID!==e)return;let i=this.client.user;if(!i){this.client.logger("error","User not set, can't connect to WS");return}let s=this.client._getToken();if(!s){this.client.logger("error","Token not set, can't connect authenticate");return}let n={token:s,user_details:{id:i.id,name:i.name,image:i.image,custom:i.custom}};null===(t=this.ws)||void 0===t||t.send(JSON.stringify(n)),this._log("onopen() - onopen callback",{wsID:e})},this.onmessage=(e,t)=>{var i,s;if(this.wsID!==e)return;this._log("onmessage() - onmessage callback",{event:t,wsID:e});let n="string"==typeof t.data?JSON.parse(t.data):null;if(!this.isResolved&&n&&"connection.error"===n.type&&(this.isResolved=!0,n.error)){null===(i=this.rejectPromise)||void 0===i||i.call(this,this._errorFromWSEvent(n,!1));return}if(this.lastEvent=new Date,n&&("health.check"===n.type||"connection.ok"===n.type)&&this.scheduleNextPing(),n&&"connection.ok"===n.type&&(null===(s=this.resolvePromise)||void 0===s||s.call(this,n),this._setHealth(!0)),n&&"connection.error"===n.type&&n.error){let{code:e}=n.error;this.isHealthy=!1,this.isConnecting=!1,this.consecutiveFailures+=1,e!==st.TOKEN_EXPIRED||this.client.tokenManager.isStatic()||(clearTimeout(this.connectionCheckTimeoutRef),this._log("connect() - WS failure due to expired token, so going to try to reload token and reconnect"),this._reconnect({refreshToken:!0}))}n&&(n.received_at=new Date,this.client.dispatchEvent(n)),this.scheduleConnectionCheck()}
1,this.onclose=(e,t)=>{var i,s;if(this.wsID===e){if(this._log("onclose() - onclose callback - "+t.code,{event:t,wsID:e}),t.code===st.WS_CLOSED_SUCCESS){let e=Error("WS connection reject with error ".concat(t.reason));e.reason=t.reason,e.code=t.code,e.wasClean=t.wasClean,e.target=t.target,null===(i=this.rejectPromise)||void 0===i||i.call(this,e),this._log("onclose() - WS connection reject with error ".concat(t.reason),{event:t})}else this.consecutiveFailures+=1,this.totalFailures+=1,this._setHealth(!1),this.isConnecting=!1,null===(s=this.rejectPromise)||void 0===s||s.call(this,this._errorFromWSEvent(t)),this._log("onclose() - WS connection closed. Calling reconnect ...",{event:t}),this._reconnect()}},this.onerror=(e,t)=>{var i;this.wsID===e&&(this.consecutiveFailures+=1,this.totalFailures+=1,this._setHealth(!1),this.isConnecting=!1,null===(i=this.rejectPromise)||void 0===i||i.call(this,Error("WebSocket error: ".concat(t))),this._log("onerror() - WS connection resulted into error",{event:t}),this._reconnect())},this._setHealth=function(e){let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(e!==t.isHealthy){if(t.isHealthy=e,t.isHealthy||i){t.client.dispatchEvent({type:"connection.changed",online:t.isHealthy});return}setTimeout(()=>{t.isHealthy||t.client.dispatchEvent({type:"connection.changed",online:t.isHealthy})},5e3)}},this._errorFromWSEvent=function(e){let i,s,n,a=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(void 0!==e.code)i=e.code,n=e.reason,s=0;else{let{error:t}=e;i=t.code,n=t.message,s=t.StatusCode}let r="WS failed with code: ".concat(i," and reason: ").concat(n);t._log(r,{event:e},"warn");let o=Error(r);return o.code=i,o.StatusCode=s,o.isWSFailure=a,o},this._setupConnectionPromise=()=>{this.isResolved=!1,this.connectionOpenSafe=nW(new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t}))},this.scheduleNextPing=()=>{let e=nz();this.healthCheckTimeoutRef&&e.clearTimeout(this.healthCheckTimeoutRef),this.healthCheckTimeoutRef=e.setTimeout(()=>{let e=[{type:"health.check",client_id:this.client.clientID}];try{var t;null===(t=this.ws)||void 0===t||t.send(JSON.stringify(e))}catch(e){}},this.pingInterval)},this.scheduleConnectionCheck=()=>{clearTimeout(this.connectionCheckTimeoutRef),this.connectionCheckTimeoutRef=setTimeout(()=>{let e=new Date;this.lastEvent&&e.getTime()-this.lastEvent.getTime()>this.connectionCheckTimeout&&(this._log("scheduleConnectionCheck - going to reconnect"),this._setHealth(!1),this._reconnect())},this.connectionCheckTimeout)},this.client=e,this.consecutiveFailures=0,this.totalFailures=0,this.isConnecting=!1,this.isDisconnected=!1,this.isResolved=!1,this.isHealthy=!1,this.wsID=1,this.lastEvent=null,this.pingInterval=25e3,this.connectionCheckTimeout=this.pingInterval+1e4,sr(this.onlineStatusChanged)}}let a6=e=>{let t={},i=String.fromCharCode,s=e.length,n,a=0,r,o=0,c,l="";for(n=0;n<64;n++)t["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(n)]=n;for(r=0;r<s;r++)for(a=(a<<6)+t[e.charAt(r)],o+=6;o>=8;)((c=a>>>(o-=8)&255)||r<s-2)&&(l+=i(c));return l};class a7{constructor(e){this.setTokenOrProvider=async(e,t,i)=>{this.validateToken(e,t,i),this.user=t,se(e)&&(this.tokenProvider=e,this.type="provider"),"string"==typeof e&&(this.token=e,this.type="static"),await this.loadToken()},this.reset=()=>{this.token=void 0,this.tokenProvider=void 0,this.type="static",this.user=void 0,this.loadTokenPromise=null},this.validateToken=(e,t,i)=>{if(!t||!i||e){if(!this.secret&&!e)throw Error("UserWithId token can not be empty");if(e&&"string"!=typeof e&&!se(e))throw Error("user token should either be a string or a function");if("string"==typeof e){if(i&&""===e)return;let s=function(e){let t=e.split(".");return 3!==t.length?"":JSON.parse(a6(t[1])).user_id}(e);if(null!=e&&(null==s||""===s||!i&&s!==t.id))throw Error("userToken does not have a user_id or is not matching with user.id")}}},this.tokenReady=()=>this.loadTokenPromise,this.loadToken=()=>(this.loadTokenPromise=new Promise(async(e,t)=>{if("static"===this.type)return e(this.token);if(this.tokenProvider&&"string"!=typeof this.tokenProvider){try{this.token=await this.tokenProvider()}catch(e){return t(Error("Call to tokenProvider failed with message: ".concat(e)))}e(this.token)}}),this.loadTokenPromise),this.getToken=()=>
1{if(this.token||this.user&&!this.token)return this.token;throw Error("User token is not set. Either client.connectUser wasn't called or client.disconnect was called")},this.isStatic=()=>"static"===this.type,this.loadTokenPromise=null,this.secret=e,this.type="static"}}let re=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"https://hint.stream-io-video.com/",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2e3,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,s=sm(["location-hint"]),n=0,a="ERR";do{let i=new AbortController,n=setTimeout(()=>i.abort(),t);try{let t=(await fetch(e,{method:"HEAD",signal:i.signal})).headers.get("x-amz-cf-pop")||"ERR";s("debug","Location header: ".concat(t)),a=t.substring(0,3)}catch(t){s("warn","Failed to get location hint from ".concat(e),t),a="ERR"}finally{clearTimeout(n)}}while("ERR"===a&&++n<i);return a};class rt{get connectionIdPromise(){var e;return null===(e=this.connectionIdPromiseSafe)||void 0===e?void 0:e.call(this)}get isConnectionIsPromisePending(){var e,t;return null!==(t=null===(e=this.connectionIdPromiseSafe)||void 0===e?void 0:e.checkPending())&&void 0!==t&&t}get wsPromise(){var e;return null===(e=this.wsPromiseSafe)||void 0===e?void 0:e.call(this)}constructor(e,t){var i,s=this;this.listeners={},this.getAuthType=()=>this.anonymous?"anonymous":"jwt",this.setBaseURL=e=>{this.baseURL=e,this.wsBaseURL=this.baseURL.replace("http","ws").replace(":3030",":8800")},this.getLocationHint=async(e,t)=>{let i=await this.locationHint;return i&&"ERR"!==i?i:(this.locationHint=re(null!=e?e:this.options.locationHintUrl,null!=t?t:this.options.locationHintTimeout),this.locationHint)},this._getConnectionID=()=>{var e;return null===(e=this.wsConnection)||void 0===e?void 0:e.connectionID},this._hasConnectionID=()=>!!this._getConnectionID(),this.connectUser=async(e,t)=>{if(!e.id)throw Error('The "id" field on the user is missing');if(this.userID===e.id&&this.setUserPromise)return this.logger("warn","Consecutive calls to connectUser is detected, ideally you should only call this function once in your app."),this.setUserPromise;if(this.userID)throw Error("Use client.disconnect() before trying to connect as a different user. connectUser was called twice.");(this._isUsingServerAuth()||this.node)&&!this.options.allowServerSideConnect&&this.logger("warn","Please do not use connectUser server side. Use our @stream-io/node-sdk instead: https://getstream.io/video/docs/api/"),this.userID=e.id,this.anonymous=!1;let i=this._setToken(e,t,this.anonymous);this._setUser(e);let s=this.openConnection();this.setUserPromise=Promise.all([i,s]).then(e=>e[1]);try{return sr(this.updateNetworkConnectionStatus),await this.setUserPromise}catch(e){throw this.persistUserOnConnectionFailure?this.closeConnection():this.disconnectUser(),e}},this._setToken=(e,t,i)=>this.tokenManager.setTokenOrProvider(t,e,i),this._setUser=e=>{this.user=e,this.userID=e.id,this._user={...e}},this.closeConnection=async e=>{var t;await (null===(t=this.wsConnection)||void 0===t?void 0:t.disconnect(e))},this.openConnection=async()=>{var e,t,i;if(!this.userID)throw Error("UserWithId is not set on client, use client.connectUser or client.connectAnonymousUser instead");let s=null===(e=this.wsPromiseSafe)||void 0===e?void 0:e.call(this);if((null===(t=this.wsConnection)||void 0===t?void 0:t.isConnecting)&&s)return this.logger("info","client:openConnection() - connection already in progress"),await s;if((null===(i=this.wsConnection)||void 0===i?void 0:i.isHealthy)&&this._hasConnectionID()){this.logger("info","client:openConnection() - openConnection called twice, healthy connection already exists");return}await this._setupConnectionIdPromise(),this.clientID="".concat(this.userID,"--").concat(sn());let n=this.connect();return this.wsPromiseSafe=nW(n),await n},this.disconnectUser=async e=>{this.logger("info","client:disconnect() - Disconnecting the client"),delete this.user,delete this._user,delete this.userID,this.anonymous=!1,await this.closeConnection(e),so(this.updateNetworkConnectionStatus),this.tokenManager.reset(),this.connectionIdPromiseSafe=void 0,this.rejectConnectionId=void 0,this.resolveConnectionId=void 0},this.connectGuestUser=async e=>{this.guestUserCreatePromise=this.doAxiosRequest("post","/guest",{user:e},{publicEndpoint:!0});let t=await this.guestUserCreatePromise;return this.guestUserCreatePromise.finally(()=>this.guestUserCreatePromise=void 0),this.connectUser(t.user,t.access_token)},this.connectAnonymousUser=async(e,t)=>{var i;sr(this.updateNetworkConnectionStatus),await this._setupConnectionIdPromise(),this.anonymous=!0,await this._setToken(e,t,this.anonymous),this._setUser(e),null===(i=this.resolveConnectionId)||void 0===i||i.call(this)},this.on=(e,t)=>{var i;return this.listeners[e]||(this.listeners[e]=[]),this.logger("debug","Adding listener for ".concat(e," event")),null===(i=this.listeners[e])||void 0===i||i.push(t),()=>{this.off(e,t)}},this.off=(e,t)=>{var i;this.listeners[e]||(this.listeners[e]=[]),this.logger("debug","Removing listener for ".concat(e," event")),this.listeners[e]=null===(i=this.listeners[e])||void 0===i?void 0:i.filter(e=>e!==t)},this._setupConnectionIdPromise=()=>{this.connectionIdPromiseSafe=nW(new Promise((e,t)=>
1{this.resolveConnectionId=e,this.rejectConnectionId=t}))},this._logApiRequest=(e,t,i,s)=>{this.logger("trace","client: ".concat(e," - Request - ").concat(t),{payload:i,config:s})},this._logApiResponse=(e,t,i)=>{this.logger("trace","client:".concat(e," - Response - url: ").concat(t," > status ").concat(i.status),{response:i})},this._logApiError=(e,t,i)=>{this.logger("error","client:".concat(e," - Error - url: ").concat(t),{url:t,error:i})},this.doAxiosRequest=async function(e,t,i){var n,a;let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!r.publicEndpoint){await Promise.all([s.tokenManager.tokenReady(),s.guestUserCreatePromise]);try{await s.connectionIdPromise}catch(e){await (null===(n=s.wsConnection)||void 0===n?void 0:n._waitForHealthy()),await s.connectionIdPromise}}let o=s._enrichAxiosOptions(r);try{let n;switch(s._logApiRequest(e,t,i,o),e){case"get":n=await s.axiosInstance.get(t,o);break;case"delete":n=await s.axiosInstance.delete(t,o);break;case"post":n=await s.axiosInstance.post(t,i,o);break;case"put":n=await s.axiosInstance.put(t,i,o);break;case"patch":n=await s.axiosInstance.patch(t,i,o);break;case"options":n=await s.axiosInstance.options(t,o);break;default:throw Error("Invalid request type")}return s._logApiResponse(e,t,n),s.consecutiveFailures=0,s.handleResponse(n)}catch(n){if(n.client_request_id=null===(a=o.headers)||void 0===a?void 0:a["x-client-request-id"],s.consecutiveFailures+=1,n.response){if(s._logApiError(e,t,n.response),n.response.data.code===st.TOKEN_EXPIRED&&!s.tokenManager.isStatic())return s.consecutiveFailures>1&&await i7(si(s.consecutiveFailures)),await s.tokenManager.loadToken(),await s.doAxiosRequest(e,t,i,r);return s.handleResponse(n.response)}throw s._logApiError(e,t,n),n}},this.get=(e,t)=>this.doAxiosRequest("get",e,null,{params:t}),this.put=(e,t,i)=>this.doAxiosRequest("put",e,t,{params:i}),this.post=(e,t,i)=>this.doAxiosRequest("post",e,t,{params:i}),this.patch=(e,t,i)=>this.doAxiosRequest("patch",e,t,{params:i}),this.delete=(e,t)=>this.doAxiosRequest("delete",e,null,{params:t}),this.errorFromResponse=e=>{let{data:t,status:i}=e,s=new ev;return s.message="Stream error code ".concat(t.code,": ").concat(t.message),s.code=t.code,s.unrecoverable=t.unrecoverable,s.response=e,s.status=i,s},this.handleResponse=e=>{let t=e.data;if(!e.status||e.status<200||300<=e.status)throw this.errorFromResponse(e);return t},this.dispatchEvent=e=>{if(this.logger("debug","Dispatching event: ".concat(e.type),e),this.listeners){for(let t of this.listeners.all||[])t(e);for(let t of this.listeners[e.type]||[])t(e)}},this.connect=async()=>{if(!this.userID||!this._user)throw Error("Call connectUser or connectAnonymousUser before starting the connection");if(!this.wsBaseURL)throw Error("Websocket base url not set");if(!this.clientID)throw Error("clientID is not set");return this.wsConnection=new a8(this),this.logger("info","StreamClient.connect: this.wsConnection.connect()"),await this.wsConnection.connect(this.defaultWSTimeout)},this.getUserAgent=()=>this.userAgent||"stream-video-javascript-client-".concat(this.node?"node":"browser","-").concat("1.14.0"),this.setUserAgent=e=>{this.userAgent=e},this._isUsingServerAuth=()=>!!this.secret,this._enrichAxiosOptions=function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{params:{},headers:{},config:{}},i=t.publicEndpoint&&!s.user?void 0:s._getToken();return(null===(e=t.headers)||void 0===e?void 0:e["x-client-request-id"])||(t.headers={...t.headers,"x-client-request-id":sn()}),{params:{user_id:s.userID,connection_id:s._getConnectionID(),api_key:s.key,...t.params},headers:{...i?{Authorization:i}:void 0,"stream-auth-type":t.publicEndpoint&&!s.user?"anonymous":s.getAuthType(),"X-Stream-Client":s.getUserAgent(),...t.headers},...t.config,...s.options.axiosRequestConfig}},this._getToken=()=>this.tokenManager?this.tokenManager.getToken():null,this.updateNetworkConnectionStatus=e=>{"offline"===e.type?(this.logger("debug","device went offline"),this.dispatchEvent({type:"network.changed",online:!1})):"online"===e.type&&(this.logger("debug","device went online"),this.dispatchEvent({type:"network.changed",online:!0}))},this.key=e,this.secret=null==t?void 0:t.secret;let n=t||{browser:!0};this.browser=n.browser||!0,this.node=!this.browser,this.browser&&(this.locationHint=re(null==t?void 0:t.locationHintUrl,null==t?void 0:t.locationHintTimeout,null==t?void 0:t.locationHintMaxAttempts)),this.options={timeout:5e3,withCredentials:!1,...n},this.node&&!this.options.httpsAgent&&(this.options.httpsAgent=new null.Agent({keepAlive:!0,keepAliveMsecs:3e3})),this.setBaseURL(this.options.baseURL||"https://video.stream-io-api.com/video"),this.axiosInstance=J.Z.create({...this.options,baseURL:this.baseURL}
1),this.wsConnection=null,this.wsPromiseSafe=null,this.setUserPromise=null,this.anonymous=!1,this.persistUserOnConnectionFailure=null===(i=this.options)||void 0===i?void 0:i.persistUserOnConnectionFailure,this.tokenManager=new a7(this.secret),this.consecutiveFailures=0,this.defaultWSTimeout=15e3,this.logger=se(n.logger)?n.logger:()=>null}}class ri{static getOrCreateInstance(e){let t=e.user;if(!t.id){if("anonymous"===e.user.type)t.id="!anon";else throw Error("User ID is required for a non-anonymous user")}if(!e.token&&!e.tokenProvider&&"anonymous"!==e.user.type&&"guest"!==e.user.type)throw Error("TokenProvider or token is required for a user that is not a guest or anonymous");let i=ri._instanceMap.get(e.apiKey+t.id);return i||(i=new ri({...e,user:t})),i}get state(){return this.readOnlyStateStore}constructor(e,t){var i,s,n,a=this;this.logLevel="warn",this.eventHandlersToUnregister=[],this.connectionConcurrencyTag=Symbol("connectionConcurrencyTag"),this.connectUser=async(e,t)=>{if("anonymous"===e.type)return e.id="!anon",this.connectAnonymousUser(e,t);let i=()=>this.streamClient.connectUser(e,t);"guest"===e.type&&(i=async()=>this.streamClient.connectGuestUser(e));let s=await s3(this.connectionConcurrencyTag,()=>i());return(null==s?void 0:s.me)&&this.writeableStateStore.setConnectedUser(s.me),this.eventHandlersToUnregister.push(this.on("connection.changed",e=>{if(e.online){let e=this.writeableStateStore.calls.filter(e=>e.watching).map(e=>e.cid);this.logger("info","Rewatching calls after connection changed ".concat(e.join(", "))),e.length>0&&this.queryCalls({watch:!0,filter_conditions:{cid:{$in:e}},sort:[{field:"cid",direction:1}]}).catch(e=>{this.logger("error","Failed to re-watch calls",e)})}})),this.eventHandlersToUnregister.push(this.on("call.created",t=>{let{call:i,members:s}=t;if(e.id===i.created_by.id){this.logger("warn","Received `call.created` sent by the current user");return}this.logger("info","New call created and registered: ".concat(i.cid));let n=new a4({streamClient:this.streamClient,type:i.type,id:i.id,members:s,clientStore:this.writeableStateStore});n.state.updateFromCallResponse(i),this.writeableStateStore.registerCall(n)})),this.eventHandlersToUnregister.push(this.on("call.ring",async t=>{let{call:i,members:s}=t;if(e.id===i.created_by.id){this.logger("debug","Received `call.ring` sent by the current user so ignoring the event");return}let n=this.writeableStateStore.findCall(i.type,i.id);if(n)await n.updateFromRingingEvent(t);else{let e=new a4({streamClient:this.streamClient,type:i.type,id:i.id,members:s,clientStore:this.writeableStateStore,ringing:!0});await e.get()}})),s},this.disconnectUser=async e=>{var t;if(!this.streamClient.user)return;let i=null===(t=this.streamClient.user)||void 0===t?void 0:t.id,s=this.streamClient.key,n=()=>this.streamClient.disconnectUser(e);await s3(this.connectionConcurrencyTag,()=>n()),i&&ri._instanceMap.delete(s+i),this.eventHandlersToUnregister.forEach(e=>e()),this.eventHandlersToUnregister=[],this.writeableStateStore.setConnectedUser(void 0)},this.on=(e,t)=>this.streamClient.on(e,t),this.off=(e,t)=>this.streamClient.off(e,t),this.call=(e,t)=>new a4({streamClient:this.streamClient,id:t,type:e,clientStore:this.writeableStateStore}),this.createGuestUser=async e=>this.streamClient.doAxiosRequest("post","/guest",e,{publicEndpoint:!0}),this.queryCalls=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=await a.streamClient.post("/calls",e),i=[];for(let s of t.calls){let t=new a4({streamClient:a.streamClient,id:s.call.id,type:s.call.type,members:s.members,ownCapabilities:s.own_capabilities,watching:e.watch,clientStore:a.writeableStateStore});t.state.updateFromCallResponse(s.call),await t.applyDeviceConfig(!1),e.watch&&a.writeableStateStore.registerCall(t),i.push(t)}return{...t,calls:i}},this.queryCallStats=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return a.streamClient.post("/call/stats",e)},this.queryAggregateCallStats=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return a.streamClient.post("/stats",e)},this.edges=async()=>this.streamClient.get("/edges"),this.addDevice=async(e,t,i,s,n)=>await this.streamClient.post("/devices",{id:e,push_provider:t,voip_token:n,...null!=s?{user_id:s}:{},...null!=i?{push_provider_name:i}:{}}),this.addVoipDevice=async(e,t,i,s)=>await this.addDevice(e,t,i,s,!0),this.getDevices=async e=>await this.streamClient.get("/devices",e?{user_id:e}:{}),this.removeDevice=async(e,t)=>await this.streamClient.delete("/devices",{id:e,...t?{user_id:t}:{}}),this.onRingingCall=async e=>{let t=this.state.calls.find(t=>t.cid===e&&t.ringing);if(!t){let[i,s]=e.split(":");t=new a4({streamClient:this.streamClient,type:i,id:s,clientStore:this.writeableStateStore,ringing:!0}),await t.get()}return t},this.connectAnonymousUser=async(e,t)=>{let i=()=>this.streamClient.connectAnonymousUser(e,t);return await s3(this.connectionConcurrencyTag,()=>i())};let r=sh,o="warn";"string"==typeof e?(o=(null==t?void 0:t.logLevel)||o,r=(null==t?void 0:t.logger)||r,(null==t?void 0:t.enableTimerWorker)&&nY()):(o=(null===(i=e.options)||void 0===i?void 0:i.logLevel)||o,r=(null===(s=e.options)||void 0===s?void 0:s.logger)||r,(null===(n=e.options)||void 0===n?void 0:n.enableTimerWorker)&&nY()),su(r,o),this.logger=sm(["client"]);let c=sm(["coordinator"]);if("string"==typeof e)this.streamClient=new rt(e,{persistUserOnConnectionFailure:!0,...t,logLevel:o,logger:c});else{this.streamClient=new rt(e.apiKey,{persistUserOnConnectionFailure:!0,...e.options,logLevel:o,logger:c});let t=sy();if(t){let e=A[t.type].toLowerCase(),i="".concat(t.major,".").concat(t.minor,".").concat(t.patch),s=this.streamClient.getUserAgent();this.streamClient.setUserAgent("".concat(s,"-video-").concat(e,"-sdk-").concat(i))}}if(this.writeableStateStore=new na,this.readOnlyStateStore=new nr(this.writeableStateStore),"string"!=typeof e){let t=e.user,i=e.token||e.tokenProvider;if(t){let s=t.id;"anonymous"===t.type&&(s="!anon"),s&&(ri._instanceMap.has(e.apiKey+s)&&this.logger("warn","A StreamVideoClient already exists for ".concat("anonymous"===t.type?"an anonymous user":s,"; Prefer using getOrCreateInstance method")),t.id=s,ri._instanceMap.set(e.apiKey+s,this)),this.connectUser(t,i).catch(e=>{this.logger("error","Failed to connect",e)})}}}}ri._instanceMap=new Map}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.