@sanseng/livekit-ws-sdk 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.esm.js +1 -1
- package/dist/index.full.umd.js +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.full.umd.js
CHANGED
|
@@ -144,4 +144,4 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
|
|
|
144
144
|
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
145
145
|
`);n.RTCSessionDescription&&s instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Si(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Ei(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var Nl=Object.freeze({__proto__:null,removeExtmapAllowMixed:_n,shimAddIceCandidateNullOrEmpty:Si,shimConnectionState:vn,shimMaxMessageSize:ki,shimParameterlessSetLocalDescription:Ei,shimRTCIceCandidate:Ti,shimRTCIceCandidateRelayProtocol:gn,shimSendThrowTypeError:Ci});function xl(){let{window:n}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=Gr,i=wl(n),s={browserDetails:i,commonShim:Nl,extractVersion:jt,disableLog:Pl,disableWarnings:Il,sdp:Ol};switch(i.browser){case"chrome":if(!ro||!pn||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=ro,Si(n,i),Ei(n),Yr(n,i),Xr(n),pn(n,i),Zr(n),no(n,i),eo(n),to(n),so(n,i),Ti(n),gn(n),vn(n),ki(n,i),Ci(n),_n(n,i);break;case"firefox":if(!vo||!mn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=vo,Si(n,i),Ei(n),oo(n,i),mn(n,i),ao(n),uo(n),co(n),lo(n),ho(n),po(n),mo(n),fo(n),go(n),Ti(n),vn(n),ki(n,i),Ci(n);break;case"safari":if(!Po||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Po,Si(n,i),Ei(n),Co(n),Eo(n),yo(n),_o(n),bo(n),So(n),To(n),Ro(n),Ti(n),gn(n),ki(n,i),Ci(n),_n(n,i);break;default:t("Unsupported browser!");break}return s}xl({window:typeof window>"u"?void 0:window});var bn,Do;class ue extends(Do=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}bn=ue,ue.resolve=n=>Reflect.get(Do,"resolve",bn).call(bn,n);const Ml=/version\/(\d+(\.?_?\d+)+)/i;let yn;function be(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(yn===void 0||e){const i=Ll.find(s=>{let{test:r}=s;return r.test(t)});yn=i?.describe(t)}return yn}const Ll=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Ri(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Tn(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Ri(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Tn(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Ri(Ml,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Tn(n)}}}];function Ri(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function Tn(n){return n.includes("mac os")?Ri(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Ul="2.17.1";const Fl=Ul,Vl=16;class Qe extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof i?.cause<"u"&&(this.cause=i?.cause)}}class kn extends Qe{}var $;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest",n[n.Timeout=5]="Timeout",n[n.WebSocket=6]="WebSocket",n[n.ServiceNotFound=7]="ServiceNotFound"})($||($={}));class V extends kn{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=$[t]}static notAllowed(e,t,i){return new V(e,$.NotAllowed,t,i)}static timeout(e){return new V(e,$.Timeout)}static leaveRequest(e,t){return new V(e,$.LeaveRequest,void 0,t)}static internal(e,t){return new V(e,$.InternalError,void 0,t)}static cancelled(e){return new V(e,$.Cancelled)}static serverUnreachable(e,t){return new V(e,$.ServerUnreachable,t)}static websocket(e,t,i){return new V(e,$.WebSocket,t,i)}static serviceNotFound(e,t){return new V(e,$.ServiceNotFound,void 0,t)}}class Cn extends Qe{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Ke extends Qe{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Bl extends Qe{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class re extends Qe{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Tt extends Qe{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Ao extends Qe{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Oo extends kn{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:dn[t]}}var me;(function(n){n[n.AlreadyOpened=0]="AlreadyOpened",n[n.AbnormalEnd=1]="AbnormalEnd",n[n.DecodeFailed=2]="DecodeFailed",n[n.LengthExceeded=3]="LengthExceeded",n[n.Incomplete=4]="Incomplete",n[n.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",n[n.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(me||(me={}));class Se extends kn{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=me[t]}}class kt extends Qe{constructor(e){super(18,e),this.name="SignalReconnectError"}}var Pi;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(Pi||(Pi={})),(function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e})(Pi||(Pi={}));class de{}de.setTimeout=function(){return setTimeout(...arguments)},de.setInterval=function(){return setInterval(...arguments)},de.clearTimeout=function(){return clearTimeout(...arguments)},de.clearInterval=function(){return clearInterval(...arguments)};var E;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(E||(E={}));var I;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackCpuConstrained="localTrackCpuConstrained",n.LocalSenderCreated="localSenderCreated",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.TrackCpuConstrained="trackCpuConstrained",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(I||(I={}));var w;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved"})(w||(w={}));var P;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.CpuConstrained="cpuConstrained",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate",n.PreConnectBufferFlushed="preConnectBufferFlushed"})(P||(P={}));function jl(n){return typeof n>"u"?n:typeof structuredClone=="function"?typeof n=="object"&&n!==null?structuredClone(Object.assign({},n)):structuredClone(n):JSON.parse(JSON.stringify(n))}class J{constructor(e,t,i,s,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:s,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const ql=["vp8","h264"],Kl=["vp8","h264","vp9","av1","h265"];function Wl(n){return!!ql.find(e=>e===n)}const Hl=Wl;var No;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(No||(No={}));var Sn;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(Sn||(Sn={}));const qt={h90:new J(160,90,9e4,20),h180:new J(320,180,16e4,20),h216:new J(384,216,18e4,20),h360:new J(640,360,45e4,20),h540:new J(960,540,8e5,25),h720:new J(1280,720,17e5,30),h1080:new J(1920,1080,3e6,30),h1440:new J(2560,1440,5e6,30),h2160:new J(3840,2160,8e6,30)},En={h120:new J(160,120,7e4,20),h180:new J(240,180,125e3,20),h240:new J(320,240,14e4,20),h360:new J(480,360,33e4,20),h480:new J(640,480,5e5,20),h540:new J(720,540,6e5,25),h720:new J(960,720,13e5,30),h1080:new J(1440,1080,23e5,30),h1440:new J(1920,1440,38e5,30)},Rn={h360fps3:new J(640,360,2e5,3,"medium"),h360fps15:new J(640,360,4e5,15,"medium"),h720fps5:new J(1280,720,8e5,5,"medium"),h720fps15:new J(1280,720,15e5,15,"medium"),h720fps30:new J(1280,720,2e6,30,"medium"),h1080fps15:new J(1920,1080,25e5,15,"medium"),h1080fps30:new J(1920,1080,5e6,30,"medium"),original:new J(0,0,7e6,30,"medium")};function xo(n,e,t){var i,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=Uo(n??{}),l=e?.processor,u=t?.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(Pn(h.audio,e),(i=(r=h.audio).deviceId)!==null&&i!==void 0||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=c??l)),h.video&&(Pn(h.video,t),(s=(a=h.video).deviceId)!==null&&s!==void 0||(a.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=d??u)),h}function Pn(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function In(n){var e,t,i,s;const r={};if(n.video)if(typeof n.video=="object"){const a={},o=a,c=n.video;Object.keys(c).forEach(d=>{d==="resolution"?Pn(o,c.resolution):o[d]=c[d]}),r.video=a,(e=(i=r.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else r.video=n.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return n.audio?typeof n.audio=="object"?(r.audio=n.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Mo(n){return p(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=Lo();if(i){const s=i.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,a=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield le(t),s.getByteTimeDomainData(a);const c=a.some(d=>d!==128&&d!==0);return i.close(),!c}return!1})()})}function Lo(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>p(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function Gl(n){return n==="audioinput"?C.Source.Microphone:n==="videoinput"?C.Source.Camera:C.Source.Unknown}function wn(n){return n===C.Source.Microphone?"audioinput":n===C.Source.Camera?"videoinput":void 0}function zl(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,lt()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function Kt(n){return n.split("/")[1].toLowerCase()}function Jl(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new sn({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function K(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?K(n.track):{})}}function $l(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Ql(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],s={};for(const r of i)n[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Uo(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:jl(e)}}function Yl(n){switch(n){case oe.CAMERA:return C.Source.Camera;case oe.MICROPHONE:return C.Source.Microphone;case oe.SCREEN_SHARE:return C.Source.ScreenShare;case oe.SCREEN_SHARE_AUDIO:return C.Source.ScreenShareAudio;default:return C.Source.Unknown}}function Fo(n,e){return n.width*n.height<e.width*e.height}function Xl(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const Zl=5e3,Wt=[];var Te;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Te||(Te={}));class C extends Me.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=C.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=B,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Zl):this.handleAppVisibilityChanged()},this.log=je((s=i.loggerName)!==null&&s!==void 0?s:we.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=C.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),K(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===C.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===C.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Wt.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Wt.splice(Wt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Ct(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),s=i.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?P.AudioPlaybackStarted:P.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?P.AudioPlaybackFailed:P.VideoPlaybackFailed,r):r.name==="AbortError"?B.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):B.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&i.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(P.ElementAttached,e),e}detach(e){try{if(e){St(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(P.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{St(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(P.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=je(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Wt.forEach(i=>{i.parentElement||(t=!1)}),t&&Wt.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===C.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){ye()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){ye()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Ct(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(s=>{t.removeTrack(s)}),t.addTrack(n)),(!lt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(lt()||dt())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function St(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function s(d){switch(d){case e.Audio:return Pe.AUDIO;case e.Video:return Pe.VIDEO;default:return Pe.DATA}}n.kindToProto=s;function r(d){switch(d){case Pe.AUDIO:return e.Audio;case Pe.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function a(d){switch(d){case t.Camera:return oe.CAMERA;case t.Microphone:return oe.MICROPHONE;case t.ScreenShare:return oe.SCREEN_SHARE;case t.ScreenShareAudio:return oe.SCREEN_SHARE_AUDIO;default:return oe.UNKNOWN}}n.sourceToProto=a;function o(d){switch(d){case oe.CAMERA:return t.Camera;case oe.MICROPHONE:return t.Microphone;case oe.SCREEN_SHARE:return t.ScreenShare;case oe.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function c(d){switch(d){case tn.ACTIVE:return i.Active;case tn.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(C||(C={}));const eu="|",Vo="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function tu(n){const e=n.split(eu);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function le(n){return new ue(e=>de.setTimeout(e,n))}function Dn(){return"addTransceiver"in RTCPeerConnection.prototype}function An(){return"addTrack"in RTCPeerConnection.prototype}function iu(){if(!("getCapabilities"in RTCRtpSender)||lt()||dt())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function nu(){if(!("getCapabilities"in RTCRtpSender)||dt())return!1;if(lt()){const t=be();if(t?.version&&Ue(t.version,"16")<0||t?.os==="iOS"&&t?.osVersion&&Ue(t.osVersion,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function De(n){return n==="av1"||n==="vp9"}function On(n){return!document||Ht()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function su(){return typeof RTCPeerConnection>"u"?!1:Dn()||An()}function dt(){var n;return((n=be())===null||n===void 0?void 0:n.name)==="Firefox"}function Bo(){const n=be();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function lt(){var n;return((n=be())===null||n===void 0?void 0:n.name)==="Safari"}function Ht(){const n=be();return n?.name==="Safari"||n?.os==="iOS"}function ru(){const n=be();return n?.name==="Safari"&&n.version.startsWith("17.")||n?.os==="iOS"&&!!n?.osVersion&&Ue(n.osVersion,"17")>=0}function ou(n){return n||(n=be()),n?.name==="Safari"&&Ue(n.version,"18.3")>0||n?.os==="iOS"&&!!n?.osVersion&&Ue(n.osVersion,"18.3")>0}function jo(){var n,e;return ye()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function au(){const n=be(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Ue(n.osVersion,e)>=0?!0:n.name==="Safari"&&Ue(n.version,e)>=0}function ye(){return typeof document<"u"}function Le(){return navigator.product=="ReactNative"}function Et(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Nn(n){return Et(n)?n.hostname.split(".")[0]:null}function qo(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Ko(){if(!Le())return;let n=qo();if(n)return n.platform}function Wo(){if(ye())return window.devicePixelRatio;if(Le()){let n=qo();if(n)return n.devicePixelRatio}return 1}function Ue(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(i[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function cu(n){for(const e of n)e.target.handleResize(e)}function du(n){for(const e of n)e.target.handleVisibilityChanged(e)}let xn=null;const Ho=()=>(xn||(xn=new ResizeObserver(cu)),xn);let Mn=null;const Go=()=>(Mn||(Mn=new IntersectionObserver(du,{root:null,rootMargin:"0px"})),Mn);function lu(){var n;const e=new yr({sdk:Tr.JS,protocol:Vl,version:Fl});return Le()&&(e.os=(n=Ko())!==null&&n!==void 0?n:""),e}function zo(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=n,s.height=e;const r=s.getContext("2d");r?.fillRect(0,0,s.width,s.height),i&&r&&(r.beginPath(),r.arc(n/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Gt;function Ln(){if(!Gt){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const i=n.createMediaStreamDestination();if(e.connect(t),t.connect(i),e.start(),[Gt]=i.stream.getAudioTracks(),!Gt)throw Error("Could not get empty media stream audio track");Gt.enabled=!1}return Gt.clone()}class Ee{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,s)=>p(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function uu(n){return Kl.includes(n)}function Ye(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact!==void 0)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal!==void 0)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function hu(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function zt(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function pu(n,e){return n.segments.map(t=>{let{id:i,text:s,language:r,startTime:a,endTime:o,final:c}=t;var d;const l=(d=e.get(i))!==null&&d!==void 0?d:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,l),{id:i,text:s,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function mu(n){const{id:e,timestamp:t,message:i,editTimestamp:s}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:i}}function Jo(n){switch(n.reason){case $.LeaveRequest:return n.context;case $.Cancelled:return Ce.CLIENT_INITIATED;case $.NotAllowed:return Ce.USER_REJECTED;case $.ServerUnreachable:return Ce.JOIN_FAILURE;default:return Ce.UNKNOWN_REASON}}function Ii(n){return n!==void 0?Number(n):void 0}function ut(n){return n!==void 0?BigInt(n):void 0}function Rt(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Fe(n){return!!n&&n.kind==C.Kind.Audio}function Xe(n){return!!n&&n.kind==C.Kind.Video}function Ze(n){return Rt(n)&&Xe(n)}function We(n){return Rt(n)&&Fe(n)}function Un(n){return!!n&&!n.isLocal}function fu(n){return!!n&&!n.isLocal}function Fn(n){return Un(n)&&Xe(n)}function gu(n){return n.isLocal}function vu(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let s=e;for(;s>0;){const r=i[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(i.slice(0,s)),i=i.slice(s)}return i.length>0&&t.push(i),t}function _u(n){var e;const t=n.get("Cache-Control");if(t){const i=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function bu(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=yu(n,e);return t?i:Vn(i,"v1")}function yu(n,e){const t=new URL(hu(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),Vn(t,"rtc")}function Tu(n){const e=new URL(zt(n));return Vn(e,"validate")}function $o(n){return n.endsWith("/")?n:"".concat(n,"/")}function Vn(n,e){return n.pathname="".concat($o(n.pathname)).concat(e),n}function Qo(n){if(typeof n=="string")return Pr.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return Pr.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function ku(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(n instanceof AbortSignal))return e;const t=n.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const Cu=10,Jt="lk_e2ee",Su={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Cu,keyringSize:16};var et;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(et||(et={}));var Yo;(function(n){n.KeyRatcheted="keyRatcheted"})(Yo||(Yo={}));var tt;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(tt||(tt={}));var Xo;(function(n){n.Error="cryptorError"})(Xo||(Xo={}));function Eu(){return Ru()||Bn()}function Bn(){return typeof window.RTCRtpScriptTransform<"u"}function Ru(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Pu(n){var e,t,i,s,r;if(((e=n.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=n.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((i=n.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((s=n.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=n.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new pr({value:n.value})}class gp extends Me.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,s)=>{B.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Su),e),this.on(et.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const s={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),s),this.emit(et.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(et.RatchetRequest,e,t)}}var Zo;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(Zo||(Zo={}));class Iu extends Me.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var s,r;const{kind:a,data:o}=i.data;switch(a){case"error":if(B.error(o.error.message),o.uuid){const l=this.decryptDataRequests.get(o.uuid);if(l?.reject){l.reject(o.error);break}const u=this.encryptDataRequests.get(o.uuid);if(u?.reject){u.reject(o.error);break}}this.emit(tt.EncryptionError,o.error,o.participantIdentity);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit(tt.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const l=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!l)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(tt.ParticipantEncryptionStatusChanged,o.enabled,l)}break;case"ratchetKey":this.keyProvider.emit(et.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(o.uuid);c?.resolve&&c.resolve(o);break;case"encryptDataResponse":const d=this.encryptDataRequests.get(o.uuid);d?.resolve&&d.resolve(o);break}},this.onWorkerError=i=>{B.error("e2ee worker encountered an error:",{error:i.error}),this.emit(tt.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Eu())throw new Cn("tried to setup end-to-end encryption on an unsupported browser");if(B.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:kl.getLevel()}};this.worker&&(B.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){B.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?B.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(w.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(E.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==se.NONE,s.identity)),e.on(E.ConnectionStateChanged,i=>{i===z.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==se.NONE,s.identity)})})}).on(E.TrackUnsubscribed,(i,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(E.TrackSubscribed,(i,s,r)=>{this.setupE2EEReceiver(i,r.identity,s.trackInfo)}).on(E.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(I.LocalSenderCreated,(i,s)=>p(this,void 0,void 0,function*(){this.setupE2EESender(s,i)})),e.localParticipant.on(I.LocalTrackPublished,i=>{if(!Xe(i.track)||!Ht())return;const s={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:Kt(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(et.SetKey,i=>this.postKey(i)).on(et.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}encryptData(e){return p(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new Ee;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(i),s.promise})}handleEncryptedData(e,t,i,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:s}},o=new Ee;return o.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!i?.mimeType||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Kt(i.mimeType):void 0)}}setupE2EESender(e,t){if(!Rt(e)||!t){t||B.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,s){return p(this,void 0,void 0,function*(){if(this.worker){if(Bn()&&!Bo()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Jt in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(c);return}let r=e.writableStream,a=e.readableStream;if(!r||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:s,participantIdentity:i,isReuse:Jt in e}};this.worker.postMessage(o,[a,r])}e[Jt]=!0}})}handleSender(e,t,i){var s;if(!(Jt in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Bn()&&!Bo()){B.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{B.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(a,[r.readable,r.writable])}e[Jt]=!0}}}const wu=500,Du=15e3;class Pt{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Pt),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),s=Nn(i);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,le(Math.min(wu*Math.pow(2,r),Du)))}getBackOffPromise(e){const t=new URL(e),i=t&&Nn(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&Nn(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Pt._instance=null;const jn="default";class ce{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new ce),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=ce.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){B.debug("awaiting getUserMedia promise");try{t?yield ce.userMediaPromiseMap.get(t):yield Promise.all(ce.userMediaPromiseMap.values())}catch{B.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(lt()&&i.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.some(c=>{const d=c.label==="",l=t?c.kind===t:!0;return d&&l}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},d=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),d.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a})()})}normalizeDeviceId(e,t,i){return p(this,void 0,void 0,function*(){if(t!==jn)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===jn);if(!r){B.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==jn&&o.groupId===(i??r.groupId));if(!a){B.warn("could not reliably determine default device");return}return a?.deviceId})}hasDeviceInUse(e){return e?ce.userMediaPromiseMap.has(e):ce.userMediaPromiseMap.size>0}}ce.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],ce.userMediaPromiseMap=new Map;var $t;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})($t||($t={}));class Au{constructor(){this.pendingTasks=new Map,this.taskMutex=new he,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:$t.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=$t.RUNNING,yield e()}finally{t.status=$t.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return p(this,void 0,void 0,function*(){return this.run(()=>p(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class Ou{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,s;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const a=function(){let{closeCode:o,reason:c}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r.close(o,c)};this.opened=new ue((o,c)=>{const d=()=>{c(V.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{o({readable:new ReadableStream({start(l){r.onmessage=u=>{let{data:h}=u;return l.enqueue(h)},r.onerror=u=>l.error(u)},cancel:a}),writable:new WritableStream({write(l){r.send(l)},abort(){r.close()},close:a}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),this.closed=new ue((o,c)=>{const d=()=>p(this,void 0,void 0,function*(){const l=new ue(h=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",f=>{h(f)},{once:!0})}),u=yield ue.race([le(250),l]);u?o(u):c(V.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=l=>{let{code:u,reason:h}=l;o({closeCode:u,reason:h}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=a}}const Nu=["syncState","trickle","offer","answer","simulate","leave"];function xu(n){const e=Nu.indexOf(n.case)>=0;return B.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Q;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(Q||(Q={}));const Mu=250;class qn{get currentState(){return this.state}get isDisconnected(){return this.state===Q.DISCONNECTING||this.state===Q.DISCONNECTED}get isEstablishingConnection(){return this.state===Q.CONNECTING||this.state===Q.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=Q.DISCONNECTED,this.log=B,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=je((i=t.loggerName)!==null&&i!==void 0?i:we.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Au,this.queuedRequests=[],this.closingLock=new he,this.connectionLock=new he,this.state=Q.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return d.state=Q.CONNECTING,d.options=o,yield d.connect(r,a,o,c,l)})()})}reconnect(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=Q.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const u=yield d.connectionLock.lock();d.connectOptions=o,d.useV0SignalPath=l;const h=lu(),f=l?Lu(a,h,o):Uu(a,h,o),_=bu(r,f,l).toString(),v=Tu(_).toString();return new Promise((R,T)=>p(d,void 0,void 0,function*(){var A,x;try{let b=!1;const y=O=>p(this,void 0,void 0,function*(){if(b)return;b=!0;const U=O instanceof Event?O.currentTarget:O,q=ku(U,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(q)).catch(Z=>{this.log.error(Z),this.close()}):this.close(),S(),T(V.cancelled(q))});c?.addEventListener("abort",y);const S=()=>{clearTimeout(N),c?.removeEventListener("abort",y)},N=setTimeout(()=>{y(V.timeout("room connection has timed out (signal)"))},o.websocketTimeout),F=(O,U)=>{this.handleSignalConnected(O,N,U)},M=new URL(_);M.searchParams.has("access_token")&&M.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(M),Object.assign({reconnect:o.reconnect,reconnectReason:o.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new Ou(_);try{this.ws.closed.then(ge=>{var rt;this.isEstablishingConnection&&T(V.internal("Websocket got closed during a (re)connection attempt: ".concat(ge.reason))),ge.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:ge.reason,code:ge.closeCode,wasClean:ge.closeCode===1e3,state:this.state})),this.state===Q.CONNECTED&&this.handleOnClose((rt=ge.reason)!==null&&rt!==void 0?rt:"Unexpected WS error"))}).catch(ge=>{this.isEstablishingConnection&&T(V.internal("Websocket error during a (re)connection attempt: ".concat(ge)))});const O=yield this.ws.opened.catch(ge=>p(this,void 0,void 0,function*(){if(this.state!==Q.CONNECTED){this.state=Q.DISCONNECTED,clearTimeout(N);const rt=yield this.handleConnectionError(ge,v);T(rt);return}this.handleWSError(ge),T(ge)}));if(clearTimeout(N),!O)return;const U=O.readable.getReader();this.streamWriter=O.writable.getWriter();const q=yield U.read();if(U.releaseLock(),!q.value)throw V.internal("no message received as first message");const Z=Qo(q.value),ke=this.validateFirstMessage(Z,(A=o.reconnect)!==null&&A!==void 0?A:!1);if(!ke.isValid){T(ke.error);return}((x=Z.message)===null||x===void 0?void 0:x.case)==="join"&&(this.pingTimeoutDuration=Z.message.value.pingTimeout,this.pingIntervalDuration=Z.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));const pt=ke.shouldProcessFirstMessage?Z:void 0;F(O,pt),R(ke.response)}catch(O){T(O)}finally{S()}}finally{u()}}))})()})}startReadingLoop(e,t){return p(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield le(this.signalLatency));const{done:i,value:s}=yield e.read();if(i)break;const r=Qo(s);this.handleSignalResponse(r)}})}close(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([Q.DISCONNECTING||Q.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Q.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,le(Mu)])}}catch(r){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:r}))}finally{t&&(e.state=Q.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:It(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:It(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new mi({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new fi({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const o=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new on({requestId:o,metadata:i,name:s,attributes:a})}),o})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Nr({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Lr({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:X.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Vr({timestamp:X.parse(Date.now()),rtt:X.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new rn({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new vi({reason:Ce.CLIENT_INITIATED,action:bt.DISCONNECT})})}sendRequest(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!xu(t)&&i.state===Q.RECONNECTING){i.queuedRequests.push(()=>p(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield i.requestQueue.flush()),i.signalLatency&&(yield le(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t?.case),i.logContext);return}const a=new qd({message:t});try{i.useJSON?yield i.streamWriter.write(a.toJsonString()):yield i.streamWriter.write(a.toBinary())}catch(o){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:o}))}})()})}handleSignalResponse(e){var t,i;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const a=ea(s.value);this.onAnswer&&this.onAnswer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const a=ea(s.value);this.onOffer&&this.onOffer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const a=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(a,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=s.value.speakers)!==null&&i!==void 0?i:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return p(this,void 0,void 0,function*(){if(this.state===Q.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=de.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&de.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=de.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&de.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=Q.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,s,r,a,o;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===Q.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((a=e.message)===null||a===void 0?void 0:a.case)==="leave"?{isValid:!1,error:V.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:V.internal("Unexpected first message")}:{isValid:!1,error:V.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return p(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:return V.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield i.text();return V.notAllowed(s,i.status);default:break}return e instanceof V?e:V.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof V?i:V.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function ea(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function It(n,e){return new $e({sdp:n.sdp,type:n.type,id:e})}function Lu(n,e,t){var i;const s=new URLSearchParams;return s.set("access_token",n),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Le()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&s.set("network",navigator.connection.type),s}function Uu(n,e,t){const i=new URLSearchParams;i.set("access_token",n);const s=new fl({clientInfo:e,connectionSettings:new Br({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const r=new gl({joinRequest:s.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),i}class ta{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Fu{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const s=i+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[s,r]of i.entries())t.push(e(r,s,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var Ae={},Kn={},Wn={exports:{}},ia;function Hn(){if(ia)return Wn.exports;ia=1;var n=Wn.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),Wn.exports}var na;function Vu(){return na||(na=1,(function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,d,l){if(l&&!d)c[l]=e(o[1]);else for(var u=0;u<d.length;u+=1)o[u+1]!=null&&(c[d[u]]=e(o[u+1]))},i=function(o,c,d){var l=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:l&&!c[o.name]&&(c[o.name]={});var u=o.push?{}:l?c[o.name]:c;t(d.match(o.reg),u,o.names,o.name),o.push&&c[o.push].push(u)},s=Hn(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var c={},d=[],l=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(d.push({rtp:[],fmtp:[]}),l=d[d.length-1]);for(var _=0;_<(s[h]||[]).length;_+=1){var v=s[h][_];if(v.reg.test(f))return i(v,l,f)}}),c.media=d,c};var a=function(o,c){var d=c.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&c.length>1&&(o[d[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var c=[],d=o.split(" ").map(e),l=0;l<d.length;l+=3)c.push({component:d[l],ip:d[l+1],port:d[l+2]});return c},n.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(d){var l,u=!1;return d[0]!=="~"?l=e(d):(l=e(d.substring(1,d.length)),u=!0),{scid:l,paused:u}})})}})(Kn)),Kn}var Gn,sa;function Bu(){if(sa)return Gn;sa=1;var n=Hn(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,d=c.length;return a.replace(e,function(l){if(o>=d)return l;var u=c[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(a,o,c){var d=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,l=[a+"="+d];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?l.push(c[o.name][h]):l.push(c[o.names[u]])}else l.push(c[o.name]);return t.apply(null,l)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Gn=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=o.outerOrder||s,d=o.innerOrder||r,l=[];return c.forEach(function(u){n[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(i(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(f){l.push(i(u,h,f))})})}),a.media.forEach(function(u){l.push(i("m",n.m[0],u)),d.forEach(function(h){n[h].forEach(function(f){f.name in u&&u[f.name]!=null?l.push(i(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(_){l.push(i(h,f,_))})})})}),l.join(`\r
|
|
146
146
|
`)+`\r
|
|
147
|
-
`},Gn}var ra;function ju(){if(ra)return Ae;ra=1;var n=Vu(),e=Bu(),t=Hn();return Ae.grammar=t,Ae.write=e,Ae.parse=n.parse,Ae.parseParams=n.parseParams,Ae.parseFmtpConfig=n.parseFmtpConfig,Ae.parsePayloads=n.parsePayloads,Ae.parseRemoteCandidates=n.parseRemoteCandidates,Ae.parseImageAttributes=n.parseImageAttributes,Ae.parseSimulcastStreamList=n.parseSimulcastStreamList,Ae}var it=ju();function zn(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var f=Date.now()-d;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),_=this;return new Promise(function(v,R){var T=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!a){var x=n.apply(_,f);o&&o(x),l.forEach(function(b){return(0,b.resolve)(x)}),l=[]}},u()),T){var A=n.apply(_,f);return o&&o(A),v(A)}l.push({resolve:v,reject:R})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),l.forEach(function(_){return(0,_.reject)(f)}),l=[]},h}const qu=.7,Ku=20,wt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class oa extends Me.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=B,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=zn(s=>p(this,void 0,void 0,function*(){this.emit(wt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Ku),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=je((i=t.loggerName)!==null&&i!==void 0?i:we.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new he}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return p(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:a}=Wu(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=it.parse((i=e.sdp)!==null&&i!==void 0?i:"");r.media.forEach(a=>{const o=Jn(a.mid);a.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||o!=c.transceiver.mid)return!1;let d=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0)return!0;let l=!1;for(const u of a.fmtp)if(u.payload===d){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),l=!0;break}return l||c.maxbr>0&&a.fmtp.push({payload:d,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=it.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(wt.NegotiationComplete),e.sdp&&it.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(wt.RTPVideoPayloadTypes,a.rtp)})),!0})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(e?.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const a=it.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{ca(o),o.type==="audio"?aa(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(c=>{if(!o.msid||!c.cid||!o.msid.includes(c.cid))return!1;let d=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0||(De(c.codec)&&!lt()&&this.ensureVideoDDExtensionForSVC(o,a),!De(c.codec)))return!0;const l=Math.round(c.maxbr*qu);for(const u of o.fmtp)if(u.payload===d){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,it.write(a)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=it.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{ca(s),s.type==="audio"&&aa(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,it.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new re("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new re("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return p(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,s=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,i){return p(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const a={error:r,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new Tt(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Vo))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(d=>{d.value>a&&(a=d.value)}))}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Vo})}}}function aa(n,e,t){const i=Jn(n.mid);let s=0;n.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&n.rtcpFb.push({payload:s,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function Wu(n){var e;const t=[],i=[],s=it.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;const c=Jn(a.mid);a.type==="audio"&&(a.rtp.some(d=>d.codec==="opus"?(r=d.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(d=>d.payload===r&&d.type==="nack")&&i.push(c),a.fmtp.some(d=>d.payload===r?(d.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:i}}function ca(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function Jn(n){return typeof n=="number"?n.toFixed(0):n}const $n="vp8",Hu={audioPreset:Sn.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Rn.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:$n,backupCodec:!0,preConnectBuffer:!1},da={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},la={deviceId:{ideal:"default"},resolution:qt.h720.resolution},Gu={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Sl,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Qn={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var te;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(te||(te={}));class zu{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var s;this.peerConnectionTimeout=Qn.peerConnectionTimeout,this.log=B,this.updateState=()=>{var r,a;const o=this.state,c=this.requiredTransports.map(d=>d.getConnectionState());c.every(d=>d==="connected")?this.state=te.CONNECTED:c.some(d=>d==="failed")?this.state=te.FAILED:c.some(d=>d==="connecting")?this.state=te.CONNECTING:c.every(d=>d==="closed")?this.state=te.CLOSED:c.some(d=>d==="closed")?this.state=te.CLOSING:c.every(d=>d==="new")&&(this.state=te.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(te[o]," to ").concat(te[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.log=je((s=i.loggerName)!==null&&s!==void 0?s:we.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new oa(e,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new oa(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Ie.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,r)},this.subscriber.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Ie.PUBLISHER)},this.publisher.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)},this.publisher.onOffer=(r,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r,a)},this.state=te.NEW,this.connectionLock=new he,this.remoteOfferLock=new he}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return p(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){var i;t===Ie.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return p(this,void 0,void 0,function*(){var i,s,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const a=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return p(this,void 0,void 0,function*(){var i;const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new ue((t,i)=>p(this,void 0,void 0,function*(){const s=setTimeout(()=>{i(new Tt("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i(new Tt("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(wt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(wt.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),a instanceof Error?i(a):i(new Error(String(a)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return i?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Ie.PUBLISHER?this.publisher.getConnectedAddress():e===Ie.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>p(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),de.clearTimeout(u),d(V.cancelled("room connection has been cancelled"))};s?.signal.aborted&&l(),s?.signal.addEventListener("abort",l);const u=de.setTimeout(()=>{s?.signal.removeEventListener("abort",l),d(V.internal("could not establish pc connection"))},a);for(;this.state!==te.CONNECTED;)if(yield le(50),s?.signal.aborted){d(V.cancelled("room connection has been cancelled"));return}de.clearTimeout(u),s?.signal.removeEventListener("abort",l),c()}))})()})}}const ua=5e3,Ju=3e4;class G{static fetchRegionSettings(e,t,i){return p(this,void 0,void 0,function*(){const s=yield G.fetchLock.lock();try{const r=yield fetch("".concat($u(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const a=_u(r.headers),o=a?a*1e3:ua;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw r.status===401?V.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):V.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof V?r:i?.aborted?V.cancelled("Region fetching was aborted"):V.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,i){return p(this,void 0,void 0,function*(){const s=G.settingsTimeouts.get(e.hostname);clearTimeout(s),G.settingsTimeouts.set(e.hostname,setTimeout(()=>p(this,void 0,void 0,function*(){try{const r=yield G.fetchRegionSettings(e,t);G.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof V&&r.reason===$.NotAllowed){B.debug("token is not valid, cancelling auto region refresh");return}B.debug("auto refetching of region settings failed",{error:r}),G.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){G.cache.set(e.hostname,i),G.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=G.settingsTimeouts.get(e);t&&(clearTimeout(t),G.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=G.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=G.connectionTrackers.get(e);i&&i.connectionCount===0&&(B.debug("stopping region refetch after disconnect delay",{hostname:e}),G.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},Ju))}static cancelCleanup(e){const t=G.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=G.connectionTrackers.get(e);t||(t={connectionCount:0},G.connectionTrackers.set(e,t)),t.connectionCount++,G.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=G.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&G.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Et(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){return G.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return p(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=G.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),G.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(i.length>0){const s=i[0];return this.attemptedRegions.push(s),B.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){G.updateCachedRegionSettings(this.serverUrl,this.token,e)}}G.cache=new Map,G.settingsTimeouts=new Map,G.connectionTrackers=new Map,G.fetchLock=new he;function $u(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class ie extends Error{constructor(e,t,i){super(t),this.code=e,this.message=pa(t,ie.MAX_MESSAGE_BYTES),this.data=i?pa(i,ie.MAX_DATA_BYTES):void 0}static fromProto(e){return new ie(e.code,e.message,e.data)}toProto(){return new gr({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ie(ie.ErrorCode[e],ie.ErrorMessage[e],t)}}ie.MAX_MESSAGE_BYTES=256,ie.MAX_DATA_BYTES=15360,ie.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},ie.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const ha=15360;function Yn(n){return new TextEncoder().encode(n).length}function pa(n,e){if(Yn(n)<=e)return n;let t=0,i=n.length;const s=new TextEncoder;for(;t<i;){const r=Math.floor((t+i+1)/2);s.encode(n.slice(0,r)).length<=e?t=r:i=r-1}return n.slice(0,t)}const Xn=2e3;function wi(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const Zn=typeof MediaRecorder<"u";class Qu{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Yu=Zn?MediaRecorder:Qu;class Xu extends Yu{constructor(e,t){if(!Zn)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,s;const r=()=>s===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s?.close(),s=void 0},o=c=>{s?.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,i=d=>p(this,void 0,void 0,function*(){let l;if(d.data.arrayBuffer){const u=yield d.data.arrayBuffer();l=new Uint8Array(u)}else if(d.data.byteArray)l=d.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function Zu(){return Zn}const eh=1e3,th=1e4;class ma extends C{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=zn(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(P.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new he,this.pauseUpstreamLock=new he,this.trackChangeLock=new he,this.trackChangeLock.lock().then(a=>p(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==C.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return p(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{St(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Ct(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Ct(s??e,r)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:eh;return(function*(){var i;if(e.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=be())===null||i===void 0?void 0:i.os)==="iOS"&&(yield le(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield le(50)}throw new Ke("unable to get track dimensions after timeout")})()})}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ye(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Ye(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===C.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===C.Kind.Audio?"audioinput":"videoinput";return t?ce.getInstance().normalizeDeviceId(r,i,s):i})()})}mute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return p(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ke("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:s}=e,r=El(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===C.Kind.Video?a.video=i||s?{deviceId:i,facingMode:s}:!0:a.audio=i?Object.assign({deviceId:i},r):!0,this.attachedElements.forEach(d=>{St(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===C.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(P.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?P.Muted:P.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),jo()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(P.UpstreamPaused,this);const i=be();if(i?.name==="Safari"&&Ue(i.version,"12.0")<0)throw new Cn("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(P.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return p(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Ct(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(d=>{d instanceof DOMException&&d.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:d})),setTimeout(()=>{o.play().catch(l=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:l}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:d}))}),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const d of i.attachedElements)d!==i.processorElement&&s&&(St(i._mediaStreamTrack,d),Ct(i.processor.processedTrack,d));yield(r=i.sender)===null||r===void 0?void 0:r.replaceTrack(i.processor.processedTrack)}i.emit(P.TrackProcessorUpdate,i.processor)}finally{a()}})()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}})()})}internalStopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(P.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Zu()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Xu(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},th)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class Di extends ma{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,C.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=wi(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===C.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Ye(this._constraints.deviceId);return this.source===C.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return p(this,void 0,void 0,function*(){let t;if(e){const i=In({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){ye()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Xn)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Le()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(P.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield Mo(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(P.AudioSilenceDetected)),e})}}function ih(n,e,t){switch(n.kind){case"audio":return new Di(n,e,!1,void 0,t);case"video":return new Ai(n,e,!1,t);default:throw new Ke("unsupported track type: ".concat(n.kind))}}const nh=Object.values(qt),sh=Object.values(En),rh=Object.values(Rn),oh=[qt.h180,qt.h360],ah=[En.h180,En.h360],ch=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new J(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),es=["q","h","f"];function ts(n,e,t,i){var s,r;let a=i?.videoEncoding;n&&(a=i?.screenShareEncoding);const o=i?.simulcast,c=i?.scalabilityMode,d=i?.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=lh(n,e,t,d),B.debug("using video encoding",a));const l=a.maxFramerate,u=new J(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&De(d)){const _=new va(c),v=[];if(_.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const R=be();if(Ht()||Le()||R?.name==="Chrome"&&Ue(R?.version,"113")<0){const T=_.suffix=="h"?2:3,A=ou(R);for(let x=0;x<_.spatial;x+=1)v.push({rid:es[2-x],maxBitrate:a.maxBitrate/Math.pow(T,x),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:A?Math.pow(2,x):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),B.debug("using svc encoding",{encodings:v}),v}if(!o)return[a];let h=[];n?h=(s=ga(i?.screenShareSimulcastLayers))!==null&&s!==void 0?s:fa(n,u):h=(r=ga(i?.videoSimulcastLayers))!==null&&r!==void 0?r:fa(n,u);let f;if(h.length>0){const _=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return is(e,t,[_,f,u],l);if(v>=480)return is(e,t,[_,u],l)}return is(e,t,[u])}function dh(n,e,t){var i,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&B.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=o.height)!==null&&r!==void 0?r:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===C.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),ts(n.source===C.Source.ScreenShare,c,d,t)}function lh(n,e,t,i){const s=uh(n,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function uh(n,e,t){if(n)return rh;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?nh:sh}function fa(n,e){if(n)return ch(e);const{width:t,height:i}=e,s=t>i?t/i:i/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?oh:ah}function is(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=es.length)return;const o=Math.min(n,e),d={rid:es[a],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=i&&r.encoding.maxFramerate?Math.min(i,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(d.maxFramerate=l);const u=dt()||a===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Le()&&Ko()==="ios"){let r;s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var c;o.maxFramerate!=r&&(a&&(a=!1,B.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),B.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function ga(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:s}=t;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class va{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function hh(n){return n.source===C.Source.ScreenShare||n.constraints.height&&Ye(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const ph=5e3;class Ai extends ma{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,C.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const a=new Map(r.map(c=>[c.rid,c])),o=r.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(P.CpuConstrained)),this.prevStats){let c=0;a.forEach((d,l)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);c+=wi(d,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new he}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!ye())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Xn))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=qe(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)r=d.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=qe(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){r=d.value,o=!1;const l=r;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(s=>{var r;if(s.type==="outbound-rtp"){const a={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},o=i.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((s,r)=>{var a,o;return((a=r.frameWidth)!==null&&a!==void 0?a:0)-((o=s.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Te.LOW;i<=Te.HIGH;i+=1)t.push(new an({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(De(this.codec),t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const u=In({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,d=qe(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.value,c=!1;const u=r;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,c,d,l,u;if(yield t.setProcessor.call(s,i,r),!((l=s.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,f=qe(s.simulcastCodecs.values()),_;_=yield f.next(),a=_.done,!a;h=!0)d=_.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){o={error:v}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return p(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},ph))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(De(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=qe(e);s=yield i.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(De(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield _a(u.sender,u.encodings,l.qualities,this.senderLock,De(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e,t){return p(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield _a(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return p(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((i,s)=>{var r;return Object.assign(Object.assign({},i),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&De(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),jo()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function _a(n,e,t,i,s,r,a){return p(this,void 0,void 0,function*(){const o=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{const c=n.getParameters(),{encodings:d}=c;if(!d)return;if(d.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:d,senderEncodings:e}));return}let l=!1;!1&&d[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),d.forEach((h,f)=>{var _;let v=(_=h.rid)!==null&&_!==void 0?_:"";v===""&&(v="q");const R=ba(v),T=t.find(A=>A.quality===R);T&&h.active!==T.enabled&&(l=!0,h.active=T.enabled,r.debug("setting layer ".concat(T.quality," to ").concat(h.active?"enabled":"disabled"),a),dt()&&(T.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),l&&(c.encodings=d,r.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield n.setParameters(c))}finally{o()}})}function ba(n){switch(n){case"f":return Te.HIGH;case"h":return Te.MEDIUM;case"q":return Te.LOW;default:return Te.HIGH}}function ya(n,e,t,i){if(!t)return[new Je({quality:Te.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new va(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)a.push(new Je({quality:Math.min(Te.HIGH,r.spatial-1)-d,width:Math.ceil(n/Math.pow(o,d)),height:Math.ceil(e/Math.pow(o,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=ba((a=s.rid)!==null&&a!==void 0?a:"");return new Je({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Ta="_lossy",ka="_reliable",mh=2*1e3,ns="leave-reconnect",fh=3e4,gh=8*1024,vh=256*1024;var Re;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Re||(Re={}));class _h extends Me.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Qn.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Re.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=B,this.reliableDataSequence=1,this.reliableMessageBuffer=new ta,this.reliableReceivedState=new Fu(fh),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>p(this,[i],void 0,function(s){var r=this;let{channel:a}=s;return(function*(){if(a){if(a.label===ka)r.reliableDCSub=a;else if(a.label===Ta)r.lossyDCSub=a;else return;r.log.debug("on data channel ".concat(a.id,", ").concat(a.label),r.logContext),a.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=i=>p(this,void 0,void 0,function*(){var s,r,a,o,c;const d=yield this.dataProcessLock.lock();try{let l;if(i.data instanceof ArrayBuffer)l=i.data;else if(i.data instanceof Blob)l=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const u=pe.fromBinary(new Uint8Array(l));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(w.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=pr.fromBinary(h.payload),_=new pe({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=_.value)===null||o===void 0?void 0:o.case)==="user"&&Ca(_,_.value.value),this.emit(w.DataPacketReceived,_,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&Ca(u,u.value.value),this.emit(w.DataPacketReceived,u,se.NONE)}finally{d()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const r=i.currentTarget.maxRetransmits===0?j.LOSSY:j.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(w.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}i===ns&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=de.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Re.Connected&&i();const r=()=>{this.off(w.Disconnected,a),i()},a=()=>{this.off(w.Restarted,r),s()};this.once(w.Restarted,r),this.once(w.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{if(i===j.RELIABLE){const r=this.dataChannelForKind(i);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(w.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>p(this,void 0,void 0,function*(){!this.url||!(yield fetch(zt(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Q.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Q.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(ot.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>p(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(zt(this.url),{method:"HEAD"}),le(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=je((t=e.loggerName)!==null&&t!==void 0?t:we.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new qn(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new he,this.dataProcessLock=new he,this.dcBufferStatus=new Map([[j.LOSSY,!0],[j.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(w.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(w.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(w.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(w.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(w.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(w.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(w.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(w.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||s===void 0?void 0:s.sid,participant:(a=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||a===void 0?void 0:a.identity,pID:this.participantSid}}join(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){d.url=r,d.token=a,d.signalOpts=o,d.maxJoinAttempts=o.maxRetries;try{d.joinAttempts+=1,d.setupSignalClientCallbacks();const u=yield d.client.join(r,a,o,c,l);return d._isClosed=!1,d.latestJoinResponse=u,d.subscriberPrimary=u.subscriberPrimary,d.pcManager||(yield d.configure(u,!l)),(!d.subscriberPrimary||u.fastPublish)&&d.negotiate().catch(h=>{B.error(h,d.logContext)}),d.registerOnLineListener(),d.clientConfiguration=u.clientConfiguration,d.emit(w.SignalConnected,u),u}catch(u){if(u instanceof V){if(u.reason===$.ServerUnreachable){if(d.log.warn("Couldn't connect to server, attempt ".concat(d.joinAttempts," of ").concat(d.maxJoinAttempts),d.logContext),d.joinAttempts<d.maxJoinAttempts)return d.join(r,a,o,c,l)}else if(u.reason===$.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(u.message," \u2013 Retrying")),d.join(r,a,o,c,!0)}throw u}})()})}close(){return p(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(w.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return p(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new ta,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Ke("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(V.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return p(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return p(this,void 0,void 0,function*(){var i,s;if(this.pcManager&&this.pcManager.currentState!==te.NEW)return;this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new zu(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(w.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(a,o)=>{this.client.sendIceCandidate(a,o)},this.pcManager.onPublisherOffer=(a,o)=>{this.client.sendOffer(a,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(a,o,c)=>p(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(a),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),a===te.CONNECTED){const u=this.pcState===Re.New;this.pcState=Re.Connected,u&&this.emit(w.Connected,e)}else a===te.FAILED&&(this.pcState===Re.Connected||this.pcState===Re.Reconnecting)&&(this.pcState=Re.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?ot.RR_SUBSCRIBER_FAILED:ot.RR_PUBLISHER_FAILED));const d=this.client.isDisconnected||this.client.currentState===Q.RECONNECTING,l=[te.FAILED,te.CLOSING,te.CLOSED].includes(a);d&&l&&!this._isClosed&&this.emit(w.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(w.MediaTrackAdded,a.track,a.streams[0],a.receiver)},bh((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>p(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>p(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(w.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(w.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(w.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(w.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(w.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",ot.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:ua,regionSettings:e.regions})),e.action){case bt.DISCONNECT:this.emit(w.Disconnected,e?.reason),this.close();break;case bt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ns);break;case bt.RESUME:this.handleDisconnect(ns)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(r=>{const a={urls:r.urls};r.username&&(a.username=r.username),r.credential&&(a.credential=r.credential),s.push(a)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ut.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ta,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(ka,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(j.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,gh),vh)}},1e3))}createSender(e,t,i){return p(this,void 0,void 0,function*(){if(Dn())return yield this.createTransceiverRTCRtpSender(e,t,i);if(An())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(Dn())return this.createSimulcastTransceiverSender(e,t,i,s);if(An())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Xe(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){B.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ut.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:te.NEW)===te.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let a=!0;r instanceof re?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof kt||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",ot.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(w.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return p(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(w.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new kt;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(a){throw a instanceof V&&a.reason===$.NotAllowed?new re("could not reconnect, token might be expired"):new kt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(w.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Q.CONNECTED)throw new kt("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(w.Restarted)}catch(r){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");if(!this.pcManager)throw new re("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(w.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof V&&s.reason===$.NotAllowed?new re("could not reconnect, token might be expired"):s instanceof V&&s.reason===$.LeaveRequest?s:new kt(r)}if(this.emit(w.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Q.CONNECTED)throw new kt("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i?.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(w.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Re.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield le(mh),!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Re.Connected}catch(e){throw this.pcState=Re.Disconnected,V.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,s){return p(this,void 0,void 0,function*(){const r=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcResponse",value:new Zi({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,j.RELIABLE)})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){const i=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcAck",value:new Xi({requestId:t})}});yield this.sendDataPacket(i,j.RELIABLE)})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=Pu(e);if(r){const a=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new hr({encryptedValue:a.payload,iv:a.iv,keyIndex:a.keyIndex})}}}t===j.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===j.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;s.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return p(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(j.RELIABLE);const t=this.dataChannelForKind(j.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(j.RELIABLE)})}waitForBufferStatusLow(e){return new ue((t,i)=>p(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i(new re("engine closed"));for(this.once(w.Closing,s);!this.dcBufferStatus.get(e);)yield le(10);this.off(w.Closing,s),t()}}))}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!i.pcManager)throw new re("PC manager is closed");const a=s?i.pcManager.subscriber:i.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw V.internal("".concat(o," connection not set"));let c=!1;!s&&!i.dataChannelForKind(t,s)&&(i.createDataChannels(),c=!0),!c&&!s&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate().catch(u=>{B.error(u,i.logContext)});const d=i.dataChannelForKind(t,s);if(d?.readyState==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield le(50)}throw V.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return p(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==te.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new ue((e,t)=>p(this,void 0,void 0,function*(){if(!this.pcManager){t(new Tt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new Tt("cannot negotiate on closed engine")),this.on(w.Closing,s),this.pcManager.publisher.once(wt.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();uu(c)&&a.set(o.payload,c)}),this.emit(w.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof Tt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ot.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(w.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===j.LOSSY)return this.lossyDCSub;if(e===j.RELIABLE)return this.reliableDCSub}else{if(e===j.LOSSY)return this.lossyDC;if(e===j.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s,r,a;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),l=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(a=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&a!==void 0?a:!0,h=new Array,f=new Array;e.forEach(_=>{_.isDesired!==u&&h.push(_.trackSid),_.isEnabled||f.push(_.trackSid)}),this.client.sendSyncState(new cn({answer:this.pcManager.mode==="publisher-only"?c?It({sdp:c.sdp,type:c.type}):void 0:l?It({sdp:l.sdp,type:l.type}):void 0,offer:this.pcManager.mode==="publisher-only"?o?It({sdp:o.sdp,type:o.type}):void 0:d?It({sdp:d.sdp,type:d.type}):void 0,subscription:new gi({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:Jl(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((_,v)=>new Ur({publisherSid:v,lastSeq:_}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{i?.id!==void 0&&i.id!==null&&e.push(new Fr({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(j.LOSSY),Ie.PUBLISHER),t(this.dataChannelForKind(j.RELIABLE),Ie.PUBLISHER),t(this.dataChannelForKind(j.LOSSY,!0),Ie.SUBSCRIBER),t(this.dataChannelForKind(j.RELIABLE,!0),Ie.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&de.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ye()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){ye()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const s=Object.entries(this.midToTrackId).find(r=>{let[a]=r;return a===i});if(s)return s[1]}}}function bh(n){return n!==void 0&&n>13}function Ca(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class Sa{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new Se("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),me.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Se("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),me.LengthExceeded)}}constructor(e,t,i,s){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class yh extends Sa{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Ee,i=null,s=null;if(this.signal){const a=this.signal;s=()=>{var o;(o=t.reject)===null||o===void 0||o.call(t,a.reason)},a.addEventListener("abort",s),i=a}const r=()=>{e.releaseLock(),i&&s&&i.removeEventListener("abort",s),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var a,o;try{const{done:c,value:d}=yield Promise.race([e.read(),t.promise,(o=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&o!==void 0?o:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(d),{done:!1,value:d.content})}catch(c){throw r(),c}}),return(){return p(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=qe(c),u;u=yield l.next(),i=u.done,!i;d=!0){a=u.value,d=!1;const h=a;o.add(h)}}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return Array.from(o)})()})}}class Th extends Sa{constructor(e,t,i,s){super(e,t,i,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Ii(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new Ee,s=null,r=null;if(this.signal){const o=this.signal;r=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,o.reason)},o.addEventListener("abort",r),s=o}const a=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var o,c;try{const{done:d,value:l}=yield Promise.race([e.read(),i.promise,(c=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(d)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(l);let u;try{u=t.decode(l.content)}catch(h){throw new Se("Cannot decode datastream chunk ".concat(l.chunkIndex," as text: ").concat(h),me.DecodeFailed)}return{done:!1,value:u}}}catch(d){throw a(),d}}),return(){return p(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=qe(c),u;u=yield l.next(),i=u.done,!i;d=!0)a=u.value,d=!1,o+=a}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return o})()})}}class kh{constructor(){this.log=B,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Se('A text stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Se('A byte stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,s,r;const a=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(a.length>0||o.length>0){const c=new Se("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),me.AbnormalEnd);for(const[d,l]of o)(i=(t=l.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(t,c),this.byteStreamControllers.delete(d);for(const[d,l]of a)(r=(s=l.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(d)}}handleDataStreamPacket(e,t){return p(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return p(this,void 0,void 0,function*(){var s;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o=new Ee;o.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Ii(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new yh(c,d,Ii(e.totalLength),o),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o=new Ee;o.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new Th(c,d,Ii(e.totalLength),o),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Ea{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return p(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Ch extends Ea{}class Sh extends Ea{}const Ra=15e3;class Eh{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return p(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t?.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),d=(u,h)=>{var f;c[h]=u;const _=c.reduce((v,R)=>v+R,0);(f=t?.onProgress)===null||f===void 0||f.call(t,_)},l=yield this.streamText({streamId:s,totalSize:a,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield l.write(e),d(1,0),yield l.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>p(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{d(f,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,i,s;const r=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e?.topic)!==null&&i!==void 0?i:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?se.GCM:se.NONE,attachedStreamIds:e?.attachedStreamIds},o=new ui({streamId:r,mimeType:a.mimeType,topic:a.topic,timestamp:ut(a.timestamp),totalLength:ut(e?.totalSize),attributes:a.attributes,contentHeader:{case:"textHeader",value:new Er({version:e?.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?en.UPDATE:en.CREATE})}}),c=e?.destinationIdentities,d=new pe({destinationIdentities:c,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(d,j.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(v){return p(this,void 0,void 0,function*(){for(const R of vu(v,Ra)){const T=new hi({content:R,streamId:r,chunkIndex:ut(l)}),A=new pe({destinationIdentities:c,value:{case:"streamChunk",value:T}});yield u.sendDataPacket(A,j.RELIABLE),l+=1}})},close(){return p(this,void 0,void 0,function*(){const v=new pi({streamId:r}),R=new pe({destinationIdentities:c,value:{case:"streamTrailer",value:v}});yield u.sendDataPacket(R,j.RELIABLE)})},abort(v){console.log("Sink error:",v)}});let f=()=>p(this,void 0,void 0,function*(){yield _.close()});u.once(w.Closing,f);const _=new Ch(h,a,()=>this.engine.off(w.Closing,f));return _})}sendFile(e,t){return p(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return p(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=i?.mimeType)!==null&&s!==void 0?s:t.type,topic:i?.topic,destinationIdentities:i?.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o;const c=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e?.destinationIdentities,l={id:c,mimeType:(i=e?.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(s=e?.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?se.GCM:se.NONE},u=new ui({totalLength:ut((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:ut(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new Rr({name:l.name})}}),h=new pe({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,j.RELIABLE);let f=0;const _=new he,v=this.engine,R=this.log,T=new WritableStream({write(x){return p(this,void 0,void 0,function*(){const b=yield _.lock();let y=0;try{for(;y<x.byteLength;){const S=x.slice(y,y+Ra),N=new pe({destinationIdentities:d,value:{case:"streamChunk",value:new hi({content:S,streamId:c,chunkIndex:ut(f)})}});yield v.sendDataPacket(N,j.RELIABLE),f+=1,y+=S.byteLength}}finally{b()}})},close(){return p(this,void 0,void 0,function*(){const x=new pi({streamId:c}),b=new pe({destinationIdentities:d,value:{case:"streamTrailer",value:x}});yield v.sendDataPacket(b,j.RELIABLE)})},abort(x){R.error("Sink error:",x)}});return new Sh(T,l)})}}class Pa extends C{constructor(e,t,i,s,r){super(e,i,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?P.Muted:P.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(P.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return p(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Xn)),$l()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:s,rtpTimestamp:r}=i;r&&this.rtpTimestamp!==r&&(this.emit(P.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Rh extends Pa{constructor(e,t,i,s,r,a){super(e,t,C.Kind.Audio,i,a),this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=wi(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Le()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Le())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(On(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&On(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(P.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(P.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const ss=100;class Ph extends Pa{constructor(e,t,i,s,r){super(e,t,C.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=wi(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=zn(()=>{this.updateDimensions()},ss),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===C.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?St(this._mediaStreamTrack,t):Ct(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Ih(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const s=this.elementInfos.reduce((c,d)=>Math.max(c,d.visibilityChangedAt||0),0),r=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!r||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-s<ss){de.setTimeout(()=>{this.updateVisibility()},ss);return}this.lastVisible=o,this.emit(P.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>i+s&&(i=o,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(P.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Wo():t||(Wo()>2?2:1)}}class Ih{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:a}=i;r===this.element&&(this.isIntersecting=a,this.isPiP=Qt(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i,s,r;(s=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Qt(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Qt(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??rs(e),this.isPiP=ye()&&Qt(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=rs(this.element),this.isPiP=Qt(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Go().observe(this.element),Ho().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,s,r;(e=Go())===null||e===void 0||e.unobserve(this.element),(t=Ho())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function Qt(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?rs(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function rs(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:c}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,s+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&s+r>t.pageXOffset&&!o&&c!=="none"}class He extends Me.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=se.NONE,this.log=B,this.handleMuted=()=>{this.emit(P.Muted)},this.handleUnmuted=()=>{this.emit(P.Unmuted)},this.log=je((r=s?.loggerName)!==null&&r!==void 0?r:we.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=C.Source.Unknown}setTrack(e){this.track&&(this.track.off(P.Muted,this.handleMuted),this.track.off(P.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(P.Muted,this.handleMuted),e.on(P.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),K(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==se.NONE}get audioTrack(){if(Fe(this.track))return this.track}get videoTrack(){if(Xe(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=C.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===C.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(He||(He={}));class os extends He{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(P.Ended)},this.handleCpuConstrained=()=>{this.track&&Xe(this.track)&&this.emit(P.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(P.Ended,this.handleTrackEnded),this.track.off(P.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(P.Ended,this.handleTrackEnded),e.on(P.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Fe(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ae.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ae.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ae.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ae.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(ae.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ae.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Oi(n,e){return p(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=Uo(n);let a=r.audio,o=r.video;if(i&&typeof r.audio=="object"&&(r.audio.processor=i),s&&typeof r.video=="object"&&(r.video.processor=s),n.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=xo(r,da,la),d=In(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(ce.userMediaPromiseMap.set("audioinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("audioinput"))),r.video&&(ce.userMediaPromiseMap.set("videoinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(h=>p(this,void 0,void 0,function*(){const f=h.kind==="audio";let _=f?c.audio:c.video;(typeof _=="boolean"||!_)&&(_={});let v;const R=f?d.audio:d.video;typeof R!="boolean"&&(v=R);const T=h.getSettings().deviceId;v?.deviceId&&Ye(v.deviceId)!==T?v.deviceId=T:v||(v={deviceId:T});const A=ih(h,v,e);return A.kind===C.Kind.Video?A.source=C.Source.Camera:A.kind===C.Kind.Audio&&(A.source=C.Source.Microphone),A.mediaStream=u,Fe(A)&&i?yield A.setProcessor(i):Xe(A)&&s&&(yield A.setProcessor(s)),A})))}catch(u){if(!t)throw u;return Oi(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function Ia(n){return p(this,void 0,void 0,function*(){return(yield Oi({audio:!1,video:n??!0}))[0]})}function wa(n){return p(this,void 0,void 0,function*(){return(yield Oi({audio:n??!0,video:!1}))[0]})}var nt;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(nt||(nt={}));function wh(n){switch(n){case Lt.EXCELLENT:return nt.Excellent;case Lt.GOOD:return nt.Good;case Lt.POOR:return nt.Poor;case Lt.LOST:return nt.Lost;default:return nt.Unknown}}class Da extends Me.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Ft.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===vt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ft.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=nt.Unknown,this.log=B,this.log=je((c=a?.loggerName)!==null&&c!==void 0?c:we.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Ee,this.once(I.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(C.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(C.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(C.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===vt.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==vt.ACTIVE&&this.emit(I.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(I.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(I.ParticipantNameChanged,e)}_setAttributes(e){const t=Ql(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(I.AttributesChanged,t)}setPermissions(e){var t,i,s,r,a,o;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit(I.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(I.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=wh(e),t!==this._connectionQuality&&this.emit(I.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Fe(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(P.Muted,()=>{this.emit(I.TrackMuted,e)}),e.on(P.Unmuted,()=>{this.emit(I.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case C.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case C.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Dh(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Mr({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class Ah extends Da{constructor(e,t,i,s,r,a){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=se.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ee)},this.handleReconnected=()=>{var o,c;(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||c===void 0||c.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var o,c,d,l,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||c===void 0||c.call(o,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(d=this.signalConnectedFuture).reject)===null||l===void 0||l.call(d,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var c,d;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Ee),(d=(c=this.signalConnectedFuture).resolve)===null||d===void 0||d.call(c)},this.handleSignalRequestResponse=o=>{const{requestId:c,reason:d,message:l}=o,u=this.pendingSignalRequests.get(c);u&&(d!==dn.OK&&u.reject(new Oo(l,d)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let c=o.value.value,d=null,l=null;c.value.case==="payload"?d=c.value.value:c.value.case==="error"&&(l=ie.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,d,l);break;case"rpcAck":let u=o.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>Dh(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,c)=>{if(c===void 0&&(c=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),K(o)));return}this.engine.updateMuteStatus(o.sid,c)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),K(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),K(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const c=this.audioTrackPublications.get(o.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(o,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),K(c))),this.emit(I.LocalTrackCpuConstrained,o,c)},this.handleSubscribedQualityUpdate=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!f.videoTrack)return;const _=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var v=!0,R=qe(_),T;T=yield R.next(),c=T.done,!c;v=!0){u=T.value,v=!1;const A=u;Hl(A)&&(this.log.debug("publish ".concat(A," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),K(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,A,f.options))}}catch(A){d={error:A}}finally{try{!v&&!c&&(l=R.return)&&(yield l.call(R))}finally{if(d)throw d.error}}}),this.handleLocalTrackUnpublished=o=>{const c=this.trackPublications.get(o.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=o=>p(this,void 0,void 0,function*(){if(o.source===C.Source.ScreenShare||o.source===C.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),K(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(We(o)||Ze(o))try{if(ye())try{const c=yield navigator?.permissions.query({name:o.source===C.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),K(o))),c.onchange=()=>{c.state!=="denied"&&(o.isMuted||o.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),K(o))),We(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),K(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=a}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==se.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(w.RemoteMute,(i,s)=>{const r=this.trackPublications.get(i);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(w.Connected,this.handleReconnected).on(w.SignalConnected,this.handleSignalConnected).on(w.SignalRestarted,this.handleReconnected).on(w.SignalResumed,this.handleReconnected).on(w.Restarting,this.handleReconnecting).on(w.Resuming,this.handleReconnecting).on(w.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(w.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(w.Closing,this.handleClosing).on(w.SignalRequestResponse,this.handleSignalRequestResponse).on(w.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return p(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:a}=t;return(function*(){return new ue((o,c)=>p(i,void 0,void 0,function*(){var d,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((d=s??this.metadata)!==null&&d!==void 0?d:"",(l=r??this.name)!==null&&l!==void 0?l:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:_=>{c(_),u=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(_=>{let[v,R]=_;return this.attributes[v]===R||R===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),o();return}yield le(50)}c(new Oo("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(C.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(C.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(C.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?se.GCM:se.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){return p(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const d=yield this.waitForPendingPublicationOfSource(e);return d||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield d?.unmute(),d}this.pendingPublishing.add(e);try{switch(e){case C.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case C.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case C.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Ke(e)}}catch(d){throw c?.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(I.MediaDevicesError,d,wn(e)),this.pendingPublishing.delete(e),d}for(const d of c){const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===C.Source.Microphone&&Fe(d)&&l.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),d.startPreConnectBuffer())}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),K(u))),d.push(this.publishTrack(u,s));[o]=yield Promise.all(d)}catch(d){throw c?.forEach(l=>{l.stop()}),d}finally{this.pendingPublishing.delete(e)}}else if(!o?.track&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===C.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(C.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(C.Source.Camera)||this.pendingPublishing.has(C.Source.Microphone))){this.pendingPublishing.add(C.Source.Camera),this.pendingPublishing.add(C.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(C.Source.Camera),this.pendingPublishing.delete(C.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,i;e??(e={});const s=xo(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Oi(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Fe(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=C.Source.Microphone,this.emit(I.AudioStreamAcquired)),Xe(o)&&(this.cameraError=void 0,o.source=C.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Cn("getDisplayMedia not supported");e.resolution===void 0&&!ru()&&(e.resolution=Rn.h1080fps30.resolution);const t=zl(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new Ke("no video track found");const r=new Ai(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=C.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(I.AudioStreamAcquired);const o=new Di(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=C.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return p(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var o,c,d,l;We(i)&&i.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),Rt(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let T;switch(i.source){case C.Source.Microphone:T="audioinput";break;case C.Source.Camera:T="videoinput"}T&&r.activeDeviceMap.has(T)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(T)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Di(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new Ai(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new Ke("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(T=>{T.track&&T.track===i&&(h=T)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),K(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),_="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,v=(c=f.forceStereo)!==null&&c!==void 0?c:_;v&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),K(i))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=f.dtx)!==null&&d!==void 0||(f.dtx=!1),(l=f.red)!==null&&l!==void 0||(f.red=!1)),!au()&&r.roomOptions.e2ee&&(r.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},r.logContext)),f.simulcast=!1),f.source&&(i.source=f.source);const R=new Promise((T,A)=>p(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Q.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:K(i)}));let x=!1;const b=setTimeout(()=>{x=!0,i.stop(),A(new Ao("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(b),x)return;const y=yield this.publish(i,f,v);T(y)}else try{const x=yield this.publish(i,f,v);T(x)}catch(x){A(x)}}catch(x){A(x)}}));r.pendingPublishPromises.set(i,R);try{return yield R}catch(T){throw T}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Ee),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),K(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>Yl(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),K(e))),!1)}publish(e,t,i){return p(this,void 0,void 0,function*(){var s,r,a,o,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new Ao("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>Rt(e)&&M.source===e.source)&&e.source!==C.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),K(e))),t.stopMicTrackOnMute&&Fe(e)&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&dt()&&(t.simulcast=!1),t.videoCodec==="av1"&&!iu()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!nu()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=$n),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===Kt(M.mime))||(t.videoCodec=Kt(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(P.Muted,this.onTrackMuted),e.on(P.Unmuted,this.onTrackUnmuted),e.on(P.Ended,this.handleTrackEnded),e.on(P.UpstreamPaused,this.onTrackUpstreamPaused),e.on(P.UpstreamResumed,this.onTrackUpstreamResumed),e.on(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const R=[],T=!(!((s=t.dtx)!==null&&s!==void 0)||s),A=e.getSourceTrackSettings();A.autoGainControl&&R.push(ae.TF_AUTO_GAIN_CONTROL),A.echoCancellation&&R.push(ae.TF_ECHO_CANCELLATION),A.noiseSuppression&&R.push(ae.TF_NOISE_SUPPRESSION),A.channelCount&&A.channelCount>1&&R.push(ae.TF_STEREO),T&&R.push(ae.TF_NO_DTX),We(e)&&e.hasPreConnectBuffer&&R.push(ae.TF_PRECONNECT_BUFFER);const x=new Vt({cid:e.mediaStreamTrack.id,name:t.name,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),disableDtx:T,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:R});let b;if(e.kind===C.Kind.Video){let M={width:0,height:0};try{M=yield e.waitForDimensions()}catch{const U=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:qt.h720.resolution;M={width:U.width,height:U.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{dims:M}))}x.width=M.width,x.height=M.height,Ze(e)&&(De(v)&&(e.source===C.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),K(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),x.simulcastCodecs=[new nn({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:$n}),t.backupCodec&&v!==t.backupCodec.codec&&x.encryption===se.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new nn({codec:t.backupCodec.codec,cid:""})))),b=ts(e.source===C.Source.ScreenShare,x.width,x.height,t),x.layers=ya(x.width,x.height,b,De(t.videoCodec))}else e.kind===C.Kind.Audio&&(b=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const y=()=>p(this,void 0,void 0,function*(){var M,O,U;if(!this.engine.pcManager)throw new re("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(I.LocalSenderCreated,e.sender,e),Ze(e)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=hh(e)),e.setDegradationPreference(t.degradationPreference)),b)if(dt()&&e.kind===C.Kind.Audio){let q;for(const Z of this.engine.pcManager.publisher.getTransceivers())if(Z.sender===e.sender){q=Z;break}q&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:q,codec:"opus",maxbr:!((O=b[0])===null||O===void 0)&&O.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&De(e.codec)&&(!((U=b[0])===null||U===void 0)&&U.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let S;const N=new Promise((M,O)=>p(this,void 0,void 0,function*(){var U;try{S=yield this.engine.addTrack(x),M(S)}catch(q){e.sender&&(!((U=this.engine.pcManager)===null||U===void 0)&&U.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(Z=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{error:Z}))})),O(q)}}));if(this.enabledPublishVideoCodecs.length>0)S=(yield Promise.all([N,y()]))[0];else{S=yield N;let M;if(S.codecs.forEach(O=>{M===void 0&&(M=O.mimeType)}),M&&e.kind===C.Kind.Video){const O=Kt(M);O!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{codec:O})),t.videoCodec=O,b=ts(e.source===C.Source.ScreenShare,x.width,x.height,t))}yield y()}const F=new os(e.kind,S,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(F.on(P.CpuConstrained,M=>this.onTrackCpuConstrained(M,F)),F.options=t,e.sid=S.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:S})),Ze(e)?e.startMonitor(this.engine.client):We(e)&&e.startMonitor(),this.addTrackPublication(F),this.emit(I.LocalTrackPublished,F),We(e)&&S.audioFeatures.includes(ae.TF_PRECONNECT_BUFFER)){const M=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(I.LocalTrackSubscribed,U=>{if(U.trackSid===S.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),K(e))),e.stopPreConnectBuffer()}}),M&&new Promise((q,Z)=>p(this,void 0,void 0,function*(){var ke,pt,ge,rt,cs,ds;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),K(e)));const ps=setTimeout(()=>{Z(new Error("agent not active within 10 seconds"))},1e4),mp=yield this.waitUntilActiveAgentPresent();clearTimeout(ps),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),K(e)));const Ba=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[mp.identity],attributes:{trackId:F.trackSid,sampleRate:String((cs=A.sampleRate)!==null&&cs!==void 0?cs:"48000"),channels:String((ds=A.channelCount)!==null&&ds!==void 0?ds:"1")}});try{for(var ls=!0,us=qe(M),hs;hs=yield us.next(),ke=hs.done,!ke;ls=!0){rt=hs.value,ls=!1;const ms=rt;yield Ba.write(ms)}}catch(ms){pt={error:ms}}finally{try{!ls&&!ke&&(ge=us.return)&&(yield ge.call(us))}finally{if(pt)throw pt.error}}yield Ba.close(),q()}catch(ps){Z(ps)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),K(e)))}).catch(q=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{error:q}))})}return F})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return p(this,void 0,void 0,function*(){var s;if(this.encryptionType!==se.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new Ke("track is not published");if(!Ze(e))throw new Ke("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),o=dh(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),K(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=new Vt({cid:c.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=ya(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const l=()=>p(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(d),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:h}))})}unpublishTrack(e,t){return p(this,void 0,void 0,function*(){var i,s;if(Rt(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),K(e))),yield d)}const r=this.getPublicationForTrack(e),a=r?K(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=r.track,e.off(P.Muted,this.onTrackMuted),e.off(P.Unmuted,this.onTrackUnmuted),e.off(P.Ended,this.handleTrackEnded),e.off(P.UpstreamPaused,this.onTrackUpstreamPaused),e.off(P.UpstreamResumed,this.onTrackUpstreamResumed),e.off(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<te.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Ze(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(o=!0),d.sender=void 0);e.simulcastCodecs.clear()}}catch(d){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case C.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case C.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(I.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return p(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new ue((r,a)=>p(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>p(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==C.Source.ScreenShare&&d.source!==C.Source.ScreenShareAudio&&(We(d)||Ze(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),r()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?j.RELIABLE:j.LOSSY,a=s.destinationIdentities,o=s.topic;let c=new Qi({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o});const d=new pe({kind:r,value:{case:"user",value:c}});yield i.engine.sendDataPacket(d,r)})()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){const i=new pe({kind:j.RELIABLE,value:{case:"sipDtmf",value:new fr({code:e,digit:t})}});yield this.engine.sendDataPacket(i,j.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},s=new pe({value:{case:"chatMessage",value:new li(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,j.RELIABLE),this.emit(I.ChatMessage,i),i})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new pe({value:{case:"chatMessage",value:new li(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp),editTimestamp:X.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,j.RELIABLE),this.emit(I.ChatMessage,i),i})}sendText(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:s,responseTimeout:r=15e3}=e;const a=7e3,o=a+1e3;return new ue((c,d)=>p(this,void 0,void 0,function*(){var l,u,h,f;if(Yn(s)>ha){d(ie.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||u===void 0)&&u.version&&Ue((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){d(ie.builtIn("UNSUPPORTED_SERVER"));return}const _=Math.max(r,o),v=crypto.randomUUID();yield this.publishRpcRequest(t,v,i,s,_);const R=setTimeout(()=>{this.pendingAcks.delete(v),d(ie.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(T)},a);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(R)},participantIdentity:t});const T=setTimeout(()=>{this.pendingResponses.delete(v),d(ie.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(A,x)=>{clearTimeout(T),this.pendingAcks.has(v)&&(this.log.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(R)),x?d(x):c(A??"")},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const s=this.pendingResponses.get(e);s?(s.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,s,r){return p(this,void 0,void 0,function*(){const a=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcRequest",value:new Yi({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,j.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:s}]of this.pendingResponses)i===e&&(s(null,ie.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),K(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Ee),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(We(s)||Ze(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[a]=r;return a.source===e});if(s)return s[1];yield le(20)}})}}class Oh extends He{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(P.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new gi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new vr({participantSid:"",trackSids:[this.trackSid]})]});this.emit(P.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?He.SubscriptionStatus.Unsubscribed:super.isSubscribed?He.SubscriptionStatus.Subscribed:He.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?He.PermissionStatus.Allowed:He.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Fn(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Fn(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Te.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(P.VisibilityChanged,this.handleVisibilityChange),s.off(P.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(P.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(P.VisibilityChanged,this.handleVisibilityChange),e.on(P.Ended,this.handleEnded),this.emit(P.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(P.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?P.Muted:P.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(P.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(P.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Fn(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ar({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===C.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Fo(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Xl(this.trackInfo,this.requestedMaxQuality);i&&Fo(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Te.HIGH})),e.quality=Te.HIGH)}this.emit(P.UpdateSettings,e)}}class Ni extends Da{static fromParticipantInfo(e,t,i){return new Ni(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ft.STANDARD;super(t,i||"",s,r,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(P.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(P.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(P.SubscriptionPermissionChanged,t=>{this.emit(I.TrackSubscriptionPermissionChanged,e,t)}),e.on(P.SubscriptionStatusChanged,t=>{this.emit(I.TrackSubscriptionStatusChanged,e,t)}),e.on(P.Subscribed,t=>{this.emit(I.TrackSubscribed,t,e)}),e.on(P.Unsubscribed,t=>{this.emit(I.TrackUnsubscribed,t,e)}),e.on(P.SubscriptionFailed,t=>{this.emit(I.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:C.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:C.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(I.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),K(o))),this.emit(I.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new Ph(e,t,s,r):d=new Rh(e,t,s,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(i),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&Un(d)&&Fe(d)&&d.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const c=C.kindFromProto(s.type);if(!c)return;o=new Oh(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(s),i.set(s.sid,o);const d=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);d&&o.source!==C.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:K(d),newTrack:K(o)})),this.addTrackPublication(o)}t.set(s.sid,o)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),K(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(I.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case C.Kind.Audio:this.audioTrackPublications.delete(e);break;case C.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(I.TrackUnpublished,i)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;Fe(i.track)&&Un(i.track)&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var z;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(z||(z={}));const Nh=4*1e3;class Dt extends Me.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,a;if(super(),t=this,this.state=z.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=B,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,c,d)=>p(this,void 0,void 0,function*(){var l;if(!su())throw Le()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===z.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(z.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==$o(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Et(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new G(o,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(_=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(_)}).catch(_=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:_}))}));const h=(_,v,R)=>p(this,void 0,void 0,function*(){var T,A;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,u?.();try{if(yield Pt.getInstance().getBackOffPromise(o),x.signal.aborted)throw V.cancelled("Connection attempt aborted");yield this.attemptConnection(R??o,c,d,x),this.abortController=void 0,_()}catch(b){if(this.regionUrlProvider&&b instanceof V&&b.reason!==$.Cancelled&&b.reason!==$.NotAllowed){let y=null;try{this.log.debug("Fetching next region"),y=yield this.regionUrlProvider.getNextBestRegionUrl((T=this.abortController)===null||T===void 0?void 0:T.signal)}catch(S){if(S instanceof V&&(S.status===401||S.reason===$.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(S);return}}[$.InternalError,$.ServerUnreachable,$.Timeout].includes(b.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Pt.getInstance().addFailedConnectionAttempt(o)),y&&!(!((A=this.abortController)===null||A===void 0)&&A.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(b.message,". Retrying with another region: ").concat(y),this.logContext),this.recreateEngine(),yield h(_,v,y)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Jo(b)),v(b))}else{let y=Ce.UNKNOWN_REASON;b instanceof V&&(y=Jo(b)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,y),v(b)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ee((_,v)=>{h(_,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,c,d,l,u,h)=>p(this,void 0,void 0,function*(){var f,_,v;const R=yield d.join(o,c,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},h.signal,!u.singlePeerConnection);let T=R.serverInfo;if(T||(T={version:R.serverVersion,region:R.serverRegion}),this.serverInfo=T,this.log.debug("connected to Livekit Server ".concat(Object.entries(T).map(A=>{let[x,b]=A;return"".concat(x,": ").concat(b)}).join(", ")),{room:(f=R.room)===null||f===void 0?void 0:f.name,roomSid:(_=R.room)===null||_===void 0?void 0:_.sid,identity:(v=R.participant)===null||v===void 0?void 0:v.identity}),!T.version)throw new Bl("unknown server version");return T.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),R}),this.applyJoinResponse=o=>{const c=o.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(d){this.log.error(d instanceof Error?d.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:d}))}this.handleParticipantUpdates([c,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,c,d,l)=>p(this,void 0,void 0,function*(){var u,h;this.state===z.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Qn),d),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(o,c,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const _=l.signal.aborted?V.cancelled("Signal connection aborted"):V.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(_.message="".concat(_.message,": ").concat(f.message)),f instanceof V&&(_.reason=f.reason,_.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),_}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),V.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}ye()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ye()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(z.Connected),this.emit(E.Connected),Pt.getInstance().resetFailedConnectionAttempts(o),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var o=arguments.length,c=new Array(o),d=0;d<o;d++)c[d]=arguments[d];return p(t,[...c],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,_;const v=yield l.disconnectLock.lock();try{if(l.state===z.Disconnected){l.log.debug("already disconnected",l.logContext);return}if(l.log.info("disconnect from room",Object.assign({},l.logContext)),l.state===z.Connecting||l.state===z.Reconnecting||l.isResuming){const R="Abort connection attempt due to user initiated disconnect";l.log.warn(R,l.logContext),(h=l.abortController)===null||h===void 0||h.abort(R),(_=(f=l.connectFuture)===null||f===void 0?void 0:f.reject)===null||_===void 0||_.call(f,V.cancelled("Client initiated disconnect")),l.connectFuture=void 0}l.engine&&(l.engine.client.isDisconnected||(yield l.engine.client.sendLeave()),yield l.engine.close()),l.handleDisconnect(u,Ce.CLIENT_INITIATED),l.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){const o=[],c=be();if(c&&c.os==="iOS"){const d="livekit-dummy-audio-el";let l=document.getElementById(d);if(!l){l=document.createElement("audio"),l.id=d,l.autoplay=!0,l.hidden=!0;const u=Ln();u.enabled=!0;const h=new MediaStream([u]);l.srcObject=h,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(E.Disconnected,()=>{l?.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(d=>{d.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(d=>(d.muted=!1,d.play()))]),this.handleAudioPlaybackStarted()}catch(d){throw this.handleAudioPlaybackFailed(d),d}}),this.startVideo=()=>p(this,void 0,void 0,function*(){const o=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(d=>{var l;(l=d.track)===null||l===void 0||l.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(z.Reconnecting)&&this.emit(E.Reconnecting)},this.handleSignalRestarted=o=>p(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(z.Connected),this.emit(E.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(c=>{var d;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(d=this.sidToIdentity.get(c.sid))!==null&&d!==void 0?d:"");let l=this.remoteParticipants.get(c.identity);c.state===vt.DISCONNECTED?this.handleParticipantDisconnected(c.identity,l):l=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=o=>{const c=[],d={};o.forEach(l=>{if(d[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),c.push(u))}}),d[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{d[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(E.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=o=>{const c=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||c.set(l.sid,l)}),o.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?c.set(l.sid,u):c.delete(l.sid))});const d=Array.from(c.values());d.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=d,this.emitWhenConnected(E.ActiveSpeakersChanged,d)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(c=>{const d=this.getRemoteParticipantBySid(c.participantSid);if(!d)return;const l=d.getTrackPublicationBySid(c.trackSid);if(!l||!l.track)return;const u=C.streamStateFromProto(c.state);l.track.setStreamState(u),u!==l.track.streamState&&(d.emit(I.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(E.TrackStreamStateChanged,l,l.track.streamState,d))})},this.handleSubscriptionPermissionUpdate=o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const c=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setSubscriptionError(o.err)},this.handleDataPacket=(o,c)=>{const d=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(d,o.value.value,o.kind,c);else if(o.value.case==="transcription")this.handleTranscription(d,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(d,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(d,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,d);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o,c);else if(o.value.case==="rpcRequest"){const l=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,l.id,l.method,l.payload,l.responseTimeoutMs,l.version)}},this.handleUserPacket=(o,c,d,l)=>{this.emit(E.DataReceived,c.payload,o,d,c.topic,l),o?.emit(I.DataReceived,c.payload,d,l)},this.handleSipDtmf=(o,c)=>{this.emit(E.SipDTMFReceived,c,o),o?.emit(I.SipDTMFReceived,c)},this.handleTranscription=(o,c)=>{const d=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),l=d?.trackPublications.get(c.trackId),u=pu(c,this.transcriptionReceivedTimes);l?.emit(P.TranscriptionReceived,u),d?.emit(I.TranscriptionReceived,u,l),this.emit(E.TranscriptionReceived,u,d,l)},this.handleChatMessage=(o,c)=>{const d=mu(c);this.emit(E.ChatMessage,d,o)},this.handleMetrics=(o,c)=>{this.emit(E.MetricsReceived,o,c)},this.handleDataStream=(o,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(o,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(E.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(E.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(E.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(E.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var o;((o=be())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(E.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const c=this.roomInfo;this.roomInfo=o,c&&c.metadata!==o.metadata&&this.emitWhenConnected(E.RoomMetadataChanged,o.metadata),c?.activeRecording!==o.activeRecording&&this.emitWhenConnected(E.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const d=this.getRemoteParticipantBySid(c.participantSid);d&&d.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(E.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(E.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(E.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(E.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(E.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var c;(c=o?.onPublish)===null||c===void 0||c.call(o,this)},this.onLocalTrackPublished=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h,f;(c=o.track)===null||c===void 0||c.on(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.on(P.Restarted,this.onLocalTrackRestarted),(h=(u=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(E.LocalTrackPublished,o,this.localParticipant),We(o.track)&&(yield o.track.checkForSilence())&&this.emit(E.LocalAudioSilenceDetected,o);const _=yield(f=o.track)===null||f===void 0?void 0:f.getDeviceId(!1),v=wn(o.source);v&&_&&_!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,_),this.emit(E.ActiveDeviceChanged,v,_))}),this.onLocalTrackUnpublished=o=>{var c,d;(c=o.track)===null||c===void 0||c.off(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.off(P.Restarted,this.onLocalTrackRestarted),this.emit(E.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>p(this,void 0,void 0,function*(){const c=yield o.getDeviceId(!1),d=wn(o.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.log.debug("local track restarted, setting ".concat(d," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(d,c),this.emit(E.ActiveDeviceChanged,d,c))}),this.onLocalConnectionQualityChanged=o=>{this.emit(E.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,c)=>{this.emit(E.MediaDevicesError,o,c)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(E.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(E.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Gu),e),this.log=je((i=this.options.loggerName)!==null&&i!==void 0?i:we.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},da),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},la),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Hu),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new kh,this.outgoingDataStreamManager=new Eh(this.engine,this.log),this.disconnectLock=new he,this.localParticipant=new Ah("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Ye(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ye(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Ye(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),ye()){const o=new AbortController;(a=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||a===void 0||a.call(r,"devicechange",this.handleDeviceChange,{signal:o.signal}),Dt.cleanupRegistry&&Dt.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new Iu(i,t),this.e2eeManager.on(tt.ParticipantEncryptionStatusChanged,(s,r)=>{gu(r)&&(this.isE2EEEnabled=s),this.emit(E.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on(tt.EncryptionError,(s,r)=>{const a=r?this.getParticipantByIdentity(r):void 0;this.emit(E.EncryptionError,s,a)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===z.Disconnected?ue.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?ue.resolve(this.roomInfo.sid):new ue((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(w.RoomUpdate,i),e(s.sid))};this.engine.on(w.RoomUpdate,i),this.once(E.Disconnected,()=>{this.engine.off(w.RoomUpdate,i),t(new re("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new _h(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(w.ParticipantUpdate,this.handleParticipantUpdates).on(w.RoomUpdate,this.handleRoomUpdate).on(w.SpeakersChanged,this.handleSpeakersChanged).on(w.StreamStateChanged,this.handleStreamStateUpdate).on(w.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(w.SubscriptionError,this.handleSubscriptionError).on(w.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(w.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(w.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(w.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(w.DataPacketReceived,this.handleDataPacket).on(w.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(z.SignalReconnecting)&&this.emit(E.SignalReconnecting)}).on(w.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(z.Connected)&&this.emit(E.Reconnected)}).on(w.SignalResumed,()=>{this.bufferedEvents=[],(this.state===z.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(w.Restarting,this.handleRestarting).on(w.SignalRestarted,this.handleSignalRestarted).on(w.Offline,()=>{this.setAndEmitConnectionState(z.Reconnecting)&&this.emit(E.Reconnecting)}).on(w.DCBufferStatusChanged,(e,t)=>{this.emit(E.DCBufferStatusChanged,e,t)}).on(w.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:s}=i;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(I.LocalTrackSubscribed,t),this.emitWhenConnected(E.LocalTrackSubscribed,t,this.localParticipant)}).on(w.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(E.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return ce.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===z.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Et(new URL(e))&&t){this.regionUrlProvider=new G(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===z.Disconnected&&(this.regionUrl=i,yield fetch(zt(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(zt(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return p(this,void 0,void 0,function*(){let i=()=>p(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new xe({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new xe({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new xe({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new xe({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new xe({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new xe({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new xe({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>p(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new vi({reason:Ce.CLIENT_INITIATED,action:bt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new xe({scenario:{case:"subscriberBandwidth",value:ut(t)}});break;case"leave-full-reconnect":s=new xe({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,c,d,l,u,h,f;let _=!0,v=!1;const R=a?{exact:s}:s;if(i==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const T=(o=r.getActiveDevice(i))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.audioTrackPublications.values()).filter(b=>b.source===C.Source.Microphone);try{_=(yield Promise.all(A.map(b=>{var y;return(y=b.audioTrack)===null||y===void 0?void 0:y.setDeviceId(R)}))).every(b=>b===!0)}catch(b){throw r.options.audioCaptureDefaults.deviceId=T,b}const x=A.some(b=>{var y,S;return(S=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&S!==void 0?S:!1});_&&x&&(v=!0)}else if(i==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const T=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.videoTrackPublications.values()).filter(b=>b.source===C.Source.Camera);try{_=(yield Promise.all(A.map(b=>{var y;return(y=b.videoTrack)===null||y===void 0?void 0:y.setDeviceId(R)}))).every(b=>b===!0)}catch(b){throw r.options.videoCaptureDefaults.deviceId=T,b}const x=A.some(b=>{var y,S;return(S=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&S!==void 0?S:!1});_&&x&&(v=!0)}else if(i==="audiooutput"){if(v=!0,!On()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(d=yield ce.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(f=r.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});const T=(u=r.getActiveDevice(i))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(A=>A.setAudioOutput({deviceId:s})))}catch(A){throw r.options.audioOutput.deviceId=T,A}}return v&&(r.localParticipant.activeDeviceMap.set(i,s),r.emit(E.ActiveDeviceChanged,i,s)),_})()})}setupLocalParticipantEvents(){this.localParticipant.on(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(I.AttributesChanged,this.onLocalAttributesChanged).on(I.TrackMuted,this.onLocalTrackMuted).on(I.TrackUnmuted,this.onLocalTrackUnmuted).on(I.LocalTrackPublished,this.onLocalTrackPublished).on(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(I.MediaDevicesError,this.onMediaDevicesError).on(I.AudioStreamAcquired,this.startAudio).on(I.ChatMessage,this.onLocalChatMessageSent).on(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===z.Connecting||this.state===z.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,i),h()},h=()=>{this.off(E.Reconnected,u),this.off(E.Connected,u),this.off(E.Disconnected,h)};this.once(E.Reconnected,u),this.once(E.Connected,u),this.once(E.Disconnected,h);return}if(this.state===z.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const s=tu(t.id),r=s[0];let a=s[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!o.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(i);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}o=u}o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(a,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:a,trackId:o}));let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={});const l=c.addSubscribedMediaTrack(e,o,t,i,d);l?.isEncrypted&&!this.e2eeManager&&this.emit(E.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==z.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(a=>{r.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var a,o,c;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((a=r.track)===null||a===void 0||a.detach(),(o=r.track)===null||o===void 0||o.stop()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(I.AttributesChanged,this.onLocalAttributesChanged).off(I.TrackMuted,this.onLocalTrackMuted).off(I.TrackUnmuted,this.onLocalTrackUnmuted).off(I.LocalTrackPublished,this.onLocalTrackPublished).off(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(I.MediaDevicesError,this.onMediaDevicesError).off(I.AudioStreamAcquired,this.startAudio).off(I.ChatMessage,this.onLocalChatMessageSent).off(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),ye()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||s===void 0||s.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(z.Disconnected),this.emit(E.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(E.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,s,r,a){return p(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Yn(l)>ha?(c=ie.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):d=l}catch(l){l instanceof ie?c=l:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),l),c=ie.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}selectDefaultDevices(){return p(this,void 0,void 0,function*(){var e,t,i;const s=ce.getInstance().previousDevices,r=yield ce.getInstance().getDevices(void 0,!1),a=be();if(a?.name==="Chrome"&&a.os!=="iOS")for(let c of r){const d=s.find(l=>l.deviceId===c.deviceId);d&&d.label!==""&&d.kind===c.kind&&d.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(E.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const d=Gl(c),l=this.localParticipant.getTrackPublication(d);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Ht()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Ht())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return p(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Lo())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),le(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(E.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=Ni.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Ni(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(E.ParticipantConnected,i),i.on(I.TrackPublished,s=>{this.emitWhenConnected(E.TrackPublished,s,i)}).on(I.TrackSubscribed,(s,r)=>{s.kind===C.Kind.Audio?(s.on(P.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(P.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===C.Kind.Video&&(s.on(P.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(P.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(E.TrackSubscribed,s,r,i)}).on(I.TrackUnpublished,s=>{this.emit(E.TrackUnpublished,s,i)}).on(I.TrackUnsubscribed,(s,r)=>{this.emit(E.TrackUnsubscribed,s,r,i)}).on(I.TrackMuted,s=>{this.emitWhenConnected(E.TrackMuted,s,i)}).on(I.TrackUnmuted,s=>{this.emitWhenConnected(E.TrackUnmuted,s,i)}).on(I.ParticipantMetadataChanged,s=>{this.emitWhenConnected(E.ParticipantMetadataChanged,s,i)}).on(I.ParticipantNameChanged,s=>{this.emitWhenConnected(E.ParticipantNameChanged,s,i)}).on(I.AttributesChanged,s=>{this.emitWhenConnected(E.ParticipantAttributesChanged,s,i)}).on(I.ConnectionQualityChanged,s=>{this.emitWhenConnected(E.ConnectionQualityChanged,s,i)}).on(I.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(E.ParticipantPermissionsChanged,s,i)}).on(I.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionStatusChanged,s,r,i)}).on(I.TrackSubscriptionFailed,(s,r)=>{this.emit(E.TrackSubscriptionFailed,s,i,r)}).on(I.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionPermissionChanged,s,r,i)}).on(I.Active,()=>{this.emitWhenConnected(E.ParticipantActive,i),i.kind===Ft.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,s)=>(i.push(...s.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&fu(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=de.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ce.STATE_MISMATCH))):e=0},Nh)}clearConnectionReconcile(){this.connectionReconcileInterval&&de.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(E.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===z.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===z.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,i,s,r;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ci({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:X.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new at({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected),this.emit(E.Connected),this.setAndEmitConnectionState(z.Connected),a.video){const c=new os(C.Kind.Video,new _t({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Pe.AUDIO,name:"video-dummy"}),new Ai(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:zo(160*((i=o.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}if(a.audio){const c=new os(C.Kind.Audio,new _t({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Pe.AUDIO}),new Di(a.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ln(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}for(let c=0;c<o.count-1;c+=1){let d=new at({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:vt.ACTIVE,tracks:[],joinedAt:X.parse(Date.now())});const l=this.getOrCreateParticipant(d.identity,d);if(o.video){const u=zo(160*((r=o.aspectRatios[c%o.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new _t({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Pe.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}if(o.audio){const u=Ln(),h=new _t({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Pe.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}l.updateInfo(d)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==E.ActiveSpeakersChanged&&e!==E.TranscriptionReceived){const r=Aa(i).filter(a=>a!==void 0);(e===E.TrackSubscribed||e===E.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}Dt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Aa(n){return n.map(e=>{if(e)return Array.isArray(e)?Aa(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Oe;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(Oe||(Oe={}));class st extends Me.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Oe.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Dt(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return p(this,void 0,void 0,function*(){if(this.status!==Oe.IDLE)throw Error("check is running already");this.setStatus(Oe.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Oe.SKIPPED&&this.setStatus(this.isSuccess()?Oe.SUCCESS:Oe.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return p(this,void 0,void 0,function*(){return this.room.state===z.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==z.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Oe.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(E.Reconnecting,()=>{t=!0}),this.room.once(E.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield le(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class xh extends st{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){const e=new G(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,a)=>(r.duration-a.duration)*.5+(r.rtt-a.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,d="A".repeat(a),l=Date.now();for(let _=0;_<c;_++)yield r.write(d);yield r.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:s,rtt:1e4,duration:u-l};return h?.forEach(_=>{_.type==="candidate-pair"&&_.nominated&&(f.rtt=_.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const as=1e4;class Mh extends st{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(as/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(as/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return p(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,i.fillStyle="hsl(".concat(s,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>p(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h?.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,as)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class Lh extends st{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield wa();if(yield Mo(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let a=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class Uh extends st{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Ia();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(r+=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return p(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,a,o,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(a=(r=l.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const f=d.getContext("2d");f.drawImage(i,0,0);const v=f.getImageData(0,0,d.width,d.height).data;let R=!0;for(let T=0;T<v.length;T+=4)if(v[T]!==0||v[T+1]!==0||v[T+2]!==0){R=!1;break}R?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),t.getTracks().forEach(s=>s.stop()),i.remove()})}}class Fh extends st{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const a=new Promise(d=>{setTimeout(d,5e3),r=d}),o=()=>{i=!0};t.on(E.SignalReconnecting,o).on(E.Reconnecting,o).on(E.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,i){if(!s||t.state!==z.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class Vh extends st{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;Et(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new G(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new qn,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,c=!1;for(let d of r.iceServers)for(let l of d.urls)l.startsWith("turn:")?(o=!0,c=!0):l.startsWith("turns:")&&(o=!0,c=!0,a=!0),l.startsWith("stun:")&&(c=!0);c?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(d=>setTimeout(d,0)))})}}class Bh extends st{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(E.SignalConnected,()=>{var i;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,a)=>{if(r.candidate){const o=new RTCIceCandidate(r);let c="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(jh(o.address)?c+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,c+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),B.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function jh(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class qh extends st{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new qn,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(Et(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const c=yield new G(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===br.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class vp extends Me.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Oe.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Oe.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=a=>{this.updateCheck(t,a)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(qh)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Bh)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Vh)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Fh)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Lh)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Uh)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Mh);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(xh)})}}function W(n,e,t){return(e=Wh(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Kh(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Wh(n){var e=Kh(n,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class fe extends Error{constructor(e,t){var i;super(e,t),W(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}W(fe,"code","ERR_JOSE_GENERIC");class Hh extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),W(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),W(this,"claim",void 0),W(this,"reason",void 0),W(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}W(Hh,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class Gh extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),W(this,"code","ERR_JWT_EXPIRED"),W(this,"claim",void 0),W(this,"reason",void 0),W(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}W(Gh,"code","ERR_JWT_EXPIRED");class zh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}W(zh,"code","ERR_JOSE_ALG_NOT_ALLOWED");class Jh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JOSE_NOT_SUPPORTED")}}W(Jh,"code","ERR_JOSE_NOT_SUPPORTED");class $h extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),W(this,"code","ERR_JWE_DECRYPTION_FAILED")}}W($h,"code","ERR_JWE_DECRYPTION_FAILED");class Qh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JWE_INVALID")}}W(Qh,"code","ERR_JWE_INVALID");class Yh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JWS_INVALID")}}W(Yh,"code","ERR_JWS_INVALID");class Xh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JWT_INVALID")}}W(Xh,"code","ERR_JWT_INVALID");class Zh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JWK_INVALID")}}W(Zh,"code","ERR_JWK_INVALID");class ep extends fe{constructor(){super(...arguments),W(this,"code","ERR_JWKS_INVALID")}}W(ep,"code","ERR_JWKS_INVALID");class tp extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),W(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}W(tp,"code","ERR_JWKS_NO_MATCHING_KEY");class ip extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),W(this,Symbol.asyncIterator,void 0),W(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}W(ip,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class np extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),W(this,"code","ERR_JWKS_TIMEOUT")}}W(np,"code","ERR_JWKS_TIMEOUT");class sp extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),W(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}W(sp,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var Oa;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(Oa||(Oa={}));var Na;(function(n){n[n.TooShort=0]="TooShort",n[n.HeaderOverrun=1]="HeaderOverrun",n[n.MissingExtWords=2]="MissingExtWords",n[n.UnsupportedVersion=3]="UnsupportedVersion",n[n.InvalidHandle=4]="InvalidHandle",n[n.MalformedExt=5]="MalformedExt"})(Na||(Na={}));var xa;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(xa||(xa={}));var xi;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(xi||(xi={})),xi.UserTimestamp,xi.E2ee;var Ma;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(Ma||(Ma={}));class rp extends ve{constructor(){super(),this._room=null,this._rtcRoom=null,this._micTrack=null,this._cameraVideoTrack=null,this._protocolDispatch=null,this._maxAttempts=Yt,this._maxDelay=Ui*Li,this._speakingHandlers=new Map,this._trackRegistry=new Nc,this._eventAdapter=new xc(this._trackRegistry),m.info("LiveKit Service created")}setContext(e){super.setContext(e),this._maxAttempts=e.options.reconnect?.maxAttempts||Yt,this._maxDelay=(e.options.reconnect?.delay??Ui)*Li,this._eventAdapter.setContext(e)}async connect(e,t,i,s){if(this.ensureNotDisposed(),this._rtcRoom&&this._rtcRoom.state===z.Connected){m.warn("Already connected to LiveKit room");return}let r;try{await this._tearDownStaleRoom(),m.info(`Connecting to LiveKit room: ${i} at ${e}`),r=new Dt({reconnectPolicy:{nextRetryDelayInMs:a=>a.elapsedMs<this._maxDelay?Math.min(Li*Math.pow(2,a.retryCount),this._maxDelay):null}}),r.prepareConnection(e,t),this._registerRoomListeners(r),m.info("Connecting to LiveKit room..."),await r.connect(e,t,{autoSubscribe:!0,maxRetries:this._context.options.reconnect?.maxAttempts||Yt}),this._eventAdapter.setRoom(r),this._rtcRoom=r,this._room=r}catch(a){if(r){try{r.removeAllListeners()}catch{}try{await r.disconnect()}catch{}}throw this._rtcRoom=null,this._room=null,H.fromError(a,L.LIVEKIT_CONNECT_FAILED)}}_registerRoomListeners(e){e.on(E.TrackSubscribed,(t,i,s)=>{this._handleTrackSubscribed(t,i,s)}),e.on(E.TrackUnsubscribed,(t,i,s)=>{this._handleTrackUnsubscribed(t,i,s)}),e.on(E.TrackMuted,(t,i)=>{this._handleTrackMuted(t,i)}),e.on(E.TrackUnmuted,(t,i)=>{this._handleTrackUnmuted(t,i)}),e.on(E.Connected,()=>{m.info("Connected to LiveKit room"),this._context.eventBus.emit("inner:rtc:connected",void 0)}),e.on(E.Disconnected,t=>{t?m.info(`LiveKit room disconnected: ${t}`):m.info("LiveKit room disconnected"),t!==Ce.CLIENT_INITIATED&&(this._context.eventBus.emit("inner:rtc:disconnected",{reason:t?String(t):void 0}),this._context.emitError(new H(L.LIVEKIT_CONNECT_FAILED,t?`LiveKit disconnected: ${String(t)}`:"LiveKit disconnected"),L.LIVEKIT_CONNECT_FAILED)),this._micTrack?.stop(),this._micTrack=null,this._cameraVideoTrack?.stop(),this._cameraVideoTrack=null,this._clearSpeakingHandlers(),this._context.mediaAudioCaptureState.end("rtc"),this._room=null,this._rtcRoom=null}),e.on(E.DataReceived,t=>{this._onRoomDataReceived(t)})}async _tearDownStaleRoom(){if(!this._rtcRoom)return;await this.stopMicrophone(),await this.stopCamera(),this._clearSpeakingHandlers();const e=this._rtcRoom;this._rtcRoom=null,this._room=null;try{e.removeAllListeners()}catch{}try{await e.disconnect()}catch{}}_clearSpeakingHandlers(){if(!this._rtcRoom){this._speakingHandlers.clear();return}for(const[e,t]of this._speakingHandlers.entries()){const i=this._findRemoteParticipantByIdentity(e);try{i?.off(I.IsSpeakingChanged,t)}catch{}}this._speakingHandlers.clear()}_findRemoteParticipantByIdentity(e){const t=this._rtcRoom;if(t){for(const i of t.remoteParticipants.values())if(i.identity===e)return i}}_removeSpeakingListenerIfNoAudioTracks(e){const t=this._speakingHandlers.get(e);if(!t)return;const i=this._trackRegistry.getParticipantTracks(e);for(const r of i)if(this._trackRegistry.getTrack(r)?.kind==="audio")return;const s=this._findRemoteParticipantByIdentity(e);try{s?.off(I.IsSpeakingChanged,t)}catch{}this._speakingHandlers.delete(e)}async startMicrophone(){this.ensureNotDisposed();const e=this._rtcRoom;if(!e||!this.isConnected())throw new H(L.LIVEKIT_CONNECT_FAILED,"LiveKit is not connected");if(!this._context.mediaAudioCaptureState.tryBegin("rtc"))throw new H(L.SDK_INVALID_STATE_TRANSITION,"WebSocket audio capture is active");try{if(this._micTrack){m.warn("Microphone already published");return}const t=await wa(this._context.options.audio?.input??{});await e.localParticipant.publishTrack(t),this._micTrack=t,m.info("Microphone published (rtc)")}catch(t){throw this._context.mediaAudioCaptureState.end("rtc"),this._context.emitError(t,L.AUDIO_CAPTURE_START_FAILED)}}async stopMicrophone(){const e=this._rtcRoom,t=this._micTrack;if(t&&e)try{await e.localParticipant.unpublishTrack(t,!0)}catch(i){throw this._context.emitError(i,L.LIVEKIT_UNPUBLISH_MICROPHONE_FAILED)}this._micTrack?.stop(),this._micTrack=null,this._context.mediaAudioCaptureState.end("rtc"),m.info("Microphone stopped (rtc)")}isMicrophoneActive(){return!!this._micTrack}async sendTextData(e,t,i,s){this.ensureNotDisposed();const r=this._rtcRoom;if(!r||!this.isConnected())throw new H(L.LIVEKIT_CONNECT_FAILED,"LiveKit is not connected");try{const a={event:i,requestId:e,data:{...s,text:t}},o=new TextEncoder().encode(JSON.stringify(a));await r.localParticipant.publishData(o,{reliable:!0}),m.debug("Text message sent via RTC data:",e)}catch(a){throw this._context.emitError(a,L.LIVEKIT_SEND_TEXT_DATA_FAILED)}}async sendSystemEvent(e,t){this.ensureNotDisposed();const i=this._rtcRoom;if(!i||!this.isConnected())throw new H(L.LIVEKIT_CONNECT_FAILED,"LiveKit is not connected");try{const s={event:e,data:t??{}},r=new TextEncoder().encode(JSON.stringify(s));await i.localParticipant.publishData(r,{reliable:!0}),m.debug("System event :",e,"sent via RTC data")}catch(s){throw this._context.emitError(s,L.LIVEKIT_SEND_TEXT_DATA_FAILED)}}setProtocolMessageDispatcher(e){this._protocolDispatch=e}async startCamera(){this.ensureNotDisposed();const e=this._rtcRoom;if(!e||!this.isConnected())throw new H(L.LIVEKIT_CONNECT_FAILED,"LiveKit is not connected");if(this._cameraVideoTrack){m.warn("RTC camera already published");return}try{const t=await Ia({});await e.localParticipant.publishTrack(t),this._cameraVideoTrack=t,m.info("Camera published (rtc)")}catch(t){throw this._context.emitError(t,L.LIVEKIT_CONNECT_FAILED)}}async stopCamera(){const e=this._rtcRoom,t=this._cameraVideoTrack;if(t&&e)try{await e.localParticipant.unpublishTrack(t,!0)}catch(i){m.error("Error unpublishing RTC camera:",i)}this._cameraVideoTrack?.stop(),this._cameraVideoTrack=null,m.info("Camera stopped (rtc)")}attachCameraTo(e){if(this.ensureNotDisposed(),!this._cameraVideoTrack)throw new H(L.LIVEKIT_CONNECT_FAILED,"Camera track is not published");this._cameraVideoTrack.attach(e)}detachCameraFrom(e){if(this.ensureNotDisposed(),!this._cameraVideoTrack)throw new H(L.LIVEKIT_CONNECT_FAILED,"Camera track is not published");this._cameraVideoTrack.detach(e)}isRtcCameraActive(){return this._cameraVideoTrack!==null}_onRoomDataReceived(e){if(!(!this._protocolDispatch||e.length===0))try{const t=new TextDecoder().decode(e),i=JSON.parse(t);if(!i||typeof i!="object")return;m.debug("RTC data message received:",t),this._protocolDispatch(i)}catch(t){m.error("RTC data message parse error:",t),this._context.emitError(t,L.LIVEKIT_DATA_MESSAGE_PARSE_ERROR)}}_handleTrackSubscribed(e,t,i){try{if(!e.mediaStreamTrack){m.warn("Track does not have MediaStreamTrack");return}if(e.kind==="audio"){const o=i.identity;if(!this._speakingHandlers.has(o)){const c=d=>{this._context.eventBus.emit("inner:audio:speaking:changed",{participantId:o,isSpeaking:d}),m.info(`Participant ${o} is speaking: ${d}`)};i.on(I.IsSpeakingChanged,c),this._speakingHandlers.set(o,c)}}const r=t.trackSid,a=i.identity;this._eventAdapter.handleTrackSubscribed(e,r,a)}catch(s){m.error("Error handling track subscribed:",s)}}_handleTrackUnsubscribed(e,t,i){try{const s=t,r=i,a=s.trackSid,o=r.identity,c=this._trackRegistry.getTrack(a),d=c?.kind==="audio";c?.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0),this._eventAdapter.handleTrackUnsubscribed(a,o),d&&this._removeSpeakingListenerIfNoAudioTracks(o)}catch(s){m.error("Error handling track unsubscribed:",s)}}_handleTrackMuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0)}catch(i){m.error("Error handling track muted:",i)}}_handleTrackUnmuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:available",void 0)}catch(i){m.error("Error handling track unmuted:",i)}}async disconnect(){await this.stopMicrophone(),await this.stopCamera(),this._clearSpeakingHandlers();const e=this._rtcRoom;if(e)try{try{e.removeAllListeners()}catch{}await e.disconnect(),this._room=null,this._rtcRoom=null,this._context.eventBus.emit("inner:rtc:disconnected",{reason:"Disconnected from LiveKit room"}),m.info("Disconnected from LiveKit room")}catch(t){m.error("Error disconnecting from LiveKit room:",t),this._room=null,this._rtcRoom=null}else this._room=null}isConnected(){return this._room?this._room.state===z.Connected:!1}getTrackRegistry(){return this._trackRegistry}get trackRegistry(){return this._trackRegistry}getEventAdapter(){return this._eventAdapter}onDispose(){this._protocolDispatch=null,this.disconnect(),this._trackRegistry.dispose(),this._eventAdapter.dispose(),m.info("LiveKit Service disposed")}}class op extends ve{constructor(){super(),this._conversationManager=null,m.info("ProtocolMessageDispatcher created")}setConversationManager(e){this._conversationManager=e,m.debug("Conversation manager set in ProtocolMessageDispatcher")}dispatch(e){this.ensureNotDisposed();try{if(e.event){this._handleLivekitServerResponseMessage(e);return}}catch(t){m.error("Error dispatching protocol message:",t)}}_handleLivekitServerResponseMessage(e){switch(e.event){case"response.chunk":this._conversationManager?.handleAnswerChunk(e.requestId,e.data.text,!1);break;case"response.done":this._conversationManager?.handleAnswerChunk(e.requestId,"",!0);break;case"input.asr.partial":this._conversationManager?.handleAsrTextReceived(e.requestId,e.data.text,!0,e.data.final??!1);break;case"input.asr.final":this._conversationManager?.handleAsrTextReceived(e.requestId,e.data.text,!1,!0);break;case"system.prompt":this._conversationManager?.handleServerInitiatedMessage(void 0,e.data.text);break;case"session.closing":break;case"input.voice.start":this._context.eventBus.emit("inner:conversation:voice:start",{requestId:e.requestId});break;case"input.voice.finish":this._context.eventBus.emit("inner:conversation:voice:finish",{requestId:e.requestId});break;default:m.warn("Unknown event:",e.event)}}onDispose(){this._conversationManager=null,m.info("ProtocolMessageDispatcher disposed")}}const Mi=["sdk:connected","sdk:disconnected","sdk:error","media:video:available","media:video:unavailable","media:video:trackAdded","media:video:trackRemoved","media:audio:trackAdded","media:audio:trackRemoved","media:audio:captureStarted","media:audio:captureStopped","media:camera:started","media:camera:stopped","media:audio:volumeChanged","media:audio:muted","media:audio:unmuted","conversation:question:sent","conversation:answer:waiting","conversation:server:message","conversation:asr:received","conversation:asr:chunk","conversation:answer:chunk","conversation:answer:completed"],La=/^[a-z]+:[a-zA-z]+(:[a-zA-Z]+)?$/;class ap{constructor(e){this.inner=e,this.listeners=new Map,this.forwardedVideoTrackIds=new Set,this.livekitConnected=!1,this.httpConnected=!1,this.internalMap={"inner:sdk:error":{public:"sdk:error",sanitizer:t=>({message:t?.error?.message,code:t?.error?.code})},"inner:rtc:video:available":{public:"media:video:available"},"inner:rtc:video:unavailable":{public:"media:video:unavailable"},"inner:video:track:added":{public:"media:video:trackAdded"},"inner:video:track:removed":{public:"media:video:trackRemoved"},"inner:audio:track:added":{public:"media:audio:trackAdded"},"inner:audio:track:removed":{public:"media:audio:trackRemoved"},"inner:audio:input:started":{public:"media:audio:captureStarted"},"inner:audio:input:stopped":{public:"media:audio:captureStopped"},"inner:camera:started":{public:"media:camera:started"},"inner:camera:stopped":{public:"media:camera:stopped"},"inner:audio:volume:changed":{public:"media:audio:volumeChanged",sanitizer:t=>({volume:t?.volume})},"inner:audio:muted":{public:"media:audio:muted"},"inner:audio:unmuted":{public:"media:audio:unmuted"},"inner:conversation:question:sent":{public:"conversation:question:sent",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:answer:waiting":{public:"conversation:answer:waiting",sanitizer:t=>({questionId:t?.questionId})},"inner:conversation:server:message":{public:"conversation:server:message",sanitizer:t=>({questionId:t?.questionId,message:String(t?.message||""),type:String(t?.type||"")})},"inner:conversation:asr:received":{public:"conversation:asr:received",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:asr:chunk":{public:"conversation:asr:chunk",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||""),isComplete:t?.isComplete??!1})},"inner:conversation:answer:chunk":{public:"conversation:answer:chunk",sanitizer:t=>({questionId:t?.questionId,chunk:String(t?.chunk||"")})},"inner:conversation:answer:completed":{public:"conversation:answer:completed",sanitizer:t=>({questionId:t?.questionId,fullAnswer:String(t?.fullAnswer||"")})}},Object.keys(this.internalMap).forEach(t=>{this.inner.on(t,i=>this.handleInternalEvent(t,i))}),this.inner.on("inner:sdk:connected",t=>this.handleConnected(t,!0)),this.inner.on("inner:sdk:disconnected",t=>this.handleConnected(t,!1)),Mi.forEach(t=>{this.inner.on(t,i=>this.handlePublicEvent(t,i))})}publicAPI(){return{on:this.on.bind(this),off:this.off.bind(this),once:this.once.bind(this)}}on(e,t){const i=String(e);return this.assertAllowed(i),this.listeners.has(i)||this.listeners.set(i,new Set),this.listeners.get(i).add(t),()=>this.off(e,t)}once(e,t){const i=String(e);this.assertAllowed(i);const s=r=>{try{t(r)}finally{this.off(e,s)}};return this.on(e,s)}off(e,t){const i=String(e);this.assertAllowed(i);const s=this.listeners.get(i);s&&(s.delete(t),s.size===0&&this.listeners.delete(i))}handleInternalEvent(e,t){const i=this.internalMap[e];if(!i)return;const s=i.public;if(Mi.indexOf(s)===-1)return;if(s==="media:video:trackAdded"){const o=t?.trackId||t?.id;if(typeof o=="string"){if(this.forwardedVideoTrackIds.has(o))return;this.forwardedVideoTrackIds.add(o)}}const r=i.sanitizer?i.sanitizer(t):t;if(!La.test(s))return;const a=this.listeners.get(s);!a||a.size===0||a.forEach(o=>{try{o(r)}catch(c){m.error("PublicEventEmitter listener error",c)}})}handlePublicEvent(e,t){if(Mi.indexOf(e)===-1)return;const i=Object.values(this.internalMap).find(a=>a.public===e),s=i&&i.sanitizer?i.sanitizer(t):t;if(e==="media:video:trackAdded"){const a=t?.trackId||t?.id;if(typeof a=="string"){if(this.forwardedVideoTrackIds.has(a))return;this.forwardedVideoTrackIds.add(a)}}const r=this.listeners.get(e);!r||r.size===0||r.forEach(a=>{try{a(s)}catch(o){m.error("PublicEventEmitter listener error",o)}})}handleConnected(e,t){e.source==="livekit"?this.livekitConnected=t:e.source==="http"&&(this.httpConnected=t),this.maybeEmitSdkConnected(t?"connected":"disconnected")}maybeEmitSdkConnected(e){const t=e==="connected",i=t?!!this.livekitConnected:!this.livekitConnected,s=t?!!this.httpConnected:!this.httpConnected,a={livekit:i,http:s,all:i&&s},o=JSON.stringify(a);this.lastConnectedPayloadJson!==o&&(this.lastConnectedPayloadJson=o,this.inner.emit(`sdk:${e}`,a))}assertAllowed(e){if(Mi.indexOf(e)===-1)throw new Error(`Event "${e}" is not allowed for public consumers`);if(!La.test(e))throw new Error(`Event name "${e}" does not follow namespace:domain[:action] naming`)}}class cp extends Y{constructor(e,t){super(),this._requestCounter=0,this._baseURL=e||"",this._defaultHeaders=t||{},m.info(`HTTP Service created with baseURL: ${this._baseURL||"none"}`)}setAuthToken(e){this._defaultHeaders.Authorization=`Bearer ${e}`}request(e){this.ensureNotDisposed();const t=e.requestId||`req_${Date.now()}_${++this._requestCounter}`,i=this._buildURL(e.url,e.params),s=this._mergeHeaders(e.headers),r={method:e.method||"GET",headers:s};e.data!==void 0&&(e.method||"GET")!=="GET"&&(typeof e.data=="string"?r.body=e.data:(r.body=JSON.stringify(e.data),!s["Content-Type"]&&!s["content-type"]&&(s["Content-Type"]="application/json")));const a=e.timeout||3e4,o=new AbortController;return r.signal=o.signal,new Promise((c,d)=>{const l=setTimeout(()=>o.abort(),a);fetch(i,r).then(async u=>{clearTimeout(l);const h={};u.headers.forEach((R,T)=>{h[T]=R});let f;const _=u.headers.get("content-type");_&&_.includes("application/json")?f=await u.json():f=await u.text();const v={requestId:t,status:u.status,headers:h,data:f,config:e};m.debug(`HTTP request succeeded: ${e.method} ${i} [${t}]`),c(v)}).catch(u=>{clearTimeout(l);const h=u&&u.name==="AbortError",f={requestId:t,status:u&&u.status||void 0,message:h?"Request aborted (timeout)":u&&u.message||"HTTP request failed",error:u,config:e};m.error(`HTTP request failed: ${e.method} ${i} [${t}]`,u),d(f)})})}get(e,t,i){return this.request({...i,url:e,method:"GET",params:t})}post(e,t,i){return this.request({...i,url:e,method:"POST",data:t})}put(e,t,i){return this.request({...i,url:e,method:"PUT",data:t})}delete(e,t){return this.request({...t,url:e,method:"DELETE"})}patch(e,t,i){return this.request({...i,url:e,method:"PATCH",data:t})}_buildURL(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return this._appendParams(e,t);let i=this._baseURL;return i&&!i.endsWith("/")&&!e.startsWith("/")?i+="/":i&&i.endsWith("/")&&e.startsWith("/")&&(i=i.slice(0,-1)),i+=e,this._appendParams(i,t)}_appendParams(e,t){if(!t||Object.keys(t).length===0)return e;const i=new URLSearchParams;for(const[r,a]of Object.entries(t))i.append(r,String(a));const s=e.includes("?")?"&":"?";return`${e}${s}${i.toString()}`}_mergeHeaders(e){const t={...this._defaultHeaders};return e&&Object.assign(t,e),t}onDispose(){m.info("HTTP Service disposed")}}function dp(n,e="https"){return n.includes("://")?n:`${e.replace(/:$/,"")}://${n}`}class lp extends ve{constructor(e,t){super(),this._httpService=new cp(e||za,t)}getAuthToken(){if(this.ensureNotDisposed(),this._context.authToken)return this._httpService?.setAuthToken(this._context.authToken),Promise.resolve();throw this._context.emitError("Auth token not found",L.SDK_AUTH_TOKEN_FAILED)}async fetchConnectionConfig(){this.ensureNotDisposed();const e=await this._httpService.request({url:"/v1/session/start",method:"POST",data:{avatarId:this._context.options.connectConfig.type==="auth"?this._context.options.connectConfig.config.avatarId:"",voice:this._context.options.connectConfig.type==="auth"&&this._context.options.connectConfig.config.avatarVoice||""},headers:this._context.options.sandbox?{"X-Env-Sandbox":"true"}:void 0}).catch(t=>{throw this._context.emitError(t,L.SDK_GET_LIVEKIT_CONFIG_FAILED)});if(e.data.code!==Ga||!e.data.data)throw this._context.emitError(new H(L.SDK_GET_LIVEKIT_CONFIG_FAILED,e.data.msg||"LiveKit config response invalid"),L.SDK_GET_LIVEKIT_CONFIG_FAILED);return{roomId:"",roomToken:e.data.data.userToken,livekitUrl:dp(e.data.data.sfuUrl,"wss")}}onDispose(){this._httpService.dispose()}}class Ua extends ve{constructor(e,t){super(),this._connectStartAt=null,this._hasReportedFirstFrame=!1,this._videoElement=null,this._videoFirstFrameHandler=null,this._pendingTextResponse=new Map,this._pendingTextAudioQueue=[],this._pendingTextAudioStartAt=new Map,this._pendingNoSpeechStartAt=null,this._eventUnsubscribers=[],this._reporter=e??null,this._now=t??(()=>Date.now())}setReporter(e){this._reporter=e??null}startConnectMeasurement(){this._connectStartAt=this._now(),this._hasReportedFirstFrame=!1}bindVideoElement(e){this._unbindVideoElement(),this._videoElement=e,this._videoFirstFrameHandler=this._handleVideoFirstFrame.bind(this),this._videoElement.addEventListener("loadeddata",this._videoFirstFrameHandler,{once:!1})}setContext(e){super.setContext(e),this._bindEventBus()}_bindEventBus(){this._clearEventListeners(),this._subscribeConversationMetrics(),this._subscribeAudioMetrics()}_subscribeConversationMetrics(){this._eventUnsubscribers.push(this._context.eventBus.on("inner:conversation:question:sent",({questionId:e})=>{const t=this._now();this._pendingTextResponse.set(e,t),this._pendingTextAudioQueue.push(e),this._pendingTextAudioStartAt.set(e,t)})),this._eventUnsubscribers.push(this._context.eventBus.on("inner:conversation:answer:chunk",({questionId:e})=>{this._tryCompleteTextResponse(e)})),this._eventUnsubscribers.push(this._context.eventBus.on("inner:conversation:answer:completed",({questionId:e})=>{this._tryCompleteTextResponse(e)})),this._eventUnsubscribers.push(this._context.eventBus.on("inner:conversation:server:message",({questionId:e})=>{this._tryCompleteTextResponse(e)}))}_subscribeAudioMetrics(){this._eventUnsubscribers.push(this._context.eventBus.on("inner:audio:speaking:changed",({isSpeaking:e})=>{e&&(this._tryCompleteTextToAudio(),this._tryCompleteNoSpeechToAudio())})),this._eventUnsubscribers.push(this._context.eventBus.on("inner:audio:no_speech:reported",({timestamp:e})=>{this._pendingNoSpeechStartAt===null&&(this._pendingNoSpeechStartAt=e)}))}_handleVideoFirstFrame(){this._hasReportedFirstFrame||this._connectStartAt===null||(this._hasReportedFirstFrame=!0,this._report({metric:"connect_to_first_frame_ms",durationMs:this._now()-this._connectStartAt,startedAt:this._connectStartAt,endedAt:this._now()}))}_tryCompleteTextResponse(e){const t=this._pendingTextResponse.get(e);if(t===void 0)return;this._pendingTextResponse.delete(e);const i=this._now();this._report({metric:"text_send_to_text_response_ms",durationMs:i-t,startedAt:t,endedAt:i,questionId:e})}_tryCompleteTextToAudio(){let e;for(;this._pendingTextAudioQueue.length>0;){const s=this._pendingTextAudioQueue.shift();if(s&&this._pendingTextAudioStartAt.has(s)){e=s;break}}if(!e)return;const t=this._pendingTextAudioStartAt.get(e);if(t===void 0)return;this._pendingTextAudioStartAt.delete(e);const i=this._now();this._report({metric:"text_send_to_audio_response_ms",durationMs:i-t,startedAt:t,endedAt:i,questionId:e})}_tryCompleteNoSpeechToAudio(){if(this._pendingNoSpeechStartAt===null)return;const e=this._pendingNoSpeechStartAt;this._pendingNoSpeechStartAt=null;const t=this._now();this._report({metric:"no_speech_report_to_audio_response_ms",durationMs:t-e,startedAt:e,endedAt:t})}_report(e){const t=this._reporter??this._defaultReporter;try{t(e)}catch(i){m.error("Performance metric reporter failed",i)}}_defaultReporter(e){m.info("[performance-metric]",e)}_unbindVideoElement(){this._videoElement&&this._videoFirstFrameHandler&&this._videoElement.removeEventListener("loadeddata",this._videoFirstFrameHandler),this._videoElement=null,this._videoFirstFrameHandler=null}_clearEventListeners(){this._eventUnsubscribers.forEach(e=>{try{e()}catch(t){m.error("Performance monitor unsubscribe failed",t)}}),this._eventUnsubscribers=[]}onDispose(){this._unbindVideoElement(),this._clearEventListeners(),this._pendingTextResponse.clear(),this._pendingTextAudioQueue.length=0,this._pendingTextAudioStartAt.clear(),this._pendingNoSpeechStartAt=null,this._reporter=null}}class ht extends ve{constructor(e,t=$a){super(),this._cachedConfig=null,this._cachedAt=null,this._inflightPromise=null,this._nextDirectConfig=null,this._httpController=e,this._ttlMs=t}async preConnect(){this.ensureNotDisposed();const e=this.getValidConfig();return e||(this._inflightPromise?this._inflightPromise:(this._inflightPromise=this._fetchConfig().finally(()=>{this._inflightPromise=null}),this._inflightPromise))}getValidConfig(){return this.ensureNotDisposed(),!this._cachedConfig||this._cachedAt===null||Date.now()-this._cachedAt>=this._ttlMs?null:this._cachedConfig}async refreshConfig(){return this.ensureNotDisposed(),this._cachedConfig=null,this._cachedAt=null,this._inflightPromise?this._inflightPromise:(this._inflightPromise=this._fetchConfig().finally(()=>{this._inflightPromise=null}),this._inflightPromise)}replaceDirectConfig(e){this.ensureNotDisposed();const t=this._validateDirectConfig(e);this._nextDirectConfig=t,this._cachedConfig=null,this._cachedAt=null}async _fetchConfig(){const e=this._context.options.connectConfig;if(e.type==="direct"){const t=this._nextDirectConfig??this._validateDirectConfig(e.config),i={livekitUrl:t.sfuUrl,token:t.clientToken};return this._cache(i),this._nextDirectConfig=null,i}return this._fetchAuthConfigWithRetry(e.config.authToken||"")}_fromAuthPayload(e){if(!e.livekitUrl||!e.roomToken)throw this._context.emitError("Invalid connection config payload",L.SDK_GET_LIVEKIT_CONFIG_FAILED);return{livekitUrl:e.livekitUrl,token:e.roomToken,roomId:e.roomId,videoOptions:{renderMode:e.greenScreen?.enabled?"processed":"raw",greenScreen:{enabled:!!e.greenScreen?.enabled,...e.greenScreen}}}}_cache(e){this._cachedConfig=e,this._cachedAt=Date.now()}async _fetchAuthConfigWithRetry(e){let t=null;for(let i=1;i<=ht.AUTH_RETRY_MAX_ATTEMPTS;i++)try{const s=this._context.authToken||e;this._context.setAuthToken(s),await this._httpController.getAuthToken();const r=await this._httpController.fetchConnectionConfig(),a=this._fromAuthPayload(r);return this._cache(a),a}catch(s){if(t=s,i>=ht.AUTH_RETRY_MAX_ATTEMPTS)break;await this._delay(ht.AUTH_RETRY_BASE_DELAY_MS*i)}throw this._context.emitError(t||"Failed to fetch auth connection config",L.SDK_GET_LIVEKIT_CONFIG_FAILED)}_delay(e){return new Promise(t=>setTimeout(t,e))}_validateDirectConfig(e){const t=(e.sfuUrl||"").trim(),i=(e.clientToken||"").trim();if(!t||!i)throw this._context.emitError("Invalid direct connection config",L.SDK_PRECONNECT_FAILED);return{sfuUrl:t,clientToken:i}}onDispose(){this._cachedConfig=null,this._cachedAt=null,this._inflightPromise=null,this._nextDirectConfig=null}}ht.AUTH_RETRY_MAX_ATTEMPTS=2,ht.AUTH_RETRY_BASE_DELAY_MS=300;class Fa extends Y{constructor(e){super(),this._videoController=null,this._audioController=null,this._conversationController=null,this._cameraController=null,this._liveKitService=null,this._connectionCoordinator=null,this._httpController=null,this._configManager=null,this._performanceMonitor=null,this._pendingDirectConfig=null,this._isReconnectInProgress=!1,this._reconnectPromise=null,this._liveKitProtocolDispatcher=null,this._context=new Ya(e),m.info("SDK Client created")}get events(){return this.ensureNotDisposed(),this._publicEventAPI||(this._publicEmitter=new ap(this._context.eventBus),this._publicEventAPI=this._publicEmitter.publicAPI()),this._publicEventAPI}sendTextQuestion(e){if(this.ensureNotDisposed(),this._ensureConnected(),this._conversationController)return this._conversationController.sendQuestion(e);throw new H(L.CONVERSATION_CONTROLLER_NOT_AVAILABLE,"Conversation controller is not available")}async interrupt(){if(this.ensureNotDisposed(),this._ensureConnected(),this._conversationController)return this._conversationController.interrupt();throw new H(L.CONVERSATION_CONTROLLER_NOT_AVAILABLE,"Conversation controller is not available")}setPerformanceMetricReporter(e){if(this.ensureNotDisposed(),!this._performanceMonitor){this._performanceMonitor=new Ua(e),this._performanceMonitor.setContext(this._context);return}this._performanceMonitor.setReporter(e)}setRenderFitMode(e){this.ensureNotDisposed(),this._ensureConnected(),this._videoController&&this._videoController.setRenderFitMode(e)}async startAudioCapture(){this.ensureNotDisposed(),this._ensureConnected(),await this._startAudioCaptureRtc()}async stopAudioCapture(){this.ensureNotDisposed(),this._ensureConnected(),await this._stopAudioCaptureRtc()}setVolume(e){this.ensureNotDisposed(),this._ensureConnected(),this._requireAudioController().setVolume(e)}getVolume(){return this.ensureNotDisposed(),this._ensureConnected(),this._requireAudioController().getVolume()||1}mute(){this.ensureNotDisposed(),this._ensureConnected(),this._requireAudioController().mute()}unmute(){this.ensureNotDisposed(),this._ensureConnected(),this._requireAudioController().unmute()}get isMuted(){return this.ensureNotDisposed(),this._ensureConnected(),this._requireAudioController().isMuted()}get isAudioCapturing(){return this.ensureNotDisposed(),this._ensureConnected(),this._liveKitService?.isMicrophoneActive()??!1}setAuthToken(e){this.ensureNotDisposed(),this._context.setAuthToken(e),this._httpController&&this._httpController.getAuthToken()}updateConnectionConfig(e){if(this.ensureNotDisposed(),this._context.options.connectConfig.type!=="direct")throw this._context.emitError(new H(L.SDK_INVALID_STATE_TRANSITION,"updateConnectionConfig is only available in direct mode"),L.SDK_INVALID_STATE_TRANSITION);this._pendingDirectConfig=this._validateDirectConnectionConfig(e)}async startCamera(){this.ensureNotDisposed(),this._ensureConnected(),await this._requireLiveKitService().startCamera()}stopCamera(){this.ensureNotDisposed(),this._ensureConnected(),this._liveKitService?.stopCamera()}getCameraStream(){return this.ensureNotDisposed(),this._ensureConnected(),this._cameraController?.getStream()??null}getCameraTrack(){return this.ensureNotDisposed(),this._ensureConnected(),this._cameraController?.getTrack()??null}attachCameraTo(e){this.ensureNotDisposed(),this._ensureConnected(),this._requireLiveKitService().attachCameraTo(e)}async preConnect(){this.ensureNotDisposed();try{this._ensureConfigManagerReady();const e=await this._configManager.preConnect();return this._applyConnectionConfig(e),!0}catch(e){throw this._context.emitError(e,L.SDK_PRECONNECT_FAILED)}}async connect(){if(this.ensureNotDisposed(),this._ensurePerformanceMonitorReady(),this._performanceMonitor?.startConnectMeasurement(),this._connectionCoordinator&&this._context.sessionState.isConnected){m.warn("SDK already initialized");return}try{this._ensureConfigManagerReady();const e=this._configManager.getValidConfig();if(e)this._applyConnectionConfig(e);else if(!await this.preConnect())throw new H(L.SDK_CONNECT_FAILED,"PreConnect failed without explicit error")}catch(e){throw this._context.emitError(e,L.SDK_CONNECT_FAILED)}try{await this._disposeConnectionRuntimeBeforeConnect(),m.info("Initializing SDK..."),this._connectionCoordinator=new Za,this._connectionCoordinator.setContext(this._context),this._context.bindConnectionState(()=>this._connectionCoordinator.getState()),this._connectionCoordinator.start(),this._connectionCoordinator.startConnecting(),this._bootstrapDomainControllers(),this._bootstrapLiveKitService(),this._wireLiveKitEventAdapterToControllers(),this._setupRtcProtocolDispatcher(),await this._establishMediaAndSessionTransports(),m.info("SDK initialized and connected")}catch(e){throw this._connectionCoordinator&&this._connectionCoordinator.transitionToIdle(),await this._cleanup(),this._context.emitError(e,L.SDK_INITIALIZATION_FAILED)}}async disconnect(){if(this.ensureNotDisposed(),!(!this._connectionCoordinator||this._connectionCoordinator.getState()==="idle"||this._connectionCoordinator.getState()==="disposed")){m.info("Disconnecting SDK..."),this._connectionCoordinator.startDisconnecting();try{this._audioController&&this._audioController.stopWsCapture(),this._liveKitService&&(await this._liveKitService.sendSystemEvent("session.stop"),await this._liveKitService.disconnect()),this._cameraController&&this._cameraController.stopCamera(),this._connectionCoordinator.completeDisconnecting(),m.info("SDK disconnected")}catch(e){throw m.error("Error during disconnect:",e),this._context.emitError(e,L.SDK_DISCONNECT_FAILED)}}}async reconnect(){if(this.ensureNotDisposed(),this._reconnectPromise)return this._reconnectPromise;const e=this._connectionCoordinator;if(!e?.canStartReconnectingManual()){const i=e?e.getSnapshot():this.connectionSnapshot;return m.warn("SDK reconnect not allowed in current state, returning current snapshot"),i}const t=e.captureSnapshotAndStartReconnectingManual();return this._reconnectPromise=(async()=>{this._isReconnectInProgress=!0;try{return await this.disconnect(),this._stageDirectConfigForNextReconnect(),await this._refreshConnectionConfigForReconnect(),await this.connect(),t}catch(i){throw m.error("Error during reconnect:",i),this._context.emitError(i,L.SDK_RECONNECT_FAILED)}finally{this._isReconnectInProgress=!1,this._reconnectPromise=null}})(),this._reconnectPromise}get connectionSnapshot(){return this.ensureNotDisposed(),this._connectionCoordinator?this._connectionCoordinator.getSnapshot():bs(_s("idle"))}async _cleanup(){if(this._conversationController?.setRtcTextSender(null),this._liveKitService?.setProtocolMessageDispatcher(null),this._liveKitProtocolDispatcher&&(this._liveKitProtocolDispatcher.dispose(),this._liveKitProtocolDispatcher=null),this._audioController&&this._audioController.stopWsCapture(),this._liveKitService)try{await this._liveKitService.disconnect()}catch(e){m.error("Error disconnecting LiveKit:",e)}this._cameraController&&this._cameraController.stopCamera()}async _disposeConnectionRuntimeBeforeConnect(){await this._cleanup(),this._conversationController?.setRtcTextSender(null),this._liveKitService?.setProtocolMessageDispatcher(null),this._liveKitProtocolDispatcher&&(this._liveKitProtocolDispatcher.dispose(),this._liveKitProtocolDispatcher=null),this._videoController?.dispose(),this._videoController=null,this._audioController?.dispose(),this._audioController=null,this._cameraController?.dispose(),this._cameraController=null,this._conversationController?.dispose(),this._conversationController=null,this._liveKitService?.dispose(),this._liveKitService=null,this._connectionCoordinator?.dispose(),this._connectionCoordinator=null}_bootstrapDomainControllers(){this._videoController=new rc(this._context.options.video),this._videoController.setContext(this._context),this._performanceMonitor?.bindVideoElement(this._videoController.getSource().getInternalElement()),this._audioController=new mc(this._context.options.audio),this._audioController.setContext(this._context),this._cameraController=new Pc,this._cameraController.setContext(this._context),this._conversationController=new Oc,this._conversationController.setContext(this._context)}_bootstrapLiveKitService(){this._liveKitService=new rp,this._liveKitService.setContext(this._context)}_wireLiveKitEventAdapterToControllers(){if(this._liveKitService&&this._videoController&&this._audioController){const e=this._liveKitService.getEventAdapter();e&&(typeof e.setVideoController=="function"&&e.setVideoController(this._videoController),typeof e.setAudioController=="function"&&e.setAudioController(this._audioController))}}_setupRtcProtocolDispatcher(){this._liveKitProtocolDispatcher&&(this._liveKitProtocolDispatcher.dispose(),this._liveKitProtocolDispatcher=null),this._liveKitProtocolDispatcher=new op,this._liveKitProtocolDispatcher.setContext(this._context),this._liveKitProtocolDispatcher.setConversationManager(this._conversationController.manager),this._liveKitService.setProtocolMessageDispatcher(e=>{this._liveKitProtocolDispatcher.dispatch(e)}),this._conversationController.setRtcTextSender(this._liveKitService)}async _establishMediaAndSessionTransports(){await this._liveKitService.connect(this._context.livekitUrl,this._context.token,this._context.options.connectConfig.type==="auth"?this._context.options.connectConfig.config.avatarId:"")}async _refreshConnectionConfigForReconnect(){this._ensureConfigManagerReady();const e=await this._configManager.refreshConfig();this._applyConnectionConfig(e)}_ensureConfigManagerReady(){m.info("Creating HTTP controller..."),this._httpController=this._httpController??new lp(this._context.options.http?.baseURL,this._context.options.http?.headers),this._httpController.setContext(this._context),this._configManager=this._configManager??new ht(this._httpController),this._configManager.setContext(this._context)}_applyConnectionConfig(e){this._context.setLivekitConfig(e.livekitUrl,e.token,e.roomId||""),e.videoOptions&&this._context.setVideoOptions(e.videoOptions),this._context.options.connectConfig.type==="auth"&&this._context.eventBus.emit("inner:sdk:connected",{source:"http"})}_stageDirectConfigForNextReconnect(){this._context.options.connectConfig.type==="direct"&&this._pendingDirectConfig&&(this._ensureConfigManagerReady(),this._configManager.replaceDirectConfig(this._pendingDirectConfig),this._pendingDirectConfig=null)}_validateDirectConnectionConfig(e){const t=(e?.sfuUrl||"").trim(),i=(e?.clientToken||"").trim();if(!t||!i)throw this._context.emitError(new H(L.SDK_PRECONNECT_FAILED,"Invalid direct connection config"),L.SDK_PRECONNECT_FAILED);return{sfuUrl:t,clientToken:i}}_ensurePerformanceMonitorReady(){const e=this._context.options.performanceMonitor;if(!(e?.enabled!==!1)){this._performanceMonitor?.dispose(),this._performanceMonitor=null;return}if(this._performanceMonitor){this._performanceMonitor.setReporter(e?.reporter);return}this._performanceMonitor=new Ua(e?.reporter),this._performanceMonitor.setContext(this._context)}get isConnected(){return this.ensureNotDisposed(),this._context.sessionState.isConnected}_ensureConnected(){if(!this._context.sessionState.isConnected)throw new H(L.SDK_NOT_CONNECTED,"SDK is not connected. Call connect() first.")}async _startAudioCaptureRtc(){await this._requireLiveKitService().startMicrophone()}async _stopAudioCaptureRtc(){await this._requireLiveKitService().stopMicrophone()}_requireAudioController(){if(!this._audioController)throw new H(L.AUDIO_CONTROLLER_NOT_AVAILABLE,"Audio controller is not available");return this._audioController}_requireLiveKitService(){if(!this._liveKitService)throw new H(L.LIVEKIT_CONNECT_FAILED,"LiveKit service is not available");return this._liveKitService}onDispose(){this.disconnect().catch(e=>{m.error("Error during disconnect in dispose:",e)}),this._videoController&&(this._videoController.dispose(),this._videoController=null),this._audioController&&(this._audioController.dispose(),this._audioController=null),this._cameraController&&(this._cameraController.dispose(),this._cameraController=null),this._conversationController?.setRtcTextSender(null),this._liveKitService?.setProtocolMessageDispatcher(null),this._liveKitProtocolDispatcher&&(this._liveKitProtocolDispatcher.dispose(),this._liveKitProtocolDispatcher=null),this._conversationController&&(this._conversationController.dispose(),this._conversationController=null),this._liveKitService&&(this._liveKitService.dispose(),this._liveKitService=null),this._httpController&&(this._httpController.dispose(),this._httpController=null),this._configManager&&(this._configManager.dispose(),this._configManager=null),this._performanceMonitor&&(this._performanceMonitor.dispose(),this._performanceMonitor=null),this._connectionCoordinator&&(this._connectionCoordinator.transitionToDisposed(),this._connectionCoordinator.dispose(),this._connectionCoordinator=null),this._context.dispose(),m.info("SDK Client disposed")}}function up(n){const e=n.connectConfig;if(e.type==="direct"&&(!e.config.sfuUrl||!e.config.clientToken))throw new H(L.INVALID_CONNECT_CONFIG,"Invalid direct connect config");if(e.type==="auth"&&!e.config.avatarId)throw new H(L.NO_AVATARID,"avatarId is required");return new Fa(n)}class Va extends Y{constructor(e,t){super(),this._videoElement=null,this._videoUrl=null,this._isPlaying=!1,this._frameCallbackId=null,this._videoUrl=e,t?this._videoElement=t:(this._videoElement=document.createElement("video"),this._videoElement.style.opacity="0",this._videoElement.muted=!0,this._videoElement.playsInline=!0,this._videoElement.loop=!0,document.querySelector("#video-container")?.appendChild(this._videoElement)),m.info("Local Video Debug Source created")}get videoElement(){return this._videoElement}async load(){if(!this._videoElement)throw new Error("Video element or URL not set");return new Promise((e,t)=>{const i=this._videoElement,s=()=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),m.info(`Video loaded: ${i.videoWidth}x${i.videoHeight}`),e()},r=a=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),t(new Error(`Failed to load video: ${a}`))};i.addEventListener("loadedmetadata",s),i.addEventListener("error",r),i.src=this._videoUrl||"",i.load()})}async play(){if(!this._videoElement)throw new Error("Video element not set");if(!this._isPlaying)try{await this._videoElement.play(),this._videoElement.style.opacity="0",this._videoElement.setAttribute("loop","true"),this._isPlaying=!0,m.info("Video playback started")}catch(e){throw m.error("Failed to play video:",e),e}}pause(){this._videoElement&&this._isPlaying&&(this._videoElement.pause(),this._isPlaying=!1,m.info("Video playback paused"))}stop(){this._videoElement&&(this._videoElement.pause(),this._videoElement.currentTime=0,this._isPlaying=!1,m.info("Video playback stopped"))}get isPlaying(){return this._isPlaying&&this._videoElement!==null&&!this._videoElement.paused}get videoWidth(){return this._videoElement?.videoWidth||0}get videoHeight(){return this._videoElement?.videoHeight||0}async captureFrame(){if(!this._videoElement||this._videoElement.readyState<2)return null;try{if("VideoFrame"in window&&typeof window.VideoFrame=="function")try{return new VideoFrame(this._videoElement,{timestamp:this._videoElement.currentTime*1e6})}catch(i){m.error("",i)}const e=await createImageBitmap(this._videoElement),t=new VideoFrame(e,{timestamp:this._videoElement.currentTime*1e6});return e.close(),t}catch(e){return m.error("Failed to capture video frame:",e),null}}onFrame(e){if(!this._videoElement)return;this.offFrame();const t=this._videoElement;if("requestVideoFrameCallback"in t){const i=(s,r)=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(a=>{a&&(e(a),a.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=t.requestVideoFrameCallback(i))}).catch(a=>{m.error("Error in frame callback:",a)})};this._frameCallbackId=t.requestVideoFrameCallback(i)}else{const i=()=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(s=>{s&&(e(s),s.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=requestAnimationFrame(i))}).catch(s=>{m.error("Error in frame callback:",s)})};this._frameCallbackId=requestAnimationFrame(i)}}offFrame(){this._frameCallbackId!==null&&(this._videoElement&&"cancelVideoFrameCallback"in this._videoElement?this._videoElement.cancelVideoFrameCallback(this._frameCallbackId):cancelAnimationFrame(this._frameCallbackId),this._frameCallbackId=null)}onDispose(){this.stop(),this.offFrame(),this._videoElement&&this._videoElement.parentElement===document.body&&document.body.removeChild(this._videoElement),this._videoElement=null,this._videoUrl=null,m.info("Local Video Debug Source disposed")}}class hp extends Y{constructor(e,t,i){super(),this._outputCanvas=null,this._outputRenderer=null,this._source=new Ts;const s={...e,renderMode:"processed"};this._pipeline=new Ss(this._source,s),this._outputRenderer=new Vi(i,t),this._pipeline.setRenderer(this._outputRenderer),this._outputCanvas=this._outputRenderer.getCanvas(),m.info("Video Pipeline Runner created")}get outputCanvas(){return this._outputCanvas}get processor(){return this._pipeline.strategy.getProcessors()[0]||null}setProcessor(e){this._pipeline.setProcessor(e),m.info("Processor set on pipeline")}async processFrame(e){if(this.ensureNotDisposed(),!this._outputRenderer){m.error("Output renderer not available"),e.close();return}try{const t=this._pipeline.strategy.getProcessors()[0]||null;let i=null;if(t){try{i=t.process(e)}catch(s){m.error("Error processing frame:",s),i=e}if(i===null&&"getImageData"in t){const s=t.getImageData();if(s&&this._outputCanvas&&this._outputRenderer.getContext()){const r=this._outputRenderer.getContext();r&&((this._outputCanvas.width!==s.width||this._outputCanvas.height!==s.height)&&(this._outputCanvas.width=s.width,this._outputCanvas.height=s.height),r.putImageData(s,0,0))}e.close();return}i&&i!==e?(this._outputRenderer.render(i),e.close()):i===e?this._outputRenderer.render(e):e.close()}else this._outputRenderer.render(e)}catch(t){m.error("Error in processFrame:",t),e.close()}}setOutputSize(e,t){this._outputCanvas&&(this._outputCanvas.width=e,this._outputCanvas.height=t,m.info(`Output canvas size set to ${e}x${t}`))}onDispose(){this._pipeline.dispose(),this._outputRenderer&&(this._outputRenderer.dispose(),this._outputRenderer=null),this._outputCanvas&&this._outputCanvas.parentElement===document.body&&document.body.removeChild(this._outputCanvas),this._outputCanvas=null,m.info("Video Pipeline Runner disposed")}}class pp extends Y{constructor(e,t,i,s){if(super(),this._isRunning=!1,this._videoSource=new Va(e,t),this._options={renderMode:"processed",containerElement:t,...s},this._pipelineRunner=new hp(this._options,t,i),this._options.greenScreen?.enabled){const r=new Bi(this._options.greenScreen);this._pipelineRunner.setProcessor(r),m.info("Green screen processor enabled in debugger")}m.info("Standalone Video Debugger created")}async switchSource(e,t){this.ensureNotDisposed();const i=this._videoSource,s=this._isRunning,r=new Va(e,t);try{await r.load(),s&&await r.play(),r.onFrame(c=>{this._pipelineRunner.processFrame(c).catch(d=>{m.error("Error processing frame:",d)})}),this._videoSource=r;try{i.offFrame(),i.stop(),i.dispose()}catch(c){m.warn("Error disposing old video source during switch:",c)}const a=this._videoSource.videoWidth,o=this._videoSource.videoHeight;a>0&&o>0&&this._pipelineRunner.setOutputSize(a,o)}catch(a){m.error("Failed to switch video source:",a);try{r.dispose()}catch(o){m.warn("Error disposing new video source after failed switch:",o)}throw a}}get outputCanvas(){return this._pipelineRunner.outputCanvas}get videoSource(){return this._videoSource}get processor(){return this._pipelineRunner.processor}setProcessor(e){this._pipelineRunner.setProcessor(e)}updateGreenScreenOptions(e){const t=this._pipelineRunner.processor;if(t&&"updateOptions"in t&&typeof t.updateOptions=="function")t.updateOptions(e),m.info("Green screen options updated");else{const i=this._options.greenScreen||{enabled:!1},s={...i,...e,enabled:e.enabled!==void 0?e.enabled:i.enabled},r=new Bi(s);this._pipelineRunner.setProcessor(r),this._options.greenScreen=s,m.info("Green screen processor recreated with new options")}}async initialize(){this.ensureNotDisposed();try{await this._videoSource.load();const e=this._videoSource.videoWidth,t=this._videoSource.videoHeight;e>0&&t>0&&this._pipelineRunner.setOutputSize(e,t),m.info("Video debugger initialized")}catch(e){throw m.error("Failed to initialize video debugger:",e),e}}async start(){if(this.ensureNotDisposed(),this._isRunning){m.warn("Debugger is already running");return}try{this._videoSource.videoWidth===0&&await this.initialize(),await this._videoSource.play(),this._videoSource.onFrame(e=>{this._pipelineRunner.processFrame(e).catch(t=>{m.error("Error processing frame:",t)})}),this._isRunning=!0,m.info("Video debugger started")}catch(e){throw m.error("Failed to start video debugger:",e),e}}stop(){this._isRunning&&(this._videoSource.stop(),this._videoSource.offFrame(),this._isRunning=!1,m.info("Video debugger stopped"))}pause(){this._isRunning&&(this._videoSource.pause(),m.info("Video debugger paused"))}async resume(){this._isRunning&&(await this._videoSource.play(),m.info("Video debugger resumed"))}get isRunning(){return this._isRunning}onDispose(){this.stop(),this._videoSource.dispose(),this._pipelineRunner.dispose(),m.info("Standalone Video Debugger disposed")}}D.DEFAULT_AUDIO_BUFFER_SIZE=Ha,D.DEFAULT_AUDIO_CHANNELS=Wa,D.DEFAULT_AUDIO_SAMPLE_RATE=Fi,D.DEFAULT_RECONNECT_ATTEMPTS=Yt,D.DEFAULT_RECONNECT_DELAY=Ui,D.DEFAULT_WS_TIMEOUT=Ka,D.Disposable=Y,D.EventBus=fs,D.Logger=m,D.SDKClient=Fa,D.SDKError=H,D.SessionState=gs,D.StandaloneVideoDebugger=pp,D.createClient=up}));
|
|
147
|
+
`},Gn}var ra;function ju(){if(ra)return Ae;ra=1;var n=Vu(),e=Bu(),t=Hn();return Ae.grammar=t,Ae.write=e,Ae.parse=n.parse,Ae.parseParams=n.parseParams,Ae.parseFmtpConfig=n.parseFmtpConfig,Ae.parsePayloads=n.parsePayloads,Ae.parseRemoteCandidates=n.parseRemoteCandidates,Ae.parseImageAttributes=n.parseImageAttributes,Ae.parseSimulcastStreamList=n.parseSimulcastStreamList,Ae}var it=ju();function zn(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var f=Date.now()-d;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),_=this;return new Promise(function(v,R){var T=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!a){var x=n.apply(_,f);o&&o(x),l.forEach(function(b){return(0,b.resolve)(x)}),l=[]}},u()),T){var A=n.apply(_,f);return o&&o(A),v(A)}l.push({resolve:v,reject:R})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),l.forEach(function(_){return(0,_.reject)(f)}),l=[]},h}const qu=.7,Ku=20,wt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class oa extends Me.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=B,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=zn(s=>p(this,void 0,void 0,function*(){this.emit(wt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Ku),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=je((i=t.loggerName)!==null&&i!==void 0?i:we.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new he}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return p(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:a}=Wu(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=it.parse((i=e.sdp)!==null&&i!==void 0?i:"");r.media.forEach(a=>{const o=Jn(a.mid);a.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||o!=c.transceiver.mid)return!1;let d=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0)return!0;let l=!1;for(const u of a.fmtp)if(u.payload===d){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),l=!0;break}return l||c.maxbr>0&&a.fmtp.push({payload:d,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=it.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(wt.NegotiationComplete),e.sdp&&it.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(wt.RTPVideoPayloadTypes,a.rtp)})),!0})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(e?.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const a=it.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{ca(o),o.type==="audio"?aa(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(c=>{if(!o.msid||!c.cid||!o.msid.includes(c.cid))return!1;let d=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0||(De(c.codec)&&!lt()&&this.ensureVideoDDExtensionForSVC(o,a),!De(c.codec)))return!0;const l=Math.round(c.maxbr*qu);for(const u of o.fmtp)if(u.payload===d){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,it.write(a)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=it.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{ca(s),s.type==="audio"&&aa(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,it.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new re("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new re("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return p(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,s=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,i){return p(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const a={error:r,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new Tt(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Vo))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(d=>{d.value>a&&(a=d.value)}))}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Vo})}}}function aa(n,e,t){const i=Jn(n.mid);let s=0;n.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&n.rtcpFb.push({payload:s,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function Wu(n){var e;const t=[],i=[],s=it.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;const c=Jn(a.mid);a.type==="audio"&&(a.rtp.some(d=>d.codec==="opus"?(r=d.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(d=>d.payload===r&&d.type==="nack")&&i.push(c),a.fmtp.some(d=>d.payload===r?(d.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:i}}function ca(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function Jn(n){return typeof n=="number"?n.toFixed(0):n}const $n="vp8",Hu={audioPreset:Sn.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Rn.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:$n,backupCodec:!0,preConnectBuffer:!1},da={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},la={deviceId:{ideal:"default"},resolution:qt.h720.resolution},Gu={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Sl,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Qn={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var te;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(te||(te={}));class zu{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var s;this.peerConnectionTimeout=Qn.peerConnectionTimeout,this.log=B,this.updateState=()=>{var r,a;const o=this.state,c=this.requiredTransports.map(d=>d.getConnectionState());c.every(d=>d==="connected")?this.state=te.CONNECTED:c.some(d=>d==="failed")?this.state=te.FAILED:c.some(d=>d==="connecting")?this.state=te.CONNECTING:c.every(d=>d==="closed")?this.state=te.CLOSED:c.some(d=>d==="closed")?this.state=te.CLOSING:c.every(d=>d==="new")&&(this.state=te.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(te[o]," to ").concat(te[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.log=je((s=i.loggerName)!==null&&s!==void 0?s:we.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new oa(e,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new oa(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Ie.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,r)},this.subscriber.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Ie.PUBLISHER)},this.publisher.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)},this.publisher.onOffer=(r,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r,a)},this.state=te.NEW,this.connectionLock=new he,this.remoteOfferLock=new he}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return p(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){var i;t===Ie.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return p(this,void 0,void 0,function*(){var i,s,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const a=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return p(this,void 0,void 0,function*(){var i;const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new ue((t,i)=>p(this,void 0,void 0,function*(){const s=setTimeout(()=>{i(new Tt("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i(new Tt("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(wt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(wt.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),a instanceof Error?i(a):i(new Error(String(a)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return i?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Ie.PUBLISHER?this.publisher.getConnectedAddress():e===Ie.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>p(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),de.clearTimeout(u),d(V.cancelled("room connection has been cancelled"))};s?.signal.aborted&&l(),s?.signal.addEventListener("abort",l);const u=de.setTimeout(()=>{s?.signal.removeEventListener("abort",l),d(V.internal("could not establish pc connection"))},a);for(;this.state!==te.CONNECTED;)if(yield le(50),s?.signal.aborted){d(V.cancelled("room connection has been cancelled"));return}de.clearTimeout(u),s?.signal.removeEventListener("abort",l),c()}))})()})}}const ua=5e3,Ju=3e4;class G{static fetchRegionSettings(e,t,i){return p(this,void 0,void 0,function*(){const s=yield G.fetchLock.lock();try{const r=yield fetch("".concat($u(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const a=_u(r.headers),o=a?a*1e3:ua;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw r.status===401?V.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):V.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof V?r:i?.aborted?V.cancelled("Region fetching was aborted"):V.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,i){return p(this,void 0,void 0,function*(){const s=G.settingsTimeouts.get(e.hostname);clearTimeout(s),G.settingsTimeouts.set(e.hostname,setTimeout(()=>p(this,void 0,void 0,function*(){try{const r=yield G.fetchRegionSettings(e,t);G.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof V&&r.reason===$.NotAllowed){B.debug("token is not valid, cancelling auto region refresh");return}B.debug("auto refetching of region settings failed",{error:r}),G.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){G.cache.set(e.hostname,i),G.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=G.settingsTimeouts.get(e);t&&(clearTimeout(t),G.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=G.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=G.connectionTrackers.get(e);i&&i.connectionCount===0&&(B.debug("stopping region refetch after disconnect delay",{hostname:e}),G.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},Ju))}static cancelCleanup(e){const t=G.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=G.connectionTrackers.get(e);t||(t={connectionCount:0},G.connectionTrackers.set(e,t)),t.connectionCount++,G.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=G.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&G.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Et(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){return G.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return p(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=G.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),G.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(i.length>0){const s=i[0];return this.attemptedRegions.push(s),B.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){G.updateCachedRegionSettings(this.serverUrl,this.token,e)}}G.cache=new Map,G.settingsTimeouts=new Map,G.connectionTrackers=new Map,G.fetchLock=new he;function $u(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class ie extends Error{constructor(e,t,i){super(t),this.code=e,this.message=pa(t,ie.MAX_MESSAGE_BYTES),this.data=i?pa(i,ie.MAX_DATA_BYTES):void 0}static fromProto(e){return new ie(e.code,e.message,e.data)}toProto(){return new gr({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ie(ie.ErrorCode[e],ie.ErrorMessage[e],t)}}ie.MAX_MESSAGE_BYTES=256,ie.MAX_DATA_BYTES=15360,ie.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},ie.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const ha=15360;function Yn(n){return new TextEncoder().encode(n).length}function pa(n,e){if(Yn(n)<=e)return n;let t=0,i=n.length;const s=new TextEncoder;for(;t<i;){const r=Math.floor((t+i+1)/2);s.encode(n.slice(0,r)).length<=e?t=r:i=r-1}return n.slice(0,t)}const Xn=2e3;function wi(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const Zn=typeof MediaRecorder<"u";class Qu{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Yu=Zn?MediaRecorder:Qu;class Xu extends Yu{constructor(e,t){if(!Zn)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,s;const r=()=>s===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s?.close(),s=void 0},o=c=>{s?.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,i=d=>p(this,void 0,void 0,function*(){let l;if(d.data.arrayBuffer){const u=yield d.data.arrayBuffer();l=new Uint8Array(u)}else if(d.data.byteArray)l=d.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function Zu(){return Zn}const eh=1e3,th=1e4;class ma extends C{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=zn(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(P.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new he,this.pauseUpstreamLock=new he,this.trackChangeLock=new he,this.trackChangeLock.lock().then(a=>p(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==C.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return p(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{St(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Ct(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Ct(s??e,r)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:eh;return(function*(){var i;if(e.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=be())===null||i===void 0?void 0:i.os)==="iOS"&&(yield le(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield le(50)}throw new Ke("unable to get track dimensions after timeout")})()})}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ye(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Ye(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===C.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===C.Kind.Audio?"audioinput":"videoinput";return t?ce.getInstance().normalizeDeviceId(r,i,s):i})()})}mute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return p(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ke("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:s}=e,r=El(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===C.Kind.Video?a.video=i||s?{deviceId:i,facingMode:s}:!0:a.audio=i?Object.assign({deviceId:i},r):!0,this.attachedElements.forEach(d=>{St(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===C.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(P.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?P.Muted:P.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),jo()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(P.UpstreamPaused,this);const i=be();if(i?.name==="Safari"&&Ue(i.version,"12.0")<0)throw new Cn("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(P.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return p(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Ct(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(d=>{d instanceof DOMException&&d.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:d})),setTimeout(()=>{o.play().catch(l=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:l}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:d}))}),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const d of i.attachedElements)d!==i.processorElement&&s&&(St(i._mediaStreamTrack,d),Ct(i.processor.processedTrack,d));yield(r=i.sender)===null||r===void 0?void 0:r.replaceTrack(i.processor.processedTrack)}i.emit(P.TrackProcessorUpdate,i.processor)}finally{a()}})()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}})()})}internalStopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(P.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Zu()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Xu(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},th)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class Di extends ma{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,C.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=wi(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===C.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Ye(this._constraints.deviceId);return this.source===C.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return p(this,void 0,void 0,function*(){let t;if(e){const i=In({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){ye()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Xn)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Le()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(P.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield Mo(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(P.AudioSilenceDetected)),e})}}function ih(n,e,t){switch(n.kind){case"audio":return new Di(n,e,!1,void 0,t);case"video":return new Ai(n,e,!1,t);default:throw new Ke("unsupported track type: ".concat(n.kind))}}const nh=Object.values(qt),sh=Object.values(En),rh=Object.values(Rn),oh=[qt.h180,qt.h360],ah=[En.h180,En.h360],ch=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new J(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),es=["q","h","f"];function ts(n,e,t,i){var s,r;let a=i?.videoEncoding;n&&(a=i?.screenShareEncoding);const o=i?.simulcast,c=i?.scalabilityMode,d=i?.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=lh(n,e,t,d),B.debug("using video encoding",a));const l=a.maxFramerate,u=new J(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&De(d)){const _=new va(c),v=[];if(_.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const R=be();if(Ht()||Le()||R?.name==="Chrome"&&Ue(R?.version,"113")<0){const T=_.suffix=="h"?2:3,A=ou(R);for(let x=0;x<_.spatial;x+=1)v.push({rid:es[2-x],maxBitrate:a.maxBitrate/Math.pow(T,x),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:A?Math.pow(2,x):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),B.debug("using svc encoding",{encodings:v}),v}if(!o)return[a];let h=[];n?h=(s=ga(i?.screenShareSimulcastLayers))!==null&&s!==void 0?s:fa(n,u):h=(r=ga(i?.videoSimulcastLayers))!==null&&r!==void 0?r:fa(n,u);let f;if(h.length>0){const _=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return is(e,t,[_,f,u],l);if(v>=480)return is(e,t,[_,u],l)}return is(e,t,[u])}function dh(n,e,t){var i,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&B.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=o.height)!==null&&r!==void 0?r:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===C.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),ts(n.source===C.Source.ScreenShare,c,d,t)}function lh(n,e,t,i){const s=uh(n,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function uh(n,e,t){if(n)return rh;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?nh:sh}function fa(n,e){if(n)return ch(e);const{width:t,height:i}=e,s=t>i?t/i:i/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?oh:ah}function is(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=es.length)return;const o=Math.min(n,e),d={rid:es[a],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=i&&r.encoding.maxFramerate?Math.min(i,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(d.maxFramerate=l);const u=dt()||a===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Le()&&Ko()==="ios"){let r;s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var c;o.maxFramerate!=r&&(a&&(a=!1,B.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),B.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function ga(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:s}=t;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class va{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function hh(n){return n.source===C.Source.ScreenShare||n.constraints.height&&Ye(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const ph=5e3;class Ai extends ma{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,C.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const a=new Map(r.map(c=>[c.rid,c])),o=r.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(P.CpuConstrained)),this.prevStats){let c=0;a.forEach((d,l)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);c+=wi(d,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new he}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!ye())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Xn))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=qe(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)r=d.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=qe(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){r=d.value,o=!1;const l=r;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(s=>{var r;if(s.type==="outbound-rtp"){const a={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},o=i.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((s,r)=>{var a,o;return((a=r.frameWidth)!==null&&a!==void 0?a:0)-((o=s.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Te.LOW;i<=Te.HIGH;i+=1)t.push(new an({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(De(this.codec),t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const u=In({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,d=qe(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.value,c=!1;const u=r;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,c,d,l,u;if(yield t.setProcessor.call(s,i,r),!((l=s.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,f=qe(s.simulcastCodecs.values()),_;_=yield f.next(),a=_.done,!a;h=!0)d=_.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){o={error:v}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return p(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},ph))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(De(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=qe(e);s=yield i.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(De(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield _a(u.sender,u.encodings,l.qualities,this.senderLock,De(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e,t){return p(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield _a(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return p(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((i,s)=>{var r;return Object.assign(Object.assign({},i),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&De(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),jo()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function _a(n,e,t,i,s,r,a){return p(this,void 0,void 0,function*(){const o=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{const c=n.getParameters(),{encodings:d}=c;if(!d)return;if(d.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:d,senderEncodings:e}));return}let l=!1;!1&&d[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),d.forEach((h,f)=>{var _;let v=(_=h.rid)!==null&&_!==void 0?_:"";v===""&&(v="q");const R=ba(v),T=t.find(A=>A.quality===R);T&&h.active!==T.enabled&&(l=!0,h.active=T.enabled,r.debug("setting layer ".concat(T.quality," to ").concat(h.active?"enabled":"disabled"),a),dt()&&(T.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),l&&(c.encodings=d,r.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield n.setParameters(c))}finally{o()}})}function ba(n){switch(n){case"f":return Te.HIGH;case"h":return Te.MEDIUM;case"q":return Te.LOW;default:return Te.HIGH}}function ya(n,e,t,i){if(!t)return[new Je({quality:Te.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new va(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)a.push(new Je({quality:Math.min(Te.HIGH,r.spatial-1)-d,width:Math.ceil(n/Math.pow(o,d)),height:Math.ceil(e/Math.pow(o,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=ba((a=s.rid)!==null&&a!==void 0?a:"");return new Je({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Ta="_lossy",ka="_reliable",mh=2*1e3,ns="leave-reconnect",fh=3e4,gh=8*1024,vh=256*1024;var Re;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Re||(Re={}));class _h extends Me.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Qn.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Re.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=B,this.reliableDataSequence=1,this.reliableMessageBuffer=new ta,this.reliableReceivedState=new Fu(fh),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>p(this,[i],void 0,function(s){var r=this;let{channel:a}=s;return(function*(){if(a){if(a.label===ka)r.reliableDCSub=a;else if(a.label===Ta)r.lossyDCSub=a;else return;r.log.debug("on data channel ".concat(a.id,", ").concat(a.label),r.logContext),a.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=i=>p(this,void 0,void 0,function*(){var s,r,a,o,c;const d=yield this.dataProcessLock.lock();try{let l;if(i.data instanceof ArrayBuffer)l=i.data;else if(i.data instanceof Blob)l=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const u=pe.fromBinary(new Uint8Array(l));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(w.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=pr.fromBinary(h.payload),_=new pe({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=_.value)===null||o===void 0?void 0:o.case)==="user"&&Ca(_,_.value.value),this.emit(w.DataPacketReceived,_,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&Ca(u,u.value.value),this.emit(w.DataPacketReceived,u,se.NONE)}finally{d()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const r=i.currentTarget.maxRetransmits===0?j.LOSSY:j.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(w.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}i===ns&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=de.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Re.Connected&&i();const r=()=>{this.off(w.Disconnected,a),i()},a=()=>{this.off(w.Restarted,r),s()};this.once(w.Restarted,r),this.once(w.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{if(i===j.RELIABLE){const r=this.dataChannelForKind(i);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(w.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>p(this,void 0,void 0,function*(){!this.url||!(yield fetch(zt(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Q.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Q.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(ot.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>p(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(zt(this.url),{method:"HEAD"}),le(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=je((t=e.loggerName)!==null&&t!==void 0?t:we.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new qn(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new he,this.dataProcessLock=new he,this.dcBufferStatus=new Map([[j.LOSSY,!0],[j.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(w.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(w.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(w.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(w.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(w.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(w.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(w.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(w.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||s===void 0?void 0:s.sid,participant:(a=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||a===void 0?void 0:a.identity,pID:this.participantSid}}join(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){d.url=r,d.token=a,d.signalOpts=o,d.maxJoinAttempts=o.maxRetries;try{d.joinAttempts+=1,d.setupSignalClientCallbacks();const u=yield d.client.join(r,a,o,c,l);return d._isClosed=!1,d.latestJoinResponse=u,d.subscriberPrimary=u.subscriberPrimary,d.pcManager||(yield d.configure(u,!l)),(!d.subscriberPrimary||u.fastPublish)&&d.negotiate().catch(h=>{B.error(h,d.logContext)}),d.registerOnLineListener(),d.clientConfiguration=u.clientConfiguration,d.emit(w.SignalConnected,u),u}catch(u){if(u instanceof V){if(u.reason===$.ServerUnreachable){if(d.log.warn("Couldn't connect to server, attempt ".concat(d.joinAttempts," of ").concat(d.maxJoinAttempts),d.logContext),d.joinAttempts<d.maxJoinAttempts)return d.join(r,a,o,c,l)}else if(u.reason===$.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(u.message," \u2013 Retrying")),d.join(r,a,o,c,!0)}throw u}})()})}close(){return p(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(w.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return p(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new ta,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Ke("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(V.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return p(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return p(this,void 0,void 0,function*(){var i,s;if(this.pcManager&&this.pcManager.currentState!==te.NEW)return;this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new zu(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(w.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(a,o)=>{this.client.sendIceCandidate(a,o)},this.pcManager.onPublisherOffer=(a,o)=>{this.client.sendOffer(a,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(a,o,c)=>p(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(a),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),a===te.CONNECTED){const u=this.pcState===Re.New;this.pcState=Re.Connected,u&&this.emit(w.Connected,e)}else a===te.FAILED&&(this.pcState===Re.Connected||this.pcState===Re.Reconnecting)&&(this.pcState=Re.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?ot.RR_SUBSCRIBER_FAILED:ot.RR_PUBLISHER_FAILED));const d=this.client.isDisconnected||this.client.currentState===Q.RECONNECTING,l=[te.FAILED,te.CLOSING,te.CLOSED].includes(a);d&&l&&!this._isClosed&&this.emit(w.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(w.MediaTrackAdded,a.track,a.streams[0],a.receiver)},bh((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>p(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>p(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(w.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(w.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(w.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(w.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(w.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",ot.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:ua,regionSettings:e.regions})),e.action){case bt.DISCONNECT:this.emit(w.Disconnected,e?.reason),this.close();break;case bt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ns);break;case bt.RESUME:this.handleDisconnect(ns)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(r=>{const a={urls:r.urls};r.username&&(a.username=r.username),r.credential&&(a.credential=r.credential),s.push(a)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ut.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ta,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(ka,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(j.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,gh),vh)}},1e3))}createSender(e,t,i){return p(this,void 0,void 0,function*(){if(Dn())return yield this.createTransceiverRTCRtpSender(e,t,i);if(An())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(Dn())return this.createSimulcastTransceiverSender(e,t,i,s);if(An())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Xe(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){B.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ut.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:te.NEW)===te.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let a=!0;r instanceof re?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof kt||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",ot.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(w.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return p(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(w.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new kt;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(a){throw a instanceof V&&a.reason===$.NotAllowed?new re("could not reconnect, token might be expired"):new kt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(w.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Q.CONNECTED)throw new kt("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(w.Restarted)}catch(r){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");if(!this.pcManager)throw new re("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(w.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof V&&s.reason===$.NotAllowed?new re("could not reconnect, token might be expired"):s instanceof V&&s.reason===$.LeaveRequest?s:new kt(r)}if(this.emit(w.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Q.CONNECTED)throw new kt("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i?.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(w.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Re.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield le(mh),!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Re.Connected}catch(e){throw this.pcState=Re.Disconnected,V.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,s){return p(this,void 0,void 0,function*(){const r=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcResponse",value:new Zi({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,j.RELIABLE)})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){const i=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcAck",value:new Xi({requestId:t})}});yield this.sendDataPacket(i,j.RELIABLE)})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=Pu(e);if(r){const a=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new hr({encryptedValue:a.payload,iv:a.iv,keyIndex:a.keyIndex})}}}t===j.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===j.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;s.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return p(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(j.RELIABLE);const t=this.dataChannelForKind(j.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(j.RELIABLE)})}waitForBufferStatusLow(e){return new ue((t,i)=>p(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i(new re("engine closed"));for(this.once(w.Closing,s);!this.dcBufferStatus.get(e);)yield le(10);this.off(w.Closing,s),t()}}))}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!i.pcManager)throw new re("PC manager is closed");const a=s?i.pcManager.subscriber:i.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw V.internal("".concat(o," connection not set"));let c=!1;!s&&!i.dataChannelForKind(t,s)&&(i.createDataChannels(),c=!0),!c&&!s&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate().catch(u=>{B.error(u,i.logContext)});const d=i.dataChannelForKind(t,s);if(d?.readyState==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield le(50)}throw V.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return p(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==te.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new ue((e,t)=>p(this,void 0,void 0,function*(){if(!this.pcManager){t(new Tt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new Tt("cannot negotiate on closed engine")),this.on(w.Closing,s),this.pcManager.publisher.once(wt.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();uu(c)&&a.set(o.payload,c)}),this.emit(w.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof Tt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ot.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(w.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===j.LOSSY)return this.lossyDCSub;if(e===j.RELIABLE)return this.reliableDCSub}else{if(e===j.LOSSY)return this.lossyDC;if(e===j.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s,r,a;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),l=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(a=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&a!==void 0?a:!0,h=new Array,f=new Array;e.forEach(_=>{_.isDesired!==u&&h.push(_.trackSid),_.isEnabled||f.push(_.trackSid)}),this.client.sendSyncState(new cn({answer:this.pcManager.mode==="publisher-only"?c?It({sdp:c.sdp,type:c.type}):void 0:l?It({sdp:l.sdp,type:l.type}):void 0,offer:this.pcManager.mode==="publisher-only"?o?It({sdp:o.sdp,type:o.type}):void 0:d?It({sdp:d.sdp,type:d.type}):void 0,subscription:new gi({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:Jl(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((_,v)=>new Ur({publisherSid:v,lastSeq:_}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{i?.id!==void 0&&i.id!==null&&e.push(new Fr({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(j.LOSSY),Ie.PUBLISHER),t(this.dataChannelForKind(j.RELIABLE),Ie.PUBLISHER),t(this.dataChannelForKind(j.LOSSY,!0),Ie.SUBSCRIBER),t(this.dataChannelForKind(j.RELIABLE,!0),Ie.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&de.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ye()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){ye()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const s=Object.entries(this.midToTrackId).find(r=>{let[a]=r;return a===i});if(s)return s[1]}}}function bh(n){return n!==void 0&&n>13}function Ca(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class Sa{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new Se("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),me.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Se("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),me.LengthExceeded)}}constructor(e,t,i,s){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class yh extends Sa{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Ee,i=null,s=null;if(this.signal){const a=this.signal;s=()=>{var o;(o=t.reject)===null||o===void 0||o.call(t,a.reason)},a.addEventListener("abort",s),i=a}const r=()=>{e.releaseLock(),i&&s&&i.removeEventListener("abort",s),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var a,o;try{const{done:c,value:d}=yield Promise.race([e.read(),t.promise,(o=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&o!==void 0?o:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(d),{done:!1,value:d.content})}catch(c){throw r(),c}}),return(){return p(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=qe(c),u;u=yield l.next(),i=u.done,!i;d=!0){a=u.value,d=!1;const h=a;o.add(h)}}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return Array.from(o)})()})}}class Th extends Sa{constructor(e,t,i,s){super(e,t,i,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Ii(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new Ee,s=null,r=null;if(this.signal){const o=this.signal;r=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,o.reason)},o.addEventListener("abort",r),s=o}const a=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var o,c;try{const{done:d,value:l}=yield Promise.race([e.read(),i.promise,(c=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(d)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(l);let u;try{u=t.decode(l.content)}catch(h){throw new Se("Cannot decode datastream chunk ".concat(l.chunkIndex," as text: ").concat(h),me.DecodeFailed)}return{done:!1,value:u}}}catch(d){throw a(),d}}),return(){return p(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=qe(c),u;u=yield l.next(),i=u.done,!i;d=!0)a=u.value,d=!1,o+=a}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return o})()})}}class kh{constructor(){this.log=B,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Se('A text stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Se('A byte stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,s,r;const a=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(a.length>0||o.length>0){const c=new Se("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),me.AbnormalEnd);for(const[d,l]of o)(i=(t=l.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(t,c),this.byteStreamControllers.delete(d);for(const[d,l]of a)(r=(s=l.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(d)}}handleDataStreamPacket(e,t){return p(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return p(this,void 0,void 0,function*(){var s;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o=new Ee;o.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Ii(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new yh(c,d,Ii(e.totalLength),o),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o=new Ee;o.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new Th(c,d,Ii(e.totalLength),o),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Ea{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return p(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Ch extends Ea{}class Sh extends Ea{}const Ra=15e3;class Eh{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return p(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t?.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),d=(u,h)=>{var f;c[h]=u;const _=c.reduce((v,R)=>v+R,0);(f=t?.onProgress)===null||f===void 0||f.call(t,_)},l=yield this.streamText({streamId:s,totalSize:a,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield l.write(e),d(1,0),yield l.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>p(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{d(f,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,i,s;const r=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e?.topic)!==null&&i!==void 0?i:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?se.GCM:se.NONE,attachedStreamIds:e?.attachedStreamIds},o=new ui({streamId:r,mimeType:a.mimeType,topic:a.topic,timestamp:ut(a.timestamp),totalLength:ut(e?.totalSize),attributes:a.attributes,contentHeader:{case:"textHeader",value:new Er({version:e?.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?en.UPDATE:en.CREATE})}}),c=e?.destinationIdentities,d=new pe({destinationIdentities:c,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(d,j.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(v){return p(this,void 0,void 0,function*(){for(const R of vu(v,Ra)){const T=new hi({content:R,streamId:r,chunkIndex:ut(l)}),A=new pe({destinationIdentities:c,value:{case:"streamChunk",value:T}});yield u.sendDataPacket(A,j.RELIABLE),l+=1}})},close(){return p(this,void 0,void 0,function*(){const v=new pi({streamId:r}),R=new pe({destinationIdentities:c,value:{case:"streamTrailer",value:v}});yield u.sendDataPacket(R,j.RELIABLE)})},abort(v){console.log("Sink error:",v)}});let f=()=>p(this,void 0,void 0,function*(){yield _.close()});u.once(w.Closing,f);const _=new Ch(h,a,()=>this.engine.off(w.Closing,f));return _})}sendFile(e,t){return p(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return p(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=i?.mimeType)!==null&&s!==void 0?s:t.type,topic:i?.topic,destinationIdentities:i?.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o;const c=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e?.destinationIdentities,l={id:c,mimeType:(i=e?.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(s=e?.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?se.GCM:se.NONE},u=new ui({totalLength:ut((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:ut(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new Rr({name:l.name})}}),h=new pe({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,j.RELIABLE);let f=0;const _=new he,v=this.engine,R=this.log,T=new WritableStream({write(x){return p(this,void 0,void 0,function*(){const b=yield _.lock();let y=0;try{for(;y<x.byteLength;){const S=x.slice(y,y+Ra),N=new pe({destinationIdentities:d,value:{case:"streamChunk",value:new hi({content:S,streamId:c,chunkIndex:ut(f)})}});yield v.sendDataPacket(N,j.RELIABLE),f+=1,y+=S.byteLength}}finally{b()}})},close(){return p(this,void 0,void 0,function*(){const x=new pi({streamId:c}),b=new pe({destinationIdentities:d,value:{case:"streamTrailer",value:x}});yield v.sendDataPacket(b,j.RELIABLE)})},abort(x){R.error("Sink error:",x)}});return new Sh(T,l)})}}class Pa extends C{constructor(e,t,i,s,r){super(e,i,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?P.Muted:P.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(P.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return p(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Xn)),$l()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:s,rtpTimestamp:r}=i;r&&this.rtpTimestamp!==r&&(this.emit(P.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Rh extends Pa{constructor(e,t,i,s,r,a){super(e,t,C.Kind.Audio,i,a),this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=wi(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Le()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Le())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(On(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&On(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(P.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(P.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const ss=100;class Ph extends Pa{constructor(e,t,i,s,r){super(e,t,C.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=wi(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=zn(()=>{this.updateDimensions()},ss),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===C.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?St(this._mediaStreamTrack,t):Ct(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Ih(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const s=this.elementInfos.reduce((c,d)=>Math.max(c,d.visibilityChangedAt||0),0),r=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!r||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-s<ss){de.setTimeout(()=>{this.updateVisibility()},ss);return}this.lastVisible=o,this.emit(P.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>i+s&&(i=o,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(P.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Wo():t||(Wo()>2?2:1)}}class Ih{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:a}=i;r===this.element&&(this.isIntersecting=a,this.isPiP=Qt(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i,s,r;(s=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Qt(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Qt(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??rs(e),this.isPiP=ye()&&Qt(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=rs(this.element),this.isPiP=Qt(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Go().observe(this.element),Ho().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,s,r;(e=Go())===null||e===void 0||e.unobserve(this.element),(t=Ho())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function Qt(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?rs(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function rs(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:c}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,s+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&s+r>t.pageXOffset&&!o&&c!=="none"}class He extends Me.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=se.NONE,this.log=B,this.handleMuted=()=>{this.emit(P.Muted)},this.handleUnmuted=()=>{this.emit(P.Unmuted)},this.log=je((r=s?.loggerName)!==null&&r!==void 0?r:we.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=C.Source.Unknown}setTrack(e){this.track&&(this.track.off(P.Muted,this.handleMuted),this.track.off(P.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(P.Muted,this.handleMuted),e.on(P.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),K(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==se.NONE}get audioTrack(){if(Fe(this.track))return this.track}get videoTrack(){if(Xe(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=C.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===C.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(He||(He={}));class os extends He{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(P.Ended)},this.handleCpuConstrained=()=>{this.track&&Xe(this.track)&&this.emit(P.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(P.Ended,this.handleTrackEnded),this.track.off(P.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(P.Ended,this.handleTrackEnded),e.on(P.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Fe(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ae.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ae.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ae.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ae.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(ae.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ae.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Oi(n,e){return p(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=Uo(n);let a=r.audio,o=r.video;if(i&&typeof r.audio=="object"&&(r.audio.processor=i),s&&typeof r.video=="object"&&(r.video.processor=s),n.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=xo(r,da,la),d=In(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(ce.userMediaPromiseMap.set("audioinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("audioinput"))),r.video&&(ce.userMediaPromiseMap.set("videoinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(h=>p(this,void 0,void 0,function*(){const f=h.kind==="audio";let _=f?c.audio:c.video;(typeof _=="boolean"||!_)&&(_={});let v;const R=f?d.audio:d.video;typeof R!="boolean"&&(v=R);const T=h.getSettings().deviceId;v?.deviceId&&Ye(v.deviceId)!==T?v.deviceId=T:v||(v={deviceId:T});const A=ih(h,v,e);return A.kind===C.Kind.Video?A.source=C.Source.Camera:A.kind===C.Kind.Audio&&(A.source=C.Source.Microphone),A.mediaStream=u,Fe(A)&&i?yield A.setProcessor(i):Xe(A)&&s&&(yield A.setProcessor(s)),A})))}catch(u){if(!t)throw u;return Oi(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function Ia(n){return p(this,void 0,void 0,function*(){return(yield Oi({audio:!1,video:n??!0}))[0]})}function wa(n){return p(this,void 0,void 0,function*(){return(yield Oi({audio:n??!0,video:!1}))[0]})}var nt;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(nt||(nt={}));function wh(n){switch(n){case Lt.EXCELLENT:return nt.Excellent;case Lt.GOOD:return nt.Good;case Lt.POOR:return nt.Poor;case Lt.LOST:return nt.Lost;default:return nt.Unknown}}class Da extends Me.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Ft.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===vt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ft.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=nt.Unknown,this.log=B,this.log=je((c=a?.loggerName)!==null&&c!==void 0?c:we.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Ee,this.once(I.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(C.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(C.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(C.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===vt.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==vt.ACTIVE&&this.emit(I.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(I.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(I.ParticipantNameChanged,e)}_setAttributes(e){const t=Ql(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(I.AttributesChanged,t)}setPermissions(e){var t,i,s,r,a,o;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit(I.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(I.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=wh(e),t!==this._connectionQuality&&this.emit(I.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Fe(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(P.Muted,()=>{this.emit(I.TrackMuted,e)}),e.on(P.Unmuted,()=>{this.emit(I.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case C.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case C.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Dh(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Mr({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class Ah extends Da{constructor(e,t,i,s,r,a){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=se.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ee)},this.handleReconnected=()=>{var o,c;(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||c===void 0||c.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var o,c,d,l,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||c===void 0||c.call(o,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(d=this.signalConnectedFuture).reject)===null||l===void 0||l.call(d,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var c,d;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Ee),(d=(c=this.signalConnectedFuture).resolve)===null||d===void 0||d.call(c)},this.handleSignalRequestResponse=o=>{const{requestId:c,reason:d,message:l}=o,u=this.pendingSignalRequests.get(c);u&&(d!==dn.OK&&u.reject(new Oo(l,d)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let c=o.value.value,d=null,l=null;c.value.case==="payload"?d=c.value.value:c.value.case==="error"&&(l=ie.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,d,l);break;case"rpcAck":let u=o.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>Dh(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,c)=>{if(c===void 0&&(c=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),K(o)));return}this.engine.updateMuteStatus(o.sid,c)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),K(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),K(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const c=this.audioTrackPublications.get(o.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(o,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),K(c))),this.emit(I.LocalTrackCpuConstrained,o,c)},this.handleSubscribedQualityUpdate=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!f.videoTrack)return;const _=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var v=!0,R=qe(_),T;T=yield R.next(),c=T.done,!c;v=!0){u=T.value,v=!1;const A=u;Hl(A)&&(this.log.debug("publish ".concat(A," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),K(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,A,f.options))}}catch(A){d={error:A}}finally{try{!v&&!c&&(l=R.return)&&(yield l.call(R))}finally{if(d)throw d.error}}}),this.handleLocalTrackUnpublished=o=>{const c=this.trackPublications.get(o.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=o=>p(this,void 0,void 0,function*(){if(o.source===C.Source.ScreenShare||o.source===C.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),K(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(We(o)||Ze(o))try{if(ye())try{const c=yield navigator?.permissions.query({name:o.source===C.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),K(o))),c.onchange=()=>{c.state!=="denied"&&(o.isMuted||o.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),K(o))),We(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),K(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=a}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==se.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(w.RemoteMute,(i,s)=>{const r=this.trackPublications.get(i);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(w.Connected,this.handleReconnected).on(w.SignalConnected,this.handleSignalConnected).on(w.SignalRestarted,this.handleReconnected).on(w.SignalResumed,this.handleReconnected).on(w.Restarting,this.handleReconnecting).on(w.Resuming,this.handleReconnecting).on(w.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(w.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(w.Closing,this.handleClosing).on(w.SignalRequestResponse,this.handleSignalRequestResponse).on(w.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return p(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:a}=t;return(function*(){return new ue((o,c)=>p(i,void 0,void 0,function*(){var d,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((d=s??this.metadata)!==null&&d!==void 0?d:"",(l=r??this.name)!==null&&l!==void 0?l:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:_=>{c(_),u=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(_=>{let[v,R]=_;return this.attributes[v]===R||R===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),o();return}yield le(50)}c(new Oo("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(C.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(C.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(C.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?se.GCM:se.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){return p(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const d=yield this.waitForPendingPublicationOfSource(e);return d||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield d?.unmute(),d}this.pendingPublishing.add(e);try{switch(e){case C.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case C.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case C.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Ke(e)}}catch(d){throw c?.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(I.MediaDevicesError,d,wn(e)),this.pendingPublishing.delete(e),d}for(const d of c){const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===C.Source.Microphone&&Fe(d)&&l.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),d.startPreConnectBuffer())}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),K(u))),d.push(this.publishTrack(u,s));[o]=yield Promise.all(d)}catch(d){throw c?.forEach(l=>{l.stop()}),d}finally{this.pendingPublishing.delete(e)}}else if(!o?.track&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===C.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(C.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(C.Source.Camera)||this.pendingPublishing.has(C.Source.Microphone))){this.pendingPublishing.add(C.Source.Camera),this.pendingPublishing.add(C.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(C.Source.Camera),this.pendingPublishing.delete(C.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,i;e??(e={});const s=xo(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Oi(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Fe(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=C.Source.Microphone,this.emit(I.AudioStreamAcquired)),Xe(o)&&(this.cameraError=void 0,o.source=C.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Cn("getDisplayMedia not supported");e.resolution===void 0&&!ru()&&(e.resolution=Rn.h1080fps30.resolution);const t=zl(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new Ke("no video track found");const r=new Ai(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=C.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(I.AudioStreamAcquired);const o=new Di(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=C.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return p(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var o,c,d,l;We(i)&&i.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),Rt(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let T;switch(i.source){case C.Source.Microphone:T="audioinput";break;case C.Source.Camera:T="videoinput"}T&&r.activeDeviceMap.has(T)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(T)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Di(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new Ai(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new Ke("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(T=>{T.track&&T.track===i&&(h=T)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),K(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),_="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,v=(c=f.forceStereo)!==null&&c!==void 0?c:_;v&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),K(i))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=f.dtx)!==null&&d!==void 0||(f.dtx=!1),(l=f.red)!==null&&l!==void 0||(f.red=!1)),!au()&&r.roomOptions.e2ee&&(r.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},r.logContext)),f.simulcast=!1),f.source&&(i.source=f.source);const R=new Promise((T,A)=>p(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Q.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:K(i)}));let x=!1;const b=setTimeout(()=>{x=!0,i.stop(),A(new Ao("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(b),x)return;const y=yield this.publish(i,f,v);T(y)}else try{const x=yield this.publish(i,f,v);T(x)}catch(x){A(x)}}catch(x){A(x)}}));r.pendingPublishPromises.set(i,R);try{return yield R}catch(T){throw T}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Ee),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),K(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>Yl(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),K(e))),!1)}publish(e,t,i){return p(this,void 0,void 0,function*(){var s,r,a,o,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new Ao("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>Rt(e)&&M.source===e.source)&&e.source!==C.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),K(e))),t.stopMicTrackOnMute&&Fe(e)&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&dt()&&(t.simulcast=!1),t.videoCodec==="av1"&&!iu()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!nu()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=$n),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===Kt(M.mime))||(t.videoCodec=Kt(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(P.Muted,this.onTrackMuted),e.on(P.Unmuted,this.onTrackUnmuted),e.on(P.Ended,this.handleTrackEnded),e.on(P.UpstreamPaused,this.onTrackUpstreamPaused),e.on(P.UpstreamResumed,this.onTrackUpstreamResumed),e.on(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const R=[],T=!(!((s=t.dtx)!==null&&s!==void 0)||s),A=e.getSourceTrackSettings();A.autoGainControl&&R.push(ae.TF_AUTO_GAIN_CONTROL),A.echoCancellation&&R.push(ae.TF_ECHO_CANCELLATION),A.noiseSuppression&&R.push(ae.TF_NOISE_SUPPRESSION),A.channelCount&&A.channelCount>1&&R.push(ae.TF_STEREO),T&&R.push(ae.TF_NO_DTX),We(e)&&e.hasPreConnectBuffer&&R.push(ae.TF_PRECONNECT_BUFFER);const x=new Vt({cid:e.mediaStreamTrack.id,name:t.name,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),disableDtx:T,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:R});let b;if(e.kind===C.Kind.Video){let M={width:0,height:0};try{M=yield e.waitForDimensions()}catch{const U=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:qt.h720.resolution;M={width:U.width,height:U.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{dims:M}))}x.width=M.width,x.height=M.height,Ze(e)&&(De(v)&&(e.source===C.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),K(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),x.simulcastCodecs=[new nn({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:$n}),t.backupCodec&&v!==t.backupCodec.codec&&x.encryption===se.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new nn({codec:t.backupCodec.codec,cid:""})))),b=ts(e.source===C.Source.ScreenShare,x.width,x.height,t),x.layers=ya(x.width,x.height,b,De(t.videoCodec))}else e.kind===C.Kind.Audio&&(b=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const y=()=>p(this,void 0,void 0,function*(){var M,O,U;if(!this.engine.pcManager)throw new re("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(I.LocalSenderCreated,e.sender,e),Ze(e)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=hh(e)),e.setDegradationPreference(t.degradationPreference)),b)if(dt()&&e.kind===C.Kind.Audio){let q;for(const Z of this.engine.pcManager.publisher.getTransceivers())if(Z.sender===e.sender){q=Z;break}q&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:q,codec:"opus",maxbr:!((O=b[0])===null||O===void 0)&&O.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&De(e.codec)&&(!((U=b[0])===null||U===void 0)&&U.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let S;const N=new Promise((M,O)=>p(this,void 0,void 0,function*(){var U;try{S=yield this.engine.addTrack(x),M(S)}catch(q){e.sender&&(!((U=this.engine.pcManager)===null||U===void 0)&&U.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(Z=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{error:Z}))})),O(q)}}));if(this.enabledPublishVideoCodecs.length>0)S=(yield Promise.all([N,y()]))[0];else{S=yield N;let M;if(S.codecs.forEach(O=>{M===void 0&&(M=O.mimeType)}),M&&e.kind===C.Kind.Video){const O=Kt(M);O!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{codec:O})),t.videoCodec=O,b=ts(e.source===C.Source.ScreenShare,x.width,x.height,t))}yield y()}const F=new os(e.kind,S,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(F.on(P.CpuConstrained,M=>this.onTrackCpuConstrained(M,F)),F.options=t,e.sid=S.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:S})),Ze(e)?e.startMonitor(this.engine.client):We(e)&&e.startMonitor(),this.addTrackPublication(F),this.emit(I.LocalTrackPublished,F),We(e)&&S.audioFeatures.includes(ae.TF_PRECONNECT_BUFFER)){const M=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(I.LocalTrackSubscribed,U=>{if(U.trackSid===S.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),K(e))),e.stopPreConnectBuffer()}}),M&&new Promise((q,Z)=>p(this,void 0,void 0,function*(){var ke,pt,ge,rt,cs,ds;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),K(e)));const ps=setTimeout(()=>{Z(new Error("agent not active within 10 seconds"))},1e4),mp=yield this.waitUntilActiveAgentPresent();clearTimeout(ps),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),K(e)));const Ba=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[mp.identity],attributes:{trackId:F.trackSid,sampleRate:String((cs=A.sampleRate)!==null&&cs!==void 0?cs:"48000"),channels:String((ds=A.channelCount)!==null&&ds!==void 0?ds:"1")}});try{for(var ls=!0,us=qe(M),hs;hs=yield us.next(),ke=hs.done,!ke;ls=!0){rt=hs.value,ls=!1;const ms=rt;yield Ba.write(ms)}}catch(ms){pt={error:ms}}finally{try{!ls&&!ke&&(ge=us.return)&&(yield ge.call(us))}finally{if(pt)throw pt.error}}yield Ba.close(),q()}catch(ps){Z(ps)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),K(e)))}).catch(q=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{error:q}))})}return F})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return p(this,void 0,void 0,function*(){var s;if(this.encryptionType!==se.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new Ke("track is not published");if(!Ze(e))throw new Ke("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),o=dh(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),K(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=new Vt({cid:c.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=ya(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const l=()=>p(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(d),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:h}))})}unpublishTrack(e,t){return p(this,void 0,void 0,function*(){var i,s;if(Rt(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),K(e))),yield d)}const r=this.getPublicationForTrack(e),a=r?K(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=r.track,e.off(P.Muted,this.onTrackMuted),e.off(P.Unmuted,this.onTrackUnmuted),e.off(P.Ended,this.handleTrackEnded),e.off(P.UpstreamPaused,this.onTrackUpstreamPaused),e.off(P.UpstreamResumed,this.onTrackUpstreamResumed),e.off(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<te.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Ze(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(o=!0),d.sender=void 0);e.simulcastCodecs.clear()}}catch(d){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case C.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case C.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(I.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return p(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new ue((r,a)=>p(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>p(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==C.Source.ScreenShare&&d.source!==C.Source.ScreenShareAudio&&(We(d)||Ze(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),r()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?j.RELIABLE:j.LOSSY,a=s.destinationIdentities,o=s.topic;let c=new Qi({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o});const d=new pe({kind:r,value:{case:"user",value:c}});yield i.engine.sendDataPacket(d,r)})()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){const i=new pe({kind:j.RELIABLE,value:{case:"sipDtmf",value:new fr({code:e,digit:t})}});yield this.engine.sendDataPacket(i,j.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},s=new pe({value:{case:"chatMessage",value:new li(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,j.RELIABLE),this.emit(I.ChatMessage,i),i})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new pe({value:{case:"chatMessage",value:new li(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp),editTimestamp:X.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,j.RELIABLE),this.emit(I.ChatMessage,i),i})}sendText(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:s,responseTimeout:r=15e3}=e;const a=7e3,o=a+1e3;return new ue((c,d)=>p(this,void 0,void 0,function*(){var l,u,h,f;if(Yn(s)>ha){d(ie.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||u===void 0)&&u.version&&Ue((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){d(ie.builtIn("UNSUPPORTED_SERVER"));return}const _=Math.max(r,o),v=crypto.randomUUID();yield this.publishRpcRequest(t,v,i,s,_);const R=setTimeout(()=>{this.pendingAcks.delete(v),d(ie.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(T)},a);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(R)},participantIdentity:t});const T=setTimeout(()=>{this.pendingResponses.delete(v),d(ie.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(A,x)=>{clearTimeout(T),this.pendingAcks.has(v)&&(this.log.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(R)),x?d(x):c(A??"")},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const s=this.pendingResponses.get(e);s?(s.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,s,r){return p(this,void 0,void 0,function*(){const a=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcRequest",value:new Yi({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,j.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:s}]of this.pendingResponses)i===e&&(s(null,ie.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),K(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Ee),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(We(s)||Ze(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[a]=r;return a.source===e});if(s)return s[1];yield le(20)}})}}class Oh extends He{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(P.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new gi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new vr({participantSid:"",trackSids:[this.trackSid]})]});this.emit(P.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?He.SubscriptionStatus.Unsubscribed:super.isSubscribed?He.SubscriptionStatus.Subscribed:He.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?He.PermissionStatus.Allowed:He.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Fn(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Fn(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Te.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(P.VisibilityChanged,this.handleVisibilityChange),s.off(P.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(P.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(P.VisibilityChanged,this.handleVisibilityChange),e.on(P.Ended,this.handleEnded),this.emit(P.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(P.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?P.Muted:P.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(P.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(P.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Fn(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ar({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===C.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Fo(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Xl(this.trackInfo,this.requestedMaxQuality);i&&Fo(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Te.HIGH})),e.quality=Te.HIGH)}this.emit(P.UpdateSettings,e)}}class Ni extends Da{static fromParticipantInfo(e,t,i){return new Ni(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ft.STANDARD;super(t,i||"",s,r,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(P.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(P.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(P.SubscriptionPermissionChanged,t=>{this.emit(I.TrackSubscriptionPermissionChanged,e,t)}),e.on(P.SubscriptionStatusChanged,t=>{this.emit(I.TrackSubscriptionStatusChanged,e,t)}),e.on(P.Subscribed,t=>{this.emit(I.TrackSubscribed,t,e)}),e.on(P.Unsubscribed,t=>{this.emit(I.TrackUnsubscribed,t,e)}),e.on(P.SubscriptionFailed,t=>{this.emit(I.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:C.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:C.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(I.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),K(o))),this.emit(I.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new Ph(e,t,s,r):d=new Rh(e,t,s,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(i),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&Un(d)&&Fe(d)&&d.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const c=C.kindFromProto(s.type);if(!c)return;o=new Oh(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(s),i.set(s.sid,o);const d=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);d&&o.source!==C.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:K(d),newTrack:K(o)})),this.addTrackPublication(o)}t.set(s.sid,o)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),K(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(I.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case C.Kind.Audio:this.audioTrackPublications.delete(e);break;case C.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(I.TrackUnpublished,i)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;Fe(i.track)&&Un(i.track)&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var z;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(z||(z={}));const Nh=4*1e3;class Dt extends Me.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,a;if(super(),t=this,this.state=z.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=B,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,c,d)=>p(this,void 0,void 0,function*(){var l;if(!su())throw Le()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===z.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(z.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==$o(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Et(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new G(o,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(_=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(_)}).catch(_=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:_}))}));const h=(_,v,R)=>p(this,void 0,void 0,function*(){var T,A;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,u?.();try{if(yield Pt.getInstance().getBackOffPromise(o),x.signal.aborted)throw V.cancelled("Connection attempt aborted");yield this.attemptConnection(R??o,c,d,x),this.abortController=void 0,_()}catch(b){if(this.regionUrlProvider&&b instanceof V&&b.reason!==$.Cancelled&&b.reason!==$.NotAllowed){let y=null;try{this.log.debug("Fetching next region"),y=yield this.regionUrlProvider.getNextBestRegionUrl((T=this.abortController)===null||T===void 0?void 0:T.signal)}catch(S){if(S instanceof V&&(S.status===401||S.reason===$.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(S);return}}[$.InternalError,$.ServerUnreachable,$.Timeout].includes(b.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Pt.getInstance().addFailedConnectionAttempt(o)),y&&!(!((A=this.abortController)===null||A===void 0)&&A.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(b.message,". Retrying with another region: ").concat(y),this.logContext),this.recreateEngine(),yield h(_,v,y)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Jo(b)),v(b))}else{let y=Ce.UNKNOWN_REASON;b instanceof V&&(y=Jo(b)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,y),v(b)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ee((_,v)=>{h(_,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,c,d,l,u,h)=>p(this,void 0,void 0,function*(){var f,_,v;const R=yield d.join(o,c,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},h.signal,!u.singlePeerConnection);let T=R.serverInfo;if(T||(T={version:R.serverVersion,region:R.serverRegion}),this.serverInfo=T,this.log.debug("connected to Livekit Server ".concat(Object.entries(T).map(A=>{let[x,b]=A;return"".concat(x,": ").concat(b)}).join(", ")),{room:(f=R.room)===null||f===void 0?void 0:f.name,roomSid:(_=R.room)===null||_===void 0?void 0:_.sid,identity:(v=R.participant)===null||v===void 0?void 0:v.identity}),!T.version)throw new Bl("unknown server version");return T.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),R}),this.applyJoinResponse=o=>{const c=o.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(d){this.log.error(d instanceof Error?d.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:d}))}this.handleParticipantUpdates([c,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,c,d,l)=>p(this,void 0,void 0,function*(){var u,h;this.state===z.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Qn),d),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(o,c,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const _=l.signal.aborted?V.cancelled("Signal connection aborted"):V.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(_.message="".concat(_.message,": ").concat(f.message)),f instanceof V&&(_.reason=f.reason,_.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),_}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),V.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}ye()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ye()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(z.Connected),this.emit(E.Connected),Pt.getInstance().resetFailedConnectionAttempts(o),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var o=arguments.length,c=new Array(o),d=0;d<o;d++)c[d]=arguments[d];return p(t,[...c],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,_;const v=yield l.disconnectLock.lock();try{if(l.state===z.Disconnected){l.log.debug("already disconnected",l.logContext);return}if(l.log.info("disconnect from room",Object.assign({},l.logContext)),l.state===z.Connecting||l.state===z.Reconnecting||l.isResuming){const R="Abort connection attempt due to user initiated disconnect";l.log.warn(R,l.logContext),(h=l.abortController)===null||h===void 0||h.abort(R),(_=(f=l.connectFuture)===null||f===void 0?void 0:f.reject)===null||_===void 0||_.call(f,V.cancelled("Client initiated disconnect")),l.connectFuture=void 0}l.engine&&(l.engine.client.isDisconnected||(yield l.engine.client.sendLeave()),yield l.engine.close()),l.handleDisconnect(u,Ce.CLIENT_INITIATED),l.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){const o=[],c=be();if(c&&c.os==="iOS"){const d="livekit-dummy-audio-el";let l=document.getElementById(d);if(!l){l=document.createElement("audio"),l.id=d,l.autoplay=!0,l.hidden=!0;const u=Ln();u.enabled=!0;const h=new MediaStream([u]);l.srcObject=h,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(E.Disconnected,()=>{l?.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(d=>{d.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(d=>(d.muted=!1,d.play()))]),this.handleAudioPlaybackStarted()}catch(d){throw this.handleAudioPlaybackFailed(d),d}}),this.startVideo=()=>p(this,void 0,void 0,function*(){const o=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(d=>{var l;(l=d.track)===null||l===void 0||l.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(z.Reconnecting)&&this.emit(E.Reconnecting)},this.handleSignalRestarted=o=>p(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(z.Connected),this.emit(E.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(c=>{var d;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(d=this.sidToIdentity.get(c.sid))!==null&&d!==void 0?d:"");let l=this.remoteParticipants.get(c.identity);c.state===vt.DISCONNECTED?this.handleParticipantDisconnected(c.identity,l):l=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=o=>{const c=[],d={};o.forEach(l=>{if(d[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),c.push(u))}}),d[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{d[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(E.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=o=>{const c=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||c.set(l.sid,l)}),o.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?c.set(l.sid,u):c.delete(l.sid))});const d=Array.from(c.values());d.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=d,this.emitWhenConnected(E.ActiveSpeakersChanged,d)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(c=>{const d=this.getRemoteParticipantBySid(c.participantSid);if(!d)return;const l=d.getTrackPublicationBySid(c.trackSid);if(!l||!l.track)return;const u=C.streamStateFromProto(c.state);l.track.setStreamState(u),u!==l.track.streamState&&(d.emit(I.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(E.TrackStreamStateChanged,l,l.track.streamState,d))})},this.handleSubscriptionPermissionUpdate=o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const c=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setSubscriptionError(o.err)},this.handleDataPacket=(o,c)=>{const d=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(d,o.value.value,o.kind,c);else if(o.value.case==="transcription")this.handleTranscription(d,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(d,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(d,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,d);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o,c);else if(o.value.case==="rpcRequest"){const l=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,l.id,l.method,l.payload,l.responseTimeoutMs,l.version)}},this.handleUserPacket=(o,c,d,l)=>{this.emit(E.DataReceived,c.payload,o,d,c.topic,l),o?.emit(I.DataReceived,c.payload,d,l)},this.handleSipDtmf=(o,c)=>{this.emit(E.SipDTMFReceived,c,o),o?.emit(I.SipDTMFReceived,c)},this.handleTranscription=(o,c)=>{const d=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),l=d?.trackPublications.get(c.trackId),u=pu(c,this.transcriptionReceivedTimes);l?.emit(P.TranscriptionReceived,u),d?.emit(I.TranscriptionReceived,u,l),this.emit(E.TranscriptionReceived,u,d,l)},this.handleChatMessage=(o,c)=>{const d=mu(c);this.emit(E.ChatMessage,d,o)},this.handleMetrics=(o,c)=>{this.emit(E.MetricsReceived,o,c)},this.handleDataStream=(o,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(o,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(E.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(E.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(E.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(E.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var o;((o=be())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(E.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const c=this.roomInfo;this.roomInfo=o,c&&c.metadata!==o.metadata&&this.emitWhenConnected(E.RoomMetadataChanged,o.metadata),c?.activeRecording!==o.activeRecording&&this.emitWhenConnected(E.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const d=this.getRemoteParticipantBySid(c.participantSid);d&&d.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(E.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(E.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(E.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(E.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(E.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var c;(c=o?.onPublish)===null||c===void 0||c.call(o,this)},this.onLocalTrackPublished=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h,f;(c=o.track)===null||c===void 0||c.on(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.on(P.Restarted,this.onLocalTrackRestarted),(h=(u=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(E.LocalTrackPublished,o,this.localParticipant),We(o.track)&&(yield o.track.checkForSilence())&&this.emit(E.LocalAudioSilenceDetected,o);const _=yield(f=o.track)===null||f===void 0?void 0:f.getDeviceId(!1),v=wn(o.source);v&&_&&_!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,_),this.emit(E.ActiveDeviceChanged,v,_))}),this.onLocalTrackUnpublished=o=>{var c,d;(c=o.track)===null||c===void 0||c.off(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.off(P.Restarted,this.onLocalTrackRestarted),this.emit(E.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>p(this,void 0,void 0,function*(){const c=yield o.getDeviceId(!1),d=wn(o.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.log.debug("local track restarted, setting ".concat(d," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(d,c),this.emit(E.ActiveDeviceChanged,d,c))}),this.onLocalConnectionQualityChanged=o=>{this.emit(E.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,c)=>{this.emit(E.MediaDevicesError,o,c)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(E.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(E.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Gu),e),this.log=je((i=this.options.loggerName)!==null&&i!==void 0?i:we.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},da),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},la),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Hu),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new kh,this.outgoingDataStreamManager=new Eh(this.engine,this.log),this.disconnectLock=new he,this.localParticipant=new Ah("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Ye(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ye(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Ye(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),ye()){const o=new AbortController;(a=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||a===void 0||a.call(r,"devicechange",this.handleDeviceChange,{signal:o.signal}),Dt.cleanupRegistry&&Dt.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new Iu(i,t),this.e2eeManager.on(tt.ParticipantEncryptionStatusChanged,(s,r)=>{gu(r)&&(this.isE2EEEnabled=s),this.emit(E.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on(tt.EncryptionError,(s,r)=>{const a=r?this.getParticipantByIdentity(r):void 0;this.emit(E.EncryptionError,s,a)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===z.Disconnected?ue.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?ue.resolve(this.roomInfo.sid):new ue((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(w.RoomUpdate,i),e(s.sid))};this.engine.on(w.RoomUpdate,i),this.once(E.Disconnected,()=>{this.engine.off(w.RoomUpdate,i),t(new re("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new _h(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(w.ParticipantUpdate,this.handleParticipantUpdates).on(w.RoomUpdate,this.handleRoomUpdate).on(w.SpeakersChanged,this.handleSpeakersChanged).on(w.StreamStateChanged,this.handleStreamStateUpdate).on(w.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(w.SubscriptionError,this.handleSubscriptionError).on(w.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(w.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(w.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(w.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(w.DataPacketReceived,this.handleDataPacket).on(w.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(z.SignalReconnecting)&&this.emit(E.SignalReconnecting)}).on(w.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(z.Connected)&&this.emit(E.Reconnected)}).on(w.SignalResumed,()=>{this.bufferedEvents=[],(this.state===z.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(w.Restarting,this.handleRestarting).on(w.SignalRestarted,this.handleSignalRestarted).on(w.Offline,()=>{this.setAndEmitConnectionState(z.Reconnecting)&&this.emit(E.Reconnecting)}).on(w.DCBufferStatusChanged,(e,t)=>{this.emit(E.DCBufferStatusChanged,e,t)}).on(w.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:s}=i;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(I.LocalTrackSubscribed,t),this.emitWhenConnected(E.LocalTrackSubscribed,t,this.localParticipant)}).on(w.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(E.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return ce.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===z.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Et(new URL(e))&&t){this.regionUrlProvider=new G(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===z.Disconnected&&(this.regionUrl=i,yield fetch(zt(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(zt(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return p(this,void 0,void 0,function*(){let i=()=>p(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new xe({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new xe({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new xe({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new xe({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new xe({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new xe({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new xe({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>p(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new vi({reason:Ce.CLIENT_INITIATED,action:bt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new xe({scenario:{case:"subscriberBandwidth",value:ut(t)}});break;case"leave-full-reconnect":s=new xe({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,c,d,l,u,h,f;let _=!0,v=!1;const R=a?{exact:s}:s;if(i==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const T=(o=r.getActiveDevice(i))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.audioTrackPublications.values()).filter(b=>b.source===C.Source.Microphone);try{_=(yield Promise.all(A.map(b=>{var y;return(y=b.audioTrack)===null||y===void 0?void 0:y.setDeviceId(R)}))).every(b=>b===!0)}catch(b){throw r.options.audioCaptureDefaults.deviceId=T,b}const x=A.some(b=>{var y,S;return(S=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&S!==void 0?S:!1});_&&x&&(v=!0)}else if(i==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const T=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.videoTrackPublications.values()).filter(b=>b.source===C.Source.Camera);try{_=(yield Promise.all(A.map(b=>{var y;return(y=b.videoTrack)===null||y===void 0?void 0:y.setDeviceId(R)}))).every(b=>b===!0)}catch(b){throw r.options.videoCaptureDefaults.deviceId=T,b}const x=A.some(b=>{var y,S;return(S=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&S!==void 0?S:!1});_&&x&&(v=!0)}else if(i==="audiooutput"){if(v=!0,!On()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(d=yield ce.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(f=r.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});const T=(u=r.getActiveDevice(i))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(A=>A.setAudioOutput({deviceId:s})))}catch(A){throw r.options.audioOutput.deviceId=T,A}}return v&&(r.localParticipant.activeDeviceMap.set(i,s),r.emit(E.ActiveDeviceChanged,i,s)),_})()})}setupLocalParticipantEvents(){this.localParticipant.on(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(I.AttributesChanged,this.onLocalAttributesChanged).on(I.TrackMuted,this.onLocalTrackMuted).on(I.TrackUnmuted,this.onLocalTrackUnmuted).on(I.LocalTrackPublished,this.onLocalTrackPublished).on(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(I.MediaDevicesError,this.onMediaDevicesError).on(I.AudioStreamAcquired,this.startAudio).on(I.ChatMessage,this.onLocalChatMessageSent).on(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===z.Connecting||this.state===z.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,i),h()},h=()=>{this.off(E.Reconnected,u),this.off(E.Connected,u),this.off(E.Disconnected,h)};this.once(E.Reconnected,u),this.once(E.Connected,u),this.once(E.Disconnected,h);return}if(this.state===z.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const s=tu(t.id),r=s[0];let a=s[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!o.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(i);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}o=u}o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(a,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:a,trackId:o}));let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={});const l=c.addSubscribedMediaTrack(e,o,t,i,d);l?.isEncrypted&&!this.e2eeManager&&this.emit(E.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==z.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(a=>{r.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var a,o,c;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((a=r.track)===null||a===void 0||a.detach(),(o=r.track)===null||o===void 0||o.stop()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(I.AttributesChanged,this.onLocalAttributesChanged).off(I.TrackMuted,this.onLocalTrackMuted).off(I.TrackUnmuted,this.onLocalTrackUnmuted).off(I.LocalTrackPublished,this.onLocalTrackPublished).off(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(I.MediaDevicesError,this.onMediaDevicesError).off(I.AudioStreamAcquired,this.startAudio).off(I.ChatMessage,this.onLocalChatMessageSent).off(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),ye()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||s===void 0||s.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(z.Disconnected),this.emit(E.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(E.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,s,r,a){return p(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Yn(l)>ha?(c=ie.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):d=l}catch(l){l instanceof ie?c=l:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),l),c=ie.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}selectDefaultDevices(){return p(this,void 0,void 0,function*(){var e,t,i;const s=ce.getInstance().previousDevices,r=yield ce.getInstance().getDevices(void 0,!1),a=be();if(a?.name==="Chrome"&&a.os!=="iOS")for(let c of r){const d=s.find(l=>l.deviceId===c.deviceId);d&&d.label!==""&&d.kind===c.kind&&d.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(E.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const d=Gl(c),l=this.localParticipant.getTrackPublication(d);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Ht()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Ht())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return p(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Lo())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),le(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(E.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=Ni.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Ni(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(E.ParticipantConnected,i),i.on(I.TrackPublished,s=>{this.emitWhenConnected(E.TrackPublished,s,i)}).on(I.TrackSubscribed,(s,r)=>{s.kind===C.Kind.Audio?(s.on(P.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(P.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===C.Kind.Video&&(s.on(P.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(P.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(E.TrackSubscribed,s,r,i)}).on(I.TrackUnpublished,s=>{this.emit(E.TrackUnpublished,s,i)}).on(I.TrackUnsubscribed,(s,r)=>{this.emit(E.TrackUnsubscribed,s,r,i)}).on(I.TrackMuted,s=>{this.emitWhenConnected(E.TrackMuted,s,i)}).on(I.TrackUnmuted,s=>{this.emitWhenConnected(E.TrackUnmuted,s,i)}).on(I.ParticipantMetadataChanged,s=>{this.emitWhenConnected(E.ParticipantMetadataChanged,s,i)}).on(I.ParticipantNameChanged,s=>{this.emitWhenConnected(E.ParticipantNameChanged,s,i)}).on(I.AttributesChanged,s=>{this.emitWhenConnected(E.ParticipantAttributesChanged,s,i)}).on(I.ConnectionQualityChanged,s=>{this.emitWhenConnected(E.ConnectionQualityChanged,s,i)}).on(I.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(E.ParticipantPermissionsChanged,s,i)}).on(I.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionStatusChanged,s,r,i)}).on(I.TrackSubscriptionFailed,(s,r)=>{this.emit(E.TrackSubscriptionFailed,s,i,r)}).on(I.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionPermissionChanged,s,r,i)}).on(I.Active,()=>{this.emitWhenConnected(E.ParticipantActive,i),i.kind===Ft.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,s)=>(i.push(...s.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&fu(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=de.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ce.STATE_MISMATCH))):e=0},Nh)}clearConnectionReconcile(){this.connectionReconcileInterval&&de.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(E.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===z.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===z.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,i,s,r;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ci({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:X.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new at({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected),this.emit(E.Connected),this.setAndEmitConnectionState(z.Connected),a.video){const c=new os(C.Kind.Video,new _t({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Pe.AUDIO,name:"video-dummy"}),new Ai(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:zo(160*((i=o.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}if(a.audio){const c=new os(C.Kind.Audio,new _t({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Pe.AUDIO}),new Di(a.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ln(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}for(let c=0;c<o.count-1;c+=1){let d=new at({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:vt.ACTIVE,tracks:[],joinedAt:X.parse(Date.now())});const l=this.getOrCreateParticipant(d.identity,d);if(o.video){const u=zo(160*((r=o.aspectRatios[c%o.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new _t({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Pe.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}if(o.audio){const u=Ln(),h=new _t({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Pe.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}l.updateInfo(d)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==E.ActiveSpeakersChanged&&e!==E.TranscriptionReceived){const r=Aa(i).filter(a=>a!==void 0);(e===E.TrackSubscribed||e===E.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}Dt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Aa(n){return n.map(e=>{if(e)return Array.isArray(e)?Aa(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Oe;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(Oe||(Oe={}));class st extends Me.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Oe.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Dt(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return p(this,void 0,void 0,function*(){if(this.status!==Oe.IDLE)throw Error("check is running already");this.setStatus(Oe.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Oe.SKIPPED&&this.setStatus(this.isSuccess()?Oe.SUCCESS:Oe.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return p(this,void 0,void 0,function*(){return this.room.state===z.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==z.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Oe.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(E.Reconnecting,()=>{t=!0}),this.room.once(E.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield le(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class xh extends st{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){const e=new G(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,a)=>(r.duration-a.duration)*.5+(r.rtt-a.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,d="A".repeat(a),l=Date.now();for(let _=0;_<c;_++)yield r.write(d);yield r.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:s,rtt:1e4,duration:u-l};return h?.forEach(_=>{_.type==="candidate-pair"&&_.nominated&&(f.rtt=_.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const as=1e4;class Mh extends st{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(as/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(as/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return p(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,i.fillStyle="hsl(".concat(s,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>p(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h?.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,as)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class Lh extends st{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield wa();if(yield Mo(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let a=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class Uh extends st{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Ia();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(r+=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return p(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,a,o,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(a=(r=l.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const f=d.getContext("2d");f.drawImage(i,0,0);const v=f.getImageData(0,0,d.width,d.height).data;let R=!0;for(let T=0;T<v.length;T+=4)if(v[T]!==0||v[T+1]!==0||v[T+2]!==0){R=!1;break}R?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),t.getTracks().forEach(s=>s.stop()),i.remove()})}}class Fh extends st{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const a=new Promise(d=>{setTimeout(d,5e3),r=d}),o=()=>{i=!0};t.on(E.SignalReconnecting,o).on(E.Reconnecting,o).on(E.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,i){if(!s||t.state!==z.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class Vh extends st{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;Et(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new G(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new qn,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,c=!1;for(let d of r.iceServers)for(let l of d.urls)l.startsWith("turn:")?(o=!0,c=!0):l.startsWith("turns:")&&(o=!0,c=!0,a=!0),l.startsWith("stun:")&&(c=!0);c?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(d=>setTimeout(d,0)))})}}class Bh extends st{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(E.SignalConnected,()=>{var i;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,a)=>{if(r.candidate){const o=new RTCIceCandidate(r);let c="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(jh(o.address)?c+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,c+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),B.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function jh(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class qh extends st{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new qn,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(Et(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const c=yield new G(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===br.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class vp extends Me.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Oe.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Oe.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=a=>{this.updateCheck(t,a)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(qh)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Bh)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Vh)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Fh)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Lh)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Uh)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Mh);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(xh)})}}function W(n,e,t){return(e=Wh(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Kh(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Wh(n){var e=Kh(n,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class fe extends Error{constructor(e,t){var i;super(e,t),W(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}W(fe,"code","ERR_JOSE_GENERIC");class Hh extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),W(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),W(this,"claim",void 0),W(this,"reason",void 0),W(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}W(Hh,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class Gh extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),W(this,"code","ERR_JWT_EXPIRED"),W(this,"claim",void 0),W(this,"reason",void 0),W(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}W(Gh,"code","ERR_JWT_EXPIRED");class zh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}W(zh,"code","ERR_JOSE_ALG_NOT_ALLOWED");class Jh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JOSE_NOT_SUPPORTED")}}W(Jh,"code","ERR_JOSE_NOT_SUPPORTED");class $h extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),W(this,"code","ERR_JWE_DECRYPTION_FAILED")}}W($h,"code","ERR_JWE_DECRYPTION_FAILED");class Qh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JWE_INVALID")}}W(Qh,"code","ERR_JWE_INVALID");class Yh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JWS_INVALID")}}W(Yh,"code","ERR_JWS_INVALID");class Xh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JWT_INVALID")}}W(Xh,"code","ERR_JWT_INVALID");class Zh extends fe{constructor(){super(...arguments),W(this,"code","ERR_JWK_INVALID")}}W(Zh,"code","ERR_JWK_INVALID");class ep extends fe{constructor(){super(...arguments),W(this,"code","ERR_JWKS_INVALID")}}W(ep,"code","ERR_JWKS_INVALID");class tp extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),W(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}W(tp,"code","ERR_JWKS_NO_MATCHING_KEY");class ip extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),W(this,Symbol.asyncIterator,void 0),W(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}W(ip,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class np extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),W(this,"code","ERR_JWKS_TIMEOUT")}}W(np,"code","ERR_JWKS_TIMEOUT");class sp extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),W(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}W(sp,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var Oa;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(Oa||(Oa={}));var Na;(function(n){n[n.TooShort=0]="TooShort",n[n.HeaderOverrun=1]="HeaderOverrun",n[n.MissingExtWords=2]="MissingExtWords",n[n.UnsupportedVersion=3]="UnsupportedVersion",n[n.InvalidHandle=4]="InvalidHandle",n[n.MalformedExt=5]="MalformedExt"})(Na||(Na={}));var xa;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(xa||(xa={}));var xi;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(xi||(xi={})),xi.UserTimestamp,xi.E2ee;var Ma;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(Ma||(Ma={}));class rp extends ve{constructor(){super(),this._room=null,this._rtcRoom=null,this._micTrack=null,this._cameraVideoTrack=null,this._protocolDispatch=null,this._maxAttempts=Yt,this._maxDelay=Ui*Li,this._speakingHandlers=new Map,this._trackRegistry=new Nc,this._eventAdapter=new xc(this._trackRegistry),m.info("LiveKit Service created")}setContext(e){super.setContext(e),this._maxAttempts=e.options.reconnect?.maxAttempts||Yt,this._maxDelay=(e.options.reconnect?.delay??Ui)*Li,this._eventAdapter.setContext(e)}async connect(e,t,i,s){if(this.ensureNotDisposed(),this._rtcRoom&&this._rtcRoom.state===z.Connected){m.warn("Already connected to LiveKit room");return}let r;try{await this._tearDownStaleRoom(),m.info(`Connecting to LiveKit room: ${i} at ${e}`),r=new Dt({reconnectPolicy:{nextRetryDelayInMs:a=>a.elapsedMs<this._maxDelay?Math.min(Li*Math.pow(2,a.retryCount),this._maxDelay):null}}),r.prepareConnection(e,t),this._registerRoomListeners(r),m.info("Connecting to LiveKit room..."),await r.connect(e,t,{autoSubscribe:!0,maxRetries:this._context.options.reconnect?.maxAttempts||Yt}),this._eventAdapter.setRoom(r),this._rtcRoom=r,this._room=r}catch(a){if(r){try{r.removeAllListeners()}catch{}try{await r.disconnect()}catch{}}throw this._rtcRoom=null,this._room=null,H.fromError(a,L.LIVEKIT_CONNECT_FAILED)}}_registerRoomListeners(e){e.on(E.TrackSubscribed,(t,i,s)=>{this._handleTrackSubscribed(t,i,s)}),e.on(E.TrackUnsubscribed,(t,i,s)=>{this._handleTrackUnsubscribed(t,i,s)}),e.on(E.TrackMuted,(t,i)=>{this._handleTrackMuted(t,i)}),e.on(E.TrackUnmuted,(t,i)=>{this._handleTrackUnmuted(t,i)}),e.on(E.Connected,()=>{m.info("Connected to LiveKit room"),this._context.eventBus.emit("inner:rtc:connected",void 0)}),e.on(E.Disconnected,t=>{t?m.info(`LiveKit room disconnected: ${t}`):m.info("LiveKit room disconnected"),t!==Ce.CLIENT_INITIATED&&(this._context.eventBus.emit("inner:rtc:disconnected",{reason:t?String(t):void 0}),this._context.emitError(new H(L.LIVEKIT_CONNECT_FAILED,t?`LiveKit disconnected: ${String(t)}`:"LiveKit disconnected"),L.LIVEKIT_CONNECT_FAILED)),this._micTrack?.stop(),this._micTrack=null,this._cameraVideoTrack?.stop(),this._cameraVideoTrack=null,this._clearSpeakingHandlers(),this._context.mediaAudioCaptureState.end("rtc"),this._room=null,this._rtcRoom=null}),e.on(E.DataReceived,t=>{this._onRoomDataReceived(t)})}async _tearDownStaleRoom(){if(!this._rtcRoom)return;await this.stopMicrophone(),await this.stopCamera(),this._clearSpeakingHandlers();const e=this._rtcRoom;this._rtcRoom=null,this._room=null;try{e.removeAllListeners()}catch{}try{await e.disconnect()}catch{}}_clearSpeakingHandlers(){if(!this._rtcRoom){this._speakingHandlers.clear();return}for(const[e,t]of this._speakingHandlers.entries()){const i=this._findRemoteParticipantByIdentity(e);try{i?.off(I.IsSpeakingChanged,t)}catch{}}this._speakingHandlers.clear()}_findRemoteParticipantByIdentity(e){const t=this._rtcRoom;if(t){for(const i of t.remoteParticipants.values())if(i.identity===e)return i}}_removeSpeakingListenerIfNoAudioTracks(e){const t=this._speakingHandlers.get(e);if(!t)return;const i=this._trackRegistry.getParticipantTracks(e);for(const r of i)if(this._trackRegistry.getTrack(r)?.kind==="audio")return;const s=this._findRemoteParticipantByIdentity(e);try{s?.off(I.IsSpeakingChanged,t)}catch{}this._speakingHandlers.delete(e)}async startMicrophone(){this.ensureNotDisposed();const e=this._rtcRoom;if(!e||!this.isConnected())throw new H(L.LIVEKIT_CONNECT_FAILED,"LiveKit is not connected");if(!this._context.mediaAudioCaptureState.tryBegin("rtc"))throw new H(L.SDK_INVALID_STATE_TRANSITION,"WebSocket audio capture is active");try{if(this._micTrack){m.warn("Microphone already published");return}const t=await wa(this._context.options.audio?.input??{});await e.localParticipant.publishTrack(t),this._micTrack=t,m.info("Microphone published (rtc)")}catch(t){throw this._context.mediaAudioCaptureState.end("rtc"),this._context.emitError(t,L.AUDIO_CAPTURE_START_FAILED)}}async stopMicrophone(){const e=this._rtcRoom,t=this._micTrack;if(t&&e)try{await e.localParticipant.unpublishTrack(t,!0)}catch(i){throw this._context.emitError(i,L.LIVEKIT_UNPUBLISH_MICROPHONE_FAILED)}this._micTrack?.stop(),this._micTrack=null,this._context.mediaAudioCaptureState.end("rtc"),m.info("Microphone stopped (rtc)")}isMicrophoneActive(){return!!this._micTrack}async sendTextData(e,t,i,s){this.ensureNotDisposed();const r=this._rtcRoom;if(!r||!this.isConnected())throw new H(L.LIVEKIT_CONNECT_FAILED,"LiveKit is not connected");try{const a={event:i,requestId:e,data:{...s,text:t}},o=new TextEncoder().encode(JSON.stringify(a));await r.localParticipant.publishData(o,{reliable:!0}),m.debug("Text message sent via RTC data:",e)}catch(a){throw this._context.emitError(a,L.LIVEKIT_SEND_TEXT_DATA_FAILED)}}async sendSystemEvent(e,t){this.ensureNotDisposed();const i=this._rtcRoom;if(!i||!this.isConnected())throw new H(L.LIVEKIT_CONNECT_FAILED,"LiveKit is not connected");try{const s={event:e,data:t??{}},r=new TextEncoder().encode(JSON.stringify(s));await i.localParticipant.publishData(r,{reliable:!0}),m.debug("System event :",e,"sent via RTC data")}catch(s){throw this._context.emitError(s,L.LIVEKIT_SEND_TEXT_DATA_FAILED)}}setProtocolMessageDispatcher(e){this._protocolDispatch=e}async startCamera(){this.ensureNotDisposed();const e=this._rtcRoom;if(!e||!this.isConnected())throw new H(L.LIVEKIT_CONNECT_FAILED,"LiveKit is not connected");if(this._cameraVideoTrack){m.warn("RTC camera already published");return}try{const t=await Ia({});await e.localParticipant.publishTrack(t),this._cameraVideoTrack=t,m.info("Camera published (rtc)")}catch(t){throw this._context.emitError(t,L.LIVEKIT_CONNECT_FAILED)}}async stopCamera(){const e=this._rtcRoom,t=this._cameraVideoTrack;if(t&&e)try{await e.localParticipant.unpublishTrack(t,!0)}catch(i){m.error("Error unpublishing RTC camera:",i)}this._cameraVideoTrack?.stop(),this._cameraVideoTrack=null,m.info("Camera stopped (rtc)")}attachCameraTo(e){if(this.ensureNotDisposed(),!this._cameraVideoTrack)throw new H(L.LIVEKIT_CONNECT_FAILED,"Camera track is not published");this._cameraVideoTrack.attach(e)}detachCameraFrom(e){if(this.ensureNotDisposed(),!this._cameraVideoTrack)throw new H(L.LIVEKIT_CONNECT_FAILED,"Camera track is not published");this._cameraVideoTrack.detach(e)}isRtcCameraActive(){return this._cameraVideoTrack!==null}_onRoomDataReceived(e){if(!(!this._protocolDispatch||e.length===0))try{const t=new TextDecoder().decode(e),i=JSON.parse(t);if(!i||typeof i!="object")return;m.debug("RTC data message received:",t),this._protocolDispatch(i)}catch(t){m.error("RTC data message parse error:",t),this._context.emitError(t,L.LIVEKIT_DATA_MESSAGE_PARSE_ERROR)}}_handleTrackSubscribed(e,t,i){try{if(!e.mediaStreamTrack){m.warn("Track does not have MediaStreamTrack");return}if(e.kind==="audio"){const o=i.identity;if(!this._speakingHandlers.has(o)){const c=d=>{this._context.eventBus.emit("inner:audio:speaking:changed",{participantId:o,isSpeaking:d}),m.info(`Participant ${o} is speaking: ${d}`)};i.on(I.IsSpeakingChanged,c),this._speakingHandlers.set(o,c)}}const r=t.trackSid,a=i.identity;this._eventAdapter.handleTrackSubscribed(e,r,a)}catch(s){m.error("Error handling track subscribed:",s)}}_handleTrackUnsubscribed(e,t,i){try{const s=t,r=i,a=s.trackSid,o=r.identity,c=this._trackRegistry.getTrack(a),d=c?.kind==="audio";c?.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0),this._eventAdapter.handleTrackUnsubscribed(a,o),d&&this._removeSpeakingListenerIfNoAudioTracks(o)}catch(s){m.error("Error handling track unsubscribed:",s)}}_handleTrackMuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0)}catch(i){m.error("Error handling track muted:",i)}}_handleTrackUnmuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:available",void 0)}catch(i){m.error("Error handling track unmuted:",i)}}async disconnect(){await this.stopMicrophone(),await this.stopCamera(),this._clearSpeakingHandlers();const e=this._rtcRoom;if(e)try{try{e.removeAllListeners()}catch{}await e.disconnect(),this._room=null,this._rtcRoom=null,this._context.eventBus.emit("inner:rtc:disconnected",{reason:"Disconnected from LiveKit room"}),m.info("Disconnected from LiveKit room")}catch(t){m.error("Error disconnecting from LiveKit room:",t),this._room=null,this._rtcRoom=null}else this._room=null}isConnected(){return this._room?this._room.state===z.Connected:!1}getTrackRegistry(){return this._trackRegistry}get trackRegistry(){return this._trackRegistry}getEventAdapter(){return this._eventAdapter}onDispose(){this._protocolDispatch=null,this.disconnect(),this._trackRegistry.dispose(),this._eventAdapter.dispose(),m.info("LiveKit Service disposed")}}class op extends ve{constructor(){super(),this._conversationManager=null,m.info("ProtocolMessageDispatcher created")}setConversationManager(e){this._conversationManager=e,m.debug("Conversation manager set in ProtocolMessageDispatcher")}dispatch(e){this.ensureNotDisposed();try{if(e.event){this._handleLivekitServerResponseMessage(e);return}}catch(t){m.error("Error dispatching protocol message:",t)}}_handleLivekitServerResponseMessage(e){switch(e.event){case"response.chunk":this._conversationManager?.handleAnswerChunk(e.requestId,e.data.text,!1);break;case"response.done":this._conversationManager?.handleAnswerChunk(e.requestId,"",!0);break;case"input.asr.partial":this._conversationManager?.handleAsrTextReceived(e.requestId,e.data.text,!0,e.data.final??!1);break;case"input.asr.final":this._conversationManager?.handleAsrTextReceived(e.requestId,e.data.text,!1,!0);break;case"system.prompt":this._conversationManager?.handleServerInitiatedMessage(void 0,e.data.text);break;case"session.closing":break;case"input.voice.start":this._context.eventBus.emit("inner:conversation:voice:start",{requestId:e.requestId});break;case"input.voice.finish":this._context.eventBus.emit("inner:conversation:voice:finish",{requestId:e.requestId});break;default:m.warn("Unknown event:",e.event)}}onDispose(){this._conversationManager=null,m.info("ProtocolMessageDispatcher disposed")}}const Mi=["sdk:connected","sdk:disconnected","sdk:error","media:video:available","media:video:unavailable","media:video:trackAdded","media:video:trackRemoved","media:audio:trackAdded","media:audio:trackRemoved","media:audio:captureStarted","media:audio:captureStopped","media:camera:started","media:camera:stopped","media:audio:volumeChanged","media:audio:muted","media:audio:unmuted","conversation:question:sent","conversation:answer:waiting","conversation:server:message","conversation:asr:received","conversation:asr:chunk","conversation:answer:chunk","conversation:answer:completed"],La=/^[a-z]+:[a-zA-z]+(:[a-zA-Z]+)?$/;class ap{constructor(e){this.inner=e,this.listeners=new Map,this.forwardedVideoTrackIds=new Set,this.livekitConnected=!1,this.httpConnected=!1,this.internalMap={"inner:sdk:error":{public:"sdk:error",sanitizer:t=>({message:t?.error?.message,code:t?.error?.code})},"inner:rtc:video:available":{public:"media:video:available"},"inner:rtc:video:unavailable":{public:"media:video:unavailable"},"inner:video:track:added":{public:"media:video:trackAdded"},"inner:video:track:removed":{public:"media:video:trackRemoved"},"inner:audio:track:added":{public:"media:audio:trackAdded"},"inner:audio:track:removed":{public:"media:audio:trackRemoved"},"inner:audio:input:started":{public:"media:audio:captureStarted"},"inner:audio:input:stopped":{public:"media:audio:captureStopped"},"inner:camera:started":{public:"media:camera:started"},"inner:camera:stopped":{public:"media:camera:stopped"},"inner:audio:volume:changed":{public:"media:audio:volumeChanged",sanitizer:t=>({volume:t?.volume})},"inner:audio:muted":{public:"media:audio:muted"},"inner:audio:unmuted":{public:"media:audio:unmuted"},"inner:conversation:question:sent":{public:"conversation:question:sent",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:answer:waiting":{public:"conversation:answer:waiting",sanitizer:t=>({questionId:t?.questionId})},"inner:conversation:server:message":{public:"conversation:server:message",sanitizer:t=>({questionId:t?.questionId,message:String(t?.message||""),type:String(t?.type||"")})},"inner:conversation:asr:received":{public:"conversation:asr:received",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:asr:chunk":{public:"conversation:asr:chunk",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||""),isComplete:t?.isComplete??!1})},"inner:conversation:answer:chunk":{public:"conversation:answer:chunk",sanitizer:t=>({questionId:t?.questionId,chunk:String(t?.chunk||"")})},"inner:conversation:answer:completed":{public:"conversation:answer:completed",sanitizer:t=>({questionId:t?.questionId,fullAnswer:String(t?.fullAnswer||"")})}},Object.keys(this.internalMap).forEach(t=>{this.inner.on(t,i=>this.handleInternalEvent(t,i))}),this.inner.on("inner:sdk:connected",t=>this.handleConnected(t,!0)),this.inner.on("inner:sdk:disconnected",t=>this.handleConnected(t,!1)),Mi.forEach(t=>{this.inner.on(t,i=>this.handlePublicEvent(t,i))})}publicAPI(){return{on:this.on.bind(this),off:this.off.bind(this),once:this.once.bind(this)}}on(e,t){const i=String(e);return this.assertAllowed(i),this.listeners.has(i)||this.listeners.set(i,new Set),this.listeners.get(i).add(t),()=>this.off(e,t)}once(e,t){const i=String(e);this.assertAllowed(i);const s=r=>{try{t(r)}finally{this.off(e,s)}};return this.on(e,s)}off(e,t){const i=String(e);this.assertAllowed(i);const s=this.listeners.get(i);s&&(s.delete(t),s.size===0&&this.listeners.delete(i))}handleInternalEvent(e,t){const i=this.internalMap[e];if(!i)return;const s=i.public;if(Mi.indexOf(s)===-1)return;if(s==="media:video:trackAdded"){const o=t?.trackId||t?.id;if(typeof o=="string"){if(this.forwardedVideoTrackIds.has(o))return;this.forwardedVideoTrackIds.add(o)}}const r=i.sanitizer?i.sanitizer(t):t;if(!La.test(s))return;const a=this.listeners.get(s);!a||a.size===0||a.forEach(o=>{try{o(r)}catch(c){m.error("PublicEventEmitter listener error",c)}})}handlePublicEvent(e,t){if(Mi.indexOf(e)===-1)return;const i=Object.values(this.internalMap).find(a=>a.public===e),s=i&&i.sanitizer?i.sanitizer(t):t;if(e==="media:video:trackAdded"){const a=t?.trackId||t?.id;if(typeof a=="string"){if(this.forwardedVideoTrackIds.has(a))return;this.forwardedVideoTrackIds.add(a)}}const r=this.listeners.get(e);!r||r.size===0||r.forEach(a=>{try{a(s)}catch(o){m.error("PublicEventEmitter listener error",o)}})}handleConnected(e,t){e.source==="livekit"?this.livekitConnected=t:e.source==="http"&&(this.httpConnected=t),this.maybeEmitSdkConnected(t?"connected":"disconnected")}maybeEmitSdkConnected(e){const t=e==="connected",i=t?!!this.livekitConnected:!this.livekitConnected,s=t?!!this.httpConnected:!this.httpConnected,a={livekit:i,http:s,all:i&&s},o=JSON.stringify(a);this.lastConnectedPayloadJson!==o&&(this.lastConnectedPayloadJson=o,this.inner.emit(`sdk:${e}`,a))}assertAllowed(e){if(Mi.indexOf(e)===-1)throw new Error(`Event "${e}" is not allowed for public consumers`);if(!La.test(e))throw new Error(`Event name "${e}" does not follow namespace:domain[:action] naming`)}}class cp extends Y{constructor(e,t){super(),this._requestCounter=0,this._baseURL=e||"",this._defaultHeaders=t||{},m.info(`HTTP Service created with baseURL: ${this._baseURL||"none"}`)}setAuthToken(e){this._defaultHeaders.Authorization=`Bearer ${e}`}request(e){this.ensureNotDisposed();const t=e.requestId||`req_${Date.now()}_${++this._requestCounter}`,i=this._buildURL(e.url,e.params),s=this._mergeHeaders(e.headers),r={method:e.method||"GET",headers:s};e.data!==void 0&&(e.method||"GET")!=="GET"&&(typeof e.data=="string"?r.body=e.data:(r.body=JSON.stringify(e.data),!s["Content-Type"]&&!s["content-type"]&&(s["Content-Type"]="application/json")));const a=e.timeout||3e4,o=new AbortController;return r.signal=o.signal,new Promise((c,d)=>{const l=setTimeout(()=>o.abort(),a);fetch(i,r).then(async u=>{clearTimeout(l);const h={};u.headers.forEach((R,T)=>{h[T]=R});let f;const _=u.headers.get("content-type");_&&_.includes("application/json")?f=await u.json():f=await u.text();const v={requestId:t,status:u.status,headers:h,data:f,config:e};m.debug(`HTTP request succeeded: ${e.method} ${i} [${t}]`),c(v)}).catch(u=>{clearTimeout(l);const h=u&&u.name==="AbortError",f={requestId:t,status:u&&u.status||void 0,message:h?"Request aborted (timeout)":u&&u.message||"HTTP request failed",error:u,config:e};m.error(`HTTP request failed: ${e.method} ${i} [${t}]`,u),d(f)})})}get(e,t,i){return this.request({...i,url:e,method:"GET",params:t})}post(e,t,i){return this.request({...i,url:e,method:"POST",data:t})}put(e,t,i){return this.request({...i,url:e,method:"PUT",data:t})}delete(e,t){return this.request({...t,url:e,method:"DELETE"})}patch(e,t,i){return this.request({...i,url:e,method:"PATCH",data:t})}_buildURL(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return this._appendParams(e,t);let i=this._baseURL;return i&&!i.endsWith("/")&&!e.startsWith("/")?i+="/":i&&i.endsWith("/")&&e.startsWith("/")&&(i=i.slice(0,-1)),i+=e,this._appendParams(i,t)}_appendParams(e,t){if(!t||Object.keys(t).length===0)return e;const i=new URLSearchParams;for(const[r,a]of Object.entries(t))i.append(r,String(a));const s=e.includes("?")?"&":"?";return`${e}${s}${i.toString()}`}_mergeHeaders(e){const t={...this._defaultHeaders};return e&&Object.assign(t,e),t}onDispose(){m.info("HTTP Service disposed")}}function dp(n,e="https"){return n.includes("://")?n:`${e.replace(/:$/,"")}://${n}`}class lp extends ve{constructor(e,t){super(),this._httpService=new cp(e||za,t)}getAuthToken(){if(this.ensureNotDisposed(),this._context.authToken)return this._httpService?.setAuthToken(this._context.authToken),Promise.resolve();throw this._context.emitError("Auth token not found",L.SDK_AUTH_TOKEN_FAILED)}async fetchConnectionConfig(){this.ensureNotDisposed();const e=await this._httpService.request({url:"/v1/session/start",method:"POST",data:{avatarId:this._context.options.connectConfig.type==="auth"?this._context.options.connectConfig.config.avatarId:"",voice:this._context.options.connectConfig.type==="auth"&&this._context.options.connectConfig.config.avatarVoice||""},headers:this._context.options.sandbox?{"X-Env-Sandbox":"true"}:void 0}).catch(t=>{throw this._context.emitError(t,L.SDK_GET_LIVEKIT_CONFIG_FAILED)});if(e.data.code!==Ga||!e.data.data)throw this._context.emitError(new H(L.SDK_GET_LIVEKIT_CONFIG_FAILED,e.data.msg||"LiveKit config response invalid"),L.SDK_GET_LIVEKIT_CONFIG_FAILED);return{roomId:"",roomToken:e.data.data.userToken,livekitUrl:dp(e.data.data.sfuUrl,"wss")}}onDispose(){this._httpService.dispose()}}class Ua extends ve{constructor(e,t){super(),this._connectStartAt=null,this._hasReportedFirstFrame=!1,this._videoElement=null,this._videoFirstFrameHandler=null,this._pendingTextResponse=new Map,this._pendingTextAudioQueue=[],this._pendingTextAudioStartAt=new Map,this._pendingNoSpeechStartAt=null,this._eventUnsubscribers=[],this._reporter=e??null,this._now=t??(()=>Date.now())}setReporter(e){this._reporter=e??null}startConnectMeasurement(){this._connectStartAt=this._now(),this._hasReportedFirstFrame=!1}bindVideoElement(e){this._unbindVideoElement(),this._videoElement=e,this._videoFirstFrameHandler=this._handleVideoFirstFrame.bind(this),this._videoElement.addEventListener("loadeddata",this._videoFirstFrameHandler,{once:!1})}setContext(e){super.setContext(e),this._bindEventBus()}_bindEventBus(){this._clearEventListeners(),this._subscribeConversationMetrics(),this._subscribeAudioMetrics()}_subscribeConversationMetrics(){this._eventUnsubscribers.push(this._context.eventBus.on("inner:conversation:question:sent",({questionId:e})=>{const t=this._now();this._pendingTextResponse.set(e,t),this._pendingTextAudioQueue.push(e),this._pendingTextAudioStartAt.set(e,t)})),this._eventUnsubscribers.push(this._context.eventBus.on("inner:conversation:answer:chunk",({questionId:e})=>{this._tryCompleteTextResponse(e)})),this._eventUnsubscribers.push(this._context.eventBus.on("inner:conversation:answer:completed",({questionId:e})=>{this._tryCompleteTextResponse(e)})),this._eventUnsubscribers.push(this._context.eventBus.on("inner:conversation:server:message",({questionId:e})=>{this._tryCompleteTextResponse(e)}))}_subscribeAudioMetrics(){this._eventUnsubscribers.push(this._context.eventBus.on("inner:audio:speaking:changed",({isSpeaking:e})=>{e&&(this._tryCompleteTextToAudio(),this._tryCompleteNoSpeechToAudio())})),this._eventUnsubscribers.push(this._context.eventBus.on("inner:audio:no_speech:reported",({timestamp:e})=>{this._pendingNoSpeechStartAt===null&&(this._pendingNoSpeechStartAt=e)}))}_handleVideoFirstFrame(){this._hasReportedFirstFrame||this._connectStartAt===null||(this._hasReportedFirstFrame=!0,this._report({metric:"connect_to_first_frame_ms",durationMs:this._now()-this._connectStartAt,startedAt:this._connectStartAt,endedAt:this._now()}))}_tryCompleteTextResponse(e){const t=this._pendingTextResponse.get(e);if(t===void 0)return;this._pendingTextResponse.delete(e);const i=this._now();this._report({metric:"text_send_to_text_response_ms",durationMs:i-t,startedAt:t,endedAt:i,questionId:e})}_tryCompleteTextToAudio(){let e;for(;this._pendingTextAudioQueue.length>0;){const s=this._pendingTextAudioQueue.shift();if(s&&this._pendingTextAudioStartAt.has(s)){e=s;break}}if(!e)return;const t=this._pendingTextAudioStartAt.get(e);if(t===void 0)return;this._pendingTextAudioStartAt.delete(e);const i=this._now();this._report({metric:"text_send_to_audio_response_ms",durationMs:i-t,startedAt:t,endedAt:i,questionId:e})}_tryCompleteNoSpeechToAudio(){if(this._pendingNoSpeechStartAt===null)return;const e=this._pendingNoSpeechStartAt;this._pendingNoSpeechStartAt=null;const t=this._now();this._report({metric:"no_speech_report_to_audio_response_ms",durationMs:t-e,startedAt:e,endedAt:t})}_report(e){const t=this._reporter??this._defaultReporter;try{t(e)}catch(i){m.error("Performance metric reporter failed",i)}}_defaultReporter(e){m.info("[performance-metric]",e)}_unbindVideoElement(){this._videoElement&&this._videoFirstFrameHandler&&this._videoElement.removeEventListener("loadeddata",this._videoFirstFrameHandler),this._videoElement=null,this._videoFirstFrameHandler=null}_clearEventListeners(){this._eventUnsubscribers.forEach(e=>{try{e()}catch(t){m.error("Performance monitor unsubscribe failed",t)}}),this._eventUnsubscribers=[]}onDispose(){this._unbindVideoElement(),this._clearEventListeners(),this._pendingTextResponse.clear(),this._pendingTextAudioQueue.length=0,this._pendingTextAudioStartAt.clear(),this._pendingNoSpeechStartAt=null,this._reporter=null}}class ht extends ve{constructor(e,t=$a){super(),this._cachedConfig=null,this._cachedAt=null,this._inflightPromise=null,this._nextDirectConfig=null,this._httpController=e,this._ttlMs=t}async preConnect(){this.ensureNotDisposed();const e=this.getValidConfig();return e||(this._inflightPromise?this._inflightPromise:(this._inflightPromise=this._fetchConfig().finally(()=>{this._inflightPromise=null}),this._inflightPromise))}getValidConfig(){return this.ensureNotDisposed(),!this._cachedConfig||this._cachedAt===null||Date.now()-this._cachedAt>=this._ttlMs?null:this._cachedConfig}async refreshConfig(){return this.ensureNotDisposed(),this._cachedConfig=null,this._cachedAt=null,this._inflightPromise?this._inflightPromise:(this._inflightPromise=this._fetchConfig().finally(()=>{this._inflightPromise=null}),this._inflightPromise)}replaceDirectConfig(e){this.ensureNotDisposed();const t=this._validateDirectConfig(e);this._nextDirectConfig=t,this._cachedConfig=null,this._cachedAt=null}async _fetchConfig(){const e=this._context.options.connectConfig;if(e.type==="direct"){const t=this._nextDirectConfig??this._validateDirectConfig(e.config),i={livekitUrl:t.sfuUrl,token:t.userToken};return this._cache(i),this._nextDirectConfig=null,i}return this._fetchAuthConfigWithRetry(e.config.authToken||"")}_fromAuthPayload(e){if(!e.livekitUrl||!e.roomToken)throw this._context.emitError("Invalid connection config payload",L.SDK_GET_LIVEKIT_CONFIG_FAILED);return{livekitUrl:e.livekitUrl,token:e.roomToken,roomId:e.roomId,videoOptions:{renderMode:e.greenScreen?.enabled?"processed":"raw",greenScreen:{enabled:!!e.greenScreen?.enabled,...e.greenScreen}}}}_cache(e){this._cachedConfig=e,this._cachedAt=Date.now()}async _fetchAuthConfigWithRetry(e){let t=null;for(let i=1;i<=ht.AUTH_RETRY_MAX_ATTEMPTS;i++)try{const s=this._context.authToken||e;this._context.setAuthToken(s),await this._httpController.getAuthToken();const r=await this._httpController.fetchConnectionConfig(),a=this._fromAuthPayload(r);return this._cache(a),a}catch(s){if(t=s,i>=ht.AUTH_RETRY_MAX_ATTEMPTS)break;await this._delay(ht.AUTH_RETRY_BASE_DELAY_MS*i)}throw this._context.emitError(t||"Failed to fetch auth connection config",L.SDK_GET_LIVEKIT_CONFIG_FAILED)}_delay(e){return new Promise(t=>setTimeout(t,e))}_validateDirectConfig(e){const t=(e.sfuUrl||"").trim(),i=(e.userToken||"").trim();if(!t||!i)throw this._context.emitError("Invalid direct connection config",L.SDK_PRECONNECT_FAILED);return{sfuUrl:t,userToken:i}}onDispose(){this._cachedConfig=null,this._cachedAt=null,this._inflightPromise=null,this._nextDirectConfig=null}}ht.AUTH_RETRY_MAX_ATTEMPTS=2,ht.AUTH_RETRY_BASE_DELAY_MS=300;class Fa extends Y{constructor(e){super(),this._videoController=null,this._audioController=null,this._conversationController=null,this._cameraController=null,this._liveKitService=null,this._connectionCoordinator=null,this._httpController=null,this._configManager=null,this._performanceMonitor=null,this._pendingDirectConfig=null,this._isReconnectInProgress=!1,this._reconnectPromise=null,this._liveKitProtocolDispatcher=null,this._context=new Ya(e),m.info("SDK Client created")}get events(){return this.ensureNotDisposed(),this._publicEventAPI||(this._publicEmitter=new ap(this._context.eventBus),this._publicEventAPI=this._publicEmitter.publicAPI()),this._publicEventAPI}sendTextQuestion(e){if(this.ensureNotDisposed(),this._ensureConnected(),this._conversationController)return this._conversationController.sendQuestion(e);throw new H(L.CONVERSATION_CONTROLLER_NOT_AVAILABLE,"Conversation controller is not available")}async interrupt(){if(this.ensureNotDisposed(),this._ensureConnected(),this._conversationController)return this._conversationController.interrupt();throw new H(L.CONVERSATION_CONTROLLER_NOT_AVAILABLE,"Conversation controller is not available")}setPerformanceMetricReporter(e){if(this.ensureNotDisposed(),!this._performanceMonitor){this._performanceMonitor=new Ua(e),this._performanceMonitor.setContext(this._context);return}this._performanceMonitor.setReporter(e)}setRenderFitMode(e){this.ensureNotDisposed(),this._ensureConnected(),this._videoController&&this._videoController.setRenderFitMode(e)}async startAudioCapture(){this.ensureNotDisposed(),this._ensureConnected(),await this._startAudioCaptureRtc()}async stopAudioCapture(){this.ensureNotDisposed(),this._ensureConnected(),await this._stopAudioCaptureRtc()}setVolume(e){this.ensureNotDisposed(),this._ensureConnected(),this._requireAudioController().setVolume(e)}getVolume(){return this.ensureNotDisposed(),this._ensureConnected(),this._requireAudioController().getVolume()||1}mute(){this.ensureNotDisposed(),this._ensureConnected(),this._requireAudioController().mute()}unmute(){this.ensureNotDisposed(),this._ensureConnected(),this._requireAudioController().unmute()}get isMuted(){return this.ensureNotDisposed(),this._ensureConnected(),this._requireAudioController().isMuted()}get isAudioCapturing(){return this.ensureNotDisposed(),this._ensureConnected(),this._liveKitService?.isMicrophoneActive()??!1}setAuthToken(e){this.ensureNotDisposed(),this._context.setAuthToken(e),this._httpController&&this._httpController.getAuthToken()}updateConnectionConfig(e){if(this.ensureNotDisposed(),this._context.options.connectConfig.type!=="direct")throw this._context.emitError(new H(L.SDK_INVALID_STATE_TRANSITION,"updateConnectionConfig is only available in direct mode"),L.SDK_INVALID_STATE_TRANSITION);this._pendingDirectConfig=this._validateDirectConnectionConfig(e)}async startCamera(){this.ensureNotDisposed(),this._ensureConnected(),await this._requireLiveKitService().startCamera()}stopCamera(){this.ensureNotDisposed(),this._ensureConnected(),this._liveKitService?.stopCamera()}getCameraStream(){return this.ensureNotDisposed(),this._ensureConnected(),this._cameraController?.getStream()??null}getCameraTrack(){return this.ensureNotDisposed(),this._ensureConnected(),this._cameraController?.getTrack()??null}attachCameraTo(e){this.ensureNotDisposed(),this._ensureConnected(),this._requireLiveKitService().attachCameraTo(e)}async preConnect(){this.ensureNotDisposed();try{this._ensureConfigManagerReady();const e=await this._configManager.preConnect();return this._applyConnectionConfig(e),!0}catch(e){throw this._context.emitError(e,L.SDK_PRECONNECT_FAILED)}}async connect(){if(this.ensureNotDisposed(),this._ensurePerformanceMonitorReady(),this._performanceMonitor?.startConnectMeasurement(),this._connectionCoordinator&&this._context.sessionState.isConnected){m.warn("SDK already initialized");return}try{this._ensureConfigManagerReady();const e=this._configManager.getValidConfig();if(e)this._applyConnectionConfig(e);else if(!await this.preConnect())throw new H(L.SDK_CONNECT_FAILED,"PreConnect failed without explicit error")}catch(e){throw this._context.emitError(e,L.SDK_CONNECT_FAILED)}try{await this._disposeConnectionRuntimeBeforeConnect(),m.info("Initializing SDK..."),this._connectionCoordinator=new Za,this._connectionCoordinator.setContext(this._context),this._context.bindConnectionState(()=>this._connectionCoordinator.getState()),this._connectionCoordinator.start(),this._connectionCoordinator.startConnecting(),this._bootstrapDomainControllers(),this._bootstrapLiveKitService(),this._wireLiveKitEventAdapterToControllers(),this._setupRtcProtocolDispatcher(),await this._establishMediaAndSessionTransports(),m.info("SDK initialized and connected")}catch(e){throw this._connectionCoordinator&&this._connectionCoordinator.transitionToIdle(),await this._cleanup(),this._context.emitError(e,L.SDK_INITIALIZATION_FAILED)}}async disconnect(){if(this.ensureNotDisposed(),!(!this._connectionCoordinator||this._connectionCoordinator.getState()==="idle"||this._connectionCoordinator.getState()==="disposed")){m.info("Disconnecting SDK..."),this._connectionCoordinator.startDisconnecting();try{this._audioController&&this._audioController.stopWsCapture(),this._liveKitService&&(await this._liveKitService.sendSystemEvent("session.stop"),await this._liveKitService.disconnect()),this._cameraController&&this._cameraController.stopCamera(),this._connectionCoordinator.completeDisconnecting(),m.info("SDK disconnected")}catch(e){throw m.error("Error during disconnect:",e),this._context.emitError(e,L.SDK_DISCONNECT_FAILED)}}}async reconnect(){if(this.ensureNotDisposed(),this._reconnectPromise)return this._reconnectPromise;const e=this._connectionCoordinator;if(!e?.canStartReconnectingManual()){const i=e?e.getSnapshot():this.connectionSnapshot;return m.warn("SDK reconnect not allowed in current state, returning current snapshot"),i}const t=e.captureSnapshotAndStartReconnectingManual();return this._reconnectPromise=(async()=>{this._isReconnectInProgress=!0;try{return await this.disconnect(),this._stageDirectConfigForNextReconnect(),await this._refreshConnectionConfigForReconnect(),await this.connect(),t}catch(i){throw m.error("Error during reconnect:",i),this._context.emitError(i,L.SDK_RECONNECT_FAILED)}finally{this._isReconnectInProgress=!1,this._reconnectPromise=null}})(),this._reconnectPromise}get connectionSnapshot(){return this.ensureNotDisposed(),this._connectionCoordinator?this._connectionCoordinator.getSnapshot():bs(_s("idle"))}async _cleanup(){if(this._conversationController?.setRtcTextSender(null),this._liveKitService?.setProtocolMessageDispatcher(null),this._liveKitProtocolDispatcher&&(this._liveKitProtocolDispatcher.dispose(),this._liveKitProtocolDispatcher=null),this._audioController&&this._audioController.stopWsCapture(),this._liveKitService)try{await this._liveKitService.disconnect()}catch(e){m.error("Error disconnecting LiveKit:",e)}this._cameraController&&this._cameraController.stopCamera()}async _disposeConnectionRuntimeBeforeConnect(){await this._cleanup(),this._conversationController?.setRtcTextSender(null),this._liveKitService?.setProtocolMessageDispatcher(null),this._liveKitProtocolDispatcher&&(this._liveKitProtocolDispatcher.dispose(),this._liveKitProtocolDispatcher=null),this._videoController?.dispose(),this._videoController=null,this._audioController?.dispose(),this._audioController=null,this._cameraController?.dispose(),this._cameraController=null,this._conversationController?.dispose(),this._conversationController=null,this._liveKitService?.dispose(),this._liveKitService=null,this._connectionCoordinator?.dispose(),this._connectionCoordinator=null}_bootstrapDomainControllers(){this._videoController=new rc(this._context.options.video),this._videoController.setContext(this._context),this._performanceMonitor?.bindVideoElement(this._videoController.getSource().getInternalElement()),this._audioController=new mc(this._context.options.audio),this._audioController.setContext(this._context),this._cameraController=new Pc,this._cameraController.setContext(this._context),this._conversationController=new Oc,this._conversationController.setContext(this._context)}_bootstrapLiveKitService(){this._liveKitService=new rp,this._liveKitService.setContext(this._context)}_wireLiveKitEventAdapterToControllers(){if(this._liveKitService&&this._videoController&&this._audioController){const e=this._liveKitService.getEventAdapter();e&&(typeof e.setVideoController=="function"&&e.setVideoController(this._videoController),typeof e.setAudioController=="function"&&e.setAudioController(this._audioController))}}_setupRtcProtocolDispatcher(){this._liveKitProtocolDispatcher&&(this._liveKitProtocolDispatcher.dispose(),this._liveKitProtocolDispatcher=null),this._liveKitProtocolDispatcher=new op,this._liveKitProtocolDispatcher.setContext(this._context),this._liveKitProtocolDispatcher.setConversationManager(this._conversationController.manager),this._liveKitService.setProtocolMessageDispatcher(e=>{this._liveKitProtocolDispatcher.dispatch(e)}),this._conversationController.setRtcTextSender(this._liveKitService)}async _establishMediaAndSessionTransports(){await this._liveKitService.connect(this._context.livekitUrl,this._context.token,this._context.options.connectConfig.type==="auth"?this._context.options.connectConfig.config.avatarId:"")}async _refreshConnectionConfigForReconnect(){this._ensureConfigManagerReady();const e=await this._configManager.refreshConfig();this._applyConnectionConfig(e)}_ensureConfigManagerReady(){m.info("Creating HTTP controller..."),this._httpController=this._httpController??new lp(this._context.options.http?.baseURL,this._context.options.http?.headers),this._httpController.setContext(this._context),this._configManager=this._configManager??new ht(this._httpController),this._configManager.setContext(this._context)}_applyConnectionConfig(e){this._context.setLivekitConfig(e.livekitUrl,e.token,e.roomId||""),e.videoOptions&&this._context.setVideoOptions(e.videoOptions),this._context.options.connectConfig.type==="auth"&&this._context.eventBus.emit("inner:sdk:connected",{source:"http"})}_stageDirectConfigForNextReconnect(){this._context.options.connectConfig.type==="direct"&&this._pendingDirectConfig&&(this._ensureConfigManagerReady(),this._configManager.replaceDirectConfig(this._pendingDirectConfig),this._pendingDirectConfig=null)}_validateDirectConnectionConfig(e){const t=(e?.sfuUrl||"").trim(),i=(e?.userToken||"").trim();if(!t||!i)throw this._context.emitError(new H(L.SDK_PRECONNECT_FAILED,"Invalid direct connection config"),L.SDK_PRECONNECT_FAILED);return{sfuUrl:t,userToken:i}}_ensurePerformanceMonitorReady(){const e=this._context.options.performanceMonitor;if(!(e?.enabled!==!1)){this._performanceMonitor?.dispose(),this._performanceMonitor=null;return}if(this._performanceMonitor){this._performanceMonitor.setReporter(e?.reporter);return}this._performanceMonitor=new Ua(e?.reporter),this._performanceMonitor.setContext(this._context)}get isConnected(){return this.ensureNotDisposed(),this._context.sessionState.isConnected}_ensureConnected(){if(!this._context.sessionState.isConnected)throw new H(L.SDK_NOT_CONNECTED,"SDK is not connected. Call connect() first.")}async _startAudioCaptureRtc(){await this._requireLiveKitService().startMicrophone()}async _stopAudioCaptureRtc(){await this._requireLiveKitService().stopMicrophone()}_requireAudioController(){if(!this._audioController)throw new H(L.AUDIO_CONTROLLER_NOT_AVAILABLE,"Audio controller is not available");return this._audioController}_requireLiveKitService(){if(!this._liveKitService)throw new H(L.LIVEKIT_CONNECT_FAILED,"LiveKit service is not available");return this._liveKitService}onDispose(){this.disconnect().catch(e=>{m.error("Error during disconnect in dispose:",e)}),this._videoController&&(this._videoController.dispose(),this._videoController=null),this._audioController&&(this._audioController.dispose(),this._audioController=null),this._cameraController&&(this._cameraController.dispose(),this._cameraController=null),this._conversationController?.setRtcTextSender(null),this._liveKitService?.setProtocolMessageDispatcher(null),this._liveKitProtocolDispatcher&&(this._liveKitProtocolDispatcher.dispose(),this._liveKitProtocolDispatcher=null),this._conversationController&&(this._conversationController.dispose(),this._conversationController=null),this._liveKitService&&(this._liveKitService.dispose(),this._liveKitService=null),this._httpController&&(this._httpController.dispose(),this._httpController=null),this._configManager&&(this._configManager.dispose(),this._configManager=null),this._performanceMonitor&&(this._performanceMonitor.dispose(),this._performanceMonitor=null),this._connectionCoordinator&&(this._connectionCoordinator.transitionToDisposed(),this._connectionCoordinator.dispose(),this._connectionCoordinator=null),this._context.dispose(),m.info("SDK Client disposed")}}function up(n){const e=n.connectConfig;if(e.type==="direct"&&(!e.config.sfuUrl||!e.config.userToken))throw new H(L.INVALID_CONNECT_CONFIG,"Invalid direct connect config");if(e.type==="auth"&&!e.config.avatarId)throw new H(L.NO_AVATARID,"avatarId is required");return new Fa(n)}class Va extends Y{constructor(e,t){super(),this._videoElement=null,this._videoUrl=null,this._isPlaying=!1,this._frameCallbackId=null,this._videoUrl=e,t?this._videoElement=t:(this._videoElement=document.createElement("video"),this._videoElement.style.opacity="0",this._videoElement.muted=!0,this._videoElement.playsInline=!0,this._videoElement.loop=!0,document.querySelector("#video-container")?.appendChild(this._videoElement)),m.info("Local Video Debug Source created")}get videoElement(){return this._videoElement}async load(){if(!this._videoElement)throw new Error("Video element or URL not set");return new Promise((e,t)=>{const i=this._videoElement,s=()=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),m.info(`Video loaded: ${i.videoWidth}x${i.videoHeight}`),e()},r=a=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),t(new Error(`Failed to load video: ${a}`))};i.addEventListener("loadedmetadata",s),i.addEventListener("error",r),i.src=this._videoUrl||"",i.load()})}async play(){if(!this._videoElement)throw new Error("Video element not set");if(!this._isPlaying)try{await this._videoElement.play(),this._videoElement.style.opacity="0",this._videoElement.setAttribute("loop","true"),this._isPlaying=!0,m.info("Video playback started")}catch(e){throw m.error("Failed to play video:",e),e}}pause(){this._videoElement&&this._isPlaying&&(this._videoElement.pause(),this._isPlaying=!1,m.info("Video playback paused"))}stop(){this._videoElement&&(this._videoElement.pause(),this._videoElement.currentTime=0,this._isPlaying=!1,m.info("Video playback stopped"))}get isPlaying(){return this._isPlaying&&this._videoElement!==null&&!this._videoElement.paused}get videoWidth(){return this._videoElement?.videoWidth||0}get videoHeight(){return this._videoElement?.videoHeight||0}async captureFrame(){if(!this._videoElement||this._videoElement.readyState<2)return null;try{if("VideoFrame"in window&&typeof window.VideoFrame=="function")try{return new VideoFrame(this._videoElement,{timestamp:this._videoElement.currentTime*1e6})}catch(i){m.error("",i)}const e=await createImageBitmap(this._videoElement),t=new VideoFrame(e,{timestamp:this._videoElement.currentTime*1e6});return e.close(),t}catch(e){return m.error("Failed to capture video frame:",e),null}}onFrame(e){if(!this._videoElement)return;this.offFrame();const t=this._videoElement;if("requestVideoFrameCallback"in t){const i=(s,r)=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(a=>{a&&(e(a),a.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=t.requestVideoFrameCallback(i))}).catch(a=>{m.error("Error in frame callback:",a)})};this._frameCallbackId=t.requestVideoFrameCallback(i)}else{const i=()=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(s=>{s&&(e(s),s.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=requestAnimationFrame(i))}).catch(s=>{m.error("Error in frame callback:",s)})};this._frameCallbackId=requestAnimationFrame(i)}}offFrame(){this._frameCallbackId!==null&&(this._videoElement&&"cancelVideoFrameCallback"in this._videoElement?this._videoElement.cancelVideoFrameCallback(this._frameCallbackId):cancelAnimationFrame(this._frameCallbackId),this._frameCallbackId=null)}onDispose(){this.stop(),this.offFrame(),this._videoElement&&this._videoElement.parentElement===document.body&&document.body.removeChild(this._videoElement),this._videoElement=null,this._videoUrl=null,m.info("Local Video Debug Source disposed")}}class hp extends Y{constructor(e,t,i){super(),this._outputCanvas=null,this._outputRenderer=null,this._source=new Ts;const s={...e,renderMode:"processed"};this._pipeline=new Ss(this._source,s),this._outputRenderer=new Vi(i,t),this._pipeline.setRenderer(this._outputRenderer),this._outputCanvas=this._outputRenderer.getCanvas(),m.info("Video Pipeline Runner created")}get outputCanvas(){return this._outputCanvas}get processor(){return this._pipeline.strategy.getProcessors()[0]||null}setProcessor(e){this._pipeline.setProcessor(e),m.info("Processor set on pipeline")}async processFrame(e){if(this.ensureNotDisposed(),!this._outputRenderer){m.error("Output renderer not available"),e.close();return}try{const t=this._pipeline.strategy.getProcessors()[0]||null;let i=null;if(t){try{i=t.process(e)}catch(s){m.error("Error processing frame:",s),i=e}if(i===null&&"getImageData"in t){const s=t.getImageData();if(s&&this._outputCanvas&&this._outputRenderer.getContext()){const r=this._outputRenderer.getContext();r&&((this._outputCanvas.width!==s.width||this._outputCanvas.height!==s.height)&&(this._outputCanvas.width=s.width,this._outputCanvas.height=s.height),r.putImageData(s,0,0))}e.close();return}i&&i!==e?(this._outputRenderer.render(i),e.close()):i===e?this._outputRenderer.render(e):e.close()}else this._outputRenderer.render(e)}catch(t){m.error("Error in processFrame:",t),e.close()}}setOutputSize(e,t){this._outputCanvas&&(this._outputCanvas.width=e,this._outputCanvas.height=t,m.info(`Output canvas size set to ${e}x${t}`))}onDispose(){this._pipeline.dispose(),this._outputRenderer&&(this._outputRenderer.dispose(),this._outputRenderer=null),this._outputCanvas&&this._outputCanvas.parentElement===document.body&&document.body.removeChild(this._outputCanvas),this._outputCanvas=null,m.info("Video Pipeline Runner disposed")}}class pp extends Y{constructor(e,t,i,s){if(super(),this._isRunning=!1,this._videoSource=new Va(e,t),this._options={renderMode:"processed",containerElement:t,...s},this._pipelineRunner=new hp(this._options,t,i),this._options.greenScreen?.enabled){const r=new Bi(this._options.greenScreen);this._pipelineRunner.setProcessor(r),m.info("Green screen processor enabled in debugger")}m.info("Standalone Video Debugger created")}async switchSource(e,t){this.ensureNotDisposed();const i=this._videoSource,s=this._isRunning,r=new Va(e,t);try{await r.load(),s&&await r.play(),r.onFrame(c=>{this._pipelineRunner.processFrame(c).catch(d=>{m.error("Error processing frame:",d)})}),this._videoSource=r;try{i.offFrame(),i.stop(),i.dispose()}catch(c){m.warn("Error disposing old video source during switch:",c)}const a=this._videoSource.videoWidth,o=this._videoSource.videoHeight;a>0&&o>0&&this._pipelineRunner.setOutputSize(a,o)}catch(a){m.error("Failed to switch video source:",a);try{r.dispose()}catch(o){m.warn("Error disposing new video source after failed switch:",o)}throw a}}get outputCanvas(){return this._pipelineRunner.outputCanvas}get videoSource(){return this._videoSource}get processor(){return this._pipelineRunner.processor}setProcessor(e){this._pipelineRunner.setProcessor(e)}updateGreenScreenOptions(e){const t=this._pipelineRunner.processor;if(t&&"updateOptions"in t&&typeof t.updateOptions=="function")t.updateOptions(e),m.info("Green screen options updated");else{const i=this._options.greenScreen||{enabled:!1},s={...i,...e,enabled:e.enabled!==void 0?e.enabled:i.enabled},r=new Bi(s);this._pipelineRunner.setProcessor(r),this._options.greenScreen=s,m.info("Green screen processor recreated with new options")}}async initialize(){this.ensureNotDisposed();try{await this._videoSource.load();const e=this._videoSource.videoWidth,t=this._videoSource.videoHeight;e>0&&t>0&&this._pipelineRunner.setOutputSize(e,t),m.info("Video debugger initialized")}catch(e){throw m.error("Failed to initialize video debugger:",e),e}}async start(){if(this.ensureNotDisposed(),this._isRunning){m.warn("Debugger is already running");return}try{this._videoSource.videoWidth===0&&await this.initialize(),await this._videoSource.play(),this._videoSource.onFrame(e=>{this._pipelineRunner.processFrame(e).catch(t=>{m.error("Error processing frame:",t)})}),this._isRunning=!0,m.info("Video debugger started")}catch(e){throw m.error("Failed to start video debugger:",e),e}}stop(){this._isRunning&&(this._videoSource.stop(),this._videoSource.offFrame(),this._isRunning=!1,m.info("Video debugger stopped"))}pause(){this._isRunning&&(this._videoSource.pause(),m.info("Video debugger paused"))}async resume(){this._isRunning&&(await this._videoSource.play(),m.info("Video debugger resumed"))}get isRunning(){return this._isRunning}onDispose(){this.stop(),this._videoSource.dispose(),this._pipelineRunner.dispose(),m.info("Standalone Video Debugger disposed")}}D.DEFAULT_AUDIO_BUFFER_SIZE=Ha,D.DEFAULT_AUDIO_CHANNELS=Wa,D.DEFAULT_AUDIO_SAMPLE_RATE=Fi,D.DEFAULT_RECONNECT_ATTEMPTS=Yt,D.DEFAULT_RECONNECT_DELAY=Ui,D.DEFAULT_WS_TIMEOUT=Ka,D.Disposable=Y,D.EventBus=fs,D.Logger=m,D.SDKClient=Fa,D.SDKError=H,D.SessionState=gs,D.StandaloneVideoDebugger=pp,D.createClient=up}));
|