sceyt-call 1.2.0 → 1.2.1
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/index.js +1 -1
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! For license information please see index.js.LICENSE.txt */
|
|
2
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["sceyt-call"]=t():e["sceyt-call"]=t()}(this,(()=>{return e={547:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CallStateMachine=void 0;const n=i(578),a=(0,i(645).createLogger)("CallStateMachine");class l{constructor(e){this.callId=e}isValidStateTransition(e,t){var i,n;return null!==(n=null===(i=l.validStateTransitions.get(t))||void 0===i?void 0:i.has(e))&&void 0!==n&&n}setState(e,t,i){return this.isValidStateTransition(e,t)?(a.info(`[25] [CallId: ${this.callId}] Call state changed ${t} -> ${e}, reason: ${i}`,{color:"cyan"}),!0):(a.warn(`[28] [CallId: ${this.callId}] Invalid CallState changed ${t} -> ${e}, reason: ${i}`,{color:"red"}),!1)}updateState(e,t,i){return this.setState(e,t,i)}}t.CallStateMachine=l,l.validStateTransitions=new Map([[n.CallState.Idle,new Set([n.CallState.Connecting,n.CallState.Closed])],[n.CallState.Connecting,new Set([n.CallState.Connected,n.CallState.Closed,n.CallState.Idle])],[n.CallState.Connected,new Set([n.CallState.Closed,n.CallState.Idle])],[n.CallState.Closed,new Set([])]])},758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ParticipantStateMachine=void 0;const n=i(578),a=(0,i(645).createLogger)("ParticipantStateMachine");class l{constructor(e,t){this.userId=e,this.callId=t}isValidParticipantStateTransition(e,t){var i,n;return null!==(n=null===(i=l.validParticipantStateTransitions.get(t))||void 0===i?void 0:i.has(e))&&void 0!==n&&n}isValidConnectionTransition(e,t){var i,n;return null!==(n=null===(i=l.validConnectionTransitions.get(t))||void 0===i?void 0:i.has(e))&&void 0!==n&&n}setState(e,t,i,l){let s=!1;void 0!==e&&void 0!==i&&this.isValidParticipantStateTransition(e,i)?(a.debug(`[43] [CallId: ${this.callId}] Participant state transition: ${i} -> ${e}`),s=!0):e&&a.warn(`[46] [CallId: ${this.callId}] Invalid ParticipantState transition from ${i?n.ParticipantState[i]:"undefined"} to ${e?n.ParticipantState[e]:"undefined"}`,{color:"yellow"}),void 0!==t&&void 0!==l&&this.isValidConnectionTransition(t,l)?(a.debug(`[50] [CallId: ${this.callId}] Connection state transition: ${l} -> ${t}`),s=!0):t&&a.warn(`[53] [CallId: ${this.callId}] Invalid ConnectionState transition from ${l?n.ParticipantConnectionState[l]:"undefined"} to ${t?n.ParticipantConnectionState[t]:"undefined"}`,{color:"yellow"})}updateState(e,t){return this.isValidParticipantStateTransition(e,t)?(this.setState(e,void 0,t,void 0),!0):(a.warn(`[63] [CallId: ${this.callId}] Invalid ParticipantState transition from ${n.ParticipantState[t]} to ${n.ParticipantState[e]}`,{color:"yellow"}),!1)}updateConnectionState(e,t){return this.isValidConnectionTransition(e,t)?(this.setState(void 0,e,void 0,t),!0):(a.warn(`[71] [CallId: ${this.callId}] Invalid ConnectionState transition from ${n.ParticipantConnectionState[t]} to ${n.ParticipantConnectionState[e]}`,{color:"yellow"}),!1)}}t.ParticipantStateMachine=l,l.validParticipantStateTransitions=new Map([[n.ParticipantState.Idle,new Set([n.ParticipantState.Ringing,n.ParticipantState.Declined,n.ParticipantState.Kicked,n.ParticipantState.NoAnswer,n.ParticipantState.Joined,n.ParticipantState.Left])],[n.ParticipantState.Ringing,new Set([n.ParticipantState.Joined,n.ParticipantState.Declined,n.ParticipantState.Kicked,n.ParticipantState.NoAnswer,n.ParticipantState.Idle])],[n.ParticipantState.Joined,new Set([n.ParticipantState.Left,n.ParticipantState.Kicked,n.ParticipantState.Idle])],[n.ParticipantState.Left,new Set([n.ParticipantState.Idle,n.ParticipantState.Joined])],[n.ParticipantState.Declined,new Set([n.ParticipantState.Idle,n.ParticipantState.Joined])],[n.ParticipantState.Kicked,new Set([n.ParticipantState.Idle])],[n.ParticipantState.NoAnswer,new Set([n.ParticipantState.Idle,n.ParticipantState.Joined])]]),l.validConnectionTransitions=new Map([[n.ParticipantConnectionState.Idle,new Set([n.ParticipantConnectionState.Connecting])],[n.ParticipantConnectionState.Connecting,new Set([n.ParticipantConnectionState.Connected,n.ParticipantConnectionState.Disconnected,n.ParticipantConnectionState.Idle])],[n.ParticipantConnectionState.Connected,new Set([n.ParticipantConnectionState.Reconnecting,n.ParticipantConnectionState.Disconnected,n.ParticipantConnectionState.Idle])],[n.ParticipantConnectionState.Reconnecting,new Set([n.ParticipantConnectionState.Connected,n.ParticipantConnectionState.Connecting,n.ParticipantConnectionState.Disconnected,n.ParticipantConnectionState.Idle])],[n.ParticipantConnectionState.Disconnected,new Set([n.ParticipantConnectionState.Idle,n.ParticipantConnectionState.Reconnecting,n.ParticipantConnectionState.Connected])]])},258:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ActiveSpeakerManager=void 0;const a=i(645),l=i(578),s=(0,a.createLogger)("ActiveSpeakerManager");class r{constructor(e){this.speakingStates=new Map,this.activeSpeakers=[],this.dominantSpeaker=null,this.lastActiveSpeakers=[],this.lastDominantSpeaker=null,this.dominantSpeakerLastChangeTime=0,this.processingInterval=null,this.call=null,this.internalCallHandler=null,this.call=e}start(e){var t,i;this.processingInterval||(this.internalCallHandler=e,this.internalCallHandler&&this.call?(this.processingInterval=setInterval((()=>n(this,void 0,void 0,(function*(){var e,t,i,n,a;try{if(this.call&&this.internalCallHandler){if(this.call.localParticipant){let i=0;if(this.call.mediaFlow!==l.MediaFlow.SFU){const t=this.call.participants.find((e=>{var t,i,n,a;return e.id!==(null===(i=null===(t=this.call)||void 0===t?void 0:t.localParticipant)||void 0===i?void 0:i.id)||e.clientId!==(null===(a=null===(n=this.call)||void 0===n?void 0:n.localParticipant)||void 0===a?void 0:a.clientId)}));if(t){const n=null===(e=this.internalCallHandler.callParticipantsRTCMap[this.call.id])||void 0===e?void 0:e[t.getFullId()];if(n){const e=yield n.getConnectionStats(),t=Array.from(e.values()).filter((e=>this.isOutboundAudio(e)||this.isMediaSourceAudio(e))).map((e=>this.getStatsAudioLevel(e))).filter((e=>null!==e));i=t.length>0?Math.max(...t):0}}}else{const e=this.call.serverParticipant;if(e){const n=null===(t=this.internalCallHandler.callParticipantsRTCMap[this.call.id])||void 0===t?void 0:t[e.getFullId()];if(n){const e=yield n.getConnectionStats(),t=Array.from(e.values()).filter((e=>this.isOutboundAudio(e)||this.isMediaSourceAudio(e))).map((e=>this.getStatsAudioLevel(e))).filter((e=>null!==e));i=t.length>0?Math.max(...t):0}}}this.call.localParticipant.muted&&(i=0),this.processAudioLevels(this.call.localParticipant,i)}for(const e of this.call.participants){if(e.id===this.call.localParticipant.id&&e.clientId===this.call.localParticipant.clientId)continue;let t=0;if(this.call.mediaFlow!==l.MediaFlow.SFU){const n=null===(i=this.internalCallHandler.callParticipantsRTCMap[this.call.id])||void 0===i?void 0:i[e.getFullId()];if(n){const e=yield n.getConnectionStats(),i=Array.from(e.values()).filter((e=>this.isInboundAudio(e))).map((e=>this.getStatsAudioLevel(e))).filter((e=>null!==e));t=i.length>0?Math.max(...i):0}}else{const i=null===(n=this.internalCallHandler.callParticipantsRTCMap[this.call.id])||void 0===n?void 0:n[e.getFullId()];if(i){const e=yield i.getConnectionStats(),n=Array.from(e.values()).filter((e=>this.isInboundAudio(e))).map((e=>this.getStatsAudioLevel(e))).filter((e=>null!==e));t=n.length>0?Math.max(...n):0}}e.muted&&(t=0),this.processAudioLevels(e,t)}}this.processActiveSpeakers(),this.call&&(this.call.emitActiveSpeakersChanged(this.activeSpeakers),this.call.emitDominantSpeakerChanged(this.dominantSpeaker))}catch(e){s.error(`[137] [CallId: ${null===(a=this.call)||void 0===a?void 0:a.id}] Error processing audio levels: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"})}}))),r.POLLING_INTERVAL_MS),s.info(`[141] [CallId: ${null===(i=this.call)||void 0===i?void 0:i.id}] Active speaker detection started`)):s.error(`[47] [CallId: ${null===(t=this.call)||void 0===t?void 0:t.id}] Call or InternalCallHandler is not set`,{color:"red"}))}getActiveSpeakers(){return this.activeSpeakers}stop(){var e;this.processingInterval&&(clearInterval(this.processingInterval),this.processingInterval=null),this.activeSpeakers=[],this.dominantSpeaker=null,this.speakingStates.clear(),this.lastActiveSpeakers=[],this.lastDominantSpeaker=null,s.info(`[154] [CallId: ${null===(e=this.call)||void 0===e?void 0:e.id}] Active speaker detection stopped`)}addParticipant(e){var t;const i=this.getParticipantKey(e);this.speakingStates.has(i)||(this.speakingStates.set(i,{participant:e,audioLevel:0,smoothedAudioLevel:0,isSpeaking:!1,speakingStartTime:0}),s.info(`[167] [CallId: ${null===(t=this.call)||void 0===t?void 0:t.id}] Added participant for active speaker detection: ${e.getFullId()}`))}updateParticipant(e){const t=this.getParticipantKey(e),i=this.speakingStates.get(t);i&&this.speakingStates.set(t,Object.assign(Object.assign({},i),{participant:e}))}removeParticipant(e){var t,i,n;const a=this.getParticipantKey(e);this.speakingStates.delete(a),this.lastActiveSpeakers.some((t=>t.participant.id===e.id&&t.participant.clientId===e.clientId))&&this.processActiveSpeakers(),(null===(t=this.lastDominantSpeaker)||void 0===t?void 0:t.participant.id)===e.id&&(null===(i=this.lastDominantSpeaker)||void 0===i?void 0:i.participant.clientId)===e.clientId&&(this.dominantSpeaker=null,this.lastDominantSpeaker=null),s.info(`[199] [CallId: ${null===(n=this.call)||void 0===n?void 0:n.id}] Removed participant from active speaker detection: ${e.getFullId()}`)}getAudioLevel(e){var t,i;const n=this.getParticipantKey(e);return null!==(i=null===(t=this.speakingStates.get(n))||void 0===t?void 0:t.smoothedAudioLevel)&&void 0!==i?i:null}isSpeaking(e){var t,i;const n=this.getParticipantKey(e);return null!==(i=null===(t=this.speakingStates.get(n))||void 0===t?void 0:t.isSpeaking)&&void 0!==i&&i}isDominantSpeaker(e){var t,i;return(null===(t=this.dominantSpeaker)||void 0===t?void 0:t.participant.id)===e.id&&(null===(i=this.dominantSpeaker)||void 0===i?void 0:i.participant.clientId)===e.clientId}processActiveSpeakers(){const e=Date.now(),t=new Map;this.speakingStates.forEach(((i,n)=>{t.set(n,this.updateSpeakingState(i,e))})),this.speakingStates=t;const i=Array.from(this.speakingStates.values()).filter((e=>e.isSpeaking)).sort(((e,t)=>t.smoothedAudioLevel-e.smoothedAudioLevel));JSON.stringify(i)!==JSON.stringify(this.lastActiveSpeakers)&&(this.activeSpeakers=i,this.lastActiveSpeakers=i),this.updateDominantSpeaker(i,e)}updateDominantSpeaker(e,t){if(0===e.length)return void(this.lastDominantSpeaker&&t-this.dominantSpeakerLastChangeTime>r.DOMINANT_SPEAKER_HYSTERESIS_MS&&(this.dominantSpeaker=null,this.lastDominantSpeaker=null));if(!this.lastDominantSpeaker)return this.dominantSpeaker=e[0],this.lastDominantSpeaker=e[0],void(this.dominantSpeakerLastChangeTime=t);const i=e[0];i.participant.id===this.lastDominantSpeaker.participant.id&&i.participant.clientId===this.lastDominantSpeaker.participant.clientId||i.smoothedAudioLevel>.5&&t-i.speakingStartTime>r.DOMINANT_SPEAKER_HYSTERESIS_MS&&(this.dominantSpeaker=i,this.lastDominantSpeaker=i,this.dominantSpeakerLastChangeTime=t)}updateSpeakingState(e,t){const i=e.audioLevel>e.smoothedAudioLevel?Math.max(e.smoothedAudioLevel,e.smoothedAudioLevel+(e.audioLevel-e.smoothedAudioLevel)*r.ACTIVE_LEVEL_BOOST):Math.max(0,e.smoothedAudioLevel-(e.smoothedAudioLevel-e.audioLevel)*r.ACTIVE_LEVEL_DECAY);let n=e.isSpeaking,a=e.speakingStartTime;return i>=r.AUDIO_LEVEL_THRESHOLD?e.isSpeaking||(n=!0,a=t):e.isSpeaking&&t-e.speakingStartTime>r.SPEAKING_TIME_THRESHOLD_MS&&(n=!1),Object.assign(Object.assign({},e),{smoothedAudioLevel:i,isSpeaking:n,speakingStartTime:a})}processAudioLevels(e,t){var i;try{let i=null;if(e.muted)i=0;else if("number"==typeof t)i=t;else{const e=Array.from(t.values()).filter((e=>this.isOutboundAudio(e)||this.isMediaSourceAudio(e))).map((e=>this.getStatsAudioLevel(e))).filter((e=>null!==e));i=e.length>0?Math.max(...e):0}if(null!==i){const t=this.getParticipantKey(e),n=this.speakingStates.get(t);n&&this.speakingStates.set(t,Object.assign(Object.assign({},n),{audioLevel:i}))}}catch(e){s.error(`[330] [CallId: ${null===(i=this.call)||void 0===i?void 0:i.id}] Error processing audio levels: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"})}}getParticipantKey(e){return`${e.id}/${e.clientId}`}isOutboundAudio(e){return"outbound-rtp"===e.type&&"audio"===e.kind}isMediaSourceAudio(e){return"media-source"===e.type&&"audio"===e.kind}getStatsAudioLevel(e){var t;return null!==(t=e.audioLevel)&&void 0!==t?t:null}isInboundAudio(e){return"inbound-rtp"===e.type&&"audio"===e.kind}}t.ActiveSpeakerManager=r,r.AUDIO_LEVEL_THRESHOLD=.1,r.SPEAKING_TIME_THRESHOLD_MS=250,r.DOMINANT_SPEAKER_HYSTERESIS_MS=1e3,r.ACTIVE_LEVEL_DECAY=.2,r.ACTIVE_LEVEL_BOOST=1.5,r.POLLING_INTERVAL_MS=150},250:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AudioTrack=void 0,t.AudioTrack=class{constructor(e){this._enabled=!0,this.id=e.id,this.audioTrack=e}set enabled(e){this._enabled=e,this.audioTrack.enabled=e}get enabled(){return this._enabled}}},271:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SceytCallClient=void 0;const n=i(650),a=i(645),l=i(185),s=i(297),r=i(228),o=(0,a.createLogger)("CallClient");class d extends s.TypedEventEmitter{constructor(e){super(),this.getCall=e=>{o.info(`[20] [CallId: ${e}] Get call from server`,{color:"cyan"});const t=this.internalCallHandler.activeCalls.find((t=>t.id===e));return t?Promise.resolve({success:!0,data:t}):this.internalCallHandler.prepareCallFromCallID(e)},this.getOngoingCalls=()=>(this.internalCallHandler.getCalls(),this.internalCallHandler.activeCalls),this.onLog=e=>((0,a.addLogListener)(e),()=>(0,a.removeLogListener)(e)),this.internalCallHandler=new n.InternalCallHandler(e),this.setupInternalEventBridge()}setupInternalEventBridge(){this.internalCallHandler.setCallEvent("onInvitedToCall",(e=>{this.emit("invitedToCall",{call:e})})),this.internalCallHandler.setCallEvent("onOngoingCallsUpdated",(e=>{this.emit("ongoingCallsUpdated",{calls:e})}))}get activeCalls(){return this.internalCallHandler.activeCalls}prepareCall(e,t){o.info(`[19] [CallId: ${e}] Prepare call`,{color:"cyan"});try{return this.internalCallHandler.prepareCall(e,t)}catch(t){return o.error(`[19] [CallId: ${e}] Prepare call failed: ${t.message||JSON.stringify(t)}`,{color:"red"}),{success:!1,error:(0,r.toCallException)(t)}}}get RecentCallQueryBuilder(){return l.RecentCallQueryBuilder}}t.SceytCallClient=d},998:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Call=void 0;const a=i(302),l=i(65),s=i(650),r=i(578),o=i(547),d=i(645),c=i(258),u=i(297),p=i(228),g=(0,d.createLogger)("Call");class h extends u.TypedEventEmitter{get activeSpeakers(){return this._activeSpeakers}set activeSpeakers(e){this._activeSpeakers=e}constructor({id:e,sessionId:t="",mediaFlow:i,createdBy:a="",localParticipant:l,participants:o,metadata:d,chatClient:u,isCallSilenced:h}){super(),this.state=r.CallState.Idle,this._localAudioTracks=[],this._localVideoTracks=[],this._muted=!1,this._onHold=!1,this._screenSharing=!1,this._activeSpeakers=[],this.videoEnabled=!1,this.eventsQueue=new Map,this.isCallSilenced=!1,this.videoCall=!1,this.isCreatedRemotely=!1,this.videoDeviceId=null,this.audioDeviceId=null,this.getStats=()=>n(this,void 0,void 0,(function*(){try{const e=[];for(const t of this.participants){const i=yield this.getParticipantStats(t);i.success&&i.data&&e.push(i.data)}return{success:!0,data:e}}catch(e){return g.error(`[502] [CallId: ${this.id}] Error getting call stats ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}})),this.getParticipantStats=e=>n(this,void 0,void 0,(function*(){try{g.info(`[503] [CallId: ${this.id}] getParticipantStats for ${e.getFullId()}`,{color:"cyan"});const t=s.InternalCallHandler.getInstance().callParticipantsRTCMap[this.id],i=null==t?void 0:t[e.getFullId()];return i?{success:!0,data:yield i.getConnectionStats()}:{success:!1,error:(0,p.toCallException)(new Error("Participant RTC client not found"))}}catch(e){return g.error(`[504] [CallId: ${this.id}] Error getting participant stats ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}})),this.id=e,this.sessionId=t,this.createdBy=a,this.participants=o,this.localParticipant=l,this.mediaFlow=i,this.metadata=d,this.activeSpeakerManager=new c.ActiveSpeakerManager(this),this.chatClient=u,this.isCallSilenced=h}emitAudioTrackAdded(e,t){this.emit("audioTrackAdded",{call:this,participant:e,track:t})}emitAudioTrackRemoved(e){this.emit("audioTrackRemoved",{call:this,participant:e})}emitVideoTrackAdded(e,t){this.emit("videoTrackAdded",{call:this,participant:e,track:t})}emitVideoTrackRemoved(e){this.emit("videoTrackRemoved",{call:this,participant:e})}emitCallStateChanged(e){this.emit("callStateChanged",{call:this,state:e})}emitParticipantStateChanged(e,t,i){this.emit("participantStateChanged",{call:this,participant:e,state:t,reason:i})}emitParticipantConnectionStateChanged(e,t){this.emit("participantConnectionStateChanged",{call:this,participant:e,state:t})}emitParticipantEvent(e,t){this.emit("participantEvent",{call:this,participant:e,event:t})}emitParticipantsAdded(e){this.emit("participantsAdded",{call:this,participants:e})}emitParticipantsRemoved(e){this.emit("participantsRemoved",{call:this,participants:e})}emitActiveSpeakersChanged(e){this._activeSpeakers=e,this.emit("activeSpeakersChanged",{call:this,activeSpeakers:e})}emitDominantSpeakerChanged(e){this.emit("dominantSpeakerChanged",{call:this,dominantSpeaker:e})}emitMediaFlowChanged(e){this.emit("mediaFlowChanged",{call:this,mediaFlow:e})}emitSessionRenewed(e){this.emit("sessionRenewed",{call:this,sessionId:e})}clearEventsQueue(){this.eventsQueue.clear()}setState(e,t){const i=new o.CallStateMachine(this.id).updateState(e,this.state,t);return i&&(this.state=e,e===r.CallState.Connected?this.activeSpeakerManager.start(s.InternalCallHandler.getInstance()):this.activeSpeakerManager.stop(),this.emitCallStateChanged(e)),i}addParticipants(e){const t=e=>s.InternalCallHandler.getInstance().addParticipantsToCall(e,this);return this.sessionId?t(e):this.eventsQueue.set("ADD_PARTICIPANTS",(()=>t(e))),{success:!0}}join(e,t){g.info(`[J1] [CallId: ${this.id}] Join call`,{color:"cyan"});try{if(!(new a.SendSignalValidator).canSendSignalEvent(r.SignalEvent.JOIN,this)){const e=`Cannot join call with ID ${this.id} due to invalid call state or participant state.`;return g.warn(`[J2] [CallId: ${this.id}] ${e}`,{color:"red"}),{success:!1,error:l.SceytCallException.BadRequest(4006,e)}}const i=s.InternalCallHandler.getInstance().joinCall(this,e,t);return(null==i?void 0:i.data)&&i.data.activeSpeakerManager.addParticipant(i.data.localParticipant),i}catch(e){return g.error(`[J3] [CallId: ${this.id}] Join failed: ${e.message||JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}reject(e,t){try{return g.info(`[R1] [CallId: ${this.id}] Rejecting call`,{color:"cyan"}),s.InternalCallHandler.getInstance().rejectCall(this,e,t),this.activeSpeakerManager.removeParticipant(this.localParticipant),{success:!0}}catch(e){return g.error(`[R2] [CallId: ${this.id}] Rejection failed: ${e.message||JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}leave(){try{return g.info(`[L1] [CallId: ${this.id}] Leaving call`,{color:"cyan"}),s.InternalCallHandler.getInstance().leaveCall(this,!0,"leave"),this.activeSpeakerManager.removeParticipant(this.localParticipant),{success:!0}}catch(e){return g.error(`[L2] [CallId: ${this.id}] Leave failed: ${e.message||JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}create(e){g.info(`[C1] [CallId: ${this.id}] Create call`,{color:"cyan"});try{return s.InternalCallHandler.getInstance().createCall(this,e)}catch(e){return g.error(`[C3] [CallId: ${this.id}] create failed: ${e.message||JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}addParticipantToList(e){this.participants.push(e)}kickParticipantFromList(e,t=!0){if(this.participants=this.participants.filter((t=>t.id!==e.id&&t.clientId!==e.clientId)),t)return s.InternalCallHandler.getInstance().kickParticipantFromCall(e,this)}setSessionId(e){this.sessionId=e}setCreatedBy(e){this.createdBy=e}setVideoCall(e){this.videoCall=e}changeMediaFlow(e){this.mediaFlow!=e&&(this.mediaFlow=e,this.emitMediaFlowChanged(e))}switchToSFU(e){return n(this,void 0,void 0,(function*(){const t=t=>{g.info(`[159] [CallId: ${this.id}] handle switch call to ${r.MediaFlow.SFU}`,{color:"cyan"});const i=s.InternalCallHandler.getInstance(),n=i.activeCalls.find((e=>e.id===t));return i.switchCallToSfu(n,e)};return this.sessionId?t(this.id):this.eventsQueue.set(r.SignalEvent.SWITCH_MEDIA_FLOW,(()=>t(this.id))),{success:!0}}))}mute(e,t){this.muted=e,this.localParticipant.setMuted(e,this);const i=e=>{s.InternalCallHandler.getInstance().sendAudioEnable(this,e,t)};return this.sessionId?i(e):this.eventsQueue.set(r.SignalEvent.MUTE,(()=>i(e))),{success:!0}}hold(e){this.onHold=e,this.localAudioTracks.forEach((t=>{t.enabled=!e})),this.localVideoTracks.forEach((t=>{t.enabled=!e})),this.localParticipant.audioTracks.forEach((t=>{t.enabled=!e})),this.localParticipant.videoTracks.forEach((t=>{t.enabled=!e}));const t=e=>{s.InternalCallHandler.getInstance().sendHold(this,e)};return this.sessionId?t(e):this.eventsQueue.set(r.SignalEvent.HOLD,(()=>t(e))),{success:!0}}set localAudioTracks(e){this._localAudioTracks=e}get localAudioTracks(){return this._localAudioTracks}set localVideoTracks(e){this._localVideoTracks=e}get localVideoTracks(){return this._localVideoTracks}setServerParticipant(e){this.serverParticipant=e}set muted(e){this._muted=e}get muted(){return this._muted}set screenSharing(e){this._screenSharing=e}get screenSharing(){return this._screenSharing}set onHold(e){this._onHold=e}get onHold(){return this._onHold}setIsCallSilenced(e){this.isCallSilenced=e}getIsCallSilenced(){return this.isCallSilenced}setVideoDeviceId(e){this.videoDeviceId=e}getVideoDeviceId(){return this.videoDeviceId}setAudioDeviceId(e){this.audioDeviceId=e}getAudioDeviceId(){return this.audioDeviceId}setIsCreatedRemotely(e){this.isCreatedRemotely=e}getIsCreatedRemotely(){return this.isCreatedRemotely}enableVideo(e,t){return n(this,void 0,void 0,(function*(){return this.localParticipantVideoEnable(e,t)}))}localParticipantVideoEnable(e,t,i,a=!0){return n(this,void 0,void 0,(function*(){const l=s.InternalCallHandler.getInstance();let o=[];return this.localVideoTracks.forEach((e=>{e.stop()})),this.localParticipant.videoTracks.forEach((e=>{e.enabled=!1})),yield(()=>n(this,void 0,void 0,(function*(){var s,d,c;try{if(e){const e=(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind));this.videoDeviceId&&(e.some((e=>e.deviceId===this.videoDeviceId))||(g.warn(`Previously selected video device with ID ${this.videoDeviceId} not found. Falling back to default camera.`),this.setVideoDeviceId(null)));const t=yield navigator.mediaDevices.getUserMedia({video:Object.assign(Object.assign({},this.videoDeviceId?{deviceId:{exact:this.videoDeviceId}}:{}),{width:{min:640,max:1280},height:{min:480,max:720}})});o=t.getVideoTracks(),o.sort(((e,t)=>(e.getSettings().deviceId||"")===this.videoDeviceId?-1:1)),this.setVideoDeviceId((null===(s=o[0])||void 0===s?void 0:s.getSettings().deviceId)||null)}else o=this.localVideoTracks;!this.videoDeviceId&&o.length>0&&this.setVideoDeviceId((null===(d=o[0])||void 0===d?void 0:d.getSettings().deviceId)||null),this.setVideoEnabled(e),this.localVideoTracks=o,this.localParticipant.setVideoTracks(o,this),this.localParticipant.setParticipantVideoEnabled(e,this),this.localParticipant.videoTracks.forEach((t=>{t.enabled=e})),i&&this.localVideoTracks&&(null===(c=this.localVideoTracks)||void 0===c?void 0:c.length)&&(yield l.changeVideoTracks(this,this.localVideoTracks[0],e));const u=(e,i)=>n(this,void 0,void 0,(function*(){try{yield l.changeVideoTracks(this,i,e),l.sendVideoEnabled(this,e,t)}catch(e){return g.error(`[323] [CallId: ${this.id}] Failed to send video enabled signal: message: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),void(null==t||t({error:(0,p.toCallException)(e)}))}}));a&&(this.sessionId?u(e,o[0]):this.eventsQueue.set(e?r.SignalEvent.VIDEO_ON:r.SignalEvent.VIDEO_OFF,(()=>u(e,o[0]))))}catch(e){return g.error(`[325] [CallId: ${this.id}] Error enabling video ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}})))(),{success:!0}}))}shareScreen(e,t){return n(this,void 0,void 0,(function*(){let i=[];this.screenSharing=e;try{if(e){const t=yield navigator.mediaDevices.getDisplayMedia({video:{width:{max:1280},height:{max:720},frameRate:{max:30}}});if(this.localVideoTracks.forEach((e=>{e.stop()})),i=t.getVideoTracks(),t.addEventListener("inactive",(()=>{this.localParticipant.screenSharing&&this.stopScreenShare()})),this.localVideoTracks=i,this.localParticipant.setVideoTracks(i,this),this.localParticipant.videoTracks.forEach((t=>{t.enabled=e})),i&&i.length){const t=s.InternalCallHandler.getInstance();yield t.changeVideoTracks(this,i[0],e,!0)}this.localParticipant.setScreenSharing(e,this)}else this.localParticipant.videoEnabled&&!e&&(this.localParticipant.setScreenSharing(e,this),yield this.localParticipantVideoEnable(!0,t,!0));const a=e=>n(this,void 0,void 0,(function*(){const i=s.InternalCallHandler.getInstance();yield i.sendScreenShare(this,e,t)}));return this.sessionId?a(e):this.eventsQueue.set(e?r.SignalEvent.SCREEN_SHARE_ON:r.SignalEvent.SCREEN_SHARE_OFF,(()=>a(e))),{success:!0}}catch(e){return g.error(`[324] [CallId: ${this.id}] Error sharing screen ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}))}startScreenShare(e){return n(this,void 0,void 0,(function*(){return this.shareScreen(!0,e)}))}stopScreenShare(e){return n(this,void 0,void 0,(function*(){return yield this.shareScreen(!1,e)}))}getAvailableVideoDevices(){return n(this,void 0,void 0,(function*(){try{return{success:!0,data:(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))}}catch(e){return g.error(`[306] [CallId: ${this.id}] Error getting video devices ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}))}getAvailableAudioDevices(){return n(this,void 0,void 0,(function*(){try{return{success:!0,data:(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))}}catch(e){return g.error(`[307] [CallId: ${this.id}] Error getting audio devices ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}))}selectVideoDevice(e){return n(this,void 0,void 0,(function*(){if(this.setVideoDeviceId(e),!this.videoEnabled||this.localParticipant.screenSharing)return{success:!0};try{this.localVideoTracks.forEach((e=>{e.stop()}));const t=(yield navigator.mediaDevices.getUserMedia({video:{deviceId:{exact:e},width:{min:640,max:1280},height:{min:480,max:720}}})).getVideoTracks();this.localVideoTracks=t,this.localParticipant.setVideoTracks(t,this);const i=s.InternalCallHandler.getInstance();return yield i.changeVideoTracks(this,t[0],this.localParticipant.videoEnabled),{success:!0}}catch(e){return g.error(`[308] [CallId: ${this.id}] Error selecting video device ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}))}selectAudioDevice(e){var t;return n(this,void 0,void 0,(function*(){try{const i=s.InternalCallHandler.getInstance(),n=(yield navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e}}})).getAudioTracks();return this.localAudioTracks=n,this.localParticipant.setAudioTracks(n,this),this.setAudioDeviceId((null===(t=n[0])||void 0===t?void 0:t.getSettings().deviceId)||null),yield i.changeAudioTracks(this,n[0],this.localParticipant.muted),{success:!0}}catch(e){return g.error(`[309] [CallId: ${this.id}] Error selecting audio device ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}))}setVideoEnabled(e){this.videoEnabled=e}setMuted(e){this._muted=e}getParticipant(e,t){return this.participants.find((i=>i.id===e&&i.clientId===t))}sendRinging(e){return s.InternalCallHandler.getInstance().sendRinging(this,e)}setSettings(e){return this.settings=e,{success:!0}}toJson(){return{id:this.id,sessionId:this.sessionId,mediaFlow:this.mediaFlow,participants:this.participants,localParticipant:this.localParticipant,createdBy:this.createdBy,metadata:this.metadata,state:this.state,activeSpeakerManager:this.activeSpeakerManager,eventsQueue:this.eventsQueue,chatClient:this.chatClient,serverParticipant:this.serverParticipant,videoEnabled:this.videoEnabled,onHold:this.onHold,localAudioTracks:this.localAudioTracks,localVideoTracks:this.localVideoTracks,muted:this.muted,isCallSilenced:this.isCallSilenced}}}t.Call=h},228:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkCode=t.toCallException=t.handleAck=void 0;const n=i(65);function a(e,t){switch(e){case 4e3:return n.SceytCallException.BadSignal(e,t);case 4001:return n.SceytCallException.CallNotFound(e,t);case 4002:return n.SceytCallException.ParticipantNotFound(e,t);case 4005:case 4003:return n.SceytCallException.NotAllowed(e,t);case 4004:return n.SceytCallException.ParticipantAlreadyExists(e,t);case 5001:return n.SceytCallException.InternalError(e,t);case 9901:case 9903:case 9904:return n.SceytCallException.NetworkError(e,t);case 9902:return n.SceytCallException.Timeout(e,t);case 4006:return n.SceytCallException.BadRequest(e,t);default:return n.SceytCallException.Unknown(e,t)}}t.handleAck=function(e){return e.error&&a(e.error.code,e.error.message),e},t.toCallException=function(e){try{if(null==e?void 0:e.code)return a(e.code,e.message)}catch(e){if(e instanceof n.SceytCallException)return e}return n.SceytCallException.Unknown(void 0,(null==e?void 0:e.message)||String(e))},t.checkCode=a},65:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SceytCallException=void 0;class i extends Error{get isResendable(){return this._isResendable}constructor(e,t,i="SceytCallException"){super(e),this.code=t,this.name=i,this._isResendable=!1,this.name=i}static BadSignal(e,t){return new i(t,e,"BadSignal")}static CallNotFound(e,t){return new i(t,e,"CallNotFound")}static ParticipantNotFound(e,t){return new i(t,e,"ParticipantNotFound")}static NotAllowed(e,t){return new i(t,e,"NotAllowed")}static ParticipantAlreadyExists(e,t){return new i(t,e,"ParticipantAlreadyExists")}static InternalError(e,t){const n=new i(t,e,"InternalError");return n._isResendable=!0,n}static NetworkError(e,t){const n=new i(t,e,"NetworkError");return n._isResendable=!0,n}static Timeout(e,t){const n=new i(t,e,"Timeout");return n._isResendable=!0,n}static BadRequest(e,t){return new i(t,e,"BadRequest")}static Unknown(e,t){return new i(t,e)}}t.SceytCallException=i},650:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.InternalCallHandler=void 0;const l=a(i(583)),s=i(787),r=i(546),o=i(786),d=i(578),c=i(998),u=i(489),p=i(645),g=i(429),h=i(65),v=i(680),S=i(228),C=(0,p.createLogger)("InternalCallHandler");class f{constructor(e){this.callParticipantsRTCMap={},this.activeCalls=[],this.prepareCalls=[],this.callEvents={},this.handleMediaConnectedSignal=e=>{const t=this.activeCalls.find((t=>t.id===e.callId));if(t){let i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));if(i||(i=t.participants.find((t=>t.id===e.from.split("/")[0]&&!t.clientId)),i?i.clientId=e.from.split("/")[1]:(i=new s.Participant(e.from),t.addParticipantToList(i),t.emitParticipantsAdded([i]))),i&&t.localParticipant.state===d.ParticipantState.Joined&&t.localParticipant.getFullId()!==i.getFullId()&&(!this.callParticipantsRTCMap[t.id]||!this.callParticipantsRTCMap[t.id][i.getFullId()]||(null==i?void 0:i.shouldResetPeerConnection))){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[968] [CallId: ${t.id}] SYNC CONNECT failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`):e.event!==d.SignalEvent.ERROR||C.error(`[971] [CallId: ${t.id}] SYNC CONNECT failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`)};C.info(`[975] [CallId: ${t.id}] SYNC CONNECT to participant ${i.getFullId()}`,{color:"blue"}),this.signalingClient.clearParticipantSignals(t.id,i.getFullId()),this.signalingClient.sendSignalMessage({to:i.getFullId(),event:d.SignalEvent.CONNECT,mediaFlow:t.mediaFlow,callId:t.id,sessionId:t.sessionId},e)}}},this.onIceCandidate=(e,t,i)=>{var n,a;if(i.mediaFlow!==d.MediaFlow.SFU)if(C.info(`[996] [CallId: ${i.id}] onIceCandidate, participantID: ${e.getFullId()}, candidate: ${null===(n=t.candidate)||void 0===n?void 0:n.candidate}, type: ${null===(a=t.candidate)||void 0===a?void 0:a.type}`,{color:"blue"}),t.candidate&&t.candidate.candidate){let n="";if(!/\bufrag\s+\S+/i.test(t.candidate.candidate)&&this.callParticipantsRTCMap[i.id]&&this.callParticipantsRTCMap[i.id][e.getFullId()]){const t=this.callParticipantsRTCMap[i.id][e.getFullId()];t&&(n=` ufrag ${t.getLocalSdpUfrag()}`)}const a={candidate:t.candidate.candidate+n,sdpMid:t.candidate.sdpMid||"",sdpMLineIndex:t.candidate.sdpMLineIndex||0};try{const t=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[1007] [CallId: ${i.id}] SYNC ICE failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`):e.event!==d.SignalEvent.ERROR||C.error(`[1011] [CallId: ${i.id}] SYNC ICE failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`)};this.signalingClient.sendSignalMessage({to:this.getParticipantId(e),event:d.SignalEvent.ICE,mediaFlow:i.mediaFlow,callId:i.id,sessionId:i.sessionId,ice:a},t)}catch(t){C.error(`[1023] [CallId: ${i.id}] Failed to send ICE candidate to ${e.getFullId()}: ${t instanceof Error?t.message:JSON.stringify(t)}`)}}else C.info(`[1025] [CallId: ${i.id}] ICE gathering complete for participant ${e.getFullId()} (null candidate)`,{color:"blue"});else C.info(`[1024] [CallId: ${i.id}] onIceCandidate, participantID: ${e.getFullId()}, skip for SFU`,{color:"blue"})},this.onTrack=(e,t,i)=>{const n=null==i?void 0:i.track;C.info(`[1032] [CallId: ${e.id}] onTrack, participantID: ${t.getFullId()}, kind: ${n.kind}`,{color:"blue"}),"audio"===(null==n?void 0:n.kind)?(t.setAudioTracks([n],e),n.onended=()=>{C.info(`[1038] [CallId: ${e.id}] Audio track ended for participant ${t.getFullId()}`,{color:"yellow"}),t.setAudioTracks([],e),e.emitAudioTrackRemoved(t)}):"video"===(null==n?void 0:n.kind)&&(t.setVideoTracks([n],e),n.onended=()=>{C.info(`[1052] [CallId: ${e.id}] Video track ended for participant ${t.getFullId()}`,{color:"yellow"}),t.setVideoTracks([],e),e.emitVideoTrackRemoved(t)})},this.kickParticipantFromCall=(e,t)=>{this.signalingClient.sendSignalMessage({mediaFlow:t.mediaFlow,callId:t.id,event:d.SignalEvent.KICK,sessionId:t.sessionId,participants:[{id:e.id,clientId:e.clientId}]},(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[1642] [CallId: ${t.id}] Kick participant failed: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[1646] [CallId: ${t.id}] Kick participant failed: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})}))},this.addParticipantsToCall=(e,t)=>{try{if(e.forEach((e=>{const i=t.participants.filter((t=>t.id===e));if(i.length>0)for(const e of i)e.state!==d.ParticipantState.Joined&&e.state!==d.ParticipantState.Ringing&&(e.updateState(d.ParticipantState.Idle,t.id),e.updateConnectionState(d.ParticipantConnectionState.Idle,t.id),t.emitParticipantStateChanged(e,d.ParticipantState.Idle),t.emitParticipantConnectionStateChanged(e,d.ParticipantConnectionState.Idle));else{const i=new s.Participant(e);t.addParticipantToList(i),t.emitParticipantsAdded([i])}})),C.info(`[1547] [CallId: ${t.id}] added participants to call: ${e}, callId: ${t.id}`,{color:"light-green"}),e.length>0){const i=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[1551] [CallId: ${t.id}] SYNC INVITE failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[1555] [CallId: ${t.id}] SYNC INVITE failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};return this.signalingClient.sendSignalMessage({callId:t.id,sessionId:t.sessionId,event:d.SignalEvent.INVITE,participants:e.map((e=>new s.Participant(e).serialize()))},i),!0}return!1}catch(i){return C.error(`[1567] [CallId: ${t.id}] Failed to add participants to call: ${e}, callId: ${t.id} message: ${i instanceof Error?i.message:JSON.stringify(i)}`,{color:"red"}),!1}},this.sendSignalScreenShare=(e,t,i)=>{try{const n=t=>t instanceof h.SceytCallException||t instanceof Error?(C.error(`[1679] [CallId: ${e.id}] SYNC SCREEN_SHARE_ON failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`),void(null==i||i({error:(0,S.toCallException)(t)}))):t.event===d.SignalEvent.ERROR?(C.error(`[1683] [CallId: ${e.id}] SYNC SCREEN_SHARE_ON failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`),void(null==i||i({error:(0,S.toCallException)(t.error)}))):void 0;return this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,event:t?d.SignalEvent.SCREEN_SHARE_ON:d.SignalEvent.SCREEN_SHARE_OFF,sessionId:e.sessionId},n),!0}catch(t){return C.error(`[1694] [CallId: ${e.id}] Failed to send screen share signal: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"}),null==i||i({error:(0,S.toCallException)(t)}),!1}},this.setupMediaStream=e=>n(this,void 0,void 0,(function*(){var t,i;try{const n=!e.getAudioDeviceId()||{deviceId:{exact:e.getAudioDeviceId()}},a=(yield navigator.mediaDevices.getUserMedia({video:!1,audio:n})).getAudioTracks();if(e.localAudioTracks=a,e.setAudioDeviceId((null===(t=a[0])||void 0===t?void 0:t.getSettings().deviceId)||null),!(null==e?void 0:e.localVideoTracks)||!(null===(i=e.localVideoTracks)||void 0===i?void 0:i.length)){const t=(0,u.getEmptyVideoTrack)();t.forEach((e=>e.enabled=!1)),e.localVideoTracks=t,e.localParticipant.setVideoTracks(t,e)}return e.localParticipant.audioTracks=a,{audioTracks:a}}catch(t){throw C.error(`[1945] [CallId: ${e.id}] Failed to get media: message: ${t instanceof Error?t.message:JSON.stringify(t)}`),(0,S.toCallException)(t)}})),this.chatClient=e,this.user=e.user,this.clientId=e.clientId,this.signalingClient=new o.Signaling(e,this.handleSignalMessage.bind(this));const t=new this.chatClient.ConnectionListener;t.onConnectionStateChanged=e=>{C.info(`[46] [CallId: GLOBAL_LOGS] Signaling connection state changed: ${e}`,{color:"cyan"}),"Connected"===e&&(this.activeCalls.forEach((e=>{const t=this.signalingClient.signalingQueues.get(e.id);t&&t.triggerSignalProcessing()})),setTimeout((()=>{this.signalingClient.sendSignalMessage({event:d.SignalEvent.GET_CALL,callId:""},(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[57] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed ${e instanceof h.SceytCallException||e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}):e.event!==d.SignalEvent.ERROR?this.syncActiveCalls(e):C.error("[63] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed message: "+(e.error?`${e.error.message} code: ${e.error.code}`:""),{color:"red"})}),"get_call")}),1e3))},this.chatClient.addConnectionListener("listener_id",t),"Connected"===this.chatClient.connectionState&&setTimeout((()=>{this.signalingClient.sendSignalMessage({event:d.SignalEvent.GET_CALL,callId:""},(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[74] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR?this.syncActiveCalls(e):C.error("[77] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed message: "+(e.error?`${e.error.message} code: ${e.error.code}`:""),{color:"red"})}),"get_call")}),1e3),f.instance=this}syncActiveCalls(e){var t,i,n;const a=this.activeCalls;try{if(!(null==e?void 0:e.calls))return;if(e.event!==d.SignalEvent.SUCCESS)return void C.error("[98] [CallId: GLOBAL_LOGS] Failed to get call information after reconnection message: "+(e.error?`${e.error.message} code: ${e.error.code}`:""),{color:"red"});for(const l of a){const a=e.calls.find((e=>(null==e?void 0:e.id)===l.id));if(!a&&!(null==l?void 0:l.sessionId))continue;if(!a){this.closeCall(l);continue}if(a.sessionId!==l.sessionId){C.info(`[syncActiveCalls] [CallId: ${l.id}] sessionId changed (${l.sessionId} → ${a.sessionId}), closing stale call`,{color:"yellow"}),this.closeCall(l),this.promoteFromPrepared(a.id,a)?C.info(`[syncActiveCalls] [CallId: ${a.id}] Promoted from prepareCalls to activeCalls`,{color:"cyan"}):this.findOrCreateCall({id:a.id,sessionId:a.sessionId,mediaFlow:a.mediaFlow,participants:[],metadata:a.metadata,createdBy:a.createdBy,settings:null==a?void 0:a.settings},a.participants);continue}const r=l.mediaFlow!==d.MediaFlow.SFU&&a.mediaFlow===d.MediaFlow.SFU;if(this.updateCallMetadata(l,a),r&&this.handleMediaFlowSwitch(l),this.syncParticipants(l,a.participants),l.localParticipant.state<=d.ParticipantState.Joined&&(l.state===d.CallState.Connected||l.state===d.CallState.Connecting)){for(const e of l.participants)if(l.mediaFlow!==d.MediaFlow.SFU&&e.connectionState===d.ParticipantConnectionState.Connected&&e.id!==l.localParticipant.id&&e.clientId!==l.localParticipant.clientId){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[139] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[143] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};this.signalingClient.sendSignalMessage({event:d.SignalEvent.MEDIA_CONNECTED,callId:l.id,sessionId:l.sessionId,mediaFlow:l.mediaFlow,to:l.id},e)}if(l.mediaFlow===d.MediaFlow.SFU&&(null===(t=l.serverParticipant)||void 0===t?void 0:t.connectionState)===d.ParticipantConnectionState.Connected&&l.state===d.CallState.Connected){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[158] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[162] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};this.signalingClient.sendSignalMessage({event:d.SignalEvent.MEDIA_CONNECTED,callId:l.id,sessionId:l.sessionId,mediaFlow:l.mediaFlow,to:l.id},e)}if(l.mediaFlow!==d.MediaFlow.SFU||this.callParticipantsRTCMap[l.id]&&this.callParticipantsRTCMap[l.id][l.id]||l.state!==d.CallState.Connected){if(l.mediaFlow===d.MediaFlow.SFU&&l.serverParticipant&&(null===(n=l.serverParticipant)||void 0===n?void 0:n.connectionState)!==d.ParticipantConnectionState.Reconnecting&&l.state===d.CallState.Connected){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[199] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[203] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};C.info(`[205] [CallId: ${l.id}] Sending offer to server participant when server participant is not connected: ${l.serverParticipant.getFullId()}`,{color:"yellow"}),this.sendOfferPeerToPeer(l,l.serverParticipant,e)}}else{if((null===(i=l.serverParticipant)||void 0===i?void 0:i.id)!==l.id){const e=new s.Participant(l.id);l.setServerParticipant(e)}if(l.serverParticipant){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[181] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[185] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};C.info(`[188] [CallId: ${l.id}] Sending offer to server participant when there is no server participant in the call: ${l.serverParticipant.getFullId()}`,{color:"yellow"}),this.sendOfferPeerToPeer(l,l.serverParticipant,e)}}}else this.leaveCall(l,!1,"syncActiveCalls")}const l=this.activeCalls.find((e=>e.state===d.CallState.Connected));l&&!e.calls.find((e=>e.id===l.id&&e.sessionId===l.sessionId))&&this.closeCall(l),this.activeCalls=this.activeCalls.filter((t=>{var i;return!(!(null===(i=null==e?void 0:e.calls)||void 0===i?void 0:i.find((e=>e.id===t.id)))&&t.sessionId&&(t.clearEventsQueue(),t.participants.forEach((e=>{this.signalingClient.clearParticipantSignals(t.id,e.getFullId())})),this.signalingClient.clearCallSignals(t.id),1))})),e.calls.forEach((e=>{!this.activeCalls.find((t=>(null==t?void 0:t.id)===(null==e?void 0:e.id)))&&e.id&&e.sessionId&&(this.promoteFromPrepared(e.id,e)?C.info(`[syncActiveCalls] [CallId: ${e.id}] Promoted from prepareCalls to activeCalls`,{color:"cyan"}):this.findOrCreateCall({id:e.id,sessionId:e.sessionId,mediaFlow:e.mediaFlow,participants:[],metadata:e.metadata,createdBy:e.createdBy,settings:null==e?void 0:e.settings},e.participants))})),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls)}catch(e){C.error(`[248] [CallId: GLOBAL_LOGS] Error syncing calls after reconnection: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"})}}setCallEvent(e,t){this.callEvents[e]=t}handleSignalMessage(e){switch(C.info(`[253] [CallId: ${e.callId}] Received ${d.SignalEvent[e.event]}: ${JSON.stringify(Object.assign({},e))}`,{color:"green"}),e.event||0){case d.SignalEvent.OFFER:this.handleOfferSignal(e);break;case d.SignalEvent.ANSWER:this.handleAnswerSignal(e);break;case d.SignalEvent.JOIN:this.handleJoinSignal(e);break;case d.SignalEvent.LEAVE:this.handleLeaveSignal(e);break;case d.SignalEvent.INVITE:this.handleInviteSignal(e);break;case d.SignalEvent.CLOSE:this.handleCloseSignal(e);break;case d.SignalEvent.DECLINE:this.handleDeclineSignal(e);break;case d.SignalEvent.RINGING:this.handleRingingSignal(e);break;case d.SignalEvent.SWITCH_MEDIA_FLOW:this.handleSwitchMediaFlowSignal(e);break;case d.SignalEvent.ICE:this.handleIceSignal(e);break;case d.SignalEvent.VIDEO_ON:this.handleVideoOnSignal(e);break;case d.SignalEvent.VIDEO_OFF:this.handleVideoOffSignal(e);break;case d.SignalEvent.SCREEN_SHARE_ON:this.handleScreenShareOnSignal(e);break;case d.SignalEvent.SCREEN_SHARE_OFF:this.handleScreenShareOffSignal(e);break;case d.SignalEvent.MUTE:this.handleMuteSignal(e);break;case d.SignalEvent.UNMUTE:this.handleUnmuteSignal(e);break;case d.SignalEvent.HOLD:this.handleHoldSignal(e);break;case d.SignalEvent.UNHOLD:this.handleUnholdSignal(e);break;case d.SignalEvent.KICK:this.handleKickSignal(e);break;case d.SignalEvent.UPDATE:this.handleUpdateSignal(e);break;case d.SignalEvent.NO_ANSWER:this.handleNoAnswerSignal(e);break;case d.SignalEvent.MEDIA_CONNECTED:this.handleMediaConnectedSignal(e);break;case d.SignalEvent.CONNECT:this.handleConnectSignal(e);break;case d.SignalEvent.SESSION_RENEWED:this.handleSessionRenewedSignal(e);break;default:C.info(`[254] [CallId: ${e.callId}] unhandled signal message: ${JSON.stringify(e)}`,{color:"green"})}}getParticipantId(e){return`${e.id}${(null==e?void 0:e.clientId)?"/"+(null==e?void 0:e.clientId):""}`}handleOfferSignal(e){var t,i,a,l;if(!this.activeCalls)return void C.warn(`[342] [CallId: ${e.callId}] No active calls found for send offer participant: ${e.from}`,{color:"red"});let s;try{const r=this.activeCalls.find((t=>t.id===e.callId));if(!r)return void C.warn(`[348] [CallId: ${e.callId}] No active call found for send offer participant: ${e.from}`,{color:"red"});if(r.state!==d.CallState.Connected)return void C.warn(`[353] [CallId: ${e.callId}] Call is not connected for send offer participant: ${e.from}`,{color:"red"});let o=null==r?void 0:r.participants.find((t=>t.getFullId()===e.from));if(o){s=o.getFullId();const c=this.callParticipantsRTCMap[r.id]&&(null===(t=this.callParticipantsRTCMap[r.id])||void 0===t?void 0:t[o.getFullId()]);let u=null==c?void 0:c.getSessionId();!o.shouldResetPeerConnection&&c&&u===(null===(i=e.sessionData)||void 0===i?void 0:i.id)||(this.closePeerConnections(r.id,o.getFullId()),r.activeSpeakerManager.removeParticipant(o),this.addParticipantToRTCMap(r,o),o.setShouldResetPeerConnection(!1),(this.callParticipantsRTCMap[r.id]&&(null===(a=this.callParticipantsRTCMap[r.id])||void 0===a?void 0:a[o.getFullId()])).setSessionId((null===(l=e.sessionData)||void 0===l?void 0:l.id)||"")),this.signalingClient.clearParticipantSignals(r.id,o.getFullId()),this.setRemoteDescription(r.id,o.getFullId(),(0,v.toSessionDescription)(e.sessionData,"offer")).then((()=>n(this,void 0,void 0,(function*(){var t,i,n;if(!o)return void C.info(`[392] [CallId: ${e.callId}] Participant not found in call: ${e.from}`,{color:"cyan"});const a=this.callParticipantsRTCMap[r.id][o.getFullId()],l=this.activeCalls.find((e=>e.id===r.id));l&&(l.mediaFlow!==d.MediaFlow.SFU||l.mediaFlow===d.MediaFlow.SFU&&o.id===(null===(t=null==l?void 0:l.serverParticipant)||void 0===t?void 0:t.id))&&(yield this.addTracksToPeerConnection(r,o.getFullId(),!1)),a.createAnswer((null===(i=e.sessionData)||void 0===i?void 0:i.id)||"",(null===(n=e.sessionData)||void 0===n?void 0:n.version)||"",r.mediaFlow).then((t=>{if(!o)return void C.info(`[392] [CallId: ${e.callId}] Participant not found in call: ${e.from}`,{color:"cyan"});if(!t)return void C.error(`[456] [CallId: ${r.id}] Failed to create answer for participant: ${o.getFullId()}`,{color:"red"});const i=a.getRemoteSdpUfrag();if(i&&a.iceQueueMap[o.getFullId()]){const e=a.iceQueueMap[o.getFullId()][i];if(e&&e.length>0)for(const t of e)a.addIceCandidate(t,o.getFullId())}this.signalingClient.sendSignalMessage({to:e.from,mediaFlow:e.mediaFlow,callId:r.id,event:d.SignalEvent.ANSWER,sessionData:t,sessionId:e.sessionId,metadata:e.metadata},(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[386] [CallId: ${r.id}] SYNC ANSWER failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[389] [CallId: ${r.id}] SYNC ANSWER failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})}))}))}))))}else C.info(`[402] [CallId: ${e.callId}] Participant not found in call: ${e.from}`,{color:"cyan"})}catch(t){C.error(`[406] [CallId: ${e.callId}] Failed to handle offer: ${s} message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"})}}handleAnswerSignal(e){var t;try{const i=this.activeCalls.find((t=>t.id===e.callId));if(i){let n;if(n=i.mediaFlow===d.MediaFlow.SFU&&i.serverParticipant&&i.serverParticipant.getFullId()===e.from?i.serverParticipant:i.participants.find((t=>t.getFullId()===e.from)),n){const a=null===(t=e.sessionData)||void 0===t?void 0:t.version;if(!a||a!==this.callParticipantsRTCMap[i.id][n.getFullId()].getVersion())return void C.warn(`[412] [CallId: ${i.id}] Version is not set or is the same as the current version: ${a}`,{color:"red"});this.callParticipantsRTCMap[i.id][n.getFullId()].setVersion(a),this.setRemoteDescription(i.id,n.getFullId(),(0,v.toSessionDescription)(e.sessionData,"answer")).then((()=>{if(!n)return void C.info(`[462] [CallId: ${e.callId}] Participant not found in call: ${e.from}`,{color:"cyan"});const t=this.callParticipantsRTCMap[i.id][n.getFullId()].getRemoteSdpUfrag();if(t&&this.callParticipantsRTCMap[i.id][n.getFullId()].iceQueueMap[n.getFullId()]){const e=this.callParticipantsRTCMap[i.id][n.getFullId()].iceQueueMap[n.getFullId()][t];if(e&&e.length>0)for(const t of e)this.callParticipantsRTCMap[i.id][n.getFullId()].addIceCandidate(t,n.getFullId())}}))}}}catch(t){C.error(`[435] [CallId: ${e.callId}] Failed to handle answer: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"})}}sendOfferPeerToPeer(e,t,i){return n(this,void 0,void 0,(function*(){this.callParticipantsRTCMap.hasOwnProperty(e.id)&&this.callParticipantsRTCMap[e.id].hasOwnProperty(t.getFullId())||(this.addParticipantToRTCMap(e,t),yield this.addTracksToPeerConnection(e,t.getFullId(),!0));const n=this.callParticipantsRTCMap[e.id][t.getFullId()];let a=n.getVersion();n.setVersion(a?String(Number(a)+1):"1"),a=n.getVersion();let l=n.getSessionId();l||(l=(0,g.v4)(),n.setSessionId(l)),n.createOffer(l,a,e.mediaFlow).then((n=>{n?this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,event:d.SignalEvent.OFFER,sessionData:n,to:t.getFullId(),sessionId:e.sessionId},i):C.error(`[456] [CallId: ${e.id}] Failed to create offer for participant: ${t.getFullId()}`,{color:"red"})}))}))}handleJoinSignal(e){var t;try{let i=this.activeCalls.find((t=>t.id===e.callId));if(!i){if(this.promoteFromPrepared(e.callId,this.signalMessageToICall(e)));else{const{call:t}=this.findOrCreateCall({id:e.callId,sessionId:e.sessionId,mediaFlow:e.mediaFlow,participants:[],metadata:e.metadata},e.participants);i=t}return}if(i&&!i.sessionId&&(i.setSessionId(e.sessionId),i.setIsCreatedRemotely(!0)),i){let n;(null===(t=e.participants)||void 0===t?void 0:t.length)&&(n=e.participants[0]);let a=!1,l=i.participants.find((t=>t.getFullId()===e.from));if(l?l&&((null==n?void 0:n.videoEnabled)&&l.setParticipantVideoEnabled(!!(null==n?void 0:n.videoEnabled),i),(null==n?void 0:n.muted)&&l.setMuted(!!(null==n?void 0:n.muted),i)):(l=i.participants.find((t=>t.id===e.from.split("/")[0]&&(t.clientId===e.from.split("/")[1]||!t.clientId))),l?(l.clientId=e.from.split("/")[1],(null==n?void 0:n.videoEnabled)&&l.setParticipantVideoEnabled(null==n?void 0:n.videoEnabled,i),(null==n?void 0:n.muted)&&l.setMuted(null==n?void 0:n.muted,i)):l=void 0),l||(l=new s.Participant(e.from),(null==n?void 0:n.videoEnabled)&&l.setParticipantVideoEnabled(!!(null==n?void 0:n.videoEnabled),i),(null==n?void 0:n.muted)&&l.setMuted(!!(null==n?void 0:n.muted),i),i.addParticipantToList(l),a=!0),i.mediaFlow===d.MediaFlow.P2P&&i.localParticipant.state===d.ParticipantState.Joined&&this.isPolitePeer(e.from,i.localParticipant.getFullId())){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[495] [CallId: ${null==i?void 0:i.id}] SYNC OFFER failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[499] [CallId: ${null==i?void 0:i.id}] SYNC OFFER failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};C.info(`[503] [CallId: ${i.id}] Sending offer to participant: ${l.getFullId()}`),this.sendOfferPeerToPeer(i,l,e)}l.updateState(d.ParticipantState.Joined,i.id),C.info(`[503] [CallId: ${i.id}] Participant joined call shouldSendEventInvited: ${a}`),a?i.emitParticipantsAdded([l]):i.emitParticipantStateChanged(l,d.ParticipantState.Joined)}}catch(t){C.error(`[514] [CallId: ${e.callId}] Failed to handle USER_JOINED: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"})}}handleLeaveSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.id===e.from.split("/")[0]&&(t.clientId===e.from.split("/")[1]||!t.clientId)));i&&i.updateState(d.ParticipantState.Left,t.id)&&(this.closePeerConnections(t.id,i.getFullId()),t.activeSpeakerManager.removeParticipant(i),i.setScreenSharing(!1,t),i.setHold(!1,t),t.emitParticipantStateChanged(i,d.ParticipantState.Left),i.updateConnectionState(d.ParticipantConnectionState.Idle,t.id)&&t.emitParticipantConnectionStateChanged(i,d.ParticipantConnectionState.Idle))}}handleInviteSignal(e){if(!e||!e.callId)return void C.warn(`[545] [CallId: ${e.callId}] Received invalid invite signal message`);let t=this.activeCalls.find((t=>t.id===e.callId));t||(t=this.promoteFromPrepared(e.callId,this.signalMessageToICall(e)));const i=(null==e?void 0:e.to)===this.user.id;if(i&&t)for(let e=0;e<t.participants.length;e++){const i=t.participants[e];i.id===this.user.id&&(i.updateConnectionState(d.ParticipantConnectionState.Idle,t.id),i.updateState(d.ParticipantState.Idle,t.id),null==t||t.emitParticipantConnectionStateChanged(i,d.ParticipantConnectionState.Idle),null==t||t.emitParticipantStateChanged(i,d.ParticipantState.Idle))}t?this.handleExistingCallInvite(t,e,i):this.handleNewCallInvite(e,i),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls)}handleExistingCallInvite(e,t,i){var n,a;if(i){e.localParticipant.updateConnectionState(d.ParticipantConnectionState.Connecting,e.id)&&(e.participants.find((e=>e.id===this.user.id&&e.clientId===this.clientId))||e.addParticipantToList(e.localParticipant),e.emitParticipantConnectionStateChanged(e.localParticipant,d.ParticipantConnectionState.Connecting));const i=(null===(a=null===(n=t.participants)||void 0===n?void 0:n.find((e=>e.id===this.user.id&&e.clientId===this.clientId)))||void 0===a?void 0:a.isCallSilenced)||!1;e.setIsCallSilenced(i),this.callEvents.onInvitedToCall&&this.callEvents.onInvitedToCall(e)}else{const i=this.addNewParticipantsToCall(e,t);i.length>0&&e.emitParticipantsAdded(i)}}handleNewCallInvite(e,t){var i,n;const a=new s.Participant(this.user.id,this.clientId);a.updateConnectionState(d.ParticipantConnectionState.Connecting,e.callId);let r=!1;const o=null===(i=e.participants)||void 0===i?void 0:i.map((t=>{if(t.id===this.user.id&&!t.clientId)return r=t.isCallSilenced||!1,a;const i=new s.Participant(t.id,null==t?void 0:t.clientId);return i.updateState(t.state||d.ParticipantState.Idle,e.callId),i.setMuted(!!(null==t?void 0:t.muted)),i.setParticipantVideoEnabled(!!(null==t?void 0:t.videoEnabled)),i}));if(!t&&!(null==o?void 0:o.find((t=>t.getFullId()===e.from)))&&e.from.split("/")[0]===this.user.id&&e.from.split("/")[1]!==this.clientId){const t=new s.Participant(e.from,e.from.split("/")[1]);t.updateState(d.ParticipantState.Joined,e.callId),null==o||o.push(t)}const p=(0,u.makeFirstById)(o||[],this.user.id,this.clientId),g=new c.Call({id:e.callId,sessionId:e.sessionId,mediaFlow:e.mediaFlow,createdBy:e.from,localParticipant:a,metadata:e.metadata,participants:p,chatClient:this.chatClient,isCallSilenced:r});if(g.setVideoCall("true"===(null===(n=e.metadata)||void 0===n?void 0:n.videoCall)),e.settings){const t=e.settings;g.setSettings(Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==t.startsAt&&{startsAt:l.default.isLong(t.startsAt)?t.startsAt.toNumber():t.startsAt}),void 0!==t.expiresAt&&{expiresAt:l.default.isLong(t.expiresAt)?t.expiresAt.toNumber():t.expiresAt}),void 0!==t.persistent&&{persistent:t.persistent}),void 0!==t.broadcastOptions&&{broadcastSettings:t.broadcastOptions}))}this.activeCalls.push(g),this.callEvents.onInvitedToCall&&t&&this.callEvents.onInvitedToCall(g),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls)}addNewParticipantsToCall(e,t){var i;const n=[];return null===(i=t.participants)||void 0===i||i.forEach((t=>{const i=t.id!==this.user.id?e.participants.find((e=>e.id===t.id)):void 0,a=i||new s.Participant(t.id,null==t?void 0:t.clientId);i?t.state!==d.ParticipantState.Joined&&(a.updateState(t.state||d.ParticipantState.Idle,e.id),a.updateConnectionState(d.ParticipantConnectionState.Idle,e.id),a.setParticipantVideoEnabled(t.videoEnabled||!1,e),e.emitParticipantStateChanged(a,d.ParticipantState.Idle),e.emitParticipantConnectionStateChanged(a,d.ParticipantConnectionState.Idle)):(a.updateState(t.state||d.ParticipantState.Idle,e.id),n.push(a),e.addParticipantToList(a))})),n}handleCloseSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));t&&this.closeCall(t)}handleDeclineSignal(e){var t;const i=this.activeCalls.find((t=>t.id===e.callId));if(i)if(this.getParticipantId({id:this.user.id,clientId:this.clientId})===e.from)this.leaveCall(i,!0,"Current user declined the call"),i.setState(d.CallState.Idle,"Current user declined the call");else{let n=null==i?void 0:i.participants.find((t=>t.getFullId()===e.from));n||(n=null==i?void 0:i.participants.find((t=>t.id===e.from.split("/")[0]&&!t.clientId)),n?n.clientId=e.from.split("/")[1]:(n=new s.Participant(e.from),i.addParticipantToList(n),i.emitParticipantsAdded([n]))),n&&n.updateState(d.ParticipantState.Declined,i.id)&&i.emitParticipantStateChanged(n,d.ParticipantState.Declined,null===(t=e.metadata)||void 0===t?void 0:t.reason)}}handleRingingSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){let i=null==t?void 0:t.participants.find((t=>t.id===e.from.split("/")[0]&&(t.clientId===e.from.split("/")[1]||!t.clientId)));i||(i=new s.Participant(e.from),t.addParticipantToList(i),t.emitParticipantsAdded([i])),i&&i.connectionState!==d.ParticipantConnectionState.Connected&&i.updateState(d.ParticipantState.Ringing,t.id)&&(i.clientId||(i.clientId=e.from.split("/")[1]),t.emitParticipantStateChanged(i,d.ParticipantState.Ringing))}}handleSwitchMediaFlowSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t&&t.localParticipant.state===d.ParticipantState.Joined){t.changeMediaFlow(d.MediaFlow.SFU);const e=new s.Participant(t.id);t.setServerParticipant(e);const i=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[738] [CallId: ${t.id}] SYNC OFFER failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`):e.event!==d.SignalEvent.ERROR||C.error(`[742] [CallId: ${t.id}] SYNC OFFER failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`)};C.info(`[747] [CallId: ${t.id}] Sending offer to server participant: ${e.getFullId()}`),this.sendOfferPeerToPeer(t,e,i),t.participants.forEach((e=>{e.setShouldResetPeerConnection(!0)}))}else t&&t.changeMediaFlow(d.MediaFlow.SFU)}handleIceSignal(e){var t;if(!e.callId||!e.ice)return void C.warn(`[756] [CallId: ${e.callId}] Invalid ICE signal: missing callId or ice data`);const i=this.activeCalls.find((t=>t.id===e.callId));if(!i)return void C.warn(`[763] [CallId: ${e.callId}] ICE candidate received for unknown call: ${e.callId}`);const n=i.participants.find((t=>t.getFullId()===e.from));if(n)try{if(!this.callParticipantsRTCMap[i.id])return void C.error(`[774] [CallId: ${i.id}] No RTC map found for call ${i.id}`);null===(t=this.callParticipantsRTCMap[i.id][n.getFullId()])||void 0===t||t.addIceCandidate(e.ice,n.getFullId())}catch(e){C.error(`[787] [CallId: ${i.id}] Failed to add ICE candidate for participant ${n.getFullId()} in call ${i.id}: ${e instanceof Error?e.message:JSON.stringify(e)}`)}else C.warn(`[768] [CallId: ${e.callId}] ICE candidate received from unknown participant: ${e.from} in call ${e.callId}`)}handleVideoOnSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from||t.id===e.from.split("/")[0]&&!t.clientId));i&&i.setParticipantVideoEnabled(!0,t)}}handleVideoOffSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){let i;null==t||t.participants.forEach((n=>{(n.getFullId()===e.from||n.id===e.from.split("/")[0]&&!n.clientId)&&(n.setParticipantVideoEnabled(!1,t),i=n)}))}}handleScreenShareOnSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.setScreenSharing(!0,t)}}handleScreenShareOffSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&(i.setScreenSharing(!1,t),i.videoEnabled&&i.setParticipantVideoEnabled(!0,t))}}handleMuteSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.setMuted(!0,t)}}handleUnmuteSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.setMuted(!1,t)}}handleHoldSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.setHold(!0,t)}}handleUnholdSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.setHold(!1,t)}}handleKickSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.updateState(d.ParticipantState.Kicked,t.id)&&t.emitParticipantStateChanged(i,d.ParticipantState.Kicked)}}handleUpdateSignal(e){var t;const i=this.activeCalls.find((t=>t.id===e.callId));i&&e.metadata&&(i.metadata=e.metadata,i.setVideoCall("true"===(null===(t=e.metadata)||void 0===t?void 0:t.videoCall)))}handleNoAnswerSignal(e){var t;const i=this.activeCalls.find((t=>t.id===e.callId));i&&(null===(t=e.participants)||void 0===t||t.forEach((e=>{(null==i?void 0:i.participants.filter((t=>t.id===e.id&&(t.clientId===e.clientId||!e.clientId)))).forEach((e=>{e.updateState(d.ParticipantState.NoAnswer,i.id)&&i.emitParticipantStateChanged(e,d.ParticipantState.NoAnswer)}))})))}static getInstance(){if(!f.instance)throw new Error("InternalCallHandler has not been initialized. Call new InternalCallHandler(chatClient) first.");return f.instance}setRTCConfig(e){this.rtcConfig=e}onIceCandidateListener(e,t){return i=>{this.onIceCandidate(e,i,t)}}onSignalingStateChangeListener(e,t){return i=>{var n;const a=(null===(n=null==i?void 0:i.currentTarget)||void 0===n?void 0:n.signalingState)||"unknown";C.info(`[1067] [CallId: ${t.id}] Signaling state change: ${a}, participantID: ${e.getFullId()}`,{color:"blue"})}}isPolitePeer(e,t){return t>e}onIceConnectionStateChangeListener(e,t){return i=>{var n;const a=(null===(n=null==i?void 0:i.currentTarget)||void 0===n?void 0:n.iceConnectionState)||"unknown";C.info(`[1078] [CallId: ${t.id}] ICE connection state change: ${a}, participantID: ${e.getFullId()}`,{color:"blue"})}}onConnectionStateChangeListener(e,t){return i=>{var n,a,l,s,r;const o=i.currentTarget.connectionState;C.info(`[1078] [CallId: ${t.id}] PC connection state changed: ${o}, participantID: ${e.getFullId()}`,{color:"disconnected"===o?"orange":"failed"===o?"red":"blue"});const c=this.activeCalls.find((e=>e.id===t.id))||t,u=(null==c?void 0:c.participants.find((t=>t.getFullId()===e.getFullId())))||e.id===(null===(n=null==c?void 0:c.serverParticipant)||void 0===n?void 0:n.id)&&e;if(!u)return;let p=0,g=null;const v=e=>{p=0,g&&(clearInterval(g),g=null),e&&clearTimeout(e)},S=(i,n=!1)=>{C.info(`[1089] [CallId: ${t.id}] start renegotiation send ${i} to participant ${u.getFullId()}`,{color:"blue"});const a=a=>{var l;const s=this.activeCalls.find((e=>e.id===t.id))||t,r=s.participants.find((t=>t.getFullId()===e.getFullId()))||e.id===(null===(l=s.serverParticipant)||void 0===l?void 0:l.id)&&e||e;if("Connected"===this.chatClient.connectionState&&r.connectionState!==d.ParticipantConnectionState.Connected&&s.state===d.CallState.Connected)if(C.info(`[1190] [CallId: ${t.id}] interval renegotiation send ${i} to participant ${r.getFullId()}`,{color:"blue"}),"offer"!==i||n&&!this.isPolitePeer(r.getFullId(),s.localParticipant.getFullId()||"")){if("connect"===i&&(!n||this.isPolitePeer(r.getFullId(),s.localParticipant.getFullId()||""))){C.info(`[1214] [CallId: ${t.id}] ${d.MediaFlow.SFU} sendConnect to participant 1 ${JSON.stringify(r)}`,{color:"blue"});try{this.signalingClient.clearParticipantSignals(s.id,r.getFullId()),this.signalingClient.sendSignalMessage({mediaFlow:s.mediaFlow,callId:s.id,sessionId:s.sessionId,event:d.SignalEvent.CONNECT,to:r.getFullId()},a)}catch(e){C.error(`[1236] [CallId: ${t.id}] Failed to send connect to participant ${r.getFullId()}: message: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"})}}}else try{C.info(`[1211] [CallId: ${t.id}] Sending offer to participant: ${r.getFullId()}`),this.sendOfferPeerToPeer(s,r,a)}catch(e){C.error(`[1211] [CallId: ${t.id}] Failed to send offer to participant ${r.getFullId()}: ${e instanceof Error?e.message:JSON.stringify(e)}`)}};g&&(clearInterval(g),g=null);let l=null;g=setInterval((()=>{var n,s,r;const o=this.activeCalls.find((e=>e.id===t.id))||t,c=o.participants.find((t=>t.getFullId()===e.getFullId()))||e.id===(null===(n=o.serverParticipant)||void 0===n?void 0:n.id)&&e||e,u=null===(r=null===(s=this.callParticipantsRTCMap[t.id])||void 0===s?void 0:s[c.getFullId()])||void 0===r?void 0:r.peerConnection;return C.info(`[1182] [CallId: ${t.id}] retry count: ${p+1}`,{color:"green"}),o&&o.state===d.CallState.Connected?c.connectionState===d.ParticipantConnectionState.Connected&&"stable"===(null==u?void 0:u.signalingState)||c.state!==d.ParticipantState.Joined?(v(l),void(l=null)):(p+=1,p>=10?(C.warn(`[1182] [CallId: ${t.id}] Max retries reached for ${i} to ${c.getFullId()}, giving up`,{color:"red"}),c.updateConnectionState(d.ParticipantConnectionState.Disconnected,t.id),v(l),void(l=null)):void a((e=>{var n;return e instanceof h.SceytCallException||e instanceof Error?(C.error(`[1202] [CallId: ${t.id}] SYNC ${i} failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}),void("NotAllowed"===e.name&&(c.updateConnectionState(d.ParticipantConnectionState.Disconnected,t.id),v(l),l=null))):e.event===d.SignalEvent.ERROR?(C.error(`[1205] [CallId: ${t.id}] SYNC ${i} failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"}),void(4002===(null===(n=e.error)||void 0===n?void 0:n.code)&&(c.updateConnectionState(d.ParticipantConnectionState.Disconnected,t.id),v(l),l=null))):void 0}))):(v(l),void(l=null))}),4e3),l=setTimeout((()=>{l=null,a((e=>{var i;return e instanceof h.SceytCallException||e instanceof Error?(C.error(`[1202] [CallId: ${t.id}] SYNC OFFER failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}),void(("NotAllowed"===e.name||e instanceof h.SceytCallException&&4002===e.code)&&u.updateConnectionState(d.ParticipantConnectionState.Disconnected,t.id))):e.event===d.SignalEvent.ERROR?(C.error(`[1205] [CallId: ${t.id}] SYNC OFFER failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"}),void(4002===(null===(i=e.error)||void 0===i?void 0:i.code)&&u.updateConnectionState(d.ParticipantConnectionState.Disconnected,t.id))):void 0}))}),2e3)},f=()=>{var i;g||u&&c&&(c.mediaFlow===d.MediaFlow.SFU&&e.id===(null===(i=null==c?void 0:c.serverParticipant)||void 0===i?void 0:i.id)&&this.callParticipantsRTCMap[c.id]&&this.callParticipantsRTCMap[c.id][e.getFullId()]&&c.localParticipant.state===d.ParticipantState.Joined&&(C.info(`[1258] [CallId: ${t.id}] start renegotiation ${d.MediaFlow.SFU} sendOffer to participant ${u.getFullId()}`,{color:"blue"}),S("offer",!1)),c.mediaFlow===d.MediaFlow.S2W&&u.state===d.ParticipantState.Joined&&this.callParticipantsRTCMap[c.id]&&this.callParticipantsRTCMap[c.id][u.getFullId()]&&c.localParticipant.state===d.ParticipantState.Joined&&(C.info(`[1263] [CallId: ${t.id}] start renegotiation ${d.MediaFlow.SFU} sendConnect to participant ${u.getFullId()}`,{color:"blue"}),S("offer",!1)))};switch(o){case"new":break;case"connecting":t.mediaFlow===d.MediaFlow.SFU&&u.id===(null===(a=null==c?void 0:c.serverParticipant)||void 0===a?void 0:a.id)&&c.localParticipant.updateConnectionState(d.ParticipantConnectionState.Connecting,t.id)&&c.emitParticipantConnectionStateChanged(c.localParticipant,d.ParticipantConnectionState.Connecting),u.updateConnectionState(d.ParticipantConnectionState.Connecting,t.id)&&c.emitParticipantConnectionStateChanged(u,d.ParticipantConnectionState.Connecting);break;case"connected":if(t.mediaFlow===d.MediaFlow.SFU&&u.id===(null===(l=null==c?void 0:c.serverParticipant)||void 0===l?void 0:l.id)&&c.localParticipant.updateConnectionState(d.ParticipantConnectionState.Connected,t.id)&&c.emitParticipantConnectionStateChanged(c.localParticipant,d.ParticipantConnectionState.Connected),u.updateConnectionState(d.ParticipantConnectionState.Connected,t.id)&&c.emitParticipantConnectionStateChanged(u,d.ParticipantConnectionState.Connected),u&&c&&"Connected"===this.chatClient.connectionState&&(c.mediaFlow!==d.MediaFlow.SFU||c.mediaFlow===d.MediaFlow.SFU&&u.id===(null==c?void 0:c.id))){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[1098] [CallId: ${c.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[1102] [CallId: ${c.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};this.signalingClient.sendSignalMessage(Object.assign({mediaFlow:c.mediaFlow,callId:c.id,sessionId:c.sessionId,event:d.SignalEvent.MEDIA_CONNECTED},c.mediaFlow!==d.MediaFlow.SFU?{to:c.id}:{}),e)}break;case"disconnected":t.mediaFlow===d.MediaFlow.SFU&&u.id===(null===(s=null==c?void 0:c.serverParticipant)||void 0===s?void 0:s.id)&&c.localParticipant.updateConnectionState(d.ParticipantConnectionState.Reconnecting,t.id)&&c.emitParticipantConnectionStateChanged(c.localParticipant,d.ParticipantConnectionState.Reconnecting),u.updateConnectionState(d.ParticipantConnectionState.Reconnecting,t.id)&&c.emitParticipantConnectionStateChanged(u,d.ParticipantConnectionState.Reconnecting),t.mediaFlow!==d.MediaFlow.S2W&&f();break;case"failed":u&&c&&(c.mediaFlow===d.MediaFlow.P2P&&u.state===d.ParticipantState.Joined&&this.callParticipantsRTCMap[c.id]&&this.callParticipantsRTCMap[c.id][u.getFullId()]&&c.localParticipant.state===d.ParticipantState.Joined?(C.info(`[1268] [CallId: ${t.id}] start renegotiation ${c.mediaFlow} sendOffer to participant ${u.getFullId()}`,{color:"blue"}),S("offer",!0)):f());break;case"closed":t.mediaFlow===d.MediaFlow.SFU&&u.id===(null===(r=null==c?void 0:c.serverParticipant)||void 0===r?void 0:r.id)&&c.localParticipant.updateConnectionState(d.ParticipantConnectionState.Idle,t.id)&&c.emitParticipantConnectionStateChanged(c.localParticipant,d.ParticipantConnectionState.Idle),u.updateConnectionState(d.ParticipantConnectionState.Idle,t.id)&&c.emitParticipantConnectionStateChanged(u,d.ParticipantConnectionState.Idle)}}}onIceCandidateErrorListener(e,t){return i=>{C.error(`[1284] [CallId: ${t.id}] ICE candidate error participantID: ${e.getFullId()}, error - code: ${i.errorCode}, message: ${i.errorText}, url: ${i.url}`,{color:"red"})}}onTrackListener(e,t){return i=>{this.onTrack(t,e,i)}}closePeerConnections(e,t){if(!this.callParticipantsRTCMap[e])return;const i=this.callParticipantsRTCMap[e][t];i?(i.listeners?(Object.keys(i.listeners).forEach((e=>{i.removeEventListener(e,i.listeners[e])})),C.info(`[1313] [CallId: ${e}] Removed all listeners for WebRTCClient of participant ${t}`,{color:"cyan"})):C.info(`[1316] [CallId: ${e}] No listeners found for WebRTCClient of participant ${t}`,{color:"cyan"}),i.close(),i.peerConnection.onicecandidate=null,i.peerConnection.ontrack=null,i.peerConnection.onconnectionstatechange=null,i.peerConnection.oniceconnectionstatechange=null,i.peerConnection.onsignalingstatechange=null,this.callParticipantsRTCMap[e][t]=null,delete this.callParticipantsRTCMap[e][t]):C.info(`[1375] [CallId: ${e}] No WebRTCClient found for participant ${t}`,{color:"cyan"})}addParticipantToRTCMap(e,t){this.callParticipantsRTCMap.hasOwnProperty(e.id)||(this.callParticipantsRTCMap[e.id]={});const i=new r.WebRTCClient(e.id,this.rtcConfig);this.callParticipantsRTCMap[e.id][t.getFullId()]=i;const n=this.onIceCandidateListener(t,e),a=this.onSignalingStateChangeListener(t,e),l=this.onIceConnectionStateChangeListener(t,e),s=this.onConnectionStateChangeListener(t,e),o=this.onTrackListener(t,e),d=this.onIceCandidateErrorListener(t,e);return i.addEventListener("icecandidate",n),i.addEventListener("signalingstatechange",a),i.addEventListener("connectionstatechange",s),i.addEventListener("track",o),i.addEventListener("icecandidateerror",d),i.addEventListener("iceconnectionstatechange",l),i.setListeners({iceCandidateListener:n,signalingStateChangeListener:a,connectionStateChangeListener:s,trackListener:o,iceCandidateErrorListener:d,iceConnectionStateChangeListener:l}),C.info(`[1371] [CallId: ${e.id}] Added Event Listeners to RTC Map: participantID: ${t.getFullId()}`,{color:"blue"}),e.activeSpeakerManager.addParticipant(t),t}joinToCall(e,t){return this.signalingClient.sendSignalMessage(Object.assign(Object.assign(Object.assign(Object.assign({mediaFlow:e.mediaFlow,callId:e.callId},e.sessionId&&{sessionId:e.sessionId}),{event:d.SignalEvent.JOIN,participants:e.participants}),(null==e?void 0:e.metadata)&&{metadata:e.metadata}),{joinOptions:e.joinOptions}),t)}sendRinging(e,t){return this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,sessionId:e.sessionId,event:d.SignalEvent.RINGING},(i=>i instanceof h.SceytCallException||i instanceof Error?(C.error(`[1389] [CallId: ${e.id}] SYNC RINGING failed message: ${i.message} code: ${i instanceof h.SceytCallException?i.code:""}`,{color:"red"}),void(null==t||t({error:(0,S.toCallException)(i)}))):i.event===d.SignalEvent.ERROR?(C.error(`[1393] [CallId: ${e.id}] SYNC RINGING failed message: ${i.error?`${i.error.message} code: ${i.error.code}`:""}`,{color:"red"}),void(null==t||t({error:(0,S.toCallException)(new Error("Failed to send ringing signal"))}))):(e.localParticipant.updateState(d.ParticipantState.Ringing,e.id),void e.emitParticipantStateChanged(e.localParticipant,d.ParticipantState.Ringing)))),{success:!0}}rejectCall(e,t,i){try{const n=this.activeCalls.find((t=>t.id===e.id));n&&(n.setState(d.CallState.Idle,"rejectCall"),n.localParticipant.updateState(d.ParticipantState.Declined,e.id)&&n.emitParticipantStateChanged(n.localParticipant,d.ParticipantState.Declined),n.localParticipant.updateConnectionState(d.ParticipantConnectionState.Idle,e.id)&&n.emitParticipantConnectionStateChanged(n.localParticipant,d.ParticipantConnectionState.Idle),this.closeTracksAndPeerConnections(n));const a=t=>t instanceof h.SceytCallException||t instanceof Error?(C.error(`[1420] [CallId: ${e.id}] SYNC DECLINE failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`,{color:"red"}),void(null==i||i({error:(0,S.toCallException)(t)}))):t.event===d.SignalEvent.ERROR?(C.error(`[1424] [CallId: ${e.id}] SYNC DECLINE failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`,{color:"red"}),void(null==i||i({error:(0,S.toCallException)(t.error||new Error("Failed to send decline signal"))}))):void 0;return this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,sessionId:e.sessionId,event:d.SignalEvent.DECLINE,metadata:Object.assign(Object.assign({},e.metadata),{reason:t||""})},a),{success:!0}}catch(t){return C.error(`[1432] [CallId: ${e.id}] Failed to reject call: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"}),{success:!1,error:(0,S.toCallException)(t)}}}closeTracksAndPeerConnections(e){e.localAudioTracks.forEach((e=>{e.stop()})),e.localVideoTracks.forEach((e=>{e.stop()})),e.participants.forEach((t=>{t.videoTracks.forEach((e=>{e.stop()})),t.audioTracks.forEach((e=>{e.stop()})),this.closePeerConnections(e.id,t.getFullId()),e.activeSpeakerManager.removeParticipant(t)})),e.localParticipant.videoTracks.forEach((e=>{e.stop()})),e.localParticipant.audioTracks.forEach((e=>{e.stop()})),e.mediaFlow===d.MediaFlow.SFU&&e.serverParticipant&&(e.serverParticipant.videoTracks.forEach((e=>{e.stop()})),e.serverParticipant.audioTracks.forEach((e=>{e.stop()})),this.closePeerConnections(e.id,e.serverParticipant.getFullId()))}closeCall(e){e.setState(d.CallState.Closed,"closeCall"),this.closeTracksAndPeerConnections(e);const t=this.activeCalls.findIndex((t=>t.id===e.id));this.activeCalls.splice(t,1),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls),delete this.callParticipantsRTCMap[e.id],C.info(`[1474] [CallId: ${e.id}] closed call and removed from active calls: callId: ${e.id}`,{color:"light-green"})}leaveCall(e,t=!0,i){const n=this.activeCalls.find((t=>t.id===e.id));if(n){this.signalingClient.cancelJoinIfPossible(e.id);const a=n.setState(d.CallState.Idle,`leaveCall: ${i}`);if(t&&a){const t=t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[1487] [CallId: ${e.id}] SYNC LEAVE failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`,{color:"red"}):t.event!==d.SignalEvent.ERROR||C.error(`[1491] [CallId: ${e.id}] SYNC LEAVE failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`,{color:"red"})};this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,sessionId:e.sessionId,event:d.SignalEvent.LEAVE},t)}this.closeTracksAndPeerConnections(n),delete this.callParticipantsRTCMap[n.id],n.localParticipant.updateState(d.ParticipantState.Left,e.id)&&n.emitParticipantStateChanged(n.localParticipant,d.ParticipantState.Left),n.localParticipant.setScreenSharing(!1,n),n.localParticipant.connectionState!==d.ParticipantConnectionState.Idle&&n.localParticipant.updateConnectionState(d.ParticipantConnectionState.Idle,e.id),n.participants.forEach((t=>{t.connectionState!==d.ParticipantConnectionState.Idle&&(t.updateConnectionState(d.ParticipantConnectionState.Idle,e.id),n.emitParticipantConnectionStateChanged(t,d.ParticipantConnectionState.Idle))})),e.sessionId||(this.activeCalls=this.activeCalls.filter((e=>e.id!=n.id))),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls)}}setRemoteDescription(e,t,i){var n;const a=null===(n=this.callParticipantsRTCMap[e])||void 0===n?void 0:n[t];return a?a.setRemoteDescription(i):(C.error(`[setRemoteDescription] [CallId: ${e}] No WebRTCClient found for participant ${t}`,{color:"red"}),Promise.reject(new Error(`No WebRTCClient found for participant ${t} in call ${e}`)))}changeVideoTracks(e,t,i,a){var l;return n(this,void 0,void 0,(function*(){if(C.info(`[1594] [CallId: ${e.id}], mediaFlow: ${e.mediaFlow}, changeVideoTracks ${i}, serverParticipant: ${(null===(l=e.serverParticipant)||void 0===l?void 0:l.id)||"null"}`,{color:"cyan"}),e.mediaFlow!==d.MediaFlow.SFU)for(let n=0;n<e.participants.length;n++){const l=e.participants[n];(l.id!==this.user.id||l.clientId!==this.clientId)&&l.clientId&&this.callParticipantsRTCMap[e.id]&&this.callParticipantsRTCMap[e.id][l.getFullId()]&&(yield this.callParticipantsRTCMap[e.id][l.getFullId()].enableVideoOnPeerConnection(i,t,!!a))}else this.callParticipantsRTCMap[e.id]&&this.callParticipantsRTCMap[e.id][e.id]&&(yield this.callParticipantsRTCMap[e.id][e.id].enableVideoOnPeerConnection(i,t,!!a))}))}changeAudioTracks(e,t,i){return n(this,void 0,void 0,(function*(){e.mediaFlow!==d.MediaFlow.SFU?e.participants.forEach((n=>{(n.id!==this.user.id||n.clientId!==this.clientId)&&this.callParticipantsRTCMap[e.id]&&this.callParticipantsRTCMap[e.id][n.getFullId()]&&(C.info(`[1561] [CallId: ${e.id}] Enabling audio on peer connection: ${n.getFullId()}`,{color:"cyan"}),this.callParticipantsRTCMap[e.id][n.getFullId()].enableAudioOnPeerConnection(i,t))})):(C.info(`[1565] [CallId: ${e.id}] Enabling audio on peer connection: ${e.id}`,{color:"cyan"}),yield this.callParticipantsRTCMap[e.id][e.id].enableAudioOnPeerConnection(i,t))}))}sendVideoEnabled(e,t,i){if(this.activeCalls.find((t=>t.id===e.id)))try{const n=t=>t instanceof h.SceytCallException||t instanceof Error?(C.error(`[1632] [CallId: ${e.id}] SYNC VIDEO_ON failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`),void(null==i||i({error:(0,S.toCallException)(t)}))):t.event===d.SignalEvent.ERROR?(C.error(`[1636] [CallId: ${e.id}] SYNC VIDEO_ON failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`),void(null==i||i({error:(0,S.toCallException)(t.error||t)}))):void 0;this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,event:t?d.SignalEvent.VIDEO_ON:d.SignalEvent.VIDEO_OFF,sessionId:e.sessionId},n)}catch(t){return C.error(`[1645] [CallId: ${e.id}] Failed to send video enabled signal: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"}),null==i||i({error:(0,S.toCallException)(t)}),!1}}sendScreenShare(e,t,i){return n(this,void 0,void 0,(function*(){const n=this.activeCalls.find((t=>t.id===e.id));try{if(n)return this.sendSignalScreenShare(e,t,i)}catch(t){return C.error(`[1668] [CallId: ${e.id}] Failed to send screen share signal: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"}),null==i||i({error:(0,S.toCallException)(t)}),!1}}))}sendAudioEnable(e,t,i){return n(this,void 0,void 0,(function*(){if(this.activeCalls.find((t=>t.id===e.id))){const a=a=>n(this,void 0,void 0,(function*(){try{if(a instanceof h.SceytCallException||a instanceof Error)return C.error(`[1704] [CallId: ${e.id}] SYNC HOLD failed message: ${a.message} code: ${a instanceof h.SceytCallException?a.code:""}`),void(null==i||i({error:(0,S.toCallException)(a)}));if(a.event===d.SignalEvent.ERROR)return C.error(`[1708] [CallId: ${e.id}] SYNC HOLD failed message: ${a.error?`${a.error.message} code: ${a.error.code}`:""}`),void(null==i||i({error:(0,S.toCallException)(a.error)}));if(e.mediaFlow!==d.MediaFlow.SFU)for(let i=0;i<e.participants.length;i++){const n=e.participants[i];(n.id!==this.user.id||n.clientId!==this.clientId)&&n.clientId&&this.callParticipantsRTCMap[e.id]&&this.callParticipantsRTCMap[e.id][n.getFullId()]&&(C.info(`[1712] [CallId: ${e.id}] Enabling audio on peer connection: ${n.getFullId()}`,{color:"cyan"}),yield this.callParticipantsRTCMap[e.id][n.getFullId()].enableAudioOnPeerConnection(t))}else this.callParticipantsRTCMap&&this.callParticipantsRTCMap[e.id]&&this.callParticipantsRTCMap[e.id][e.serverParticipant.getFullId()]&&(C.info(`[1712] [CallId: ${e.id}] Enabling audio on peer connection: ${e.serverParticipant.getFullId()}`,{color:"cyan"}),yield this.callParticipantsRTCMap[e.id][e.serverParticipant.getFullId()].enableAudioOnPeerConnection(t));e.localParticipant.audioTracks.forEach((e=>{e.enabled=!t}))}catch(t){C.error(`[1725] [CallId: ${e.id}] Failed to enable audio on peer connection: ${t instanceof Error?t.message:JSON.stringify(t)}`),null==i||i({error:(0,S.toCallException)(t)})}}));return this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,event:t?d.SignalEvent.MUTE:d.SignalEvent.UNMUTE,sessionId:e.sessionId},a)}}))}sendHold(e,t,i){if(this.activeCalls.find((t=>t.id===e.id))){const i=t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[1741] [CallId: ${e.id}] SYNC HOLD failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`):t.event!==d.SignalEvent.ERROR||C.error(`[1745] [CallId: ${e.id}] SYNC HOLD failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`)};return this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,event:t?d.SignalEvent.HOLD:d.SignalEvent.UNHOLD,sessionId:e.sessionId},i)}}addTracksToPeerConnection(e,t,i=!0){var a,l;return n(this,void 0,void 0,(function*(){let n=e.localVideoTracks;const s=e.localAudioTracks,r=this.callParticipantsRTCMap[e.id][t];try{i?yield r.addTransceiverToPeerConnection(s[0],e.mediaFlow):yield r.setStreamsToTransceiver(s[0])}catch(t){C.warn(`[1766] [CallId: ${e.id}] Failed to add track to peer connection: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"})}n&&n.length>0||(n=(0,u.getEmptyVideoTrack)());try{i?yield r.addTransceiverToPeerConnection(n[0],e.mediaFlow):yield r.setStreamsToTransceiver(n[0])}catch(t){C.warn(`[1775] [CallId: ${e.id}] Failed to add track to peer connection: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"})}e.videoEnabled&&r.enableVideoOnPeerConnection(e.videoEnabled,null===(a=e.localVideoTracks)||void 0===a?void 0:a[0]),e.muted||r.enableAudioOnPeerConnection(e.muted,null===(l=e.localAudioTracks)||void 0===l?void 0:l[0])}))}switchCallToSfu(e,t){try{const i=i=>{if(i instanceof h.SceytCallException||i instanceof Error)return C.error(`[1785] [CallId: ${e.id}] SYNC SWITCH_MEDIA_FLOW signal sent failed message: ${i.message} code: ${i instanceof h.SceytCallException?i.code:""}`),void(null==t||t({error:(0,S.toCallException)(i)}));if(i.event===d.SignalEvent.ERROR)return C.error(`[1789] [CallId: ${e.id}] SYNC SWITCH_MEDIA_FLOW signal sent failed message: ${i.error?`${i.error.message} code: ${i.error.code}`:""}`),void(null==t||t({error:(0,S.toCallException)(i)}));const n=new s.Participant(e.id);return e.setServerParticipant(n),e.participants.forEach((t=>{t.id===this.user.id&&t.clientId===this.clientId||t.updateConnectionState(d.ParticipantConnectionState.Idle,e.id),t.setShouldResetPeerConnection(!0)})),e.changeMediaFlow(d.MediaFlow.SFU),C.info(`[1818] [CallId: ${e.id}] Sending offer to server participant: ${n.getFullId()}`),this.sendOfferPeerToPeer(e,n,(t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[1805] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`):t.event!==d.SignalEvent.ERROR||C.error(`[1809] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`)})),!0};return this.signalingClient.sendSignalMessage({mediaFlow:d.MediaFlow.SFU,callId:e.id,event:d.SignalEvent.SWITCH_MEDIA_FLOW,sessionId:e.sessionId},i),C.info(`[1823] [CallId: ${e.id}] Switched call ${e.id} to SFU`,{color:"light-green"}),{success:!0}}catch(t){return C.error(`[1827] [CallId: ${e.id}] Failed to switch ${d.MediaFlow.SFU} message: ${t instanceof Error?t.message:JSON.stringify(t)}`),{success:!1,error:(0,S.toCallException)(t)}}}getCallById(e,t){return this.signalingClient.sendSignalMessage({callId:e,sessionId:t,event:d.SignalEvent.GET_CALL},(t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[1833] [CallId: ${e}] SYNC GET_CALL signal sent failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`):t.event!==d.SignalEvent.ERROR||C.error(`[1837] [CallId: ${e}] SYNC GET_CALL signal sent failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`)}),e)}getCalls(){return this.signalingClient.sendSignalMessage({callId:"",event:d.SignalEvent.GET_CALL},(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[1849] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`):e.event!==d.SignalEvent.ERROR?this.syncActiveCalls(e):C.error("[1853] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed message: "+(e.error?`${e.error.message} code: ${e.error.code}`:""))}),"get_call")}createParticipants(e){let t=null,i=!1;return{participants:null==e?void 0:e.map((e=>{const n=new s.Participant(e.id,e.clientId);return n.setMuted(!!(null==e?void 0:e.muted)),n.setParticipantVideoEnabled(!!(null==e?void 0:e.videoEnabled)),n.setScreenSharing(!!(null==e?void 0:e.screenSharing)),n.setHold(!!(null==e?void 0:e.onHold)),(null==e?void 0:e.connectionState)&&(null==e?void 0:e.connectionState)>d.ParticipantConnectionState.Connected&&(null==e?void 0:e.id)!==this.user.id&&(null==e?void 0:e.clientId)!==this.clientId&&(n.connectionState=(null==e?void 0:e.connectionState)||d.ParticipantConnectionState.Idle),n.state=(null==e?void 0:e.state)||0,i=(null==e?void 0:e.isCallSilenced)||!1,(null==n?void 0:n.id)===this.user.id&&(null==n?void 0:n.clientId)===this.clientId&&(t=n),n})),localParticipant:t,isCallSilenced:i}}findOrCreateCall(e,t){var i;let n=new s.Participant(this.user.id,this.clientId),a=[],l=!1;if(t){const e=this.createParticipants(t);a=e.participants,l=e.isCallSilenced,e.localParticipant&&(n=e.localParticipant)}else a=null!==(i=e.participants)&&void 0!==i?i:[];let r=this.activeCalls.find((t=>t.id===e.id));return r?this.applyOptionsToExistingCall(r,e,t,a):r=this.initializeNewCall(e,n,a,l),{call:r}}initializeNewCall(e,t,i,n){var a,l,s,r,o;const d=e.id||(0,g.v4)();C.info(`[1869] [CallId: ${d}] Creating new call`,{color:"cyan"});const p=(0,u.makeFirstById)([...i,t],this.user.id,this.clientId),h=new c.Call({id:d,sessionId:e.sessionId,mediaFlow:e.mediaFlow,localParticipant:t,participants:p,metadata:e.metadata,createdBy:e.createdBy,chatClient:this.chatClient,isCallSilenced:n});return e.metadata&&h.setVideoCall("true"===e.metadata.videoCall),e.settings&&h.setSettings(e.settings),h.localAudioTracks=e.localAudioTracks||[],h.localVideoTracks=e.localVideoTracks||[],h.localParticipant.setAudioTracks(e.localAudioTracks||[],h),h.localParticipant.setVideoTracks(e.localVideoTracks||[],h),null!=(null===(a=e.audioSettings)||void 0===a?void 0:a.preferredAudioRoute)&&h.setAudioDeviceId(e.audioSettings.preferredAudioRoute),h.localParticipant.setMuted(!(null===(l=e.audioSettings)||void 0===l?void 0:l.publishAudio),h),h.setVideoEnabled(!!(null===(s=e.videoSettings)||void 0===s?void 0:s.publishVideo)),h.localParticipantVideoEnable(!!(null===(r=e.videoSettings)||void 0===r?void 0:r.publishVideo),void 0,!1,!1),h.localParticipant.setParticipantVideoEnabled(!!(null===(o=e.videoSettings)||void 0===o?void 0:o.publishVideo),h),this.activeCalls.push(h),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls),h}applyOptionsToExistingCall(e,t,i,n){var a,l;if(C.info(`[1911] [CallId: ${e.id}] Using existing call`,{color:"cyan"}),void 0!==t.mediaFlow&&e.changeMediaFlow(t.mediaFlow),t.sessionId&&e.setSessionId(t.sessionId),t.createdBy&&e.setCreatedBy(t.createdBy),t.settings&&e.setSettings(t.settings),t.metadata&&(e.metadata=t.metadata,e.setVideoCall("true"===t.metadata.videoCall)),t.participants&&!i){const i=new Set(e.participants.map((e=>e.id))),n=t.participants.filter((({id:e})=>!i.has(e)&&e!==this.user.id)).map((({id:e})=>new s.Participant(e)));n.length>0&&(e.participants=(0,u.makeFirstById)([...e.participants,...n],this.user.id,this.clientId),e.emitParticipantsAdded(n))}else e.participants=n;e.participants.some((e=>e.id===this.user.id&&e.clientId===this.clientId))||e.localParticipant.id!==this.user.id||e.localParticipant.clientId!==this.clientId||(e.participants=(0,u.makeFirstById)([...e.participants,e.localParticipant],this.user.id,this.clientId),e.emitParticipantsAdded([e.localParticipant])),(null===(a=t.localAudioTracks)||void 0===a?void 0:a.length)&&(e.localAudioTracks=t.localAudioTracks,e.localParticipant.setAudioTracks(t.localAudioTracks,e)),(null===(l=t.localVideoTracks)||void 0===l?void 0:l.length)&&(e.localVideoTracks=t.localVideoTracks,e.localParticipant.setVideoTracks(t.localVideoTracks,e)),t.audioSettings&&(null!=t.audioSettings.preferredAudioRoute&&e.setAudioDeviceId(t.audioSettings.preferredAudioRoute),e.setMuted(!t.audioSettings.publishAudio),e.localParticipant.setMuted(!t.audioSettings.publishAudio,e)),t.videoSettings&&(e.setVideoEnabled(!!t.videoSettings.publishVideo),e.localParticipantVideoEnable(!!t.videoSettings.publishVideo,void 0,!1,!1),e.localParticipant.setParticipantVideoEnabled(!!t.videoSettings.publishVideo,e))}processJoinAcknowledgment(e,t,i){var n,a,l,s;if(t.event===d.SignalEvent.ERROR)throw C.error(`[1955] [CallId: ${e.id}] Join failed: message: ${null===(n=t.error)||void 0===n?void 0:n.message} code: ${null===(a=t.error)||void 0===a?void 0:a.code}`),this.leaveCall(e,!0,"processJoinAcknowledgment"),(0,S.checkCode)((null===(l=t.error)||void 0===l?void 0:l.code)||0,null===(s=t.error)||void 0===s?void 0:s.message);if(t.event===d.SignalEvent.SUCCESS)return e.eventsQueue.forEach((e=>{e()})),e.eventsQueue.clear(),this.configureRTCServers(e,t,i),e;throw C.warn(`[1969] [CallId: ${e.id}] Unexpected join event: ${t.event}`),(0,S.checkCode)(4e3,`Unexpected event type: ${t.event}`)}configureRTCServers(e,t,i){var n;(null===(n=t.turnServers)||void 0===n?void 0:n.length)&&this.setRTCConfig(Object.assign(Object.assign({},e.mediaFlow===d.MediaFlow.SFU?{}:{iceServers:t.turnServers.map((e=>({urls:[`${e.url}?transport=tcp`,`${e.url}?transport=udp`],credential:e.password,username:e.username})))}),{bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"})),this.processRemoteParticipants(e,(null==t?void 0:t.participants)||[]),this.reconcileParticipants(e,t.participants||[]),e.mediaFlow===d.MediaFlow.SFU?this.setupSFUConnection(e,i,t):e.participants.forEach((t=>{e.mediaFlow===d.MediaFlow.P2P&&t.getFullId()!=e.localParticipant.getFullId()&&t.state===d.ParticipantState.Joined&&this.isPolitePeer(t.getFullId(),e.localParticipant.getFullId())&&(C.info(`[2008] [CallId: ${e.id}] Sending offer to participant: ${t.getFullId()}`),this.sendOfferPeerToPeer(e,t,(t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[2005] [CallId: ${e.id}] SYNC OFFER failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`):t.event!==d.SignalEvent.ERROR||C.error(`[2010] [CallId: ${e.id}] SYNC OFFER failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`)})))}))}setupSFUConnection(e,t,i){const n=new s.Participant(e.id);C.info(`[2005] [CallId: ${e.id}] [serverParticipant.id:${n.getFullId()}] Adding server participant to RTC map`,{color:"cyan"});try{e.setServerParticipant(n);const a=n=>{n instanceof h.SceytCallException||n instanceof Error?C.error(`[2011] [CallId: ${e.id}] SYNC OFFER failed message: ${n.message} code: ${n instanceof h.SceytCallException?n.code:""}`):(n.event===d.SignalEvent.ERROR&&C.error(`[2015] [CallId: ${e.id}] SYNC OFFER failed message: ${n.error?`${n.error.message} code: ${n.error.code}`:""}`),n.event!==d.SignalEvent.ERROR&&(C.info(`[2019] [CallId: ${e.id}] offerAck: ${JSON.stringify(n)}`,{color:"cyan"}),e.participants.forEach((n=>{var a;if(n.id===this.user.id&&n.clientId===this.clientId||!(null===(a=null==i?void 0:i.participants)||void 0===a?void 0:a.find((e=>e.id===n.id&&e.clientId===n.clientId&&e.connectionState===d.ParticipantConnectionState.Connected))))n.connectionState&&n.connectionState>d.ParticipantConnectionState.Connected&&n.id!==this.user.id&&n.clientId!==this.clientId&&n.getFullId()!=e.localParticipant.getFullId()&&(n.updateConnectionState(n.connectionState,e.id),e.emitParticipantConnectionStateChanged(n,n.connectionState));else{const a=t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[2023] [CallId: ${e.id}] SYNC CONNECT failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`):t.event!==d.SignalEvent.ERROR||C.error(`[2028] [CallId: ${e.id}] SYNC CONNECT failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`)};this.signalingClient.clearParticipantSignals(e.id,n.getFullId()),this.signalingClient.sendSignalMessage({mediaFlow:t,callId:e.id,event:d.SignalEvent.CONNECT,sessionId:i.sessionId,to:n.getFullId(),metadata:e.metadata},a)}}))))};C.info(`[2067] [CallId: ${e.id}] Sending offer to server participant: ${n.getFullId()}`),this.sendOfferPeerToPeer(e,n,a)}catch(t){throw C.error(`[2049] [CallId: ${e.id}] SFU setup error: message: ${t instanceof Error?t.message:JSON.stringify(t)}`),(0,S.toCallException)(t)}}processRemoteParticipants(e,t){t.length&&(t.forEach((t=>{let i=e.participants.find((e=>e.getFullId()===this.getParticipantId(t)));if(i||(i=e.participants.find((e=>e.id===t.id&&(e.clientId===t.clientId||!e.clientId))),i&&!i.clientId&&(i.clientId=t.clientId)),i||e.localParticipant.getFullId()===this.getParticipantId(t))i&&e.localParticipant.getFullId()!==this.getParticipantId(t)&&(i.presenter=!!t.presenter,i.setParticipantVideoEnabled(!!t.hasOwnProperty("videoEnabled")&&!!t.videoEnabled,e),i.setMuted(!!t.hasOwnProperty("muted")&&!!t.muted,e),i.setHold(!!t.hasOwnProperty("onHold")&&!!t.onHold,e),i.setScreenSharing(!!t.hasOwnProperty("screenSharing")&&!!t.screenSharing,e),i.state!=t.state&&void 0!==t.state&&(i.updateState(t.state||d.ParticipantState.Idle,e.id),e.emitParticipantStateChanged(i,t.state,"FromJoin")));else{const i=new s.Participant(t.id,t.clientId);i.updateState(t.state||d.ParticipantState.Idle,e.id),i.setParticipantVideoEnabled(!!t.hasOwnProperty("videoEnabled")&&!!t.videoEnabled,e),i.setMuted(!!t.hasOwnProperty("muted")&&!!t.muted,e),i.setHold(!!t.hasOwnProperty("onHold")&&!!t.onHold,e),i.setScreenSharing(!!t.hasOwnProperty("screenSharing")&&!!t.screenSharing,e),e.addParticipantToList(i),e.emitParticipantsAdded([i])}})),C.info(`[2098] [CallId: ${e.id}] Processed participants - Added and Updated`,{color:"cyan"}))}reconcileParticipants(e,t){if(!(null==t?void 0:t.length))return;const i=e.participants.filter((i=>(i.id!==e.localParticipant.id||i.clientId!==e.localParticipant.clientId)&&!t.some((e=>!(e.id!==i.id||e.clientId!==i.clientId&&e.clientId&&i.clientId)))));i.length&&(e.participants=e.participants.filter((e=>!i.includes(e))),e.emitParticipantsRemoved(i))}processJoinCall(e,t,i){e.mediaFlow!==d.MediaFlow.SFU&&e.localParticipant.updateConnectionState(d.ParticipantConnectionState.Connected,e.id);const n=t.mediaFlow||d.MediaFlow.P2P;e.setSessionId(t.sessionId),e.changeMediaFlow(n),e.localParticipant.updateState(d.ParticipantState.Joined,e.id),e.setState(d.CallState.Connected,i)?(e.emitParticipantStateChanged(e.localParticipant,d.ParticipantState.Joined),e.emitParticipantConnectionStateChanged(e.localParticipant,d.ParticipantConnectionState.Connected),this.processJoinAcknowledgment(e,t,n)):this.leaveCall(e,!0,"processJoinCall")}startCall(e,t,i){const a=t.mediaFlow,s=e.participants.filter((e=>!(e.id===this.user.id&&e.clientId===this.clientId))).map((e=>e.serialize()));e.mediaFlow!==d.MediaFlow.SFU&&e.localParticipant.updateConnectionState(d.ParticipantConnectionState.Connecting,e.id);const r=(t,r)=>{var o,c,u,p;if(e.state==d.CallState.Idle)return t.forEach((e=>{e.stop()})),void(null==i||i({error:(0,S.checkCode)(5002,"Call was ended before media setup completed")}));r&&r.length>0&&(e.localParticipant.setVideoTracks(r,e),e.localVideoTracks=r,e.setVideoDeviceId(r[0].getSettings().deviceId||null)),e.localParticipant.setAudioTracks(t,e),e.localAudioTracks=t,this.joinToCall({mediaFlow:a,callId:e.id,sessionId:e.sessionId,participants:s,metadata:e.metadata,joinOptions:{muted:e.muted,videoEnabled:e.videoEnabled,settings:Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==(null===(o=e.settings)||void 0===o?void 0:o.broadcastSettings)&&{broadcastSettings:e.settings.broadcastSettings}),void 0!==(null===(c=e.settings)||void 0===c?void 0:c.startsAt)&&{startsAt:l.default.fromNumber(e.settings.startsAt)}),void 0!==(null===(u=e.settings)||void 0===u?void 0:u.expiresAt)&&{expiresAt:l.default.fromNumber(e.settings.expiresAt)}),void 0!==(null===(p=e.settings)||void 0===p?void 0:p.persistent)&&{persistent:e.settings.persistent})}},(t=>n(this,void 0,void 0,(function*(){var n;return t instanceof h.SceytCallException||t instanceof Error?(C.error(`[2137] [CallId: ${e.id}] SYNC JOIN failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`),e.setState(d.CallState.Closed,"joinCall failed"),void(null==i||i({error:(0,S.toCallException)(t)}))):t.event===d.SignalEvent.ERROR?(C.error(`[2141] [CallId: ${e.id}] SYNC JOIN failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`),void(null==i||i({error:(0,S.checkCode)(5003,(null===(n=t.error)||void 0===n?void 0:n.message)||"Unknown error")}))):void this.processJoinCall(e,t,"from joinCall")}))))};return e.localAudioTracks&&e.localAudioTracks.length>0||e.localVideoTracks&&e.localVideoTracks.length>0?!(e.localAudioTracks&&e.localAudioTracks.length>0)&&e.localVideoTracks&&e.localVideoTracks.length>0?this.setupMediaStream(e).then((({audioTracks:e})=>{r(e,t.localVideoTracks||[])})):!e.localAudioTracks||e.localVideoTracks&&e.localVideoTracks.length>0?r(e.localAudioTracks||[],e.localVideoTracks||[]):r(t.localAudioTracks||[]):this.setupMediaStream(e).then((({audioTracks:e})=>{r(e)})),e}promoteFromPrepared(e,t){var i;const n=this.prepareCalls.findIndex((t=>t.id===e));if(-1===n)return;const a=this.prepareCalls[n];return this.prepareCalls.splice(n,1),this.activeCalls.push(a),t&&(this.updateCallMetadata(a,t),(null===(i=t.participants)||void 0===i?void 0:i.length)&&this.syncParticipants(a,t.participants)),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls),a}prepareCall(e,t,i){var n,a,l;try{const r=e||(0,g.v4)();C.info(`[2155] [CallId: ${e}] prepareCall, creating call object`,{color:"blue"});const o=this.activeCalls.find((t=>t.id===e));if(o)return{success:!0,data:o};const u=this.prepareCalls.find((t=>t.id===e));if(u)return this.applyCreateOptions(u,t),this.applyServerCall(u,i),{success:!0,data:u};const p=null!==(a=null!==(n=null==i?void 0:i.mediaFlow)&&void 0!==n?n:null==t?void 0:t.mediaFlow)&&void 0!==a?a:0,h=new s.Participant(this.user.id,this.clientId),v=new c.Call({id:r,sessionId:null==i?void 0:i.sessionId,mediaFlow:null!=p?p:d.MediaFlow.P2P,localParticipant:h,participants:[h],createdBy:null!==(l=null==i?void 0:i.createdBy)&&void 0!==l?l:this.user.id,chatClient:this.chatClient,isCallSilenced:!1});return this.applyCreateOptions(v,t),this.applyServerCall(v,i),this.prepareCalls.push(v),{success:!0,data:v}}catch(t){return C.error(`[2158] [CallId: ${e}] prepareCall failed: ${t.message||JSON.stringify(t)}`,{color:"red"}),{success:!1,error:(0,S.toCallException)(t)}}}prepareCallFromCallID(e){return n(this,void 0,void 0,(function*(){return new Promise((t=>{this.signalingClient.sendSignalMessage({event:d.SignalEvent.GET_CALL,callId:e},(i=>{var n,a,l,s;if(i instanceof h.SceytCallException||i instanceof Error)return C.error(`[2160] prepareCallFromCallID GET_CALL failed: ${i.message}`,{color:"red"}),void t({success:!1,error:(0,S.toCallException)(i)});if(i.event===d.SignalEvent.ERROR)return C.error(`[2161] prepareCallFromCallID GET_CALL failed: ${null===(n=i.error)||void 0===n?void 0:n.message}`,{color:"red"}),void t({success:!1,error:(0,S.checkCode)((null===(a=i.error)||void 0===a?void 0:a.code)||5e3,(null===(l=i.error)||void 0===l?void 0:l.message)||"GET_CALL failed")});const r=null===(s=i.calls)||void 0===s?void 0:s.find((t=>t.id===e));if(!r)return void t({success:!1,error:h.SceytCallException.BadRequest(4004,`Call ${e} not found`)});const o=this.prepareCall(e,{mediaFlow:r.mediaFlow},r);o.success&&o.data&&this.updateCallMetadata(o.data,r),t(o)}),"get_call")}))}))}joinCall(e,t,i){let n=null;try{C.info(`[2159] [CallId: ${e.id}] joinCall, start call`,{color:"blue"});const a={id:e.id,sessionId:e.sessionId||void 0,mediaFlow:e.mediaFlow,participants:e.participants.filter((({id:e})=>e!==this.user.id)),metadata:e.metadata,createdBy:e.createdBy,localAudioTracks:t.localAudioTracks,localVideoTracks:t.localVideoTracks,audioSettings:t.audioSettings,videoSettings:t.videoSettings},l=e.setState(d.CallState.Connecting,"joinCall");let s=this.promoteFromPrepared(e.id);if(s)this.applyOptionsToExistingCall(s,a,s.participants,s.participants);else{const{call:e}=this.findOrCreateCall(a);s=e}return l?(s.localParticipant.clientId=this.clientId,n=this.startCall(s,a,i),{success:!0,data:s}):{success:!1,error:(0,S.checkCode)(5001,`Failed to set call state from ${s.state} to connecting`)}}catch(e){return C.error(`[2173] [CallId: ${null==n?void 0:n.id}] Join call failed: ${e.message||JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,S.toCallException)(e)}}}createCall(e,t){var i;try{C.info(`[2180] [CallId: ${e.id}] createCall, creating call link`,{color:"blue"});const n=e.settings;if(void 0!==(null==n?void 0:n.startsAt)&&void 0!==(null==n?void 0:n.expiresAt)&&n.startsAt>=n.expiresAt)return{success:!1,error:h.SceytCallException.BadRequest(4001,"startsAt must be before expiresAt")};const a=[...new Set(e.participants.filter((e=>!(e.id===this.user.id&&e.clientId===this.clientId))).map((e=>e.id)))],s=null!==(i=this.prepareCalls.find((t=>t.id===e.id)))&&void 0!==i?i:e,r=e=>{var i,n,a;return e instanceof h.SceytCallException||e instanceof Error?(C.error(`[2210] [CallId: ${s.id}] CREATE signal failed: ${e.message}`,{color:"red"}),void(null==t||t({error:(0,S.toCallException)(e)}))):e.event===d.SignalEvent.ERROR?(C.error(`[2219] [CallId: ${s.id}] CREATE signal failed: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"}),void(null==t||t({error:(0,S.checkCode)((null===(i=e.error)||void 0===i?void 0:i.code)||5e3,(null===(n=e.error)||void 0===n?void 0:n.message)||"Create call failed")}))):(C.info(`[2228] [CallId: ${s.id}] Call link created successfully`,{color:"blue"}),e.sessionId&&(this.promoteFromPrepared(s.id),s.setSessionId(e.sessionId),s.setIsCreatedRemotely(!0)),void((null===(a=e.participants)||void 0===a?void 0:a.length)&&this.reconcileParticipants(s,e.participants)))};return this.signalingClient.sendSignalMessage(Object.assign(Object.assign({event:d.SignalEvent.CREATE,callId:s.id,mediaFlow:s.mediaFlow,participants:a.map((e=>({id:e,clientId:""})))},s.metadata&&{metadata:s.metadata}),{settings:Object.assign(Object.assign(Object.assign({},void 0!==(null==n?void 0:n.startsAt)&&{startsAt:l.default.fromNumber(n.startsAt)}),void 0!==(null==n?void 0:n.expiresAt)&&{expiresAt:l.default.fromNumber(n.expiresAt)}),void 0!==(null==n?void 0:n.persistent)&&{persistent:n.persistent})}),r),{success:!0,data:s}}catch(t){return C.error(`[2238] [CallId: ${e.id}] createCall failed: ${t.message||JSON.stringify(t)}`,{color:"red"}),{success:!1,error:(0,S.toCallException)(t)}}}signalMessageToICall(e){const t=e.settings?Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e.settings.startsAt&&{startsAt:l.default.isLong(e.settings.startsAt)?e.settings.startsAt.toNumber():e.settings.startsAt}),void 0!==e.settings.expiresAt&&{expiresAt:l.default.isLong(e.settings.expiresAt)?e.settings.expiresAt.toNumber():e.settings.expiresAt}),void 0!==e.settings.persistent&&{persistent:e.settings.persistent}),void 0!==e.settings.broadcastOptions&&{broadcastSettings:e.settings.broadcastOptions}):void 0;return{id:e.callId,sessionId:e.sessionId,mediaFlow:e.mediaFlow,createdBy:e.createdBy,metadata:e.metadata||{},participants:e.participants||[],createdAt:l.default.isLong(e.createdAt)?e.createdAt.toNumber():e.createdAt,settings:t}}applyCreateOptions(e,t){if(!t)return;const i=t.videoCall?Object.assign(Object.assign({},t.metadata),{videoCall:"true"}):t.metadata;if(i&&(e.metadata=i),t.videoCall&&e.setVideoCall(!0),t.settings&&e.setSettings(t.settings),t.participantIds){const i=[...new Set(t.participantIds.filter((e=>e!==this.user.id)))],n=new Set(e.participants.map((e=>e.id))),a=i.filter((e=>!n.has(e))).map((e=>new s.Participant(e)));a.length>0&&(e.participants=(0,u.makeFirstById)([...e.participants,...a],this.user.id,this.clientId))}}applyServerCall(e,t){var i,n;t&&(t.sessionId&&e.setSessionId(t.sessionId),void 0!==t.mediaFlow&&(e.mediaFlow=t.mediaFlow),t.metadata&&(null===(i=Object.values(t.metadata))||void 0===i?void 0:i.length)&&(e.metadata=t.metadata),t.createdBy&&(e.createdBy=t.createdBy),t.settings&&e.setSettings(Object.assign(Object.assign(Object.assign({},t.settings),void 0!==t.settings.startsAt&&{startsAt:l.default.isLong(t.settings.startsAt)?t.settings.startsAt.toNumber():t.settings.startsAt}),void 0!==t.settings.expiresAt&&{expiresAt:l.default.isLong(t.settings.expiresAt)?t.settings.expiresAt.toNumber():t.settings.expiresAt})),(null===(n=t.participants)||void 0===n?void 0:n.length)&&this.syncParticipants(e,t.participants))}updateCallMetadata(e,t){var i,n;t.metadata&&(null===(i=Object.values(t.metadata))||void 0===i?void 0:i.length)&&(e.metadata=t.metadata||{}),e.createdBy=t.createdBy,e.sessionId=t.sessionId,e.id=t.id,e.setVideoCall("true"===(null===(n=e.metadata)||void 0===n?void 0:n.videoCall)),e.mediaFlow!==d.MediaFlow.SFU&&t.mediaFlow===d.MediaFlow.SFU&&e.changeMediaFlow(d.MediaFlow.SFU),t.settings&&e.setSettings(t.settings),C.info(`[2187] [CallId: ${e.id}] Updated call metadata for call ${e.id}`,{color:"light-blue"})}syncParticipants(e,t){C.info(`[2198] [CallId: ${e.id}] Syncing participants for call ${e.id}`,{color:"light-blue"}),e.participants=e.participants.filter((i=>{const n=t.find((e=>!(e.id!==i.id||e.clientId!==i.clientId&&e.clientId&&i.clientId)));return n||(C.info(`[2202] [CallId: ${e.id}] Removing participant ${i.id} who is no longer in the call`,{color:"light-blue"}),e.emitParticipantStateChanged(i,d.ParticipantState.Left),e.kickParticipantFromList(i,!1)),!!n})),C.info(`[2216] [CallId: ${e.id}] Syncing participants for call ${e.id}`,{color:"light-blue"});for(const i of t){const t=e.participants.find((e=>!(e.id!==i.id||e.clientId!==i.clientId&&i.clientId&&e.clientId)));if(C.info(`[2219] [CallId: ${e.id}] Syncing participants for call ${e.id}`,{color:"light-blue"}),t){if(t.clientId||(t.clientId=i.clientId),t.id===e.localParticipant.id&&t.clientId===e.localParticipant.clientId){i.state===d.ParticipantState.Joined&&e.localParticipant.state>d.ParticipantState.Joined&&this.leaveCall(e,!0,"syncParticipants");continue}t.state=i.state||d.ParticipantState.Idle,e.emitParticipantStateChanged(t,i.state||d.ParticipantState.Idle),t.state!==d.ParticipantState.Joined?t.getFullId()!==e.localParticipant.getFullId()&&(this.closePeerConnections(e.id,t.getFullId()),e.activeSpeakerManager.removeParticipant(t)):t.id!==e.localParticipant.id&&t.clientId!==e.localParticipant.clientId&&e.state===d.CallState.Connected&&this.handleNewParticipant(e,t),t.getFullId()===e.localParticipant.getFullId()&&(e.localParticipant=t),this.syncParticipantMediaState(e,t,i),C.info(`[2254] [CallId: ${e.id}] Syncing existing participants: ${t.getFullId()} for call ${e.id}`,{color:"light-blue"})}else{const t=new s.Participant(i.id,i.clientId);t.state=i.state||d.ParticipantState.Idle,e.addParticipantToList(t),this.syncParticipantMediaState(e,t,i),C.info(`[2263] [CallId: ${e.id}] Syncing no existing participants: ${t.getFullId()} for call ${e.id}`,{color:"light-blue"}),e.emitParticipantsAdded([t]),(e.mediaFlow!==d.MediaFlow.SFU&&i.state===d.ParticipantState.Joined||e.mediaFlow===d.MediaFlow.SFU&&i.connectionState===d.ParticipantConnectionState.Connected&&e.state===d.CallState.Connected)&&this.handleNewParticipant(e,t)}}}syncParticipantMediaState(e,t,i){if(t.getFullId()===i.id+(i.clientId?"/"+i.clientId:"")){const n=!!i.hasOwnProperty("muted")&&!!i.muted,a=!!i.hasOwnProperty("screenSharing")&&!!i.screenSharing,l=!!i.hasOwnProperty("videoEnabled")&&!!i.videoEnabled,s=!!i.hasOwnProperty("onHold")&&!!i.onHold,r=!!i.hasOwnProperty("isCallSilenced")&&!!i.isCallSilenced;n!==t.muted&&(C.info(`[2287] [CallId: ${e.id}] Participant ${t.getFullId()} audio state changed: ${t.muted} -> ${n}`,{color:"light-blue"}),t.setMuted(n,e)),l===t.videoEnabled||a||(C.info(`[2296] [CallId: ${e.id}] Participant ${t.getFullId()} video state changed: ${t.videoEnabled} -> ${l}`,{color:"light-blue"}),t.setParticipantVideoEnabled(l,e)),a!==t.screenSharing&&(C.info(`[2307] [CallId: ${e.id}] Participant ${t.getFullId()} screen sharing state changed: ${t.screenSharing} -> ${a}`,{color:"light-blue"}),t.setScreenSharing(a,e)),s!==t.onHold&&(C.info(`[2317] [CallId: ${e.id}] Participant ${t.getFullId()} hold state changed: ${t.onHold} -> ${s}`,{color:"light-blue"}),t.setHold(s,e)),t.getFullId()===e.localParticipant.getFullId()&&(C.info(`[2327] [CallId: ${e.id}] Participant ${t.getFullId()} ring allowed state changed: ${r}`,{color:"light-blue"}),e.setIsCallSilenced(r))}}handleNewParticipant(e,t){if(C.info(`[2333] [CallId: ${e.id}] Call media flow: ${e.mediaFlow}`,{color:"light-blue"}),e.mediaFlow!==d.MediaFlow.SFU){if(t.updateState(d.ParticipantState.Joined,e.id),e.emitParticipantStateChanged(t,d.ParticipantState.Joined),t.getFullId()!==e.localParticipant.getFullId()&&t.connectionState!==d.ParticipantConnectionState.Connected&&t.connectionState!==d.ParticipantConnectionState.Reconnecting){const i=t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[2341] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`,{color:"red"}):t.event!==d.SignalEvent.ERROR||C.error(`[2345] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`,{color:"red"})};C.info(`[2370] [CallId: ${e.id}] Sending offer to participant: ${t.getFullId()}`),e.localParticipant.state===d.ParticipantState.Joined&&e.mediaFlow===d.MediaFlow.P2P&&this.isPolitePeer(t.getFullId(),e.localParticipant.getFullId())?this.sendOfferPeerToPeer(e,t,i):e.localParticipant.state===d.ParticipantState.Joined&&(this.signalingClient.clearParticipantSignals(e.id,t.getFullId()),this.signalingClient.sendSignalMessage({to:t.getFullId(),mediaFlow:e.mediaFlow,callId:e.id,event:d.SignalEvent.CONNECT,sessionId:e.sessionId},i))}}else if(t.getFullId()!==e.localParticipant.getFullId()&&t.connectionState!==d.ParticipantConnectionState.Reconnecting){const i=t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[2354] [CallId: ${e.id}] SYNC CONNECT signal sent failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`,{color:"red"}):t.event!==d.SignalEvent.ERROR||C.error(`[2358] [CallId: ${e.id}] SYNC CONNECT signal sent failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`,{color:"red"})};this.signalingClient.clearParticipantSignals(e.id,t.getFullId()),this.signalingClient.sendSignalMessage({to:t.getFullId(),mediaFlow:e.mediaFlow,callId:e.id,event:d.SignalEvent.CONNECT,sessionId:e.sessionId},i)}}handleSessionRenewedSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(!t)return void C.warn(`[SessionRenewed] [CallId: ${e.callId}] No active call found`,{color:"red"});const i=e.sessionId;C.info(`[SessionRenewed] [CallId: ${t.id}] Session renewed: ${t.sessionId} -> ${i}`,{color:"cyan"}),t.setSessionId(i),t.emitSessionRenewed(i)}handleConnectSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){let i=t.participants.find((t=>t.getFullId()===e.from));i&&this.sendOfferPeerToPeer(t,i,(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[2417] [CallId: ${t.id}] SYNC OFFER signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[2421] [CallId: ${t.id}] SYNC OFFER signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})}))}}handleMediaFlowSwitch(e){C.info(`[2375] [CallId: ${e.id}] Switching call ${e.id} from P2P to SFU`,{color:"light-blue"});const t=new s.Participant(e.id);e.setServerParticipant(t),C.info(`[2395] [CallId: ${e.id}] Sending offer to server participant: ${t.getFullId()}`),this.sendOfferPeerToPeer(e,t,(t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[2386] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`,{color:"red"}):t.event!==d.SignalEvent.ERROR||C.error(`[2390] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`,{color:"red"})})),e.participants.forEach((e=>{e.setShouldResetPeerConnection(!0)}))}}t.InternalCallHandler=f},787:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Participant=void 0;const n=i(578),a=i(758),l=i(645),s=(0,l.createLogger)("ParticipantState"),r=(0,l.createLogger)("ConnectionState");t.Participant=class{constructor(e,t){this.clientId="",this.muted=!1,this.onHold=!1,this.videoEnabled=!1,this.screenSharing=!1,this.presenter=!1,this.audioTracks=[],this.videoTracks=[],this.shouldResetPeerConnection=!1,this.state=n.ParticipantState.Idle,this.connectionState=n.ParticipantConnectionState.Idle;const i=e.split("/");this.id=i[0],this.clientId=t||i[1]||""}updateState(e,t){const i=new a.ParticipantStateMachine(this.id,t).updateState(e,this.state);return i&&(this.state=e,s.info(`[35] [CallId: ${t}] Updating state: ${e}, participantID: ${this.getFullId()}`,{color:"blue"})),i}updateConnectionState(e,t){const i=new a.ParticipantStateMachine(this.id,t).updateConnectionState(e,this.connectionState);return i&&(this.connectionState=e,r.info(`[45] [CallId: ${t}] Updating connection state: ${e}, participantID: ${this.getFullId()}`,{color:"blue"})),i}setShouldResetPeerConnection(e){this.shouldResetPeerConnection=e}setMuted(e,t){this.audioTracks.forEach((t=>{t.enabled=!e})),this.muted=e,t&&t.emitParticipantEvent(this,this.muted?"Mute":"Unmute")}setParticipantVideoEnabled(e,t){this.videoTracks.forEach((t=>{t.enabled=e})),this.videoEnabled=e,t&&t.emitParticipantEvent(this,this.videoEnabled?"VideoEnabled":"VideoDisabled")}setScreenSharing(e,t){this.videoTracks.forEach((t=>{t.enabled=e})),this.screenSharing=e,t&&t.emitParticipantEvent(this,this.screenSharing?"ScreenSharingStarted":"ScreenSharingStopped")}setPresenter(e){this.presenter=e}setAudioTracks(e,t){this.audioTracks=e,this.audioTracks.forEach((e=>{e.enabled=!this.muted})),t.emitAudioTrackAdded(this,e[0])}setVideoTracks(e,t){this.videoTracks=e,this.videoTracks.forEach((e=>{e.enabled=this.videoEnabled})),t.emitVideoTrackAdded(this,e[0])}setHold(e,t){this.onHold=e,t&&t.emitParticipantEvent(this,this.onHold?"Hold":"Unhold")}serialize(){return{id:this.id,clientId:this.clientId}}getFullId(){return this.id+(this.clientId?"/"+this.clientId:"")}}},816:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.QueryBuilder=void 0,t.QueryBuilder=class{constructor(){this.count=10}}},185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RecentCallQueryBuilder=void 0;const n=i(578),a=i(650),l=i(816),s=i(343),r=i(228);class o extends l.QueryBuilder{constructor(){super(...arguments),this.order=n.CDRRequestOrder.ASC,this.count=10,this.participantCount=10,this.event=n.CDRRequestEvent.GET_RECENT_CALLS,this.direction=n.CDRRequestDirection.NEXT,this.setSessionIdList=e=>(this.sessionIdList=e,this),this.setEvent=e=>(this.event=e,this),this.setSessionId=e=>(this.sessionId=e,this),this.limit=e=>(this.count=e,this),this.setParticipantCount=e=>(this.participantCount=e,this),this.setOrder=e=>(this.order=e,this),this.setDirection=e=>(this.direction=e,this),this.build=()=>{const e=a.InternalCallHandler.getInstance();this.chatClient=e.chatClient;try{return new s.RecentCallQuery(this)}catch(e){throw(0,r.toCallException)(e)}}}}t.RecentCallQueryBuilder=o},343:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.RecentCallQuery=void 0;const a=i(578),l=i(645),s=i(228),r=(0,l.createLogger)("RecentCallQuery");t.RecentCallQuery=class{constructor(e){this.count=10,this.hasNext=!0,this.loading=!1,this.order=a.CDRRequestOrder.ASC,this.participantCount=10,this.event=a.CDRRequestEvent.GET_RECENT_CALLS,this.direction=a.CDRRequestDirection.NEXT,this.loadNextPage=()=>n(this,void 0,void 0,(function*(){if(this.loading)throw r.info("QUERY_IN_PROGRESS"),(0,s.checkCode)(5001,"QUERY_IN_PROGRESS");if(this.hasNext){this.loading=!0;const e=yield this.chatClient.sendCallDetailsRecord(Object.assign({event:this.event,order:this.order,limit:this.count,participantCount:this.participantCount,direction:this.direction},this.nextToken||this.sessionId?{position:Object.assign(Object.assign({},this.sessionId?{sessionId:this.sessionId}:{}),this.nextToken?{nextToken:this.nextToken}:{})}:{}));this.loading=!1;const{getRecentCallsResponse:{records:t,nextToken:i}}=e;return this.hasNext=!!i,this.nextToken=i,{records:t,hasNext:this.hasNext}}return{records:[],hasNext:this.hasNext}})),this.deleteCalls=()=>n(this,void 0,void 0,(function*(){var e;if(null===(e=this.sessionIdList)||void 0===e?void 0:e.length)return yield this.chatClient.sendCallDetailsRecord({event:a.CDRRequestEvent.DELETE_RECENT_CALLS,sessionIdList:{items:this.sessionIdList}})})),this.order=e.order,this.count=e.count,this.participantCount=e.participantCount,this.sessionId=e.sessionId,this.event=e.event,this.direction=e.direction,this.chatClient=e.chatClient,this.sessionIdList=e.sessionIdList}set limit(e){this.count=e}get limit(){return this.count}}},680:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSessionDescription=t.toSessionData=void 0;const n=i(578),a=i(645),l=i(19),s=(0,a.createLogger)("SignalingExtensions");t.toSessionData=function(e,t){const i=e.sdp.sdp||"",a=1e3*Date.now()+performance.now()%1*1e3;s.info(`[32] [CALL_TIME_TO_SESSION_DATA_START: ${a}]`,{color:"blue"});const r=l.SdpConverter.parseToSdpData(i,l.CODEC_NAME_TO_VIDEO_CODEC,t===n.MediaFlow.S2W?l.CODEC_NAME_TO_AUDIO_CODEC_S2W:l.CODEC_NAME_TO_AUDIO_CODEC),o=1e3*Date.now()+performance.now()%1*1e3;return s.info(`[35] [CALL_TIME_TO_SESSION_DATA_END: ${o}]`,{color:"blue"}),{id:e.sessionId,version:e.versionId,sdpData:r}},t.toSessionDescription=function(e,t){if(e.sdpData){const i=l.SdpConverter.reconstructFromSDPData(e.sdpData);return s.info(`[53] [CallId: ${e.id}] toSessionDescription in sdp-converter: sdp: ${i}`,{color:"blue"}),{type:t,sdp:i}}return s.error("SessionData has neither sdpData nor sdp field"),null}},19:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SdpConverter=t.CODEC_NAME_TO_AUDIO_CODEC_S2W=t.CODEC_NAME_TO_AUDIO_CODEC=t.CODEC_NAME_TO_VIDEO_CODEC=void 0;const n=i(645),a=i(228),l=i(799),s=(0,n.createLogger)("SdpConverter");t.CODEC_NAME_TO_VIDEO_CODEC=["vp8","rtx","red"],t.CODEC_NAME_TO_AUDIO_CODEC=["opus","red"],t.CODEC_NAME_TO_AUDIO_CODEC_S2W=["opus","red","pcmu","pcma"];class r{static parseToSdpData(e,i=t.CODEC_NAME_TO_VIDEO_CODEC,n=t.CODEC_NAME_TO_AUDIO_CODEC){var a,l,s;const o=[],d=e.split("\n").map((e=>e.trim())).filter((e=>e.length>0)),c=r.extractSessionId(d)||"",u=r.extractSessionVersion(d)||0,p=r.extractOriginAddress(d)||"127.0.0.1",g=(null===(a=d.find((e=>e.startsWith("s="))))||void 0===a?void 0:a.substring(2))||"-",h=(null===(l=d.find(((e,t)=>e.startsWith("c=")&&!r.inMediaSection(d,t))))||void 0===l?void 0:l.split(" ").slice(2)[0])||"",v=(null===(s=r.firstValueStartingWith(d,"a=msid-semantic:"))||void 0===s?void 0:s.trim())||"WMS",S=r.parseBundleGroup(d),C=d.findIndex((e=>e.startsWith("m="))),f=C>0?d.slice(0,C):d,I=r.firstValueStartingWith(f,"a=ice-ufrag:")||"",E=r.firstValueStartingWith(f,"a=ice-pwd:")||"",m=r.parseIceOptions(f),P=r.parseFingerprint(f),$=r.parseSetup(f),y=f.some((e=>"a=ice-lite"===e)),T=f.some((e=>"a=extmap-allow-mixed"===e));return{sessionId:c,sessionVersion:u,bundleGroup:S,iceUfrag:I,icePwd:E,iceOptions:m,fingerprint:P,setup:$,media:r.parseMediaSections(d,o,i,n),sessionName:g,originAddress:p,connectionAddress:h,msidSemantic:v,iceLite:y,extmapAllowMixed:T,stringPool:o}}static reconstructFromSDPData(e){var t,i,n,l,o,d;try{const c=[];if(c.push("v=0\r\n"),c.push(`o=- ${e.sessionId} ${e.sessionVersion} IN IP4 ${e.originAddress}\r\n`),c.push(`s=${e.sessionName}\r\n`),c.push("t=0 0\r\n"),(null===(i=null===(t=e.fingerprint)||void 0===t?void 0:t.hashValue)||void 0===i?void 0:i.length)>0&&c.push(`a=fingerprint:${r.fingerprintToString(e.fingerprint)}\r\n`),(null===(n=null==e?void 0:e.bundleGroup)||void 0===n?void 0:n.length)>0){const t=e.media.map((e=>e.mid)).join(" ");c.push(`a=group:BUNDLE ${t}\r\n`)}(null===(l=null==e?void 0:e.iceOptions)||void 0===l?void 0:l.length)>0&&c.push(`a=ice-options:${e.iceOptions.join(" ")}\r\n`),(null==e?void 0:e.extmapAllowMixed)&&c.push("a=extmap-allow-mixed\r\n"),(null===(o=null==e?void 0:e.msidSemantic)||void 0===o?void 0:o.length)>0&&c.push(`a=msid-semantic: ${e.msidSemantic}\r\n`),(null==e?void 0:e.iceLite)&&c.push("a=ice-lite\r\n"),null===(d=null==e?void 0:e.media)||void 0===d||d.forEach((t=>{r.buildMediaSection(c,t,e)}));const u=c.join("");if(s.debug(`Reconstructed SDP (${null==u?void 0:u.length} bytes)`),!(null==u?void 0:u.includes("m=")))throw(0,a.checkCode)(4e3,"Reconstructed SDP missing media lines");if(!(null==u?void 0:u.includes("a=ice-ufrag:"))&&!(null==u?void 0:u.includes("a=ice-pwd:")))throw(0,a.checkCode)(4e3,"Reconstructed SDP missing ICE credentials");return u}catch(e){throw s.error(`[647] [CallId: GLOBAL_LOGS] Failed to reconstruct SDP: ${e.message}`,{color:"red"}),s.error(e,{color:"red"}),(0,a.toCallException)(e)}}static extractSessionId(e){const t=e.find((e=>e.startsWith("o=")));return t&&t.split(" ")[1]||null}static extractSessionVersion(e){const t=e.find((e=>e.startsWith("o=")));if(!t)return null;const i=t.split(" "),n=parseInt(i[2]||"0",10);return isNaN(n)?null:n}static extractOriginAddress(e){const t=e.find((e=>e.startsWith("o=")));return t&&t.split(" ")[5]||null}static parseBundleGroup(e){const t=e.find((e=>e.startsWith("a=group:BUNDLE ")));return t?t.substring(15).split(" ").map((e=>parseInt(e,10))).filter((e=>!isNaN(e))):[]}static parseIceOptions(e){const t=e.find((e=>e.startsWith("a=ice-options:")));return t?t.substring(14).split(" "):[]}static parseFingerprint(e){var t;const i=e.find((e=>e.startsWith("a=fingerprint:")));if(i){const e=i.substring(14).split(" ",2);if(2===e.length){let i;switch(e[0].toLowerCase()){case"sha-256":default:i=l.HashFunction.SHA256;break;case"sha-1":i=l.HashFunction.SHA1;break;case"sha-384":i=l.HashFunction.SHA384;break;case"sha-512":i=l.HashFunction.SHA512;break;case"md5":i=l.HashFunction.MD5}const n=e[1].replace(/:/g,"");return{hashFunc:i,hashValue:new Uint8Array((null===(t=n.match(/.{1,2}/g))||void 0===t?void 0:t.map((e=>parseInt(e,16))))||[])}}}return{hashFunc:l.HashFunction.SHA256,hashValue:new Uint8Array(0)}}static parseSetup(e){const t=e.find((e=>e.startsWith("a=setup:")));switch(null==t?void 0:t.substring(8).toLowerCase()){case"active":return l.DTLSSetup.ACTIVE;case"passive":return l.DTLSSetup.PASSIVE;default:return l.DTLSSetup.ACTPASS}}static firstValueStartingWith(e,t){const i=e.find((e=>e.startsWith(t)));return i?i.substring(t.length):null}static inMediaSection(e,t){return e.map(((e,t)=>({line:e,index:t}))).filter((({line:e})=>e.startsWith("m="))).map((({index:e})=>e)).some((e=>e<t))}static parseMediaSections(e,t,i,n){const a=e.map(((e,t)=>({line:e,index:t}))).filter((({line:e})=>e.startsWith("m="))).map((({index:e})=>e));return a.map(((l,s)=>{const o=s<a.length-1?a[s+1]:e.length;return r.parseMediaSection(e.slice(l,o),t,i,n)})).filter((e=>null!==e))}static parseMediaSection(e,t,i,n){var a;try{const i=e[0].substring(2).split(" ");let n;switch(i[0].toLowerCase()){case"audio":n=l.MediaType.AUDIO;break;case"video":n=l.MediaType.VIDEO;break;default:n=l.MediaType.MEDIA_TYPE_UNSPECIFIED}if(n===l.MediaType.MEDIA_TYPE_UNSPECIFIED)return s.warn(`Skipping unknown media type: ${i[0]}`),null;const o=parseInt(i[1]||"9",10)||9,d=i.slice(3).map((e=>parseInt(e,10))).filter((e=>!isNaN(e))),c=r.firstValueStartingWith(e,"a=mid:")||"",u=r.parseDirection(e),p=r.firstValueStartingWith(e,"a=msid:"),[g,h,v]=r.parseMSID(p||null),S=e.some((e=>"a=rtcp-mux"===e)),C=e.some((e=>"a=rtcp-rsize"===e)),f=e.some((e=>"a=end-of-candidates"===e)),I=(null===(a=e.find((e=>e.startsWith("c="))))||void 0===a?void 0:a.split(" ")[2])||"",E=r.firstValueStartingWith(e,"a=rtcp:")||"",m=new Map,P=[];d.forEach((e=>{m.set(e,{codecName:{id:e,mapKey:0},fmtp:[],rtcpFeedbackIds:[]}),P.push(e)})),e.filter((e=>e.startsWith("a=rtpmap:"))).forEach((e=>{const t=e.substring(9).split(" ",2);if(2===t.length){const e=parseInt(t[0],10);if(!isNaN(e)){const i=t[1];r.dynamicCodecNames.set(e,i);const n=r.CODEC_NAME_TO_MAP_KEY.get(i)||0;if(m.has(e)){const t=m.get(e);m.set(e,{codecName:{id:e,mapKey:n},fmtp:t.fmtp,rtcpFeedbackIds:t.rtcpFeedbackIds})}}}})),e.filter((e=>e.startsWith("a=fmtp:"))).forEach((e=>{const t=e.substring(7).split(" ",2);if(2===t.length){const e=parseInt(t[0],10);if(!isNaN(e)&&m.has(e)){const i=r.parseFmtp(t[1]),n=m.get(e);m.set(e,{codecName:n.codecName,fmtp:i,rtcpFeedbackIds:n.rtcpFeedbackIds})}}})),e.filter((e=>e.startsWith("a=rtcp-fb:"))).forEach((e=>{const t=e.substring(10).split(" ");if(t.length>=2){const e=parseInt(t[0],10);if(!isNaN(e)){let i="";for(let e=1;e<t.length;e++)i+=t[e]+(e!==t.length-1?" ":"");const n=r.RTCP_FEEDBACK_STRING_TO_ID.get(i);if(void 0!==n&&m.has(e)){const t=m.get(e),i=[...t.rtcpFeedbackIds];i.includes(n)||i.push(n),m.set(e,{codecName:t.codecName,fmtp:t.fmtp,rtcpFeedbackIds:i})}}}}));const $=P.map((e=>m.get(e))).filter((e=>void 0!==e)),y=r.parseExtmaps(e),T=r.parseSsrcs(e),O=r.parseSsrcGroups(e),w=r.parseCandidates(e),b=r.firstValueStartingWith(e,"a=ice-ufrag:"),F=r.firstValueStartingWith(e,"a=ice-pwd:"),A=b?r.addToStringPool(t,b):0,R=F?r.addToStringPool(t,F):0,N=e.find((e=>e.startsWith("a=ice-options:"))),_=N?N.substring(14).split(" "):void 0,k=e.find((e=>e.startsWith("a=fingerprint:"))),M=k?r.parseFingerprint([k]):{hashFunc:l.HashFunction.SHA256,hashValue:new Uint8Array(0)},D=e.find((e=>e.startsWith("a=setup:")));return{type:n,mid:c,direction:u,msidStream:g,msidTrackLabel:h,msidTrackId:v,rtcpMux:S,rtcpRsize:C,extmaps:y,codecs:$,ssrcGroups:O,ssrcs:T,connectionAddress:I,candidates:w,endOfCandidates:f,rtcpAddress:E,iceUfragRef:A,icePwdRef:R,iceOptions:_,fingerprint:M,setup:D?r.parseSetup([D]):l.DTLSSetup.ACTPASS,port:o}}catch(e){return s.error(`[647] [CallId: GLOBAL_LOGS] Failed to parse media section: ${e.message}`,{color:"red"}),s.error(e,{color:"red"}),null}}static parseDirection(e){return e.some((e=>"a=sendrecv"===e))?l.MediaDirection.SENDRECV:e.some((e=>"a=sendonly"===e))?l.MediaDirection.SENDONLY:e.some((e=>"a=recvonly"===e))?l.MediaDirection.RECVONLY:e.some((e=>"a=inactive"===e))?l.MediaDirection.INACTIVE:l.MediaDirection.SENDRECV}static parseMSID(e){if(!e||0===e.trim().length)return["","",0];const t=e.split(" ",2);if(t.length<2)return[e,"",0];const i=t[0],n=t[1],a=n.lastIndexOf("_");if(a>0){const e=n.substring(a+1),t=parseInt(e,10);if(!isNaN(t))return[i,n.substring(0,a+1),t]}return[i,n,0]}static parseFmtp(e){if(0===e.trim().length)return[];const t=[];return e.split(";").forEach((e=>{const i=e.trim();if(0!==i.length)if(i.includes("=")){const e=i.split("=",2);t.push({key:e[0].trim(),value:e[1].trim()})}else t.push({key:"value",value:i})})),t}static parseExtmaps(e){return e.filter((e=>e.startsWith("a=extmap:"))).map((e=>{const t=e.substring(9).split(" ",2);if(2!==t.length)return null;const i=t[0].split("/")[0],n=parseInt(i,10);if(isNaN(n))return null;const a=t[1];return{id:n,mapKey:r.URI_TO_EXTMAP_ID.get(a)||0}})).filter((e=>null!==e))}static parseSsrcs(e){const t=new Map;return e.filter((e=>e.startsWith("a=ssrc:"))).forEach((e=>{const i=e.substring(7).split(" ");if(i.length>=2){const e=parseInt(i[0],10);if(isNaN(e))return;const n=e,a=t.get(n)||{};if(i[1].startsWith("cname:"))a.cname=i[1].substring(6);else if(i[1].startsWith("msid:")){let e="";for(let t=1;t<i.length;t++)e+=i[t].substring(1===t?5:0)+(i.length-1!==t?" ":"");a.msid=e}t.set(n,a)}})),Array.from(t.entries()).map((([e,t])=>({id:e,cname:t.cname||"",msid:t.msid||""})))}static parseSsrcGroups(e){return e.filter((e=>e.startsWith("a=ssrc-group:"))).map((e=>{const t=e.substring(13).split(" ");return t.length>=2?{semantics:t[0],ssrcs:t.slice(1).map((e=>parseInt(e,10))).filter((e=>!isNaN(e)))}:null})).filter((e=>null!==e))}static parseCandidates(e){return e.filter((e=>e.startsWith("a=candidate:"))).map((e=>r.parseCandidate(e.substring(12)))).filter((e=>null!==e))}static parseCandidate(e){const t=e.split(" ");if(t.length<8)return null;const i=parseInt(t[0],10);if(isNaN(i))return null;const n=parseInt(t[1],10);if(isNaN(n))return null;let a;switch(t[2].toLowerCase()){case"udp":default:a=l.IceCandidateProtocol.UDP;break;case"tcp":a=l.IceCandidateProtocol.TCP}const s=parseInt(t[3],10);if(isNaN(s))return null;const r=t[4].split("."),o=new Uint8Array(r.map((e=>parseInt(e,10)))),d=parseInt(t[5],10);if(isNaN(d))return null;let c;switch(t[7].toLowerCase()){case"host":default:c=l.IceCandidateType.HOST;break;case"srflx":c=l.IceCandidateType.SRFLX;break;case"prflx":c=l.IceCandidateType.PRFLX;break;case"relay":c=l.IceCandidateType.RELAY}let u=new Uint8Array(0),p=0,g=l.IceCandidateTcpType.ACTIVE,h=8;for(;h<t.length;){switch(t[h]){case"raddr":if(h+1<t.length){const e=t[++h];u=new Uint8Array(e.split(".").map((e=>parseInt(e,10))))}break;case"rport":h+1<t.length&&(p=parseInt(t[++h],10)||0);break;case"tcptype":if(h+1<t.length)switch(t[++h].toLowerCase()){case"active":default:g=l.IceCandidateTcpType.ACTIVE;break;case"passive":g=l.IceCandidateTcpType.PASSIVE;break;case"so":g=l.IceCandidateTcpType.SO}}h++}return{foundation:i,component:n,protocol:a,priority:s,ip:o,port:d,type:c,raddr:u,rport:p,tcptype:g}}static addToStringPool(e,t){if(0===t.length)return 0;const i=e.indexOf(t);return i>=0?i+1:(e.push(t),e.length)}static getFromStringPool(e,t){return 0===t||t>e.length?"":e[t-1]}static getCodecID(e){var t;return(null===(t=e.codecName)||void 0===t?void 0:t.id)||0}static getCodecName(e){if(!e.codecName)return null;const t=e.codecName;if(t.mapKey>0){const e=r.MAP_KEY_TO_CODEC_NAME.get(t.mapKey);if(e)return e}return r.dynamicCodecNames.get(t.id)||null}static filterVideoCodecs(e,t){if(0===t.length)return e;const i=[],n=new Set;return e.forEach((e=>{const a=r.getCodecName(e);if(!a)return;const l=a.split("/")[0];t.some((e=>e.toLowerCase()===l.toLowerCase()))&&(i.push(e),n.add(r.getCodecID(e)))})),e.forEach((e=>{const t=r.getCodecName(e);if(t&&t.toLowerCase().startsWith("rtx/")){const t=e.fmtp.find((e=>"apt"===e.key)),a=t?parseInt(t.value,10):null;null!==a&&!isNaN(a)&&n.has(a)&&i.push(e)}})),i}static buildMediaSection(e,t,i){var n,a,o,d,c,u,p,g,h,v;let S;switch(t.type){case l.MediaType.AUDIO:S="audio";break;case l.MediaType.VIDEO:S="video";break;case l.MediaType.MEDIA_TYPE_UNSPECIFIED:return void s.error("Cannot reconstruct MEDIA_TYPE_UNSPECIFIED")}const C=(null===(n=null==t?void 0:t.codecs)||void 0===n?void 0:n.map((e=>r.getCodecID(e).toString())).join(" "))||"";e.push(`m=${S} ${t.port} UDP/TLS/RTP/SAVPF ${C}\r\n`);const f=(null==t?void 0:t.connectionAddress)||(null==i?void 0:i.connectionAddress)||"0.0.0.0";e.push(`c=IN IP4 ${f}\r\n`),(null===(a=null==t?void 0:t.rtcpAddress)||void 0===a?void 0:a.length)>0&&e.push(`a=rtcp:${t.rtcpAddress}\r\n`);const I=(null==t?void 0:t.iceUfragRef)>0?r.getFromStringPool(null==i?void 0:i.stringPool,null==t?void 0:t.iceUfragRef):null==i?void 0:i.iceUfrag,E=(null==t?void 0:t.icePwdRef)>0?r.getFromStringPool(null==i?void 0:i.stringPool,null==t?void 0:t.icePwdRef):null==i?void 0:i.icePwd;I.length>0&&e.push(`a=ice-ufrag:${I}\r\n`),E.length>0&&e.push(`a=ice-pwd:${E}\r\n`);const m=(null==t?void 0:t.iceOptions)||(null==i?void 0:i.iceOptions);m.length>0&&e.push(`a=ice-options:${m.join(" ")}\r\n`);const P=(null===(d=null===(o=null==t?void 0:t.fingerprint)||void 0===o?void 0:o.hashValue)||void 0===d?void 0:d.length)>0?null==t?void 0:t.fingerprint:null==i?void 0:i.fingerprint;(null===(c=null==P?void 0:P.hashValue)||void 0===c?void 0:c.length)>0&&e.push(`a=fingerprint:${r.fingerprintToString(P)}\r\n`);const $=(null==t?void 0:t.setup)!==l.DTLSSetup.ACTPASS||(null==i?void 0:i.setup)===l.DTLSSetup.ACTPASS?t.setup:i.setup;e.push(`a=setup:${r.setupToString($)}\r\n`),e.push(`a=mid:${null==t?void 0:t.mid}\r\n`),null===(u=null==t?void 0:t.extmaps)||void 0===u||u.forEach((t=>{const i=r.EXTMAP_ID_TO_URI.get(t.mapKey)||`urn:ietf:params:rtp-hdrext:extension-${t.id}`;e.push(`a=extmap:${t.id} ${i}\r\n`)})),e.push(`a=${r.directionToString(null==t?void 0:t.direction)}\r\n`);const y=r.reconstructMSID(null==t?void 0:t.msidStream,null==t?void 0:t.msidTrackLabel,null==t?void 0:t.msidTrackId);(null==y?void 0:y.length)>0&&e.push(`a=msid:${y}\r\n`),(null==t?void 0:t.rtcpMux)&&e.push("a=rtcp-mux\r\n"),(null==t?void 0:t.rtcpRsize)&&e.push("a=rtcp-rsize\r\n"),null===(p=null==t?void 0:t.codecs)||void 0===p||p.forEach((t=>{var i,n;const a=r.getCodecID(t),l=r.getCodecName(t);if(l&&e.push(`a=rtpmap:${a} ${l}\r\n`),null===(i=null==t?void 0:t.rtcpFeedbackIds)||void 0===i||i.forEach((t=>{const i=r.RTCP_FEEDBACK_ID_TO_STRING.get(t);i&&e.push(`a=rtcp-fb:${a} ${i}\r\n`)})),(null===(n=null==t?void 0:t.fmtp)||void 0===n?void 0:n.length)>0){const i=r.reconstructFmtp(t.fmtp);e.push(`a=fmtp:${a} ${i}\r\n`)}})),null===(g=null==t?void 0:t.ssrcGroups)||void 0===g||g.forEach((t=>{const i=t.ssrcs.map((e=>(e>>>0).toString())).join(" ");e.push(`a=ssrc-group:${t.semantics} ${i}\r\n`)})),null===(h=null==t?void 0:t.ssrcs)||void 0===h||h.forEach((t=>{var i,n;const a=(t.id>>>0).toString();(null===(i=null==t?void 0:t.cname)||void 0===i?void 0:i.length)>0&&e.push(`a=ssrc:${a} cname:${t.cname}\r\n`),(null===(n=null==t?void 0:t.msid)||void 0===n?void 0:n.length)>0&&e.push(`a=ssrc:${a} msid:${t.msid}\r\n`)})),null===(v=null==t?void 0:t.candidates)||void 0===v||v.forEach((t=>{e.push(`a=candidate:${r.reconstructCandidate(t)}\r\n`)})),(null==t?void 0:t.endOfCandidates)&&e.push("a=end-of-candidates\r\n")}static reconstructMSID(e,t,i){return 0===e.length?"":0===t.length&&0===i?e:i>0&&t.length>0?`${e} ${t}${i}`:t.length>0?`${e} ${t}`:e}static reconstructFmtp(e){return e.map((e=>"value"===e.key?e.value:`${e.key}=${e.value}`)).join(";")}static fingerprintToString(e){let t;switch(e.hashFunc){case l.HashFunction.SHA256:t="sha-256";break;case l.HashFunction.SHA1:t="sha-1";break;case l.HashFunction.SHA384:t="sha-384";break;case l.HashFunction.SHA512:t="sha-512";break;case l.HashFunction.MD5:t="md5"}return`${t} ${Array.from(e.hashValue).map((e=>e.toString(16).padStart(2,"0").toUpperCase())).join(":")}`}static setupToString(e){switch(e){case l.DTLSSetup.ACTIVE:return"active";case l.DTLSSetup.PASSIVE:return"passive";case l.DTLSSetup.ACTPASS:return"actpass"}}static directionToString(e){switch(e){case l.MediaDirection.SENDONLY:return"sendonly";case l.MediaDirection.RECVONLY:return"recvonly";case l.MediaDirection.INACTIVE:return"inactive";default:return"sendrecv"}}static reconstructCandidate(e){const t=e.protocol===l.IceCandidateProtocol.UDP?"udp":"tcp";let i;switch(e.type){case l.IceCandidateType.HOST:i="host";break;case l.IceCandidateType.SRFLX:i="srflx";break;case l.IceCandidateType.PRFLX:i="prflx";break;case l.IceCandidateType.RELAY:i="relay"}const n=[e.foundation.toString(),e.component.toString(),t,e.priority.toString(),Array.from(e.ip).map((e=>(255&e).toString())).join("."),e.port.toString(),"typ",i];if(e.raddr.length>0){n.push("raddr");const t=Array.from(e.raddr).map((e=>(255&e).toString())).join(".");n.push(t)}if(e.rport>0&&(n.push("rport"),n.push(e.rport.toString())),"tcp"===t){let t;switch(e.tcptype){case l.IceCandidateTcpType.ACTIVE:t="active";break;case l.IceCandidateTcpType.PASSIVE:t="passive";break;case l.IceCandidateTcpType.SO:t="so"}n.push("tcptype"),n.push(t)}return n.join(" ")}}t.SdpConverter=r,r.EXTMAP_ID_TO_URI=new Map([[1,"urn:ietf:params:rtp-hdrext:toffset"],[2,"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"],[3,"urn:3gpp:video-orientation"],[4,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"],[5,"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"],[6,"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"],[7,"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"],[8,"http://www.webrtc.org/experiments/rtp-hdrext/color-space"],[9,"urn:ietf:params:rtp-hdrext:sdes:mid"],[10,"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"],[11,"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],[14,"urn:ietf:params:rtp-hdrext:ssrc-audio-level"],[15,"urn:ietf:params:rtp-hdrext:csrc-audio-level"]]),r.URI_TO_EXTMAP_ID=new Map(Array.from(r.EXTMAP_ID_TO_URI.entries()).map((([e,t])=>[t,e]))),r.RTCP_FEEDBACK_ID_TO_STRING=new Map([[1,"goog-remb"],[2,"transport-cc"],[3,"ccm fir"],[4,"nack"],[5,"nack pli"]]),r.RTCP_FEEDBACK_STRING_TO_ID=new Map(Array.from(r.RTCP_FEEDBACK_ID_TO_STRING.entries()).map((([e,t])=>[t,e]))),r.dynamicCodecNames=new Map,r.CODEC_NAME_TO_MAP_KEY=new Map([["VP8/90000",1],["VP9/90000",2],["AV1/90000",3],["H264/90000",4],["H265/90000",5],["rtx/90000",6],["red/90000",7],["ulpfec/90000",8],["opus/48000/2",9],["red/48000/2",10],["G722/8000",11],["G722/8000/1",11],["PCMU/8000",12],["PCMA/8000",13],["CN/8000",14],["telephone-event/48000",15],["telephone-event/8000",16],["telephone-event/8000/1",16],["ILBC/8000",17]]),r.MAP_KEY_TO_CODEC_NAME=new Map([[1,"VP8/90000"],[2,"VP9/90000"],[3,"AV1/90000"],[4,"H264/90000"],[5,"H265/90000"],[6,"rtx/90000"],[7,"red/90000"],[8,"ulpfec/90000"],[9,"opus/48000/2"],[10,"red/48000/2"],[11,"G722/8000"],[12,"PCMU/8000"],[13,"PCMA/8000"],[14,"CN/8000"],[15,"telephone-event/48000"],[16,"telephone-event/8000"],[17,"ILBC/8000"]])},799:(e,t)=>{"use strict";var i,n,a,l,s,r,o;Object.defineProperty(t,"__esModule",{value:!0}),t.IceCandidateTcpType=t.IceCandidateType=t.IceCandidateProtocol=t.MediaDirection=t.MediaType=t.DTLSSetup=t.HashFunction=void 0,function(e){e[e.SHA256=0]="SHA256",e[e.SHA1=1]="SHA1",e[e.SHA384=2]="SHA384",e[e.SHA512=3]="SHA512",e[e.MD5=4]="MD5"}(i||(t.HashFunction=i={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PASSIVE=1]="PASSIVE",e[e.ACTPASS=2]="ACTPASS"}(n||(t.DTLSSetup=n={})),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.MEDIA_TYPE_UNSPECIFIED=2]="MEDIA_TYPE_UNSPECIFIED"}(a||(t.MediaType=a={})),function(e){e[e.SENDRECV=0]="SENDRECV",e[e.SENDONLY=1]="SENDONLY",e[e.RECVONLY=2]="RECVONLY",e[e.INACTIVE=3]="INACTIVE"}(l||(t.MediaDirection=l={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP"}(s||(t.IceCandidateProtocol=s={})),function(e){e[e.HOST=0]="HOST",e[e.SRFLX=1]="SRFLX",e[e.PRFLX=2]="PRFLX",e[e.RELAY=3]="RELAY"}(r||(t.IceCandidateType=r={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PASSIVE=1]="PASSIVE",e[e.SO=2]="SO"}(o||(t.IceCandidateTcpType=o={}))},828:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.QueuedSignal=void 0;const n=i(795),a=i(429);t.QueuedSignal=class{constructor(e,t,i=n.SignalQueueStrategy.getSignalPriority(e),l=Date.now(),s=0,r=(0,a.v4)()){this.signal=e,this.callback=t,this.priority=i,this.timestamp=l,this.requeueCount=s,this.uniqueKey=r}get callId(){return this.signal.callId}compareTo(e){const t=e.priority-this.priority;return 0!==t?t:this.timestamp-e.timestamp}toString(){return`QueuedSignal(signal=${JSON.stringify(this.signal)}, timestamp=${this.timestamp}, priority=${this.priority}, requeueCount=${this.requeueCount}, uniqueKey=${this.uniqueKey})`}}},795:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignalQueueStrategy=t.SignalProcessingStrategy=void 0;const n=i(578),a=i(586),l=i(228);var s;!function(e){e[e.SEQUENTIAL=0]="SEQUENTIAL",e[e.IMMEDIATE=1]="IMMEDIATE"}(s||(t.SignalProcessingStrategy=s={}));class r{static getProcessingStrategy(e){return this.SEQUENTIAL_SIGNALS.has(e)?s.SEQUENTIAL:s.IMMEDIATE}static isSequentialSignal(e){return this.getProcessingStrategy(e)===s.SEQUENTIAL}static isImmediateSignal(e){return this.getProcessingStrategy(e)===s.IMMEDIATE}static getSignalPriorityValue(e){switch(e){case n.SignalEvent.JOIN:return 10;case n.SignalEvent.LEAVE:case n.SignalEvent.DECLINE:return 9;case n.SignalEvent.MEDIA_CONNECTED:return 8;case n.SignalEvent.OFFER:case n.SignalEvent.ANSWER:case n.SignalEvent.CONNECT:case n.SignalEvent.ICE:return 7;case n.SignalEvent.KICK:case n.SignalEvent.INVITE:case n.SignalEvent.RINGING:case n.SignalEvent.INFO:case n.SignalEvent.UPDATE:case n.SignalEvent.GET_CALL:case n.SignalEvent.SWITCH_MEDIA_FLOW:return 6;case n.SignalEvent.MUTE:case n.SignalEvent.UNMUTE:case n.SignalEvent.VIDEO_ON:case n.SignalEvent.VIDEO_OFF:case n.SignalEvent.HOLD:case n.SignalEvent.UNHOLD:case n.SignalEvent.SCREEN_SHARE_ON:case n.SignalEvent.SCREEN_SHARE_OFF:return 5;case n.SignalEvent.ERROR:case n.SignalEvent.SUCCESS:case n.SignalEvent.CLOSE:case n.SignalEvent.NO_ANSWER:throw(0,l.checkCode)(4e3,`SignalEvent ${e} should not be in queue`);default:return 0}}static getSignalPriority(e){if("number"!=typeof e.event)throw(0,l.checkCode)(4e3,`Signal event is not a number for signal: ${JSON.stringify(e)}`);return this.getSignalPriorityValue(e.event)}static getSignalLevel(e){switch(e.event){case n.SignalEvent.JOIN:case n.SignalEvent.LEAVE:case n.SignalEvent.DECLINE:return a.SignalLevel.GlobalBlocking;case n.SignalEvent.OFFER:case n.SignalEvent.ANSWER:case n.SignalEvent.ICE:case n.SignalEvent.CONNECT:return a.SignalLevel.ParticipantLevel;default:return a.SignalLevel.Immediate}}}t.SignalQueueStrategy=r,r.SEQUENTIAL_SIGNALS=new Set([n.SignalEvent.JOIN,n.SignalEvent.LEAVE,n.SignalEvent.DECLINE,n.SignalEvent.OFFER,n.SignalEvent.ANSWER,n.SignalEvent.CONNECT])},586:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.SignalingQueue=t.SignalLevel=void 0;const a=i(795),l=i(645),s=i(578),r=(0,l.createLogger)("SignalingQueue");var o;!function(e){e[e.GlobalBlocking=0]="GlobalBlocking",e[e.ParticipantLevel=1]="ParticipantLevel",e[e.Immediate=2]="Immediate"}(o||(t.SignalLevel=o={})),t.SignalingQueue=class{constructor(e,t,i){this.id=e,this.isTransportConnected=t,this.sender=i,this.globalBlockingSignals=[],this.immediateSignals=[],this.participantSignals=new Map,this.processingSignalJobs=new Map,this.participantJobs=new Map,this.sentSignals=new Set}getSignalKey(e,t){return`${t}_${e.event}_${e.callId}_${e.sessionId||""}`}addSignalToQueue(e){const t=this.getSignalKey(e.signal,e.uniqueKey);if(this.sentSignals.has(t))return void r.info(`[38] [CallId: ${e.signal.callId}] Signal already sent, skipping: ${s.SignalEvent[e.signal.event]}`);const i=a.SignalQueueStrategy.getSignalLevel(e.signal);switch(i){case o.GlobalBlocking:this.globalBlockingSignals.push(e);break;case o.ParticipantLevel:const t=e.signal.to||"";this.participantSignals.has(t)||this.participantSignals.set(t,[]),this.participantSignals.get(t).push(e);break;case o.Immediate:this.immediateSignals.push(e)}r.info(`[61] [CallId: ${e.signal.callId}] Add signal to queue ===> level: ${i}, signal Event: ${s.SignalEvent[e.signal.event]}, uniqueKey: ${e.uniqueKey}`),this.invalidateToSendSignalsIfNeeded()}removeSignalFromQueue(e){const t=this.getSignalKey(e.signal,e.uniqueKey);this.sentSignals.delete(t)}invalidateToSendSignalsIfNeeded(){this.isTransportConnected()?this.globalBlockingSignals.length>0?this.sendGlobalBlockingSignals():(this.sendParticipantSignals(),this.sendImmediateLevelSignals()):r.info(`[75] [CallId: ${this.id}] Connection is not established, skipping signal processing`)}triggerSignalProcessing(){this.invalidateToSendSignalsIfNeeded()}sendGlobalBlockingSignals(){return n(this,void 0,void 0,(function*(){if(!this.processingSignalJobs.get(o.GlobalBlocking)){this.processingSignalJobs.set(o.GlobalBlocking,!0);try{for(;this.isTransportConnected();){const e=this.globalBlockingSignals.shift();if(!e)break;const t=this.getSignalKey(e.signal,e.uniqueKey);this.sentSignals.has(t)?r.info(`[107] [CallId: ${this.id}] Global blocking signal already sent, skipping: ${s.SignalEvent[e.signal.event]}`):(r.info(`[111] [CallId: ${this.id}] Sending ${o.GlobalBlocking} level signal: ${s.SignalEvent[e.signal.event]}`),yield this.sendSignal(e),this.sentSignals.add(t))}}finally{this.processingSignalJobs.delete(o.GlobalBlocking),0===this.globalBlockingSignals.length&&(this.sendParticipantSignals(),this.sendImmediateLevelSignals())}}}))}sendImmediateLevelSignals(){return n(this,void 0,void 0,(function*(){if(!(this.globalBlockingSignals.length>0||this.processingSignalJobs.get(o.Immediate))){this.processingSignalJobs.set(o.Immediate,!0);try{for(;this.isTransportConnected()&&0===this.globalBlockingSignals.length;){const e=this.immediateSignals.shift();if(!e)break;const t=this.getSignalKey(e.signal,e.uniqueKey);this.sentSignals.has(t)?r.info(`[145] [CallId: ${this.id}] Immediate signal already sent, skipping: ${s.SignalEvent[e.signal.event]}`):(r.info(`[148] [CallId: ${this.id}] Sending ${o.Immediate} level signal: ${s.SignalEvent[e.signal.event]}`),yield this.sendSignal(e),this.sentSignals.add(t))}}finally{this.processingSignalJobs.delete(o.Immediate)}}}))}sendParticipantSignals(){if(!(this.globalBlockingSignals.length>0))for(const[e,t]of this.participantSignals.entries())t.length>0&&this.sendParticipantSignal(e,t)}sendParticipantSignal(e,t){return n(this,void 0,void 0,(function*(){if(!this.participantJobs.get(e)){this.participantJobs.set(e,!0);try{for(;this.isTransportConnected()&&0===this.globalBlockingSignals.length;){const i=t.shift();if(!i)break;const n=this.getSignalKey(i.signal,i.uniqueKey);this.sentSignals.has(n)?r.info(`[185] [CallId: ${this.id}] Participant signal already sent, skipping: ${s.SignalEvent[i.signal.event]}`):(r.info(`[188] [CallId: ${this.id}] Sending ${o.ParticipantLevel} level signal for identity ${e}: ${s.SignalEvent[i.signal.event]}`),yield this.sendSignal(i),this.sentSignals.add(n))}}finally{this.participantJobs.delete(e),0===t.length&&this.participantSignals.delete(e)}}}))}sendSignal(e){return n(this,void 0,void 0,(function*(){a.SignalQueueStrategy.getProcessingStrategy(e.signal.event)===a.SignalProcessingStrategy.SEQUENTIAL?yield this.sender(e):this.sender(e).catch((e=>{r.error(`[209] [CallId: ${this.id}] Error sending signal: ${e}`)}))}))}clearParticipantSignals(e){this.participantSignals.delete(e),this.participantJobs.delete(e),r.info(`[213] [CallId: ${this.id}] Cleared participant signals for identity: ${e}, queueId: ${this.id}`)}clearCallSignals(){this.globalBlockingSignals=[],this.immediateSignals=[],this.participantSignals.clear(),this.processingSignalJobs.clear(),this.participantJobs.clear(),this.sentSignals.clear(),r.info(`[227] [CallId: ${this.id}] Cleared all signals for queueId: ${this.id}`)}getGlobalBlockingSignals(){return this.globalBlockingSignals}}},786:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Signaling=void 0;const a=i(578),l=i(645),s=i(828),r=i(586),o=i(228),d=i(65),c=i(429),u=(0,l.createLogger)("Signaling");class p{constructor(e,t){this.signalingQueues=new Map,this.chatClient=e;const i=new this.chatClient.ChannelListener;i.onSignal=e=>{t(e)},this.chatClient.addChannelListener("call_listeners",i)}calculateRetryDelay(e){return Math.min(p.BASE_DELAY_MS*Math.pow(2,e),p.MAX_DELAY_MS)}handleRetry(e,t,i,a){var l;return n(this,void 0,void 0,(function*(){if(t>=p.MAX_RETRIES)throw u.error(`[45] [CallId: ${e.signal.callId}] Max retries exceeded for signal: ${JSON.stringify(e.signal)}`,{color:"red"}),(0,o.toCallException)(i);i instanceof d.SceytCallException&&!i.isResendable&&(u.error(`[49] [CallId: ${e.signal.callId}] Signal sending failed with non-resendable exception: ${i.message}`,{color:"red"}),null===(l=e.callback)||void 0===l||l.call(e,i),a.removeSignalFromQueue(e));const n=this.calculateRetryDelay(t);u.error(`[53] [CallId: ${e.signal.callId}] Sending signal failed with error: ${i.message}, but ChatClient is connected. Retrying in ${n}ms (attempt ${t+1}/${p.MAX_RETRIES})`,{color:"red"}),yield new Promise((e=>setTimeout(e,n)));try{const t=yield this.sendSignalSuspended(e);return u.info(`[64] [CallId: ${e.signal.callId}] Retry sending signal success: ${JSON.stringify(t)}`),t}catch(i){return u.error(`[67] [CallId: ${e.signal.callId}] Retry sending signal failed: ${i instanceof Error?i.message:String(i)}`),this.handleRetry(e,t+1,i instanceof Error?i:new Error(String(i)),a)}}))}sendSignalSuspended(e){return n(this,void 0,void 0,(function*(){try{u.info(`[78] [CallId: ${e.signal.callId}] Sending signal ${a.SignalEvent[e.signal.event]} to chat client: version: 132`);const t=yield this.chatClient.sendSignal(e.signal,132);if(null==t?void 0:t.error)throw(0,o.toCallException)(t.error);return(0,o.handleAck)(t)}catch(e){throw(0,o.toCallException)(e)}}))}sendSignalMessage(e,t,i){u.info(`[92] [CallId: ${e.callId}] Sending signal message request: ${a.SignalEvent[e.event]} uniqueKey: ${(0,c.v4)()} ${JSON.stringify(e)}`,{color:"yellow"});const l=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({mediaFlow:e.mediaFlow,callId:e.callId},e.sessionId&&{sessionId:e.sessionId}),{event:e.event}),e.sessionData&&{sessionData:e.sessionData}),e.to&&{to:e.to}),{participants:e.participants?e.participants:[]}),e.ice&&{ice:e.ice}),e.metadata?{metadata:e.metadata}:{metadata:{}}),e.joinOptions&&{joinOptions:e.joinOptions}),e.settings&&{settings:e.settings}),g=i||e.callId;let h=this.signalingQueues.get(g);h||(h=new r.SignalingQueue(g,(()=>"Connected"===this.chatClient.connectionState),(e=>n(this,void 0,void 0,(function*(){var t,i,n,l,r;try{const l=yield this.sendSignalSuspended(e);if(u.info(`[115] [CallId: ${e.signal.callId||"GLOBAL_LOGS"}] Sent signal message response: ${a.SignalEvent[e.signal.event]} uniqueKey: ${e.uniqueKey} ${JSON.stringify(l)}`,{color:"magenta"}),(null==l?void 0:l.event)===a.SignalEvent.ERROR)throw(0,o.checkCode)((null===(t=null==l?void 0:l.error)||void 0===t?void 0:t.code)||0,(null===(i=null==l?void 0:l.error)||void 0===i?void 0:i.message)||"Unknown error");return null===(n=e.callback)||void 0===n||n.call(e,l),null==h||h.removeSignalFromQueue(e),l}catch(t){if(u.error(`[125] [CallId: ${e.signal.callId||"GLOBAL_LOGS"}] Signal message error: ${a.SignalEvent[e.signal.event]} uniqueKey: ${e.uniqueKey} error: ${t instanceof Error?t.message:String(t)}, resendable: ${t instanceof d.SceytCallException&&t.isResendable}`,{color:"red"}),t instanceof d.SceytCallException&&t.isResendable){const i=e.requeueCount;i<p.REQUEUE_LIMIT?null==h||h.addSignalToQueue(new s.QueuedSignal(e.signal,e.callback,e.priority,e.timestamp,i+1,(0,c.v4)())):(u.error(`[140] [CallId: ${e.signal.callId||"GLOBAL_LOGS"}] Max requeue limit reached for signal: ${JSON.stringify(e.signal)}, will not requeue again. uniqueKey: ${e.uniqueKey}`,{color:"red"}),null===(l=e.callback)||void 0===l||l.call(e,t),null==h||h.removeSignalFromQueue(e))}const i=t instanceof d.SceytCallException?t:new Error(t instanceof Error?t.message:String(t));null===(r=e.callback)||void 0===r||r.call(e,i),null==h||h.removeSignalFromQueue(e)}})))),this.signalingQueues.set(g,h)),h.addSignalToQueue(new s.QueuedSignal(l,t,0,0,0,(0,c.v4)()))}clearCallSignals(e){const t=this.signalingQueues.get(e);t&&(t.clearCallSignals(),this.signalingQueues.delete(e))}clearParticipantSignals(e,t){const i=this.signalingQueues.get(e);i&&i.clearParticipantSignals(t)}cancelJoinIfPossible(e){const t=this.signalingQueues.get(e);return!!t&&!!t.getGlobalBlockingSignals().find((e=>e.signal.event==a.SignalEvent.JOIN))&&(t.clearCallSignals(),!0)}}t.Signaling=p,p.REQUEUE_LIMIT=10,p.MAX_RETRIES=10,p.BASE_DELAY_MS=1e3,p.MAX_DELAY_MS=8e3},342:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReceiveSignalValidator=void 0;const n=i(578),a=(0,i(645).createLogger)("ReceiveSignalValidator");class l{static canHandleSignal(e,t){const i=l.validateSignal(e,t.state,t.localParticipant);return i||a.warn(`Cannot handle signal ${e.event} in call state ${t.state} with local participant state ${t.localParticipant.state}`),i}static validateSignal(e,t,i){switch(e.event){case n.SignalEvent.JOIN:case n.SignalEvent.LEAVE:return!0;case n.SignalEvent.OFFER:case n.SignalEvent.ANSWER:return t===n.CallState.Connected;case n.SignalEvent.KICK:return!0;case n.SignalEvent.INVITE:return!e.participants||!e.participants.some((e=>e.id===i.id))||t===n.CallState.Idle;case n.SignalEvent.DECLINE:case n.SignalEvent.RINGING:case n.SignalEvent.INFO:case n.SignalEvent.UPDATE:case n.SignalEvent.CLOSE:return!0;case n.SignalEvent.ICE:return t===n.CallState.Connected;case n.SignalEvent.SWITCH_MEDIA_FLOW:case n.SignalEvent.NO_ANSWER:case n.SignalEvent.MUTE:case n.SignalEvent.UNMUTE:case n.SignalEvent.HOLD:case n.SignalEvent.UNHOLD:case n.SignalEvent.VIDEO_ON:case n.SignalEvent.VIDEO_OFF:case n.SignalEvent.SCREEN_SHARE_ON:case n.SignalEvent.SCREEN_SHARE_OFF:case n.SignalEvent.MEDIA_CONNECTED:case n.SignalEvent.CONNECT:case n.SignalEvent.GET_CALL:return!0;default:return a.warn(`Unknown signal event for handling: ${e.event}`),!1}}}t.ReceiveSignalValidator=l},771:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SendSignalValidator=void 0;const n=i(578),a=(0,i(645).createLogger)("SendSignalValidator");class l{canSendSignal(e,t){const i=l.validateSignalEvent(e.event,t.state);return i||a.warn(`Cannot send signal ${e.event} in call state ${t.state} with local participant state ${t.localParticipant.state}`),i}canSendSignalEvent(e,t){const i=l.validateSignalEvent(e,t.state);return i||a.warn(`Cannot send signal ${e} in call state ${t.state} with local participant state ${t.localParticipant.state}`),i}static validateSignalEvent(e,t){const i=t===n.CallState.Connected;switch(e){case n.SignalEvent.JOIN:return!0;case n.SignalEvent.LEAVE:return i;case n.SignalEvent.OFFER:case n.SignalEvent.ANSWER:case n.SignalEvent.CONNECT:case n.SignalEvent.KICK:case n.SignalEvent.INVITE:return t===n.CallState.Connected;case n.SignalEvent.DECLINE:return t===n.CallState.Idle;case n.SignalEvent.RINGING:return t===n.CallState.Idle||t===n.CallState.Connecting;case n.SignalEvent.INFO:case n.SignalEvent.UPDATE:return t===n.CallState.Connected;case n.SignalEvent.ICE:case n.SignalEvent.GET_CALL:return!0;case n.SignalEvent.SWITCH_MEDIA_FLOW:case n.SignalEvent.MEDIA_CONNECTED:return t===n.CallState.Connected;case n.SignalEvent.MUTE:case n.SignalEvent.UNMUTE:case n.SignalEvent.HOLD:case n.SignalEvent.UNHOLD:case n.SignalEvent.VIDEO_ON:case n.SignalEvent.VIDEO_OFF:return i;case n.SignalEvent.SCREEN_SHARE_ON:case n.SignalEvent.SCREEN_SHARE_OFF:return t===n.CallState.Connected;default:return a.warn(`Unknown signal event for sending: ${e}`),!1}}}t.SendSignalValidator=l},302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReceiveSignalValidator=t.SendSignalValidator=void 0;var n=i(771);Object.defineProperty(t,"SendSignalValidator",{enumerable:!0,get:function(){return n.SendSignalValidator}});var a=i(342);Object.defineProperty(t,"ReceiveSignalValidator",{enumerable:!0,get:function(){return a.ReceiveSignalValidator}})},740:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VideoTrack=void 0,t.VideoTrack=class{constructor(e){this._enabled=!0,this.id=e.id,this.videoTrack=e}set enabled(e){this._enabled=e,this.videoTrack.enabled=e}get enabled(){return this._enabled}}},546:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.WebRTCClient=void 0;const a=i(578),l=i(645),s=i(19),r=i(680),o=(0,l.createLogger)("WebRTCClient");t.WebRTCClient=class{constructor(e,t){this.listeners={},this.sessionId=null,this.version=null,this.iceQueueMap={},this.configuration=t,this.peerConnection=new RTCPeerConnection(this.configuration),this.callId=e}setSessionId(e){this.sessionId=e}getSessionId(){return this.sessionId||""}setVersion(e){this.version=e}getVersion(){return this.version||""}setListeners(e){o.info(`[18] [CallId: ${this.callId}] setListeners in webrtcClient: listeners`,{color:"blue"}),this.listeners=e}setConfiguration(e){o.info(`[21] [CallId: ${this.callId}] setConfiguration in webrtcClient: configuration: ${e}`,{color:"blue"}),this.configuration=e}getPreferredAudioCodecs(e){const t=RTCRtpReceiver.getCapabilities("audio");return t?t.codecs.filter((t=>{const i=t.mimeType.split("/")[1].toLowerCase();return e===a.MediaFlow.S2W?s.CODEC_NAME_TO_AUDIO_CODEC_S2W.includes(i):s.CODEC_NAME_TO_AUDIO_CODEC.includes(i)})):[]}getPreferredVideoCodecs(){const e=RTCRtpSender.getCapabilities("video");if(!e)return[];const t=[];return s.CODEC_NAME_TO_VIDEO_CODEC.forEach((i=>{const n=e.codecs.find((e=>e.mimeType.split("/")[1].toLowerCase()===i.toLowerCase()));n&&t.push(n)})),t}setPreferredCodecs(e,t,i){if("video"===t){o.info(`[74] [CallId: ${this.callId}] setPreferredCodecs: video, mediaFlow: ${e}`,{color:"blue"});const t=this.getPreferredVideoCodecs(),n=[];t.forEach((e=>{n.push({mimeType:e.mimeType,clockRate:e.clockRate,sdpFmtpLine:e.sdpFmtpLine,channels:e.channels})})),i.setCodecPreferences(n)}else if("audio"===t){o.info(`[88] [CallId: ${this.callId}] setPreferredCodecs: audio, mediaFlow: ${e}`,{color:"blue"});const t=this.getPreferredAudioCodecs(e),n=[];t.forEach((e=>{n.push({mimeType:e.mimeType,clockRate:e.clockRate,sdpFmtpLine:e.sdpFmtpLine||"",channels:e.channels||void 0})})),i.setCodecPreferences(n)}}addTransceiverToPeerConnection(e,t){return n(this,void 0,void 0,(function*(){o.info(`[56] [CallId: ${this.callId}] addTransceiverToPeerConnection in webrtcClient: track: ${null==e?void 0:e.kind}`,{color:"blue"}),this.peerConnection.addTransceiver(e,{direction:"sendrecv"});const i=this.peerConnection.getTransceivers().find((t=>{var i;return(null===(i=t.receiver.track)||void 0===i?void 0:i.kind)===(null==e?void 0:e.kind)}));if(i&&"video"===(null==e?void 0:e.kind)){this.setPreferredCodecs(t,"video",i);try{const e=i.sender.getParameters();e.encodings&&e.encodings.length>0&&(e.encodings.forEach((e=>{e.maxBitrate=5e5})),yield i.sender.setParameters(e),o.info(`[57] [CallId: ${this.callId}] addTransceiverToPeerConnection: Set video max bitrate to 500 kbps`,{color:"blue"}))}catch(e){o.warn(`[58] [CallId: ${this.callId}] addTransceiverToPeerConnection: Failed to set video bitrate: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"yellow"})}}else i&&"audio"===(null==e?void 0:e.kind)&&this.setPreferredCodecs(t,"audio",i)}))}setStreamsToTransceiver(e){var t,i;return n(this,void 0,void 0,(function*(){o.info(`[61] [CallId: ${this.callId}] setStreamsToTransceiver in webrtcClient: track: ${null==e?void 0:e.kind}`,{color:"blue"});const n=this.peerConnection.getTransceivers();o.info(`[62] [CallId: ${this.callId}] setStreamsToTransceiver: transceivers: ${n.length}`,{color:"blue"});const a=null==e?void 0:e.kind;let l=n.find((e=>{var t,i;const n=null===(t=e.receiver.track)||void 0===t?void 0:t.kind,l=null===(i=e.sender.track)||void 0===i?void 0:i.kind;return n===a||l===a}));if(o.info(`[63] [CallId: ${this.callId}] setStreamsToTransceiver: transceiver found: ${!!l}, receiver track: ${null===(t=null==l?void 0:l.receiver.track)||void 0===t?void 0:t.kind}, sender track: ${null===(i=null==l?void 0:l.sender.track)||void 0===i?void 0:i.kind}, current direction: ${null==l?void 0:l.direction}, mid: ${null==l?void 0:l.mid}`,{color:"blue"}),l){if(null!==l.sender.track)return void o.info(`[64] [CallId: ${this.callId}] setStreamsToTransceiver: Track already attached, skipping to avoid renegotiation`,{color:"blue"});e&&(e.enabled=!0),l.direction="sendrecv",yield l.sender.replaceTrack(e);const t=l.direction,i=l.sender.track,n=i?i.kind:"null";o.info(`[65] [CallId: ${this.callId}] setStreamsToTransceiver: Attached local ${a} track to transceiver, direction: ${t}, sender track: ${n}, track enabled: ${null==e?void 0:e.enabled}, track id: ${null==e?void 0:e.id}`,{color:"blue"}),i||o.error(`[66] [CallId: ${this.callId}] setStreamsToTransceiver: Failed to attach ${a} track - sender track is still null after replaceTrack`,{color:"red"})}else{const e=n.map((e=>{var t,i;return{mid:e.mid,receiverKind:(null===(t=e.receiver.track)||void 0===t?void 0:t.kind)||"null",senderKind:(null===(i=e.sender.track)||void 0===i?void 0:i.kind)||"null",direction:e.direction}}));o.warn(`[67] [CallId: ${this.callId}] setStreamsToTransceiver: No transceiver found for track kind: ${a}. Available transceivers: ${JSON.stringify(e)}`,{color:"yellow"})}}))}enableVideoOnPeerConnection(e,t,i=!1){return n(this,void 0,void 0,(function*(){o.info(`[27] [CallId: ${this.callId}] enableVideoOnPeerConnection in webrtcClient: enable: ${e}, kind: ${null==t?void 0:t.kind}`,{color:"blue"});const n=this.peerConnection.getTransceivers();for(let a=0;a<n.length;a++){const l=n[a];if(l.sender.track&&"video"===l.sender.track.kind){t?(t.enabled=e,yield l.sender.replaceTrack(t)):l.sender.track.enabled=e;const n=l.sender.getParameters();n.encodings&&n.encodings.length>0&&(n.encodings.forEach((e=>{e.maxBitrate=i?75e4:5e5})),yield l.sender.setParameters(n),o.info(`[184] [CallId: ${this.callId}] enableVideoOnPeerConnection: Set video max bitrate to ${i?75e4:5e5} kbps`,{color:"blue"}))}}}))}enableAudioOnPeerConnection(e,t){return n(this,void 0,void 0,(function*(){o.info(`[33] [CallId: ${this.callId}] enableAudioOnPeerConnection in webrtcClient: mute: ${e}, kind: ${null==t?void 0:t.kind}`,{color:"blue"});const i=this.peerConnection.getTransceivers();for(let n=0;n<i.length;n++){const a=i[n];a.sender.track&&"audio"===a.sender.track.kind&&(t?(t.enabled=!e,yield a.sender.replaceTrack(t)):a.sender.track.enabled=!e)}}))}createOffer(e,t,i){return n(this,void 0,void 0,(function*(){try{o.info(`[36] [CallId: ${this.callId}] createOffer in webrtcClient`,{color:"blue"});const n=yield this.peerConnection.createOffer({iceRestart:!0,offerToReceiveAudio:!0,offerToReceiveVideo:!0}),a=(0,r.toSessionData)({sdp:n,sessionId:e,versionId:t},i),l=(0,r.toSessionDescription)(a,"offer");return l?(yield this.setLocalDescription(l),a):(o.error(`[76] [CallId: ${this.callId}] createOffer in webrtcClient failed to convert session data to session description`,{color:"red"}),!1)}catch(e){return o.error(`[37] [CallId: ${this.callId}] createOffer in webrtcClient failed: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),!1}}))}createAnswer(e,t,i){return n(this,void 0,void 0,(function*(){try{o.info(`[75] [CallId: ${this.callId}] createAnswer in webrtcClient`,{color:"blue"});const n=yield this.peerConnection.createAnswer(),a=(0,r.toSessionData)({sdp:n,sessionId:e,versionId:t},i),l=(0,r.toSessionDescription)(a,"answer");return l?(yield this.setLocalDescription(l),a):(o.error(`[76] [CallId: ${this.callId}] createAnswer in webrtcClient failed to convert session data to session description`,{color:"red"}),!1)}catch(e){return o.error(`[70] [CallId: ${this.callId}] createAnswer in webrtcClient failed: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),!1}}))}setLocalDescription(e){var t;return o.info(`[44] [CallId: ${this.callId}] setLocalDescription in webrtcClient: sdp sliced 50: ${null===(t=null==e?void 0:e.sdp)||void 0===t?void 0:t.slice(0,50)}...`,{color:"blue"}),this.peerConnection.setLocalDescription(e)}setRemoteDescription(e){var t;return o.info(`[48] [CallId: ${this.callId}] setRemoteDescription in webrtcClient: sdp sliced 50: ${null===(t=e.sdp)||void 0===t?void 0:t.slice(0,50)}...`,{color:"blue"}),this.peerConnection.setRemoteDescription(e)}getLocalSdpUfrag(){var e;const t=((null===(e=this.peerConnection.localDescription)||void 0===e?void 0:e.sdp)||"").match(/a=ice-ufrag:(\S+)/);return t?t[1]:null}getRemoteSdpUfrag(){var e;const t=((null===(e=this.peerConnection.remoteDescription)||void 0===e?void 0:e.sdp)||"").match(/a=ice-ufrag:(\S+)/);return t?t[1]:null}getIceCandidateUfrag(e){const t=e.match(/ufrag\s+(\S+)/);return t?t[1]:null}isUfragEqualsSdpUfrag(e){return{equals:this.getIceCandidateUfrag(e)===this.getRemoteSdpUfrag(),ufrag:this.getIceCandidateUfrag(e),sdpUfrag:this.getRemoteSdpUfrag()}}addIceCandidate(e,t){if(o.info(`[52] [CallId: ${this.callId}] addIceCandidate in webrtcClient: candidate: ${e.candidate}`,{color:"blue"}),e.candidate){const i=this.isUfragEqualsSdpUfrag(e.candidate);if(!i.equals)return this.iceQueueMap[t]||(this.iceQueueMap[t]={}),void(i.ufrag&&(this.iceQueueMap[t][i.ufrag]||(this.iceQueueMap[t][i.ufrag]=[]),this.iceQueueMap[t][i.ufrag].push(e)))}return this.peerConnection.addIceCandidate(e)}addEventListener(e,t){this.peerConnection.addEventListener(e,t)}removeEventListener(e,t){this.peerConnection.removeEventListener(e,t)}close(){o.info(`[56] [CallId: ${this.callId}] close in webrtcClient`,{color:"blue"}),this.peerConnection.close()}getConnectionStats(){return n(this,void 0,void 0,(function*(){return yield this.peerConnection.getStats()}))}}},297:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TypedEventEmitter=void 0,t.TypedEventEmitter=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var i;null===(i=this.listeners.get(e))||void 0===i||i.delete(t)}}emit(e,t){var i;null===(i=this.listeners.get(e))||void 0===i||i.forEach((i=>{try{i(t)}catch(t){console.error(`Error in event handler for "${String(e)}":`,t)}}))}off(e,t){var i;t?null===(i=this.listeners.get(e))||void 0===i||i.delete(t):this.listeners.delete(e)}removeAllListeners(){this.listeners.clear()}listenerCount(e){var t,i;return null!==(i=null===(t=this.listeners.get(e))||void 0===t?void 0:t.size)&&void 0!==i?i:0}}},578:(e,t)=>{"use strict";var i,n,a,l,s,r,o,d;Object.defineProperty(t,"__esModule",{value:!0}),t.CDRRequestDirection=t.CDRRequestEvent=t.CDRRequestOrder=t.MediaFlow=t.SignalEvent=t.CallState=t.ParticipantConnectionState=t.ParticipantState=void 0,function(e){e[e.Idle=0]="Idle",e[e.Ringing=1]="Ringing",e[e.Joined=2]="Joined",e[e.Left=3]="Left",e[e.Declined=4]="Declined",e[e.Kicked=5]="Kicked",e[e.NoAnswer=6]="NoAnswer"}(i||(t.ParticipantState=i={})),function(e){e[e.Idle=0]="Idle",e[e.Connecting=1]="Connecting",e[e.Connected=2]="Connected",e[e.Reconnecting=3]="Reconnecting",e[e.Disconnected=4]="Disconnected"}(n||(t.ParticipantConnectionState=n={})),function(e){e.Idle="idle",e.Connecting="connecting",e.Connected="connected",e.Closed="closed"}(a||(t.CallState=a={})),function(e){e[e.JOIN=0]="JOIN",e[e.LEAVE=1]="LEAVE",e[e.OFFER=2]="OFFER",e[e.ANSWER=3]="ANSWER",e[e.CONNECT=4]="CONNECT",e[e.ERROR=5]="ERROR",e[e.KICK=6]="KICK",e[e.SUCCESS=7]="SUCCESS",e[e.INVITE=8]="INVITE",e[e.DECLINE=9]="DECLINE",e[e.RINGING=10]="RINGING",e[e.INFO=11]="INFO",e[e.UPDATE=12]="UPDATE",e[e.CLOSE=13]="CLOSE",e[e.ICE=14]="ICE",e[e.GET_CALL=15]="GET_CALL",e[e.SWITCH_MEDIA_FLOW=16]="SWITCH_MEDIA_FLOW",e[e.NO_ANSWER=17]="NO_ANSWER",e[e.MEDIA_CONNECTED=18]="MEDIA_CONNECTED",e[e.MUTE=19]="MUTE",e[e.UNMUTE=20]="UNMUTE",e[e.HOLD=21]="HOLD",e[e.UNHOLD=22]="UNHOLD",e[e.VIDEO_ON=23]="VIDEO_ON",e[e.VIDEO_OFF=24]="VIDEO_OFF",e[e.SCREEN_SHARE_ON=25]="SCREEN_SHARE_ON",e[e.SCREEN_SHARE_OFF=26]="SCREEN_SHARE_OFF",e[e.CREATE=27]="CREATE",e[e.SESSION_RENEWED=28]="SESSION_RENEWED"}(l||(t.SignalEvent=l={})),function(e){e[e.P2P=0]="P2P",e[e.SFU=1]="SFU",e[e.S2W=2]="S2W"}(s||(t.MediaFlow=s={})),function(e){e[e.ASC=0]="ASC",e[e.DESC=1]="DESC"}(r||(t.CDRRequestOrder=r={})),function(e){e[e.GET_RECENT_CALLS=0]="GET_RECENT_CALLS",e[e.GET_CALLS_BY_SESSION_IDS=1]="GET_CALLS_BY_SESSION_IDS",e[e.DELETE_RECENT_CALLS=2]="DELETE_RECENT_CALLS"}(o||(t.CDRRequestEvent=o={})),function(e){e[e.NEXT=0]="NEXT",e[e.PREVIOUS=1]="PREVIOUS"}(d||(t.CDRRequestDirection=d={}))},489:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.makeFirstById=t.getEmptyVideoTrack=void 0,t.getEmptyVideoTrack=()=>{const e=document.createElement("canvas");return e.getContext("2d"),e.width=640,e.height=480,e.captureStream().getVideoTracks()},t.makeFirstById=(e,t,i)=>{const n=new Set,a=e.filter((e=>{const t=`${e.id}${e.clientId?`/${e.clientId}`:""}`;return!n.has(t)&&(n.add(t),!0)})),l=a.findIndex((e=>e.id===t&&(e.clientId===i||!e.clientId)));if(l>-1){const[e]=a.splice(l,1);a.unshift(e)}return a}},607:function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var a=Object.getOwnPropertyDescriptor(t,i);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,a)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),a=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});const l=i(838);a(i(838),t),t.default=l.SceytCallClient},838:function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var a=Object.getOwnPropertyDescriptor(t,i);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,a)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),a=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),t.CDRRequestDirection=t.CDRRequestEvent=t.CDRRequestOrder=t.ParticipantConnectionState=t.ParticipantState=t.CallState=t.MediaFlow=t.VideoTrack=t.AudioTrack=t.Participant=t.Call=void 0,a(i(271),t);var l=i(998);Object.defineProperty(t,"Call",{enumerable:!0,get:function(){return l.Call}});var s=i(787);Object.defineProperty(t,"Participant",{enumerable:!0,get:function(){return s.Participant}});var r=i(250);Object.defineProperty(t,"AudioTrack",{enumerable:!0,get:function(){return r.AudioTrack}});var o=i(740);Object.defineProperty(t,"VideoTrack",{enumerable:!0,get:function(){return o.VideoTrack}});var d=i(578);Object.defineProperty(t,"MediaFlow",{enumerable:!0,get:function(){return d.MediaFlow}}),Object.defineProperty(t,"CallState",{enumerable:!0,get:function(){return d.CallState}}),Object.defineProperty(t,"ParticipantState",{enumerable:!0,get:function(){return d.ParticipantState}}),Object.defineProperty(t,"ParticipantConnectionState",{enumerable:!0,get:function(){return d.ParticipantConnectionState}}),Object.defineProperty(t,"CDRRequestOrder",{enumerable:!0,get:function(){return d.CDRRequestOrder}}),Object.defineProperty(t,"CDRRequestEvent",{enumerable:!0,get:function(){return d.CDRRequestEvent}}),Object.defineProperty(t,"CDRRequestDirection",{enumerable:!0,get:function(){return d.CDRRequestDirection}}),a(i(645),t)},645:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createLogger=t.removeLogListener=t.addLogListener=void 0;const i={green:"[32m",blue:"[34m","light-green":"[34m","light-blue":"[34m",yellow:"[33m",magenta:"[35m",cyan:"[36m",reset:"[0m",orange:"[33m",red:"[31m",white:"[37m"},n=[];t.addLogListener=e=>{n.push(e)},t.removeLogListener=e=>{const t=n.indexOf(e);-1!==t&&n.splice(t,1)},t.createLogger=(e,t="white")=>{const a=`[SceytCallClient] ${e?`[${e}]`:""}:`,l=(e,l,s,r)=>{var o;const d=null!==(o=null==r?void 0:r.color)&&void 0!==o?o:t,c={level:e,message:l,prefix:a,args:s.filter((e=>!(null==e?void 0:e.color)&&!(null==e?void 0:e.time))),color:i[d],time:(null==r?void 0:r.time)||(new Date).toISOString()};n.forEach((e=>e(c)))};return{trace:(e,t)=>{l("trace",e,[],t)},debug:(e,t)=>{l("debug",e,[],t)},info:(e,t)=>{l("info",e,[],t)},warn:(e,t)=>{l("warn",e,[],t)},error:(e,t)=>{l("error",e,[],t)}}},t.default=(0,t.createLogger)("SceytCallClient")},429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NIL",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(t,"parse",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(t,"v1",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(t,"v3",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(t,"v4",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(t,"v5",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(t,"validate",{enumerable:!0,get:function(){return d.default}}),Object.defineProperty(t,"version",{enumerable:!0,get:function(){return o.default}});var n=p(i(990)),a=p(i(237)),l=p(i(355)),s=p(i(764)),r=p(i(314)),o=p(i(464)),d=p(i(435)),c=p(i(8)),u=p(i(222));function p(e){return e&&e.__esModule?e:{default:e}}},163:(e,t)=>{"use strict";function i(e){return 14+(e+64>>>9<<4)+1}function n(e,t){const i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function a(e,t,i,a,l,s){return n((r=n(n(t,e),n(a,s)))<<(o=l)|r>>>32-o,i);var r,o}function l(e,t,i,n,l,s,r){return a(t&i|~t&n,e,t,l,s,r)}function s(e,t,i,n,l,s,r){return a(t&n|i&~n,e,t,l,s,r)}function r(e,t,i,n,l,s,r){return a(t^i^n,e,t,l,s,r)}function o(e,t,i,n,l,s,r){return a(i^(t|~n),e,t,l,s,r)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default=function(e){if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(let i=0;i<t.length;++i)e[i]=t.charCodeAt(i)}return function(e){const t=[],i=32*e.length,n="0123456789abcdef";for(let a=0;a<i;a+=8){const i=e[a>>5]>>>a%32&255,l=parseInt(n.charAt(i>>>4&15)+n.charAt(15&i),16);t.push(l)}return t}(function(e,t){e[t>>5]|=128<<t%32,e[i(t)-1]=t;let a=1732584193,d=-271733879,c=-1732584194,u=271733878;for(let t=0;t<e.length;t+=16){const i=a,p=d,g=c,h=u;a=l(a,d,c,u,e[t],7,-680876936),u=l(u,a,d,c,e[t+1],12,-389564586),c=l(c,u,a,d,e[t+2],17,606105819),d=l(d,c,u,a,e[t+3],22,-1044525330),a=l(a,d,c,u,e[t+4],7,-176418897),u=l(u,a,d,c,e[t+5],12,1200080426),c=l(c,u,a,d,e[t+6],17,-1473231341),d=l(d,c,u,a,e[t+7],22,-45705983),a=l(a,d,c,u,e[t+8],7,1770035416),u=l(u,a,d,c,e[t+9],12,-1958414417),c=l(c,u,a,d,e[t+10],17,-42063),d=l(d,c,u,a,e[t+11],22,-1990404162),a=l(a,d,c,u,e[t+12],7,1804603682),u=l(u,a,d,c,e[t+13],12,-40341101),c=l(c,u,a,d,e[t+14],17,-1502002290),d=l(d,c,u,a,e[t+15],22,1236535329),a=s(a,d,c,u,e[t+1],5,-165796510),u=s(u,a,d,c,e[t+6],9,-1069501632),c=s(c,u,a,d,e[t+11],14,643717713),d=s(d,c,u,a,e[t],20,-373897302),a=s(a,d,c,u,e[t+5],5,-701558691),u=s(u,a,d,c,e[t+10],9,38016083),c=s(c,u,a,d,e[t+15],14,-660478335),d=s(d,c,u,a,e[t+4],20,-405537848),a=s(a,d,c,u,e[t+9],5,568446438),u=s(u,a,d,c,e[t+14],9,-1019803690),c=s(c,u,a,d,e[t+3],14,-187363961),d=s(d,c,u,a,e[t+8],20,1163531501),a=s(a,d,c,u,e[t+13],5,-1444681467),u=s(u,a,d,c,e[t+2],9,-51403784),c=s(c,u,a,d,e[t+7],14,1735328473),d=s(d,c,u,a,e[t+12],20,-1926607734),a=r(a,d,c,u,e[t+5],4,-378558),u=r(u,a,d,c,e[t+8],11,-2022574463),c=r(c,u,a,d,e[t+11],16,1839030562),d=r(d,c,u,a,e[t+14],23,-35309556),a=r(a,d,c,u,e[t+1],4,-1530992060),u=r(u,a,d,c,e[t+4],11,1272893353),c=r(c,u,a,d,e[t+7],16,-155497632),d=r(d,c,u,a,e[t+10],23,-1094730640),a=r(a,d,c,u,e[t+13],4,681279174),u=r(u,a,d,c,e[t],11,-358537222),c=r(c,u,a,d,e[t+3],16,-722521979),d=r(d,c,u,a,e[t+6],23,76029189),a=r(a,d,c,u,e[t+9],4,-640364487),u=r(u,a,d,c,e[t+12],11,-421815835),c=r(c,u,a,d,e[t+15],16,530742520),d=r(d,c,u,a,e[t+2],23,-995338651),a=o(a,d,c,u,e[t],6,-198630844),u=o(u,a,d,c,e[t+7],10,1126891415),c=o(c,u,a,d,e[t+14],15,-1416354905),d=o(d,c,u,a,e[t+5],21,-57434055),a=o(a,d,c,u,e[t+12],6,1700485571),u=o(u,a,d,c,e[t+3],10,-1894986606),c=o(c,u,a,d,e[t+10],15,-1051523),d=o(d,c,u,a,e[t+1],21,-2054922799),a=o(a,d,c,u,e[t+8],6,1873313359),u=o(u,a,d,c,e[t+15],10,-30611744),c=o(c,u,a,d,e[t+6],15,-1560198380),d=o(d,c,u,a,e[t+13],21,1309151649),a=o(a,d,c,u,e[t+4],6,-145523070),u=o(u,a,d,c,e[t+11],10,-1120210379),c=o(c,u,a,d,e[t+2],15,718787259),d=o(d,c,u,a,e[t+9],21,-343485551),a=n(a,i),d=n(d,p),c=n(c,g),u=n(u,h)}return[a,d,c,u]}(function(e){if(0===e.length)return[];const t=8*e.length,n=new Uint32Array(i(t));for(let i=0;i<t;i+=8)n[i>>5]|=(255&e[i/8])<<i%32;return n}(e),8*e.length))}},790:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};t.default=i},314:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default="00000000-0000-0000-0000-000000000000"},222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,a=(n=i(435))&&n.__esModule?n:{default:n};t.default=function(e){if(!(0,a.default)(e))throw TypeError("Invalid UUID");let t;const i=new Uint8Array(16);return i[0]=(t=parseInt(e.slice(0,8),16))>>>24,i[1]=t>>>16&255,i[2]=t>>>8&255,i[3]=255&t,i[4]=(t=parseInt(e.slice(9,13),16))>>>8,i[5]=255&t,i[6]=(t=parseInt(e.slice(14,18),16))>>>8,i[7]=255&t,i[8]=(t=parseInt(e.slice(19,23),16))>>>8,i[9]=255&t,i[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,i[11]=t/4294967296&255,i[12]=t>>>24&255,i[13]=t>>>16&255,i[14]=t>>>8&255,i[15]=255&t,i}},58:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i},319:(e,t)=>{"use strict";let i;Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){if(!i&&(i="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!i))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(n)};const n=new Uint8Array(16)},757:(e,t)=>{"use strict";function i(e,t,i,n){switch(e){case 0:return t&i^~t&n;case 1:case 3:return t^i^n;case 2:return t&i^t&n^i&n}}function n(e,t){return e<<t|e>>>32-t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default=function(e){const t=[1518500249,1859775393,2400959708,3395469782],a=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=[];for(let i=0;i<t.length;++i)e.push(t.charCodeAt(i))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);const l=e.length/4+2,s=Math.ceil(l/16),r=new Array(s);for(let t=0;t<s;++t){const i=new Uint32Array(16);for(let n=0;n<16;++n)i[n]=e[64*t+4*n]<<24|e[64*t+4*n+1]<<16|e[64*t+4*n+2]<<8|e[64*t+4*n+3];r[t]=i}r[s-1][14]=8*(e.length-1)/Math.pow(2,32),r[s-1][14]=Math.floor(r[s-1][14]),r[s-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<s;++e){const l=new Uint32Array(80);for(let t=0;t<16;++t)l[t]=r[e][t];for(let e=16;e<80;++e)l[e]=n(l[e-3]^l[e-8]^l[e-14]^l[e-16],1);let s=a[0],o=a[1],d=a[2],c=a[3],u=a[4];for(let e=0;e<80;++e){const a=Math.floor(e/20),r=n(s,5)+i(a,o,d,c)+u+t[a]+l[e]>>>0;u=c,c=d,d=n(o,30)>>>0,o=s,s=r}a[0]=a[0]+s>>>0,a[1]=a[1]+o>>>0,a[2]=a[2]+d>>>0,a[3]=a[3]+c>>>0,a[4]=a[4]+u>>>0}return[a[0]>>24&255,a[0]>>16&255,a[0]>>8&255,255&a[0],a[1]>>24&255,a[1]>>16&255,a[1]>>8&255,255&a[1],a[2]>>24&255,a[2]>>16&255,a[2]>>8&255,255&a[2],a[3]>>24&255,a[3]>>16&255,a[3]>>8&255,255&a[3],a[4]>>24&255,a[4]>>16&255,a[4]>>8&255,255&a[4]]}},8:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.unsafeStringify=s;var n,a=(n=i(435))&&n.__esModule?n:{default:n};const l=[];for(let e=0;e<256;++e)l.push((e+256).toString(16).slice(1));function s(e,t=0){return l[e[t+0]]+l[e[t+1]]+l[e[t+2]]+l[e[t+3]]+"-"+l[e[t+4]]+l[e[t+5]]+"-"+l[e[t+6]]+l[e[t+7]]+"-"+l[e[t+8]]+l[e[t+9]]+"-"+l[e[t+10]]+l[e[t+11]]+l[e[t+12]]+l[e[t+13]]+l[e[t+14]]+l[e[t+15]]}t.default=function(e,t=0){const i=s(e,t);if(!(0,a.default)(i))throw TypeError("Stringified UUID is invalid");return i}},990:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,a=(n=i(319))&&n.__esModule?n:{default:n},l=i(8);let s,r,o=0,d=0;t.default=function(e,t,i){let n=t&&i||0;const c=t||new Array(16);let u=(e=e||{}).node||s,p=void 0!==e.clockseq?e.clockseq:r;if(null==u||null==p){const t=e.random||(e.rng||a.default)();null==u&&(u=s=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==p&&(p=r=16383&(t[6]<<8|t[7]))}let g=void 0!==e.msecs?e.msecs:Date.now(),h=void 0!==e.nsecs?e.nsecs:d+1;const v=g-o+(h-d)/1e4;if(v<0&&void 0===e.clockseq&&(p=p+1&16383),(v<0||g>o)&&void 0===e.nsecs&&(h=0),h>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");o=g,d=h,r=p,g+=122192928e5;const S=(1e4*(268435455&g)+h)%4294967296;c[n++]=S>>>24&255,c[n++]=S>>>16&255,c[n++]=S>>>8&255,c[n++]=255&S;const C=g/4294967296*1e4&268435455;c[n++]=C>>>8&255,c[n++]=255&C,c[n++]=C>>>24&15|16,c[n++]=C>>>16&255,c[n++]=p>>>8|128,c[n++]=255&p;for(let e=0;e<6;++e)c[n+e]=u[e];return t||(0,l.unsafeStringify)(c)}},237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=l(i(925)),a=l(i(163));function l(e){return e&&e.__esModule?e:{default:e}}var s=(0,n.default)("v3",48,a.default);t.default=s},925:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.URL=t.DNS=void 0,t.default=function(e,t,i){function n(e,n,s,r){var o;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));const t=[];for(let i=0;i<e.length;++i)t.push(e.charCodeAt(i));return t}(e)),"string"==typeof n&&(n=(0,l.default)(n)),16!==(null===(o=n)||void 0===o?void 0:o.length))throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let d=new Uint8Array(16+e.length);if(d.set(n),d.set(e,n.length),d=i(d),d[6]=15&d[6]|t,d[8]=63&d[8]|128,s){r=r||0;for(let e=0;e<16;++e)s[r+e]=d[e];return s}return(0,a.unsafeStringify)(d)}try{n.name=e}catch(e){}return n.DNS=s,n.URL=r,n};var n,a=i(8),l=(n=i(222))&&n.__esModule?n:{default:n};const s="6ba7b810-9dad-11d1-80b4-00c04fd430c8";t.DNS=s;const r="6ba7b811-9dad-11d1-80b4-00c04fd430c8";t.URL=r},355:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=s(i(790)),a=s(i(319)),l=i(8);function s(e){return e&&e.__esModule?e:{default:e}}t.default=function(e,t,i){if(n.default.randomUUID&&!t&&!e)return n.default.randomUUID();const s=(e=e||{}).random||(e.rng||a.default)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){i=i||0;for(let e=0;e<16;++e)t[i+e]=s[e];return t}return(0,l.unsafeStringify)(s)}},764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=l(i(925)),a=l(i(757));function l(e){return e&&e.__esModule?e:{default:e}}var s=(0,n.default)("v5",80,a.default);t.default=s},435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,a=(n=i(58))&&n.__esModule?n:{default:n};t.default=function(e){return"string"==typeof e&&a.default.test(e)}},464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,a=(n=i(435))&&n.__esModule?n:{default:n};t.default=function(e){if(!(0,a.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}},583:function(e,t){var i;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,i=function(){var e={};return function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function i(e,t,i){this.low=0|e,this.high=0|t,this.unsigned=!!i}function n(e){return!0===(e&&e.__isLong__)}function a(e){var t=Math.clz32(e&-e);return e?31-t:t}i.prototype.__isLong__,Object.defineProperty(i.prototype,"__isLong__",{value:!0}),i.isLong=n;var l={},s={};function r(e,t){var i,n,a;return t?(a=0<=(e>>>=0)&&e<256)&&(n=s[e])?n:(i=d(e,0,!0),a&&(s[e]=i),i):(a=-128<=(e|=0)&&e<128)&&(n=l[e])?n:(i=d(e,e<0?-1:0,!1),a&&(l[e]=i),i)}function o(e,t){if(isNaN(e))return t?f:C;if(t){if(e<0)return f;if(e>=h)return $}else{if(e<=-v)return y;if(e+1>=v)return P}return e<0?o(-e,t).neg():d(e%g|0,e/g|0,t)}function d(e,t,n){return new i(e,t,n)}i.fromInt=r,i.fromNumber=o,i.fromBits=d;var c=Math.pow;function u(e,t,i){if(0===e.length)throw Error("empty string");if("number"==typeof t?(i=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?f:C;if((i=i||10)<2||36<i)throw RangeError("radix");var n;if((n=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===n)return u(e.substring(1),t,i).neg();for(var a=o(c(i,8)),l=C,s=0;s<e.length;s+=8){var r=Math.min(8,e.length-s),d=parseInt(e.substring(s,s+r),i);if(r<8){var p=o(c(i,r));l=l.mul(p).add(o(d))}else l=(l=l.mul(a)).add(o(d))}return l.unsigned=t,l}function p(e,t){return"number"==typeof e?o(e,t):"string"==typeof e?u(e,t):d(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}i.fromString=u,i.fromValue=p;var g=4294967296,h=g*g,v=h/2,S=r(1<<24),C=r(0);i.ZERO=C;var f=r(0,!0);i.UZERO=f;var I=r(1);i.ONE=I;var E=r(1,!0);i.UONE=E;var m=r(-1);i.NEG_ONE=m;var P=d(-1,2147483647,!1);i.MAX_VALUE=P;var $=d(-1,-1,!0);i.MAX_UNSIGNED_VALUE=$;var y=d(0,-2147483648,!1);i.MIN_VALUE=y;var T=i.prototype;T.toInt=function(){return this.unsigned?this.low>>>0:this.low},T.toNumber=function(){return this.unsigned?(this.high>>>0)*g+(this.low>>>0):this.high*g+(this.low>>>0)},T.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(y)){var t=o(e),i=this.div(t),n=i.mul(t).sub(this);return i.toString(e)+n.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var a=o(c(e,6),this.unsigned),l=this,s="";;){var r=l.div(a),d=(l.sub(r.mul(a)).toInt()>>>0).toString(e);if((l=r).isZero())return d+s;for(;d.length<6;)d="0"+d;s=""+d+s}},T.getHighBits=function(){return this.high},T.getHighBitsUnsigned=function(){return this.high>>>0},T.getLowBits=function(){return this.low},T.getLowBitsUnsigned=function(){return this.low>>>0},T.getNumBitsAbs=function(){if(this.isNegative())return this.eq(y)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},T.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&-1===e&&!(0===this.low&&-2097152===this.high)},T.isZero=function(){return 0===this.high&&0===this.low},T.eqz=T.isZero,T.isNegative=function(){return!this.unsigned&&this.high<0},T.isPositive=function(){return this.unsigned||this.high>=0},T.isOdd=function(){return 1==(1&this.low)},T.isEven=function(){return 0==(1&this.low)},T.equals=function(e){return n(e)||(e=p(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},T.eq=T.equals,T.notEquals=function(e){return!this.eq(e)},T.neq=T.notEquals,T.ne=T.notEquals,T.lessThan=function(e){return this.comp(e)<0},T.lt=T.lessThan,T.lessThanOrEqual=function(e){return this.comp(e)<=0},T.lte=T.lessThanOrEqual,T.le=T.lessThanOrEqual,T.greaterThan=function(e){return this.comp(e)>0},T.gt=T.greaterThan,T.greaterThanOrEqual=function(e){return this.comp(e)>=0},T.gte=T.greaterThanOrEqual,T.ge=T.greaterThanOrEqual,T.compare=function(e){if(n(e)||(e=p(e)),this.eq(e))return 0;var t=this.isNegative(),i=e.isNegative();return t&&!i?-1:!t&&i?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},T.comp=T.compare,T.negate=function(){return!this.unsigned&&this.eq(y)?y:this.not().add(I)},T.neg=T.negate,T.add=function(e){n(e)||(e=p(e));var t=this.high>>>16,i=65535&this.high,a=this.low>>>16,l=65535&this.low,s=e.high>>>16,r=65535&e.high,o=e.low>>>16,c=0,u=0,g=0,h=0;return g+=(h+=l+(65535&e.low))>>>16,u+=(g+=a+o)>>>16,c+=(u+=i+r)>>>16,c+=t+s,d((g&=65535)<<16|(h&=65535),(c&=65535)<<16|(u&=65535),this.unsigned)},T.subtract=function(e){return n(e)||(e=p(e)),this.add(e.neg())},T.sub=T.subtract,T.multiply=function(e){if(this.isZero())return this;if(n(e)||(e=p(e)),t)return d(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return this.unsigned?f:C;if(this.eq(y))return e.isOdd()?y:C;if(e.eq(y))return this.isOdd()?y:C;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(S)&&e.lt(S))return o(this.toNumber()*e.toNumber(),this.unsigned);var i=this.high>>>16,a=65535&this.high,l=this.low>>>16,s=65535&this.low,r=e.high>>>16,c=65535&e.high,u=e.low>>>16,g=65535&e.low,h=0,v=0,I=0,E=0;return I+=(E+=s*g)>>>16,v+=(I+=l*g)>>>16,I&=65535,v+=(I+=s*u)>>>16,h+=(v+=a*g)>>>16,v&=65535,h+=(v+=l*u)>>>16,v&=65535,h+=(v+=s*c)>>>16,h+=i*g+a*u+l*c+s*r,d((I&=65535)<<16|(E&=65535),(h&=65535)<<16|(v&=65535),this.unsigned)},T.mul=T.multiply,T.divide=function(e){if(n(e)||(e=p(e)),e.isZero())throw Error("division by zero");var i,a,l;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?d((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?f:C;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return f;if(e.gt(this.shru(1)))return E;l=f}else{if(this.eq(y))return e.eq(I)||e.eq(m)?y:e.eq(y)?I:(i=this.shr(1).div(e).shl(1)).eq(C)?e.isNegative()?I:m:(a=this.sub(e.mul(i)),l=i.add(a.div(e)));if(e.eq(y))return this.unsigned?f:C;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();l=C}for(a=this;a.gte(e);){i=Math.max(1,Math.floor(a.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(i)/Math.LN2),r=s<=48?1:c(2,s-48),u=o(i),g=u.mul(e);g.isNegative()||g.gt(a);)g=(u=o(i-=r,this.unsigned)).mul(e);u.isZero()&&(u=I),l=l.add(u),a=a.sub(g)}return l},T.div=T.divide,T.modulo=function(e){return n(e)||(e=p(e)),t?d((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},T.mod=T.modulo,T.rem=T.modulo,T.not=function(){return d(~this.low,~this.high,this.unsigned)},T.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},T.clz=T.countLeadingZeros,T.countTrailingZeros=function(){return this.low?a(this.low):a(this.high)+32},T.ctz=T.countTrailingZeros,T.and=function(e){return n(e)||(e=p(e)),d(this.low&e.low,this.high&e.high,this.unsigned)},T.or=function(e){return n(e)||(e=p(e)),d(this.low|e.low,this.high|e.high,this.unsigned)},T.xor=function(e){return n(e)||(e=p(e)),d(this.low^e.low,this.high^e.high,this.unsigned)},T.shiftLeft=function(e){return n(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):d(0,this.low<<e-32,this.unsigned)},T.shl=T.shiftLeft,T.shiftRight=function(e){return n(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):d(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},T.shr=T.shiftRight,T.shiftRightUnsigned=function(e){return n(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):d(32===e?this.high:this.high>>>e-32,0,this.unsigned)},T.shru=T.shiftRightUnsigned,T.shr_u=T.shiftRightUnsigned,T.rotateLeft=function(e){var t;return n(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),d(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},T.rotl=T.rotateLeft,T.rotateRight=function(e){var t;return n(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),d(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},T.rotr=T.rotateRight,T.toSigned=function(){return this.unsigned?d(this.low,this.high,!1):this},T.toUnsigned=function(){return this.unsigned?this:d(this.low,this.high,!0)},T.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},T.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},T.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},i.fromBytes=function(e,t,n){return n?i.fromBytesLE(e,t):i.fromBytesBE(e,t)},i.fromBytesLE=function(e,t){return new i(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},i.fromBytesBE=function(e,t){return new i(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(i.fromBigInt=function(e,t){return d(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},i.fromValue=function(e,t){return"bigint"==typeof e?i.fromBigInt(e,t):p(e,t)},T.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e}),e.default=i}(e),function(e){return e.default||e}(e)}.apply(t,[]),void 0===i||(e.exports=i)}},t={},function i(n){var a=t[n];if(void 0!==a)return a.exports;var l=t[n]={exports:{}};return e[n].call(l.exports,l,l.exports,i),l.exports}(607);var e,t}));
|
|
2
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["sceyt-call"]=t():e["sceyt-call"]=t()}(this,(()=>{return e={547:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CallStateMachine=void 0;const n=i(578),a=(0,i(645).createLogger)("CallStateMachine");class l{constructor(e){this.callId=e}isValidStateTransition(e,t){var i,n;return null!==(n=null===(i=l.validStateTransitions.get(t))||void 0===i?void 0:i.has(e))&&void 0!==n&&n}setState(e,t,i){return this.isValidStateTransition(e,t)?(a.info(`[25] [CallId: ${this.callId}] Call state changed ${t} -> ${e}, reason: ${i}`,{color:"cyan"}),!0):(a.warn(`[28] [CallId: ${this.callId}] Invalid CallState changed ${t} -> ${e}, reason: ${i}`,{color:"red"}),!1)}updateState(e,t,i){return this.setState(e,t,i)}}t.CallStateMachine=l,l.validStateTransitions=new Map([[n.CallState.Idle,new Set([n.CallState.Connecting,n.CallState.Closed])],[n.CallState.Connecting,new Set([n.CallState.Connected,n.CallState.Closed,n.CallState.Idle])],[n.CallState.Connected,new Set([n.CallState.Closed,n.CallState.Idle])],[n.CallState.Closed,new Set([])]])},758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ParticipantStateMachine=void 0;const n=i(578),a=(0,i(645).createLogger)("ParticipantStateMachine");class l{constructor(e,t){this.userId=e,this.callId=t}isValidParticipantStateTransition(e,t){var i,n;return null!==(n=null===(i=l.validParticipantStateTransitions.get(t))||void 0===i?void 0:i.has(e))&&void 0!==n&&n}isValidConnectionTransition(e,t){var i,n;return null!==(n=null===(i=l.validConnectionTransitions.get(t))||void 0===i?void 0:i.has(e))&&void 0!==n&&n}setState(e,t,i,l){let s=!1;void 0!==e&&void 0!==i&&this.isValidParticipantStateTransition(e,i)?(a.debug(`[43] [CallId: ${this.callId}] Participant state transition: ${i} -> ${e}`),s=!0):e&&a.warn(`[46] [CallId: ${this.callId}] Invalid ParticipantState transition from ${i?n.ParticipantState[i]:"undefined"} to ${e?n.ParticipantState[e]:"undefined"}`,{color:"yellow"}),void 0!==t&&void 0!==l&&this.isValidConnectionTransition(t,l)?(a.debug(`[50] [CallId: ${this.callId}] Connection state transition: ${l} -> ${t}`),s=!0):t&&a.warn(`[53] [CallId: ${this.callId}] Invalid ConnectionState transition from ${l?n.ParticipantConnectionState[l]:"undefined"} to ${t?n.ParticipantConnectionState[t]:"undefined"}`,{color:"yellow"})}updateState(e,t){return this.isValidParticipantStateTransition(e,t)?(this.setState(e,void 0,t,void 0),!0):(a.warn(`[63] [CallId: ${this.callId}] Invalid ParticipantState transition from ${n.ParticipantState[t]} to ${n.ParticipantState[e]}`,{color:"yellow"}),!1)}updateConnectionState(e,t){return this.isValidConnectionTransition(e,t)?(this.setState(void 0,e,void 0,t),!0):(a.warn(`[71] [CallId: ${this.callId}] Invalid ConnectionState transition from ${n.ParticipantConnectionState[t]} to ${n.ParticipantConnectionState[e]}`,{color:"yellow"}),!1)}}t.ParticipantStateMachine=l,l.validParticipantStateTransitions=new Map([[n.ParticipantState.Idle,new Set([n.ParticipantState.Ringing,n.ParticipantState.Declined,n.ParticipantState.Kicked,n.ParticipantState.NoAnswer,n.ParticipantState.Joined,n.ParticipantState.Left])],[n.ParticipantState.Ringing,new Set([n.ParticipantState.Joined,n.ParticipantState.Declined,n.ParticipantState.Kicked,n.ParticipantState.NoAnswer,n.ParticipantState.Idle])],[n.ParticipantState.Joined,new Set([n.ParticipantState.Left,n.ParticipantState.Kicked,n.ParticipantState.Idle])],[n.ParticipantState.Left,new Set([n.ParticipantState.Idle,n.ParticipantState.Joined])],[n.ParticipantState.Declined,new Set([n.ParticipantState.Idle,n.ParticipantState.Joined])],[n.ParticipantState.Kicked,new Set([n.ParticipantState.Idle])],[n.ParticipantState.NoAnswer,new Set([n.ParticipantState.Idle,n.ParticipantState.Joined])]]),l.validConnectionTransitions=new Map([[n.ParticipantConnectionState.Idle,new Set([n.ParticipantConnectionState.Connecting])],[n.ParticipantConnectionState.Connecting,new Set([n.ParticipantConnectionState.Connected,n.ParticipantConnectionState.Disconnected,n.ParticipantConnectionState.Idle])],[n.ParticipantConnectionState.Connected,new Set([n.ParticipantConnectionState.Reconnecting,n.ParticipantConnectionState.Disconnected,n.ParticipantConnectionState.Idle])],[n.ParticipantConnectionState.Reconnecting,new Set([n.ParticipantConnectionState.Connected,n.ParticipantConnectionState.Connecting,n.ParticipantConnectionState.Disconnected,n.ParticipantConnectionState.Idle])],[n.ParticipantConnectionState.Disconnected,new Set([n.ParticipantConnectionState.Idle,n.ParticipantConnectionState.Reconnecting,n.ParticipantConnectionState.Connected])]])},258:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ActiveSpeakerManager=void 0;const a=i(645),l=i(578),s=(0,a.createLogger)("ActiveSpeakerManager");class r{constructor(e){this.speakingStates=new Map,this.activeSpeakers=[],this.dominantSpeaker=null,this.lastActiveSpeakers=[],this.lastDominantSpeaker=null,this.dominantSpeakerLastChangeTime=0,this.processingInterval=null,this.call=null,this.internalCallHandler=null,this.call=e}start(e){var t,i;this.processingInterval||(this.internalCallHandler=e,this.internalCallHandler&&this.call?(this.processingInterval=setInterval((()=>n(this,void 0,void 0,(function*(){var e,t,i,n,a;try{if(this.call&&this.internalCallHandler){if(this.call.localParticipant){let i=0;if(this.call.mediaFlow!==l.MediaFlow.SFU){const t=this.call.participants.find((e=>{var t,i,n,a;return e.id!==(null===(i=null===(t=this.call)||void 0===t?void 0:t.localParticipant)||void 0===i?void 0:i.id)||e.clientId!==(null===(a=null===(n=this.call)||void 0===n?void 0:n.localParticipant)||void 0===a?void 0:a.clientId)}));if(t){const n=null===(e=this.internalCallHandler.callParticipantsRTCMap[this.call.id])||void 0===e?void 0:e[t.getFullId()];if(n){const e=yield n.getConnectionStats(),t=Array.from(e.values()).filter((e=>this.isOutboundAudio(e)||this.isMediaSourceAudio(e))).map((e=>this.getStatsAudioLevel(e))).filter((e=>null!==e));i=t.length>0?Math.max(...t):0}}}else{const e=this.call.serverParticipant;if(e){const n=null===(t=this.internalCallHandler.callParticipantsRTCMap[this.call.id])||void 0===t?void 0:t[e.getFullId()];if(n){const e=yield n.getConnectionStats(),t=Array.from(e.values()).filter((e=>this.isOutboundAudio(e)||this.isMediaSourceAudio(e))).map((e=>this.getStatsAudioLevel(e))).filter((e=>null!==e));i=t.length>0?Math.max(...t):0}}}this.call.localParticipant.muted&&(i=0),this.processAudioLevels(this.call.localParticipant,i)}for(const e of this.call.participants){if(e.id===this.call.localParticipant.id&&e.clientId===this.call.localParticipant.clientId)continue;let t=0;if(this.call.mediaFlow!==l.MediaFlow.SFU){const n=null===(i=this.internalCallHandler.callParticipantsRTCMap[this.call.id])||void 0===i?void 0:i[e.getFullId()];if(n){const e=yield n.getConnectionStats(),i=Array.from(e.values()).filter((e=>this.isInboundAudio(e))).map((e=>this.getStatsAudioLevel(e))).filter((e=>null!==e));t=i.length>0?Math.max(...i):0}}else{const i=null===(n=this.internalCallHandler.callParticipantsRTCMap[this.call.id])||void 0===n?void 0:n[e.getFullId()];if(i){const e=yield i.getConnectionStats(),n=Array.from(e.values()).filter((e=>this.isInboundAudio(e))).map((e=>this.getStatsAudioLevel(e))).filter((e=>null!==e));t=n.length>0?Math.max(...n):0}}e.muted&&(t=0),this.processAudioLevels(e,t)}}this.processActiveSpeakers(),this.call&&(this.call.emitActiveSpeakersChanged(this.activeSpeakers),this.call.emitDominantSpeakerChanged(this.dominantSpeaker))}catch(e){s.error(`[137] [CallId: ${null===(a=this.call)||void 0===a?void 0:a.id}] Error processing audio levels: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"})}}))),r.POLLING_INTERVAL_MS),s.info(`[141] [CallId: ${null===(i=this.call)||void 0===i?void 0:i.id}] Active speaker detection started`)):s.error(`[47] [CallId: ${null===(t=this.call)||void 0===t?void 0:t.id}] Call or InternalCallHandler is not set`,{color:"red"}))}getActiveSpeakers(){return this.activeSpeakers}stop(){var e;this.processingInterval&&(clearInterval(this.processingInterval),this.processingInterval=null),this.activeSpeakers=[],this.dominantSpeaker=null,this.speakingStates.clear(),this.lastActiveSpeakers=[],this.lastDominantSpeaker=null,s.info(`[154] [CallId: ${null===(e=this.call)||void 0===e?void 0:e.id}] Active speaker detection stopped`)}addParticipant(e){var t;const i=this.getParticipantKey(e);this.speakingStates.has(i)||(this.speakingStates.set(i,{participant:e,audioLevel:0,smoothedAudioLevel:0,isSpeaking:!1,speakingStartTime:0}),s.info(`[167] [CallId: ${null===(t=this.call)||void 0===t?void 0:t.id}] Added participant for active speaker detection: ${e.getFullId()}`))}updateParticipant(e){const t=this.getParticipantKey(e),i=this.speakingStates.get(t);i&&this.speakingStates.set(t,Object.assign(Object.assign({},i),{participant:e}))}removeParticipant(e){var t,i,n;const a=this.getParticipantKey(e);this.speakingStates.delete(a),this.lastActiveSpeakers.some((t=>t.participant.id===e.id&&t.participant.clientId===e.clientId))&&this.processActiveSpeakers(),(null===(t=this.lastDominantSpeaker)||void 0===t?void 0:t.participant.id)===e.id&&(null===(i=this.lastDominantSpeaker)||void 0===i?void 0:i.participant.clientId)===e.clientId&&(this.dominantSpeaker=null,this.lastDominantSpeaker=null),s.info(`[199] [CallId: ${null===(n=this.call)||void 0===n?void 0:n.id}] Removed participant from active speaker detection: ${e.getFullId()}`)}getAudioLevel(e){var t,i;const n=this.getParticipantKey(e);return null!==(i=null===(t=this.speakingStates.get(n))||void 0===t?void 0:t.smoothedAudioLevel)&&void 0!==i?i:null}isSpeaking(e){var t,i;const n=this.getParticipantKey(e);return null!==(i=null===(t=this.speakingStates.get(n))||void 0===t?void 0:t.isSpeaking)&&void 0!==i&&i}isDominantSpeaker(e){var t,i;return(null===(t=this.dominantSpeaker)||void 0===t?void 0:t.participant.id)===e.id&&(null===(i=this.dominantSpeaker)||void 0===i?void 0:i.participant.clientId)===e.clientId}processActiveSpeakers(){const e=Date.now(),t=new Map;this.speakingStates.forEach(((i,n)=>{t.set(n,this.updateSpeakingState(i,e))})),this.speakingStates=t;const i=Array.from(this.speakingStates.values()).filter((e=>e.isSpeaking)).sort(((e,t)=>t.smoothedAudioLevel-e.smoothedAudioLevel));JSON.stringify(i)!==JSON.stringify(this.lastActiveSpeakers)&&(this.activeSpeakers=i,this.lastActiveSpeakers=i),this.updateDominantSpeaker(i,e)}updateDominantSpeaker(e,t){if(0===e.length)return void(this.lastDominantSpeaker&&t-this.dominantSpeakerLastChangeTime>r.DOMINANT_SPEAKER_HYSTERESIS_MS&&(this.dominantSpeaker=null,this.lastDominantSpeaker=null));if(!this.lastDominantSpeaker)return this.dominantSpeaker=e[0],this.lastDominantSpeaker=e[0],void(this.dominantSpeakerLastChangeTime=t);const i=e[0];i.participant.id===this.lastDominantSpeaker.participant.id&&i.participant.clientId===this.lastDominantSpeaker.participant.clientId||i.smoothedAudioLevel>.5&&t-i.speakingStartTime>r.DOMINANT_SPEAKER_HYSTERESIS_MS&&(this.dominantSpeaker=i,this.lastDominantSpeaker=i,this.dominantSpeakerLastChangeTime=t)}updateSpeakingState(e,t){const i=e.audioLevel>e.smoothedAudioLevel?Math.max(e.smoothedAudioLevel,e.smoothedAudioLevel+(e.audioLevel-e.smoothedAudioLevel)*r.ACTIVE_LEVEL_BOOST):Math.max(0,e.smoothedAudioLevel-(e.smoothedAudioLevel-e.audioLevel)*r.ACTIVE_LEVEL_DECAY);let n=e.isSpeaking,a=e.speakingStartTime;return i>=r.AUDIO_LEVEL_THRESHOLD?e.isSpeaking||(n=!0,a=t):e.isSpeaking&&t-e.speakingStartTime>r.SPEAKING_TIME_THRESHOLD_MS&&(n=!1),Object.assign(Object.assign({},e),{smoothedAudioLevel:i,isSpeaking:n,speakingStartTime:a})}processAudioLevels(e,t){var i;try{let i=null;if(e.muted)i=0;else if("number"==typeof t)i=t;else{const e=Array.from(t.values()).filter((e=>this.isOutboundAudio(e)||this.isMediaSourceAudio(e))).map((e=>this.getStatsAudioLevel(e))).filter((e=>null!==e));i=e.length>0?Math.max(...e):0}if(null!==i){const t=this.getParticipantKey(e),n=this.speakingStates.get(t);n&&this.speakingStates.set(t,Object.assign(Object.assign({},n),{audioLevel:i}))}}catch(e){s.error(`[330] [CallId: ${null===(i=this.call)||void 0===i?void 0:i.id}] Error processing audio levels: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"})}}getParticipantKey(e){return`${e.id}/${e.clientId}`}isOutboundAudio(e){return"outbound-rtp"===e.type&&"audio"===e.kind}isMediaSourceAudio(e){return"media-source"===e.type&&"audio"===e.kind}getStatsAudioLevel(e){var t;return null!==(t=e.audioLevel)&&void 0!==t?t:null}isInboundAudio(e){return"inbound-rtp"===e.type&&"audio"===e.kind}}t.ActiveSpeakerManager=r,r.AUDIO_LEVEL_THRESHOLD=.1,r.SPEAKING_TIME_THRESHOLD_MS=250,r.DOMINANT_SPEAKER_HYSTERESIS_MS=1e3,r.ACTIVE_LEVEL_DECAY=.2,r.ACTIVE_LEVEL_BOOST=1.5,r.POLLING_INTERVAL_MS=150},250:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AudioTrack=void 0,t.AudioTrack=class{constructor(e){this._enabled=!0,this.id=e.id,this.audioTrack=e}set enabled(e){this._enabled=e,this.audioTrack.enabled=e}get enabled(){return this._enabled}}},271:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SceytCallClient=void 0;const n=i(650),a=i(645),l=i(185),s=i(297),r=i(228),o=(0,a.createLogger)("CallClient");class d extends s.TypedEventEmitter{constructor(e){super(),this.getCall=e=>{o.info(`[20] [CallId: ${e}] Get call from server`,{color:"cyan"});const t=this.internalCallHandler.activeCalls.find((t=>t.id===e));return t?Promise.resolve({success:!0,data:t}):this.internalCallHandler.prepareCallFromCallID(e)},this.getOngoingCalls=()=>(this.internalCallHandler.getCalls(),this.internalCallHandler.activeCalls),this.onLog=e=>((0,a.addLogListener)(e),()=>(0,a.removeLogListener)(e)),this.internalCallHandler=new n.InternalCallHandler(e),this.setupInternalEventBridge()}setupInternalEventBridge(){this.internalCallHandler.setCallEvent("onInvitedToCall",(e=>{this.emit("invitedToCall",{call:e})})),this.internalCallHandler.setCallEvent("onOngoingCallsUpdated",(e=>{this.emit("ongoingCallsUpdated",{calls:e})}))}get activeCalls(){return this.internalCallHandler.activeCalls}prepareCall(e,t){o.info(`[19] [CallId: ${e}] Prepare call`,{color:"cyan"});try{return this.internalCallHandler.prepareCall(e,t)}catch(t){return o.error(`[19] [CallId: ${e}] Prepare call failed: ${t.message||JSON.stringify(t)}`,{color:"red"}),{success:!1,error:(0,r.toCallException)(t)}}}get RecentCallQueryBuilder(){return l.RecentCallQueryBuilder}}t.SceytCallClient=d},998:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Call=void 0;const a=i(302),l=i(65),s=i(650),r=i(578),o=i(547),d=i(645),c=i(258),u=i(297),p=i(228),g=(0,d.createLogger)("Call");class h extends u.TypedEventEmitter{get activeSpeakers(){return this._activeSpeakers}set activeSpeakers(e){this._activeSpeakers=e}constructor({id:e,sessionId:t="",mediaFlow:i,createdBy:a="",localParticipant:l,participants:o,metadata:d,chatClient:u,isCallSilenced:h}){super(),this.state=r.CallState.Idle,this._localAudioTracks=[],this._localVideoTracks=[],this._muted=!1,this._onHold=!1,this._screenSharing=!1,this._activeSpeakers=[],this.videoEnabled=!1,this.eventsQueue=new Map,this.isCallSilenced=!1,this.videoCall=!1,this.isCreatedRemotely=!1,this.videoDeviceId=null,this.audioDeviceId=null,this.getStats=()=>n(this,void 0,void 0,(function*(){try{const e=[];for(const t of this.participants){const i=yield this.getParticipantStats(t);i.success&&i.data&&e.push(i.data)}return{success:!0,data:e}}catch(e){return g.error(`[502] [CallId: ${this.id}] Error getting call stats ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}})),this.getParticipantStats=e=>n(this,void 0,void 0,(function*(){try{g.info(`[503] [CallId: ${this.id}] getParticipantStats for ${e.getFullId()}`,{color:"cyan"});const t=s.InternalCallHandler.getInstance().callParticipantsRTCMap[this.id],i=null==t?void 0:t[e.getFullId()];return i?{success:!0,data:yield i.getConnectionStats()}:{success:!1,error:(0,p.toCallException)(new Error("Participant RTC client not found"))}}catch(e){return g.error(`[504] [CallId: ${this.id}] Error getting participant stats ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}})),this.id=e,this.sessionId=t,this.createdBy=a,this.participants=o,this.localParticipant=l,this.mediaFlow=i,this.metadata=d,this.activeSpeakerManager=new c.ActiveSpeakerManager(this),this.chatClient=u,this.isCallSilenced=h}emitAudioTrackAdded(e,t){this.emit("audioTrackAdded",{call:this,participant:e,track:t})}emitAudioTrackRemoved(e){this.emit("audioTrackRemoved",{call:this,participant:e})}emitVideoTrackAdded(e,t){this.emit("videoTrackAdded",{call:this,participant:e,track:t})}emitVideoTrackRemoved(e){this.emit("videoTrackRemoved",{call:this,participant:e})}emitCallStateChanged(e){this.emit("callStateChanged",{call:this,state:e})}emitParticipantStateChanged(e,t,i){this.emit("participantStateChanged",{call:this,participant:e,state:t,reason:i})}emitParticipantConnectionStateChanged(e,t){this.emit("participantConnectionStateChanged",{call:this,participant:e,state:t})}emitParticipantEvent(e,t){this.emit("participantEvent",{call:this,participant:e,event:t})}emitParticipantsAdded(e){this.emit("participantsAdded",{call:this,participants:e})}emitParticipantsRemoved(e){this.emit("participantsRemoved",{call:this,participants:e})}emitActiveSpeakersChanged(e){this._activeSpeakers=e,this.emit("activeSpeakersChanged",{call:this,activeSpeakers:e})}emitDominantSpeakerChanged(e){this.emit("dominantSpeakerChanged",{call:this,dominantSpeaker:e})}emitMediaFlowChanged(e){this.emit("mediaFlowChanged",{call:this,mediaFlow:e})}emitSessionRenewed(e){this.emit("sessionRenewed",{call:this,sessionId:e})}clearEventsQueue(){this.eventsQueue.clear()}setState(e,t){const i=new o.CallStateMachine(this.id).updateState(e,this.state,t);return i&&(this.state=e,e===r.CallState.Connected?this.activeSpeakerManager.start(s.InternalCallHandler.getInstance()):this.activeSpeakerManager.stop(),this.emitCallStateChanged(e)),i}addParticipants(e){const t=e=>s.InternalCallHandler.getInstance().addParticipantsToCall(e,this);return this.sessionId?t(e):this.eventsQueue.set("ADD_PARTICIPANTS",(()=>t(e))),{success:!0}}join(e,t){g.info(`[J1] [CallId: ${this.id}] Join call`,{color:"cyan"});try{if(!(new a.SendSignalValidator).canSendSignalEvent(r.SignalEvent.JOIN,this)){const e=`Cannot join call with ID ${this.id} due to invalid call state or participant state.`;return g.warn(`[J2] [CallId: ${this.id}] ${e}`,{color:"red"}),{success:!1,error:l.SceytCallException.BadRequest(4006,e)}}const i=s.InternalCallHandler.getInstance().joinCall(this,e,t);return(null==i?void 0:i.data)&&i.data.activeSpeakerManager.addParticipant(i.data.localParticipant),i}catch(e){return g.error(`[J3] [CallId: ${this.id}] Join failed: ${e.message||JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}reject(e,t){try{return g.info(`[R1] [CallId: ${this.id}] Rejecting call`,{color:"cyan"}),s.InternalCallHandler.getInstance().rejectCall(this,e,t),this.activeSpeakerManager.removeParticipant(this.localParticipant),{success:!0}}catch(e){return g.error(`[R2] [CallId: ${this.id}] Rejection failed: ${e.message||JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}leave(){try{return g.info(`[L1] [CallId: ${this.id}] Leaving call`,{color:"cyan"}),s.InternalCallHandler.getInstance().leaveCall(this,!0,"leave"),this.activeSpeakerManager.removeParticipant(this.localParticipant),{success:!0}}catch(e){return g.error(`[L2] [CallId: ${this.id}] Leave failed: ${e.message||JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}create(e){g.info(`[C1] [CallId: ${this.id}] Create call`,{color:"cyan"});try{return s.InternalCallHandler.getInstance().createCall(this,e)}catch(e){return g.error(`[C3] [CallId: ${this.id}] create failed: ${e.message||JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}addParticipantToList(e){this.participants.push(e)}kickParticipantFromList(e,t=!0){if(this.participants=this.participants.filter((t=>t.id!==e.id&&t.clientId!==e.clientId)),t)return s.InternalCallHandler.getInstance().kickParticipantFromCall(e,this)}setSessionId(e){this.sessionId=e}setCreatedBy(e){this.createdBy=e}setVideoCall(e){this.videoCall=e}changeMediaFlow(e){this.mediaFlow!=e&&(this.mediaFlow=e,this.emitMediaFlowChanged(e))}switchToSFU(e){return n(this,void 0,void 0,(function*(){const t=t=>{g.info(`[159] [CallId: ${this.id}] handle switch call to ${r.MediaFlow.SFU}`,{color:"cyan"});const i=s.InternalCallHandler.getInstance(),n=i.activeCalls.find((e=>e.id===t));return i.switchCallToSfu(n,e)};return this.sessionId?t(this.id):this.eventsQueue.set(r.SignalEvent.SWITCH_MEDIA_FLOW,(()=>t(this.id))),{success:!0}}))}mute(e,t){this.muted=e,this.localParticipant.setMuted(e,this);const i=e=>{s.InternalCallHandler.getInstance().sendAudioEnable(this,e,t)};return this.sessionId?i(e):this.eventsQueue.set(r.SignalEvent.MUTE,(()=>i(e))),{success:!0}}hold(e){this.onHold=e,this.localAudioTracks.forEach((t=>{t.enabled=!e})),this.localVideoTracks.forEach((t=>{t.enabled=!e})),this.localParticipant.audioTracks.forEach((t=>{t.enabled=!e})),this.localParticipant.videoTracks.forEach((t=>{t.enabled=!e}));const t=e=>{s.InternalCallHandler.getInstance().sendHold(this,e)};return this.sessionId?t(e):this.eventsQueue.set(r.SignalEvent.HOLD,(()=>t(e))),{success:!0}}set localAudioTracks(e){this._localAudioTracks=e}get localAudioTracks(){return this._localAudioTracks}set localVideoTracks(e){this._localVideoTracks=e}get localVideoTracks(){return this._localVideoTracks}setServerParticipant(e){this.serverParticipant=e}set muted(e){this._muted=e}get muted(){return this._muted}set screenSharing(e){this._screenSharing=e}get screenSharing(){return this._screenSharing}set onHold(e){this._onHold=e}get onHold(){return this._onHold}setIsCallSilenced(e){this.isCallSilenced=e}getIsCallSilenced(){return this.isCallSilenced}setVideoDeviceId(e){this.videoDeviceId=e}getVideoDeviceId(){return this.videoDeviceId}setAudioDeviceId(e){this.audioDeviceId=e}getAudioDeviceId(){return this.audioDeviceId}setIsCreatedRemotely(e){this.isCreatedRemotely=e}getIsCreatedRemotely(){return this.isCreatedRemotely}enableVideo(e,t){return n(this,void 0,void 0,(function*(){return this.localParticipantVideoEnable(e,t)}))}localParticipantVideoEnable(e,t,i,a=!0){return n(this,void 0,void 0,(function*(){const l=s.InternalCallHandler.getInstance();let o=[];return e||(this.localVideoTracks.forEach((e=>{e.stop()})),this.localParticipant.videoTracks.forEach((e=>{e.enabled=!1}))),yield(()=>n(this,void 0,void 0,(function*(){var s,d,c,u,h;try{if(e){const e=(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind));this.videoDeviceId&&(e.some((e=>e.deviceId===this.videoDeviceId))||(g.warn(`Previously selected video device with ID ${this.videoDeviceId} not found. Falling back to default camera.`),this.setVideoDeviceId(null)));const t=null===(s=this.localVideoTracks[0])||void 0===s?void 0:s.getSettings().deviceId;if(this.videoDeviceId&&t===this.videoDeviceId&&"live"===(null===(d=this.localVideoTracks[0])||void 0===d?void 0:d.readyState))o=this.localVideoTracks;else{this.localVideoTracks.forEach((e=>{e.stop()})),this.localParticipant.videoTracks.forEach((e=>{e.enabled=!1}));const e=yield navigator.mediaDevices.getUserMedia({video:Object.assign(Object.assign({},this.videoDeviceId?{deviceId:{exact:this.videoDeviceId}}:{}),{width:{min:640,max:1280},height:{min:480,max:720}})});o=e.getVideoTracks(),o.sort((e=>(e.getSettings().deviceId||"")===this.videoDeviceId?-1:1)),this.setVideoDeviceId((null===(c=o[0])||void 0===c?void 0:c.getSettings().deviceId)||null)}}else o=this.localVideoTracks;!this.videoDeviceId&&o.length>0&&this.setVideoDeviceId((null===(u=o[0])||void 0===u?void 0:u.getSettings().deviceId)||null),this.setVideoEnabled(e),this.localVideoTracks=o,this.localParticipant.setVideoTracks(o,this),this.localParticipant.setParticipantVideoEnabled(e,this),this.localParticipant.videoTracks.forEach((t=>{t.enabled=e})),i&&this.localVideoTracks&&(null===(h=this.localVideoTracks)||void 0===h?void 0:h.length)&&(yield l.changeVideoTracks(this,this.localVideoTracks[0],e));const v=(e,i)=>n(this,void 0,void 0,(function*(){try{yield l.changeVideoTracks(this,i,e),l.sendVideoEnabled(this,e,t)}catch(e){return g.error(`[323] [CallId: ${this.id}] Failed to send video enabled signal: message: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),void(null==t||t({error:(0,p.toCallException)(e)}))}}));a&&(this.sessionId?v(e,o[0]):this.eventsQueue.set(e?r.SignalEvent.VIDEO_ON:r.SignalEvent.VIDEO_OFF,(()=>v(e,o[0]))))}catch(e){return g.error(`[325] [CallId: ${this.id}] Error enabling video ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}})))(),{success:!0}}))}shareScreen(e,t){return n(this,void 0,void 0,(function*(){let i=[];this.screenSharing=e;try{if(e){const t=yield navigator.mediaDevices.getDisplayMedia({video:{width:{max:1280},height:{max:720},frameRate:{max:30}}});if(this.localVideoTracks.forEach((e=>{e.stop()})),i=t.getVideoTracks(),t.addEventListener("inactive",(()=>{this.localParticipant.screenSharing&&this.stopScreenShare()})),this.localVideoTracks=i,this.localParticipant.setVideoTracks(i,this),this.localParticipant.videoTracks.forEach((t=>{t.enabled=e})),i&&i.length){const t=s.InternalCallHandler.getInstance();yield t.changeVideoTracks(this,i[0],e,!0)}this.localParticipant.setScreenSharing(e,this)}else this.localParticipant.videoEnabled&&!e&&(this.localParticipant.setScreenSharing(e,this),yield this.localParticipantVideoEnable(!0,t,!0));const a=e=>n(this,void 0,void 0,(function*(){const i=s.InternalCallHandler.getInstance();yield i.sendScreenShare(this,e,t)}));return this.sessionId?a(e):this.eventsQueue.set(e?r.SignalEvent.SCREEN_SHARE_ON:r.SignalEvent.SCREEN_SHARE_OFF,(()=>a(e))),{success:!0}}catch(e){return g.error(`[324] [CallId: ${this.id}] Error sharing screen ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}))}startScreenShare(e){return n(this,void 0,void 0,(function*(){return this.shareScreen(!0,e)}))}stopScreenShare(e){return n(this,void 0,void 0,(function*(){return yield this.shareScreen(!1,e)}))}getAvailableVideoDevices(){return n(this,void 0,void 0,(function*(){try{return{success:!0,data:(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))}}catch(e){return g.error(`[306] [CallId: ${this.id}] Error getting video devices ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}))}getAvailableAudioDevices(){return n(this,void 0,void 0,(function*(){try{return{success:!0,data:(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))}}catch(e){return g.error(`[307] [CallId: ${this.id}] Error getting audio devices ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}))}selectVideoDevice(e){return n(this,void 0,void 0,(function*(){if(this.setVideoDeviceId(e),!this.videoEnabled||this.localParticipant.screenSharing)return{success:!0};try{this.localVideoTracks.forEach((e=>{e.stop()}));const t=(yield navigator.mediaDevices.getUserMedia({video:{deviceId:{exact:e},width:{min:640,max:1280},height:{min:480,max:720}}})).getVideoTracks();this.localVideoTracks=t,this.localParticipant.setVideoTracks(t,this);const i=s.InternalCallHandler.getInstance();return yield i.changeVideoTracks(this,t[0],this.localParticipant.videoEnabled),{success:!0}}catch(e){return g.error(`[308] [CallId: ${this.id}] Error selecting video device ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}))}selectAudioDevice(e){var t;return n(this,void 0,void 0,(function*(){try{const i=s.InternalCallHandler.getInstance(),n=(yield navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e}}})).getAudioTracks();return this.localAudioTracks=n,this.localParticipant.setAudioTracks(n,this),this.setAudioDeviceId((null===(t=n[0])||void 0===t?void 0:t.getSettings().deviceId)||null),yield i.changeAudioTracks(this,n[0],this.localParticipant.muted),{success:!0}}catch(e){return g.error(`[309] [CallId: ${this.id}] Error selecting audio device ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,p.toCallException)(e)}}}))}setVideoEnabled(e){this.videoEnabled=e}setMuted(e){this._muted=e}getParticipant(e,t){return this.participants.find((i=>i.id===e&&i.clientId===t))}sendRinging(e){return s.InternalCallHandler.getInstance().sendRinging(this,e)}setSettings(e){return this.settings=e,{success:!0}}toJson(){return{id:this.id,sessionId:this.sessionId,mediaFlow:this.mediaFlow,participants:this.participants,localParticipant:this.localParticipant,createdBy:this.createdBy,metadata:this.metadata,state:this.state,activeSpeakerManager:this.activeSpeakerManager,eventsQueue:this.eventsQueue,chatClient:this.chatClient,serverParticipant:this.serverParticipant,videoEnabled:this.videoEnabled,onHold:this.onHold,localAudioTracks:this.localAudioTracks,localVideoTracks:this.localVideoTracks,muted:this.muted,isCallSilenced:this.isCallSilenced}}}t.Call=h},228:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkCode=t.toCallException=t.handleAck=void 0;const n=i(65);function a(e,t){switch(e){case 4e3:return n.SceytCallException.BadSignal(e,t);case 4001:return n.SceytCallException.CallNotFound(e,t);case 4002:return n.SceytCallException.ParticipantNotFound(e,t);case 4005:case 4003:return n.SceytCallException.NotAllowed(e,t);case 4004:return n.SceytCallException.ParticipantAlreadyExists(e,t);case 5001:return n.SceytCallException.InternalError(e,t);case 9901:case 9903:case 9904:return n.SceytCallException.NetworkError(e,t);case 9902:return n.SceytCallException.Timeout(e,t);case 4006:return n.SceytCallException.BadRequest(e,t);default:return n.SceytCallException.Unknown(e,t)}}t.handleAck=function(e){return e.error&&a(e.error.code,e.error.message),e},t.toCallException=function(e){try{if(null==e?void 0:e.code)return a(e.code,e.message)}catch(e){if(e instanceof n.SceytCallException)return e}return n.SceytCallException.Unknown(void 0,(null==e?void 0:e.message)||String(e))},t.checkCode=a},65:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SceytCallException=void 0;class i extends Error{get isResendable(){return this._isResendable}constructor(e,t,i="SceytCallException"){super(e),this.code=t,this.name=i,this._isResendable=!1,this.name=i}static BadSignal(e,t){return new i(t,e,"BadSignal")}static CallNotFound(e,t){return new i(t,e,"CallNotFound")}static ParticipantNotFound(e,t){return new i(t,e,"ParticipantNotFound")}static NotAllowed(e,t){return new i(t,e,"NotAllowed")}static ParticipantAlreadyExists(e,t){return new i(t,e,"ParticipantAlreadyExists")}static InternalError(e,t){const n=new i(t,e,"InternalError");return n._isResendable=!0,n}static NetworkError(e,t){const n=new i(t,e,"NetworkError");return n._isResendable=!0,n}static Timeout(e,t){const n=new i(t,e,"Timeout");return n._isResendable=!0,n}static BadRequest(e,t){return new i(t,e,"BadRequest")}static Unknown(e,t){return new i(t,e)}}t.SceytCallException=i},650:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.InternalCallHandler=void 0;const l=a(i(583)),s=i(787),r=i(546),o=i(786),d=i(578),c=i(998),u=i(489),p=i(645),g=i(429),h=i(65),v=i(680),S=i(228),C=(0,p.createLogger)("InternalCallHandler");class f{constructor(e){this.callParticipantsRTCMap={},this.activeCalls=[],this.prepareCalls=[],this.callEvents={},this.handleMediaConnectedSignal=e=>{const t=this.activeCalls.find((t=>t.id===e.callId));if(t){let i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));if(i||(i=t.participants.find((t=>t.id===e.from.split("/")[0]&&!t.clientId)),i?i.clientId=e.from.split("/")[1]:(i=new s.Participant(e.from),t.addParticipantToList(i),t.emitParticipantsAdded([i]))),i&&t.localParticipant.state===d.ParticipantState.Joined&&t.localParticipant.getFullId()!==i.getFullId()&&(!this.callParticipantsRTCMap[t.id]||!this.callParticipantsRTCMap[t.id][i.getFullId()]||(null==i?void 0:i.shouldResetPeerConnection))){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[968] [CallId: ${t.id}] SYNC CONNECT failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`):e.event!==d.SignalEvent.ERROR||C.error(`[971] [CallId: ${t.id}] SYNC CONNECT failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`)};C.info(`[975] [CallId: ${t.id}] SYNC CONNECT to participant ${i.getFullId()}`,{color:"blue"}),this.signalingClient.clearParticipantSignals(t.id,i.getFullId()),this.signalingClient.sendSignalMessage({to:i.getFullId(),event:d.SignalEvent.CONNECT,mediaFlow:t.mediaFlow,callId:t.id,sessionId:t.sessionId},e)}}},this.onIceCandidate=(e,t,i)=>{var n,a;if(i.mediaFlow!==d.MediaFlow.SFU)if(C.info(`[996] [CallId: ${i.id}] onIceCandidate, participantID: ${e.getFullId()}, candidate: ${null===(n=t.candidate)||void 0===n?void 0:n.candidate}, type: ${null===(a=t.candidate)||void 0===a?void 0:a.type}`,{color:"blue"}),t.candidate&&t.candidate.candidate){let n="";if(!/\bufrag\s+\S+/i.test(t.candidate.candidate)&&this.callParticipantsRTCMap[i.id]&&this.callParticipantsRTCMap[i.id][e.getFullId()]){const t=this.callParticipantsRTCMap[i.id][e.getFullId()];t&&(n=` ufrag ${t.getLocalSdpUfrag()}`)}const a={candidate:t.candidate.candidate+n,sdpMid:t.candidate.sdpMid||"",sdpMLineIndex:t.candidate.sdpMLineIndex||0};try{const t=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[1007] [CallId: ${i.id}] SYNC ICE failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`):e.event!==d.SignalEvent.ERROR||C.error(`[1011] [CallId: ${i.id}] SYNC ICE failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`)};this.signalingClient.sendSignalMessage({to:this.getParticipantId(e),event:d.SignalEvent.ICE,mediaFlow:i.mediaFlow,callId:i.id,sessionId:i.sessionId,ice:a},t)}catch(t){C.error(`[1023] [CallId: ${i.id}] Failed to send ICE candidate to ${e.getFullId()}: ${t instanceof Error?t.message:JSON.stringify(t)}`)}}else C.info(`[1025] [CallId: ${i.id}] ICE gathering complete for participant ${e.getFullId()} (null candidate)`,{color:"blue"});else C.info(`[1024] [CallId: ${i.id}] onIceCandidate, participantID: ${e.getFullId()}, skip for SFU`,{color:"blue"})},this.onTrack=(e,t,i)=>{const n=null==i?void 0:i.track;C.info(`[1032] [CallId: ${e.id}] onTrack, participantID: ${t.getFullId()}, kind: ${n.kind}`,{color:"blue"}),"audio"===(null==n?void 0:n.kind)?(t.setAudioTracks([n],e),n.onended=()=>{C.info(`[1038] [CallId: ${e.id}] Audio track ended for participant ${t.getFullId()}`,{color:"yellow"}),t.setAudioTracks([],e),e.emitAudioTrackRemoved(t)}):"video"===(null==n?void 0:n.kind)&&(t.setVideoTracks([n],e),n.onended=()=>{C.info(`[1052] [CallId: ${e.id}] Video track ended for participant ${t.getFullId()}`,{color:"yellow"}),t.setVideoTracks([],e),e.emitVideoTrackRemoved(t)})},this.kickParticipantFromCall=(e,t)=>{this.signalingClient.sendSignalMessage({mediaFlow:t.mediaFlow,callId:t.id,event:d.SignalEvent.KICK,sessionId:t.sessionId,participants:[{id:e.id,clientId:e.clientId}]},(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[1642] [CallId: ${t.id}] Kick participant failed: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[1646] [CallId: ${t.id}] Kick participant failed: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})}))},this.addParticipantsToCall=(e,t)=>{try{if(e.forEach((e=>{const i=t.participants.filter((t=>t.id===e));if(i.length>0)for(const e of i)e.state!==d.ParticipantState.Joined&&e.state!==d.ParticipantState.Ringing&&(e.updateState(d.ParticipantState.Idle,t.id),e.updateConnectionState(d.ParticipantConnectionState.Idle,t.id),t.emitParticipantStateChanged(e,d.ParticipantState.Idle),t.emitParticipantConnectionStateChanged(e,d.ParticipantConnectionState.Idle));else{const i=new s.Participant(e);t.addParticipantToList(i),t.emitParticipantsAdded([i])}})),C.info(`[1547] [CallId: ${t.id}] added participants to call: ${e}, callId: ${t.id}`,{color:"light-green"}),e.length>0){const i=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[1551] [CallId: ${t.id}] SYNC INVITE failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[1555] [CallId: ${t.id}] SYNC INVITE failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};return this.signalingClient.sendSignalMessage({callId:t.id,sessionId:t.sessionId,event:d.SignalEvent.INVITE,participants:e.map((e=>new s.Participant(e).serialize()))},i),!0}return!1}catch(i){return C.error(`[1567] [CallId: ${t.id}] Failed to add participants to call: ${e}, callId: ${t.id} message: ${i instanceof Error?i.message:JSON.stringify(i)}`,{color:"red"}),!1}},this.sendSignalScreenShare=(e,t,i)=>{try{const n=t=>t instanceof h.SceytCallException||t instanceof Error?(C.error(`[1679] [CallId: ${e.id}] SYNC SCREEN_SHARE_ON failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`),void(null==i||i({error:(0,S.toCallException)(t)}))):t.event===d.SignalEvent.ERROR?(C.error(`[1683] [CallId: ${e.id}] SYNC SCREEN_SHARE_ON failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`),void(null==i||i({error:(0,S.toCallException)(t.error)}))):void 0;return this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,event:t?d.SignalEvent.SCREEN_SHARE_ON:d.SignalEvent.SCREEN_SHARE_OFF,sessionId:e.sessionId},n),!0}catch(t){return C.error(`[1694] [CallId: ${e.id}] Failed to send screen share signal: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"}),null==i||i({error:(0,S.toCallException)(t)}),!1}},this.setupMediaStream=e=>n(this,void 0,void 0,(function*(){var t,i;try{const n=!e.getAudioDeviceId()||{deviceId:{exact:e.getAudioDeviceId()}},a=(yield navigator.mediaDevices.getUserMedia({video:!1,audio:n})).getAudioTracks();if(e.localAudioTracks=a,e.setAudioDeviceId((null===(t=a[0])||void 0===t?void 0:t.getSettings().deviceId)||null),!(null==e?void 0:e.localVideoTracks)||!(null===(i=e.localVideoTracks)||void 0===i?void 0:i.length)){const t=(0,u.getEmptyVideoTrack)();t.forEach((e=>e.enabled=!1)),e.localVideoTracks=t,e.localParticipant.setVideoTracks(t,e)}return e.localParticipant.audioTracks=a,{audioTracks:a}}catch(t){throw C.error(`[1945] [CallId: ${e.id}] Failed to get media: message: ${t instanceof Error?t.message:JSON.stringify(t)}`),(0,S.toCallException)(t)}})),this.chatClient=e,this.user=e.user,this.clientId=e.clientId,this.signalingClient=new o.Signaling(e,this.handleSignalMessage.bind(this));const t=new this.chatClient.ConnectionListener;t.onConnectionStateChanged=e=>{C.info(`[46] [CallId: GLOBAL_LOGS] Signaling connection state changed: ${e}`,{color:"cyan"}),"Connected"===e&&(this.activeCalls.forEach((e=>{const t=this.signalingClient.signalingQueues.get(e.id);t&&t.triggerSignalProcessing()})),setTimeout((()=>{this.signalingClient.sendSignalMessage({event:d.SignalEvent.GET_CALL,callId:""},(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[57] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed ${e instanceof h.SceytCallException||e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}):e.event!==d.SignalEvent.ERROR?this.syncActiveCalls(e):C.error("[63] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed message: "+(e.error?`${e.error.message} code: ${e.error.code}`:""),{color:"red"})}),"get_call")}),1e3))},this.chatClient.addConnectionListener("listener_id",t),"Connected"===this.chatClient.connectionState&&setTimeout((()=>{this.signalingClient.sendSignalMessage({event:d.SignalEvent.GET_CALL,callId:""},(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[74] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR?this.syncActiveCalls(e):C.error("[77] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed message: "+(e.error?`${e.error.message} code: ${e.error.code}`:""),{color:"red"})}),"get_call")}),1e3),f.instance=this}syncActiveCalls(e){var t,i,n;const a=this.activeCalls;try{if(!(null==e?void 0:e.calls))return;if(e.event!==d.SignalEvent.SUCCESS)return void C.error("[98] [CallId: GLOBAL_LOGS] Failed to get call information after reconnection message: "+(e.error?`${e.error.message} code: ${e.error.code}`:""),{color:"red"});for(const l of a){const a=e.calls.find((e=>(null==e?void 0:e.id)===l.id));if(!a&&!(null==l?void 0:l.sessionId))continue;if(!a){this.closeCall(l);continue}if(a.sessionId!==l.sessionId){C.info(`[syncActiveCalls] [CallId: ${l.id}] sessionId changed (${l.sessionId} → ${a.sessionId}), closing stale call`,{color:"yellow"}),this.closeCall(l),this.promoteFromPrepared(a.id,a)?C.info(`[syncActiveCalls] [CallId: ${a.id}] Promoted from prepareCalls to activeCalls`,{color:"cyan"}):this.findOrCreateCall({id:a.id,sessionId:a.sessionId,mediaFlow:a.mediaFlow,participants:[],metadata:a.metadata,createdBy:a.createdBy,settings:null==a?void 0:a.settings},a.participants);continue}const r=l.mediaFlow!==d.MediaFlow.SFU&&a.mediaFlow===d.MediaFlow.SFU;if(this.updateCallMetadata(l,a),r&&this.handleMediaFlowSwitch(l),this.syncParticipants(l,a.participants),l.localParticipant.state<=d.ParticipantState.Joined&&(l.state===d.CallState.Connected||l.state===d.CallState.Connecting)){for(const e of l.participants)if(l.mediaFlow!==d.MediaFlow.SFU&&e.connectionState===d.ParticipantConnectionState.Connected&&e.id!==l.localParticipant.id&&e.clientId!==l.localParticipant.clientId){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[139] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[143] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};this.signalingClient.sendSignalMessage({event:d.SignalEvent.MEDIA_CONNECTED,callId:l.id,sessionId:l.sessionId,mediaFlow:l.mediaFlow,to:l.id},e)}if(l.mediaFlow===d.MediaFlow.SFU&&(null===(t=l.serverParticipant)||void 0===t?void 0:t.connectionState)===d.ParticipantConnectionState.Connected&&l.state===d.CallState.Connected){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[158] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[162] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};this.signalingClient.sendSignalMessage({event:d.SignalEvent.MEDIA_CONNECTED,callId:l.id,sessionId:l.sessionId,mediaFlow:l.mediaFlow,to:l.id},e)}if(l.mediaFlow!==d.MediaFlow.SFU||this.callParticipantsRTCMap[l.id]&&this.callParticipantsRTCMap[l.id][l.id]||l.state!==d.CallState.Connected){if(l.mediaFlow===d.MediaFlow.SFU&&l.serverParticipant&&(null===(n=l.serverParticipant)||void 0===n?void 0:n.connectionState)!==d.ParticipantConnectionState.Reconnecting&&l.state===d.CallState.Connected){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[199] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[203] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};C.info(`[205] [CallId: ${l.id}] Sending offer to server participant when server participant is not connected: ${l.serverParticipant.getFullId()}`,{color:"yellow"}),this.sendOfferPeerToPeer(l,l.serverParticipant,e)}}else{if((null===(i=l.serverParticipant)||void 0===i?void 0:i.id)!==l.id){const e=new s.Participant(l.id);l.setServerParticipant(e)}if(l.serverParticipant){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[181] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[185] [CallId: ${l.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};C.info(`[188] [CallId: ${l.id}] Sending offer to server participant when there is no server participant in the call: ${l.serverParticipant.getFullId()}`,{color:"yellow"}),this.sendOfferPeerToPeer(l,l.serverParticipant,e)}}}else this.leaveCall(l,!1,"syncActiveCalls")}const l=this.activeCalls.find((e=>e.state===d.CallState.Connected));l&&!e.calls.find((e=>e.id===l.id&&e.sessionId===l.sessionId))&&this.closeCall(l),this.activeCalls=this.activeCalls.filter((t=>{var i;return!(!(null===(i=null==e?void 0:e.calls)||void 0===i?void 0:i.find((e=>e.id===t.id)))&&t.sessionId&&(t.clearEventsQueue(),t.participants.forEach((e=>{this.signalingClient.clearParticipantSignals(t.id,e.getFullId())})),this.signalingClient.clearCallSignals(t.id),1))})),e.calls.forEach((e=>{!this.activeCalls.find((t=>(null==t?void 0:t.id)===(null==e?void 0:e.id)))&&e.id&&e.sessionId&&(this.promoteFromPrepared(e.id,e)?C.info(`[syncActiveCalls] [CallId: ${e.id}] Promoted from prepareCalls to activeCalls`,{color:"cyan"}):this.findOrCreateCall({id:e.id,sessionId:e.sessionId,mediaFlow:e.mediaFlow,participants:[],metadata:e.metadata,createdBy:e.createdBy,settings:null==e?void 0:e.settings},e.participants))})),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls)}catch(e){C.error(`[248] [CallId: GLOBAL_LOGS] Error syncing calls after reconnection: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"})}}setCallEvent(e,t){this.callEvents[e]=t}handleSignalMessage(e){switch(C.info(`[253] [CallId: ${e.callId}] Received ${d.SignalEvent[e.event]}: ${JSON.stringify(Object.assign({},e))}`,{color:"green"}),e.event||0){case d.SignalEvent.OFFER:this.handleOfferSignal(e);break;case d.SignalEvent.ANSWER:this.handleAnswerSignal(e);break;case d.SignalEvent.JOIN:this.handleJoinSignal(e);break;case d.SignalEvent.LEAVE:this.handleLeaveSignal(e);break;case d.SignalEvent.INVITE:this.handleInviteSignal(e);break;case d.SignalEvent.CLOSE:this.handleCloseSignal(e);break;case d.SignalEvent.DECLINE:this.handleDeclineSignal(e);break;case d.SignalEvent.RINGING:this.handleRingingSignal(e);break;case d.SignalEvent.SWITCH_MEDIA_FLOW:this.handleSwitchMediaFlowSignal(e);break;case d.SignalEvent.ICE:this.handleIceSignal(e);break;case d.SignalEvent.VIDEO_ON:this.handleVideoOnSignal(e);break;case d.SignalEvent.VIDEO_OFF:this.handleVideoOffSignal(e);break;case d.SignalEvent.SCREEN_SHARE_ON:this.handleScreenShareOnSignal(e);break;case d.SignalEvent.SCREEN_SHARE_OFF:this.handleScreenShareOffSignal(e);break;case d.SignalEvent.MUTE:this.handleMuteSignal(e);break;case d.SignalEvent.UNMUTE:this.handleUnmuteSignal(e);break;case d.SignalEvent.HOLD:this.handleHoldSignal(e);break;case d.SignalEvent.UNHOLD:this.handleUnholdSignal(e);break;case d.SignalEvent.KICK:this.handleKickSignal(e);break;case d.SignalEvent.UPDATE:this.handleUpdateSignal(e);break;case d.SignalEvent.NO_ANSWER:this.handleNoAnswerSignal(e);break;case d.SignalEvent.MEDIA_CONNECTED:this.handleMediaConnectedSignal(e);break;case d.SignalEvent.CONNECT:this.handleConnectSignal(e);break;case d.SignalEvent.SESSION_RENEWED:this.handleSessionRenewedSignal(e);break;default:C.info(`[254] [CallId: ${e.callId}] unhandled signal message: ${JSON.stringify(e)}`,{color:"green"})}}getParticipantId(e){return`${e.id}${(null==e?void 0:e.clientId)?"/"+(null==e?void 0:e.clientId):""}`}handleOfferSignal(e){var t,i,a,l;if(!this.activeCalls)return void C.warn(`[342] [CallId: ${e.callId}] No active calls found for send offer participant: ${e.from}`,{color:"red"});let s;try{const r=this.activeCalls.find((t=>t.id===e.callId));if(!r)return void C.warn(`[348] [CallId: ${e.callId}] No active call found for send offer participant: ${e.from}`,{color:"red"});if(r.state!==d.CallState.Connected)return void C.warn(`[353] [CallId: ${e.callId}] Call is not connected for send offer participant: ${e.from}`,{color:"red"});let o=null==r?void 0:r.participants.find((t=>t.getFullId()===e.from));if(o){s=o.getFullId();const c=this.callParticipantsRTCMap[r.id]&&(null===(t=this.callParticipantsRTCMap[r.id])||void 0===t?void 0:t[o.getFullId()]);let u=null==c?void 0:c.getSessionId();!o.shouldResetPeerConnection&&c&&u===(null===(i=e.sessionData)||void 0===i?void 0:i.id)||(this.closePeerConnections(r.id,o.getFullId()),r.activeSpeakerManager.removeParticipant(o),this.addParticipantToRTCMap(r,o),o.setShouldResetPeerConnection(!1),(this.callParticipantsRTCMap[r.id]&&(null===(a=this.callParticipantsRTCMap[r.id])||void 0===a?void 0:a[o.getFullId()])).setSessionId((null===(l=e.sessionData)||void 0===l?void 0:l.id)||"")),this.signalingClient.clearParticipantSignals(r.id,o.getFullId()),this.setRemoteDescription(r.id,o.getFullId(),(0,v.toSessionDescription)(e.sessionData,"offer")).then((()=>n(this,void 0,void 0,(function*(){var t,i,n;if(!o)return void C.info(`[392] [CallId: ${e.callId}] Participant not found in call: ${e.from}`,{color:"cyan"});const a=this.callParticipantsRTCMap[r.id][o.getFullId()],l=this.activeCalls.find((e=>e.id===r.id));l&&(l.mediaFlow!==d.MediaFlow.SFU||l.mediaFlow===d.MediaFlow.SFU&&o.id===(null===(t=null==l?void 0:l.serverParticipant)||void 0===t?void 0:t.id))&&(yield this.addTracksToPeerConnection(r,o.getFullId(),!1)),a.createAnswer((null===(i=e.sessionData)||void 0===i?void 0:i.id)||"",(null===(n=e.sessionData)||void 0===n?void 0:n.version)||"",r.mediaFlow).then((t=>{if(!o)return void C.info(`[392] [CallId: ${e.callId}] Participant not found in call: ${e.from}`,{color:"cyan"});if(!t)return void C.error(`[456] [CallId: ${r.id}] Failed to create answer for participant: ${o.getFullId()}`,{color:"red"});const i=a.getRemoteSdpUfrag();if(i&&a.iceQueueMap[o.getFullId()]){const e=a.iceQueueMap[o.getFullId()][i];if(e&&e.length>0)for(const t of e)a.addIceCandidate(t,o.getFullId())}this.signalingClient.sendSignalMessage({to:e.from,mediaFlow:e.mediaFlow,callId:r.id,event:d.SignalEvent.ANSWER,sessionData:t,sessionId:e.sessionId,metadata:e.metadata},(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[386] [CallId: ${r.id}] SYNC ANSWER failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[389] [CallId: ${r.id}] SYNC ANSWER failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})}))}))}))))}else C.info(`[402] [CallId: ${e.callId}] Participant not found in call: ${e.from}`,{color:"cyan"})}catch(t){C.error(`[406] [CallId: ${e.callId}] Failed to handle offer: ${s} message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"})}}handleAnswerSignal(e){var t;try{const i=this.activeCalls.find((t=>t.id===e.callId));if(i){let n;if(n=i.mediaFlow===d.MediaFlow.SFU&&i.serverParticipant&&i.serverParticipant.getFullId()===e.from?i.serverParticipant:i.participants.find((t=>t.getFullId()===e.from)),n){const a=null===(t=e.sessionData)||void 0===t?void 0:t.version;if(!a||a!==this.callParticipantsRTCMap[i.id][n.getFullId()].getVersion())return void C.warn(`[412] [CallId: ${i.id}] Version is not set or is the same as the current version: ${a}`,{color:"red"});this.callParticipantsRTCMap[i.id][n.getFullId()].setVersion(a),this.setRemoteDescription(i.id,n.getFullId(),(0,v.toSessionDescription)(e.sessionData,"answer")).then((()=>{if(!n)return void C.info(`[462] [CallId: ${e.callId}] Participant not found in call: ${e.from}`,{color:"cyan"});const t=this.callParticipantsRTCMap[i.id][n.getFullId()].getRemoteSdpUfrag();if(t&&this.callParticipantsRTCMap[i.id][n.getFullId()].iceQueueMap[n.getFullId()]){const e=this.callParticipantsRTCMap[i.id][n.getFullId()].iceQueueMap[n.getFullId()][t];if(e&&e.length>0)for(const t of e)this.callParticipantsRTCMap[i.id][n.getFullId()].addIceCandidate(t,n.getFullId())}}))}}}catch(t){C.error(`[435] [CallId: ${e.callId}] Failed to handle answer: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"})}}sendOfferPeerToPeer(e,t,i){return n(this,void 0,void 0,(function*(){this.callParticipantsRTCMap.hasOwnProperty(e.id)&&this.callParticipantsRTCMap[e.id].hasOwnProperty(t.getFullId())||(this.addParticipantToRTCMap(e,t),yield this.addTracksToPeerConnection(e,t.getFullId(),!0));const n=this.callParticipantsRTCMap[e.id][t.getFullId()];let a=n.getVersion();n.setVersion(a?String(Number(a)+1):"1"),a=n.getVersion();let l=n.getSessionId();l||(l=(0,g.v4)(),n.setSessionId(l)),n.createOffer(l,a,e.mediaFlow).then((n=>{n?this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,event:d.SignalEvent.OFFER,sessionData:n,to:t.getFullId(),sessionId:e.sessionId},i):C.error(`[456] [CallId: ${e.id}] Failed to create offer for participant: ${t.getFullId()}`,{color:"red"})}))}))}handleJoinSignal(e){var t;try{let i=this.activeCalls.find((t=>t.id===e.callId));if(!i){if(this.promoteFromPrepared(e.callId,this.signalMessageToICall(e)));else{const{call:t}=this.findOrCreateCall({id:e.callId,sessionId:e.sessionId,mediaFlow:e.mediaFlow,participants:[],metadata:e.metadata},e.participants);i=t}return}if(i&&!i.sessionId&&(i.setSessionId(e.sessionId),i.setIsCreatedRemotely(!0)),i){let n;(null===(t=e.participants)||void 0===t?void 0:t.length)&&(n=e.participants[0]);let a=!1,l=i.participants.find((t=>t.getFullId()===e.from));if(l?l&&((null==n?void 0:n.videoEnabled)&&l.setParticipantVideoEnabled(!!(null==n?void 0:n.videoEnabled),i),(null==n?void 0:n.muted)&&l.setMuted(!!(null==n?void 0:n.muted),i)):(l=i.participants.find((t=>t.id===e.from.split("/")[0]&&(t.clientId===e.from.split("/")[1]||!t.clientId))),l?(l.clientId=e.from.split("/")[1],(null==n?void 0:n.videoEnabled)&&l.setParticipantVideoEnabled(null==n?void 0:n.videoEnabled,i),(null==n?void 0:n.muted)&&l.setMuted(null==n?void 0:n.muted,i)):l=void 0),l||(l=new s.Participant(e.from),(null==n?void 0:n.videoEnabled)&&l.setParticipantVideoEnabled(!!(null==n?void 0:n.videoEnabled),i),(null==n?void 0:n.muted)&&l.setMuted(!!(null==n?void 0:n.muted),i),i.addParticipantToList(l),a=!0),i.mediaFlow===d.MediaFlow.P2P&&i.localParticipant.state===d.ParticipantState.Joined&&this.isPolitePeer(e.from,i.localParticipant.getFullId())){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[495] [CallId: ${null==i?void 0:i.id}] SYNC OFFER failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[499] [CallId: ${null==i?void 0:i.id}] SYNC OFFER failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};C.info(`[503] [CallId: ${i.id}] Sending offer to participant: ${l.getFullId()}`),this.sendOfferPeerToPeer(i,l,e)}l.updateState(d.ParticipantState.Joined,i.id),C.info(`[503] [CallId: ${i.id}] Participant joined call shouldSendEventInvited: ${a}`),a?i.emitParticipantsAdded([l]):i.emitParticipantStateChanged(l,d.ParticipantState.Joined)}}catch(t){C.error(`[514] [CallId: ${e.callId}] Failed to handle USER_JOINED: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"})}}handleLeaveSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.id===e.from.split("/")[0]&&(t.clientId===e.from.split("/")[1]||!t.clientId)));i&&i.updateState(d.ParticipantState.Left,t.id)&&(this.closePeerConnections(t.id,i.getFullId()),t.activeSpeakerManager.removeParticipant(i),i.setScreenSharing(!1,t),i.setHold(!1,t),t.emitParticipantStateChanged(i,d.ParticipantState.Left),i.updateConnectionState(d.ParticipantConnectionState.Idle,t.id)&&t.emitParticipantConnectionStateChanged(i,d.ParticipantConnectionState.Idle))}}handleInviteSignal(e){if(!e||!e.callId)return void C.warn(`[545] [CallId: ${e.callId}] Received invalid invite signal message`);let t=this.activeCalls.find((t=>t.id===e.callId));t||(t=this.promoteFromPrepared(e.callId,this.signalMessageToICall(e)));const i=(null==e?void 0:e.to)===this.user.id;if(i&&t)for(let e=0;e<t.participants.length;e++){const i=t.participants[e];i.id===this.user.id&&(i.updateConnectionState(d.ParticipantConnectionState.Idle,t.id),i.updateState(d.ParticipantState.Idle,t.id),null==t||t.emitParticipantConnectionStateChanged(i,d.ParticipantConnectionState.Idle),null==t||t.emitParticipantStateChanged(i,d.ParticipantState.Idle))}t?this.handleExistingCallInvite(t,e,i):this.handleNewCallInvite(e,i),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls)}handleExistingCallInvite(e,t,i){var n,a;if(i){e.localParticipant.updateConnectionState(d.ParticipantConnectionState.Connecting,e.id)&&(e.participants.find((e=>e.id===this.user.id&&e.clientId===this.clientId))||e.addParticipantToList(e.localParticipant),e.emitParticipantConnectionStateChanged(e.localParticipant,d.ParticipantConnectionState.Connecting));const i=(null===(a=null===(n=t.participants)||void 0===n?void 0:n.find((e=>e.id===this.user.id&&e.clientId===this.clientId)))||void 0===a?void 0:a.isCallSilenced)||!1;e.setIsCallSilenced(i),this.callEvents.onInvitedToCall&&this.callEvents.onInvitedToCall(e)}else{const i=this.addNewParticipantsToCall(e,t);i.length>0&&e.emitParticipantsAdded(i)}}handleNewCallInvite(e,t){var i,n;const a=new s.Participant(this.user.id,this.clientId);a.updateConnectionState(d.ParticipantConnectionState.Connecting,e.callId);let r=!1;const o=null===(i=e.participants)||void 0===i?void 0:i.map((t=>{if(t.id===this.user.id&&!t.clientId)return r=t.isCallSilenced||!1,a;const i=new s.Participant(t.id,null==t?void 0:t.clientId);return i.updateState(t.state||d.ParticipantState.Idle,e.callId),i.setMuted(!!(null==t?void 0:t.muted)),i.setParticipantVideoEnabled(!!(null==t?void 0:t.videoEnabled)),i}));if(!t&&!(null==o?void 0:o.find((t=>t.getFullId()===e.from)))&&e.from.split("/")[0]===this.user.id&&e.from.split("/")[1]!==this.clientId){const t=new s.Participant(e.from,e.from.split("/")[1]);t.updateState(d.ParticipantState.Joined,e.callId),null==o||o.push(t)}const p=(0,u.makeFirstById)(o||[],this.user.id,this.clientId),g=new c.Call({id:e.callId,sessionId:e.sessionId,mediaFlow:e.mediaFlow,createdBy:e.from,localParticipant:a,metadata:e.metadata,participants:p,chatClient:this.chatClient,isCallSilenced:r});if(g.setVideoCall("true"===(null===(n=e.metadata)||void 0===n?void 0:n.videoCall)),e.settings){const t=e.settings;g.setSettings(Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==t.startsAt&&{startsAt:l.default.isLong(t.startsAt)?t.startsAt.toNumber():t.startsAt}),void 0!==t.expiresAt&&{expiresAt:l.default.isLong(t.expiresAt)?t.expiresAt.toNumber():t.expiresAt}),void 0!==t.persistent&&{persistent:t.persistent}),void 0!==t.broadcastOptions&&{broadcastSettings:t.broadcastOptions}))}this.activeCalls.push(g),this.callEvents.onInvitedToCall&&t&&this.callEvents.onInvitedToCall(g),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls)}addNewParticipantsToCall(e,t){var i;const n=[];return null===(i=t.participants)||void 0===i||i.forEach((t=>{const i=t.id!==this.user.id?e.participants.find((e=>e.id===t.id)):void 0,a=i||new s.Participant(t.id,null==t?void 0:t.clientId);i?t.state!==d.ParticipantState.Joined&&(a.updateState(t.state||d.ParticipantState.Idle,e.id),a.updateConnectionState(d.ParticipantConnectionState.Idle,e.id),a.setParticipantVideoEnabled(t.videoEnabled||!1,e),e.emitParticipantStateChanged(a,d.ParticipantState.Idle),e.emitParticipantConnectionStateChanged(a,d.ParticipantConnectionState.Idle)):(a.updateState(t.state||d.ParticipantState.Idle,e.id),n.push(a),e.addParticipantToList(a))})),n}handleCloseSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));t&&this.closeCall(t)}handleDeclineSignal(e){var t;const i=this.activeCalls.find((t=>t.id===e.callId));if(i)if(this.getParticipantId({id:this.user.id,clientId:this.clientId})===e.from)this.leaveCall(i,!0,"Current user declined the call"),i.setState(d.CallState.Idle,"Current user declined the call");else{let n=null==i?void 0:i.participants.find((t=>t.getFullId()===e.from));n||(n=null==i?void 0:i.participants.find((t=>t.id===e.from.split("/")[0]&&!t.clientId)),n?n.clientId=e.from.split("/")[1]:(n=new s.Participant(e.from),i.addParticipantToList(n),i.emitParticipantsAdded([n]))),n&&n.updateState(d.ParticipantState.Declined,i.id)&&i.emitParticipantStateChanged(n,d.ParticipantState.Declined,null===(t=e.metadata)||void 0===t?void 0:t.reason)}}handleRingingSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){let i=null==t?void 0:t.participants.find((t=>t.id===e.from.split("/")[0]&&(t.clientId===e.from.split("/")[1]||!t.clientId)));i||(i=new s.Participant(e.from),t.addParticipantToList(i),t.emitParticipantsAdded([i])),i&&i.connectionState!==d.ParticipantConnectionState.Connected&&i.updateState(d.ParticipantState.Ringing,t.id)&&(i.clientId||(i.clientId=e.from.split("/")[1]),t.emitParticipantStateChanged(i,d.ParticipantState.Ringing))}}handleSwitchMediaFlowSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t&&t.localParticipant.state===d.ParticipantState.Joined){t.changeMediaFlow(d.MediaFlow.SFU);const e=new s.Participant(t.id);t.setServerParticipant(e);const i=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[738] [CallId: ${t.id}] SYNC OFFER failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`):e.event!==d.SignalEvent.ERROR||C.error(`[742] [CallId: ${t.id}] SYNC OFFER failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`)};C.info(`[747] [CallId: ${t.id}] Sending offer to server participant: ${e.getFullId()}`),this.sendOfferPeerToPeer(t,e,i),t.participants.forEach((e=>{e.setShouldResetPeerConnection(!0)}))}else t&&t.changeMediaFlow(d.MediaFlow.SFU)}handleIceSignal(e){var t;if(!e.callId||!e.ice)return void C.warn(`[756] [CallId: ${e.callId}] Invalid ICE signal: missing callId or ice data`);const i=this.activeCalls.find((t=>t.id===e.callId));if(!i)return void C.warn(`[763] [CallId: ${e.callId}] ICE candidate received for unknown call: ${e.callId}`);const n=i.participants.find((t=>t.getFullId()===e.from));if(n)try{if(!this.callParticipantsRTCMap[i.id])return void C.error(`[774] [CallId: ${i.id}] No RTC map found for call ${i.id}`);null===(t=this.callParticipantsRTCMap[i.id][n.getFullId()])||void 0===t||t.addIceCandidate(e.ice,n.getFullId())}catch(e){C.error(`[787] [CallId: ${i.id}] Failed to add ICE candidate for participant ${n.getFullId()} in call ${i.id}: ${e instanceof Error?e.message:JSON.stringify(e)}`)}else C.warn(`[768] [CallId: ${e.callId}] ICE candidate received from unknown participant: ${e.from} in call ${e.callId}`)}handleVideoOnSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from||t.id===e.from.split("/")[0]&&!t.clientId));i&&i.setParticipantVideoEnabled(!0,t)}}handleVideoOffSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){let i;null==t||t.participants.forEach((n=>{(n.getFullId()===e.from||n.id===e.from.split("/")[0]&&!n.clientId)&&(n.setParticipantVideoEnabled(!1,t),i=n)}))}}handleScreenShareOnSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.setScreenSharing(!0,t)}}handleScreenShareOffSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&(i.setScreenSharing(!1,t),i.videoEnabled&&i.setParticipantVideoEnabled(!0,t))}}handleMuteSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.setMuted(!0,t)}}handleUnmuteSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.setMuted(!1,t)}}handleHoldSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.setHold(!0,t)}}handleUnholdSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.setHold(!1,t)}}handleKickSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){const i=null==t?void 0:t.participants.find((t=>t.getFullId()===e.from));i&&i.updateState(d.ParticipantState.Kicked,t.id)&&t.emitParticipantStateChanged(i,d.ParticipantState.Kicked)}}handleUpdateSignal(e){var t;const i=this.activeCalls.find((t=>t.id===e.callId));i&&e.metadata&&(i.metadata=e.metadata,i.setVideoCall("true"===(null===(t=e.metadata)||void 0===t?void 0:t.videoCall)))}handleNoAnswerSignal(e){var t;const i=this.activeCalls.find((t=>t.id===e.callId));i&&(null===(t=e.participants)||void 0===t||t.forEach((e=>{(null==i?void 0:i.participants.filter((t=>t.id===e.id&&(t.clientId===e.clientId||!e.clientId)))).forEach((e=>{e.updateState(d.ParticipantState.NoAnswer,i.id)&&i.emitParticipantStateChanged(e,d.ParticipantState.NoAnswer)}))})))}static getInstance(){if(!f.instance)throw new Error("InternalCallHandler has not been initialized. Call new InternalCallHandler(chatClient) first.");return f.instance}setRTCConfig(e){this.rtcConfig=e}onIceCandidateListener(e,t){return i=>{this.onIceCandidate(e,i,t)}}onSignalingStateChangeListener(e,t){return i=>{var n;const a=(null===(n=null==i?void 0:i.currentTarget)||void 0===n?void 0:n.signalingState)||"unknown";C.info(`[1067] [CallId: ${t.id}] Signaling state change: ${a}, participantID: ${e.getFullId()}`,{color:"blue"})}}isPolitePeer(e,t){return t>e}onIceConnectionStateChangeListener(e,t){return i=>{var n;const a=(null===(n=null==i?void 0:i.currentTarget)||void 0===n?void 0:n.iceConnectionState)||"unknown";C.info(`[1078] [CallId: ${t.id}] ICE connection state change: ${a}, participantID: ${e.getFullId()}`,{color:"blue"})}}onConnectionStateChangeListener(e,t){return i=>{var n,a,l,s,r;const o=i.currentTarget.connectionState;C.info(`[1078] [CallId: ${t.id}] PC connection state changed: ${o}, participantID: ${e.getFullId()}`,{color:"disconnected"===o?"orange":"failed"===o?"red":"blue"});const c=this.activeCalls.find((e=>e.id===t.id))||t,u=(null==c?void 0:c.participants.find((t=>t.getFullId()===e.getFullId())))||e.id===(null===(n=null==c?void 0:c.serverParticipant)||void 0===n?void 0:n.id)&&e;if(!u)return;let p=0,g=null;const v=e=>{p=0,g&&(clearInterval(g),g=null),e&&clearTimeout(e)},S=(i,n=!1)=>{C.info(`[1089] [CallId: ${t.id}] start renegotiation send ${i} to participant ${u.getFullId()}`,{color:"blue"});const a=a=>{var l;const s=this.activeCalls.find((e=>e.id===t.id))||t,r=s.participants.find((t=>t.getFullId()===e.getFullId()))||e.id===(null===(l=s.serverParticipant)||void 0===l?void 0:l.id)&&e||e;if("Connected"===this.chatClient.connectionState&&r.connectionState!==d.ParticipantConnectionState.Connected&&s.state===d.CallState.Connected)if(C.info(`[1190] [CallId: ${t.id}] interval renegotiation send ${i} to participant ${r.getFullId()}`,{color:"blue"}),"offer"!==i||n&&!this.isPolitePeer(r.getFullId(),s.localParticipant.getFullId()||"")){if("connect"===i&&(!n||this.isPolitePeer(r.getFullId(),s.localParticipant.getFullId()||""))){C.info(`[1214] [CallId: ${t.id}] ${d.MediaFlow.SFU} sendConnect to participant 1 ${JSON.stringify(r)}`,{color:"blue"});try{this.signalingClient.clearParticipantSignals(s.id,r.getFullId()),this.signalingClient.sendSignalMessage({mediaFlow:s.mediaFlow,callId:s.id,sessionId:s.sessionId,event:d.SignalEvent.CONNECT,to:r.getFullId()},a)}catch(e){C.error(`[1236] [CallId: ${t.id}] Failed to send connect to participant ${r.getFullId()}: message: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"})}}}else try{C.info(`[1211] [CallId: ${t.id}] Sending offer to participant: ${r.getFullId()}`),this.sendOfferPeerToPeer(s,r,a)}catch(e){C.error(`[1211] [CallId: ${t.id}] Failed to send offer to participant ${r.getFullId()}: ${e instanceof Error?e.message:JSON.stringify(e)}`)}};g&&(clearInterval(g),g=null);let l=null;g=setInterval((()=>{var n,s,r;const o=this.activeCalls.find((e=>e.id===t.id))||t,c=o.participants.find((t=>t.getFullId()===e.getFullId()))||e.id===(null===(n=o.serverParticipant)||void 0===n?void 0:n.id)&&e||e,u=null===(r=null===(s=this.callParticipantsRTCMap[t.id])||void 0===s?void 0:s[c.getFullId()])||void 0===r?void 0:r.peerConnection;return C.info(`[1182] [CallId: ${t.id}] retry count: ${p+1}`,{color:"green"}),o&&o.state===d.CallState.Connected?c.connectionState===d.ParticipantConnectionState.Connected&&"stable"===(null==u?void 0:u.signalingState)||c.state!==d.ParticipantState.Joined?(v(l),void(l=null)):(p+=1,p>=10?(C.warn(`[1182] [CallId: ${t.id}] Max retries reached for ${i} to ${c.getFullId()}, giving up`,{color:"red"}),c.updateConnectionState(d.ParticipantConnectionState.Disconnected,t.id),v(l),void(l=null)):void a((e=>{var n;return e instanceof h.SceytCallException||e instanceof Error?(C.error(`[1202] [CallId: ${t.id}] SYNC ${i} failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}),void("NotAllowed"===e.name&&(c.updateConnectionState(d.ParticipantConnectionState.Disconnected,t.id),v(l),l=null))):e.event===d.SignalEvent.ERROR?(C.error(`[1205] [CallId: ${t.id}] SYNC ${i} failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"}),void(4002===(null===(n=e.error)||void 0===n?void 0:n.code)&&(c.updateConnectionState(d.ParticipantConnectionState.Disconnected,t.id),v(l),l=null))):void 0}))):(v(l),void(l=null))}),4e3),l=setTimeout((()=>{l=null,a((e=>{var i;return e instanceof h.SceytCallException||e instanceof Error?(C.error(`[1202] [CallId: ${t.id}] SYNC OFFER failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}),void(("NotAllowed"===e.name||e instanceof h.SceytCallException&&4002===e.code)&&u.updateConnectionState(d.ParticipantConnectionState.Disconnected,t.id))):e.event===d.SignalEvent.ERROR?(C.error(`[1205] [CallId: ${t.id}] SYNC OFFER failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"}),void(4002===(null===(i=e.error)||void 0===i?void 0:i.code)&&u.updateConnectionState(d.ParticipantConnectionState.Disconnected,t.id))):void 0}))}),2e3)},f=()=>{var i;g||u&&c&&(c.mediaFlow===d.MediaFlow.SFU&&e.id===(null===(i=null==c?void 0:c.serverParticipant)||void 0===i?void 0:i.id)&&this.callParticipantsRTCMap[c.id]&&this.callParticipantsRTCMap[c.id][e.getFullId()]&&c.localParticipant.state===d.ParticipantState.Joined&&(C.info(`[1258] [CallId: ${t.id}] start renegotiation ${d.MediaFlow.SFU} sendOffer to participant ${u.getFullId()}`,{color:"blue"}),S("offer",!1)),c.mediaFlow===d.MediaFlow.S2W&&u.state===d.ParticipantState.Joined&&this.callParticipantsRTCMap[c.id]&&this.callParticipantsRTCMap[c.id][u.getFullId()]&&c.localParticipant.state===d.ParticipantState.Joined&&(C.info(`[1263] [CallId: ${t.id}] start renegotiation ${d.MediaFlow.SFU} sendConnect to participant ${u.getFullId()}`,{color:"blue"}),S("offer",!1)))};switch(o){case"new":break;case"connecting":t.mediaFlow===d.MediaFlow.SFU&&u.id===(null===(a=null==c?void 0:c.serverParticipant)||void 0===a?void 0:a.id)&&c.localParticipant.updateConnectionState(d.ParticipantConnectionState.Connecting,t.id)&&c.emitParticipantConnectionStateChanged(c.localParticipant,d.ParticipantConnectionState.Connecting),u.updateConnectionState(d.ParticipantConnectionState.Connecting,t.id)&&c.emitParticipantConnectionStateChanged(u,d.ParticipantConnectionState.Connecting);break;case"connected":if(t.mediaFlow===d.MediaFlow.SFU&&u.id===(null===(l=null==c?void 0:c.serverParticipant)||void 0===l?void 0:l.id)&&c.localParticipant.updateConnectionState(d.ParticipantConnectionState.Connected,t.id)&&c.emitParticipantConnectionStateChanged(c.localParticipant,d.ParticipantConnectionState.Connected),u.updateConnectionState(d.ParticipantConnectionState.Connected,t.id)&&c.emitParticipantConnectionStateChanged(u,d.ParticipantConnectionState.Connected),u&&c&&"Connected"===this.chatClient.connectionState&&(c.mediaFlow!==d.MediaFlow.SFU||c.mediaFlow===d.MediaFlow.SFU&&u.id===(null==c?void 0:c.id))){const e=e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[1098] [CallId: ${c.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[1102] [CallId: ${c.id}] SYNC MEDIA_CONNECTED signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})};this.signalingClient.sendSignalMessage(Object.assign({mediaFlow:c.mediaFlow,callId:c.id,sessionId:c.sessionId,event:d.SignalEvent.MEDIA_CONNECTED},c.mediaFlow!==d.MediaFlow.SFU?{to:c.id}:{}),e)}break;case"disconnected":t.mediaFlow===d.MediaFlow.SFU&&u.id===(null===(s=null==c?void 0:c.serverParticipant)||void 0===s?void 0:s.id)&&c.localParticipant.updateConnectionState(d.ParticipantConnectionState.Reconnecting,t.id)&&c.emitParticipantConnectionStateChanged(c.localParticipant,d.ParticipantConnectionState.Reconnecting),u.updateConnectionState(d.ParticipantConnectionState.Reconnecting,t.id)&&c.emitParticipantConnectionStateChanged(u,d.ParticipantConnectionState.Reconnecting),t.mediaFlow!==d.MediaFlow.S2W&&f();break;case"failed":u&&c&&(c.mediaFlow===d.MediaFlow.P2P&&u.state===d.ParticipantState.Joined&&this.callParticipantsRTCMap[c.id]&&this.callParticipantsRTCMap[c.id][u.getFullId()]&&c.localParticipant.state===d.ParticipantState.Joined?(C.info(`[1268] [CallId: ${t.id}] start renegotiation ${c.mediaFlow} sendOffer to participant ${u.getFullId()}`,{color:"blue"}),S("offer",!0)):f());break;case"closed":t.mediaFlow===d.MediaFlow.SFU&&u.id===(null===(r=null==c?void 0:c.serverParticipant)||void 0===r?void 0:r.id)&&c.localParticipant.updateConnectionState(d.ParticipantConnectionState.Idle,t.id)&&c.emitParticipantConnectionStateChanged(c.localParticipant,d.ParticipantConnectionState.Idle),u.updateConnectionState(d.ParticipantConnectionState.Idle,t.id)&&c.emitParticipantConnectionStateChanged(u,d.ParticipantConnectionState.Idle)}}}onIceCandidateErrorListener(e,t){return i=>{C.error(`[1284] [CallId: ${t.id}] ICE candidate error participantID: ${e.getFullId()}, error - code: ${i.errorCode}, message: ${i.errorText}, url: ${i.url}`,{color:"red"})}}onTrackListener(e,t){return i=>{this.onTrack(t,e,i)}}closePeerConnections(e,t){if(!this.callParticipantsRTCMap[e])return;const i=this.callParticipantsRTCMap[e][t];i?(i.listeners?(Object.keys(i.listeners).forEach((e=>{i.removeEventListener(e,i.listeners[e])})),C.info(`[1313] [CallId: ${e}] Removed all listeners for WebRTCClient of participant ${t}`,{color:"cyan"})):C.info(`[1316] [CallId: ${e}] No listeners found for WebRTCClient of participant ${t}`,{color:"cyan"}),i.close(),i.peerConnection.onicecandidate=null,i.peerConnection.ontrack=null,i.peerConnection.onconnectionstatechange=null,i.peerConnection.oniceconnectionstatechange=null,i.peerConnection.onsignalingstatechange=null,this.callParticipantsRTCMap[e][t]=null,delete this.callParticipantsRTCMap[e][t]):C.info(`[1375] [CallId: ${e}] No WebRTCClient found for participant ${t}`,{color:"cyan"})}addParticipantToRTCMap(e,t){this.callParticipantsRTCMap.hasOwnProperty(e.id)||(this.callParticipantsRTCMap[e.id]={});const i=new r.WebRTCClient(e.id,this.rtcConfig);this.callParticipantsRTCMap[e.id][t.getFullId()]=i;const n=this.onIceCandidateListener(t,e),a=this.onSignalingStateChangeListener(t,e),l=this.onIceConnectionStateChangeListener(t,e),s=this.onConnectionStateChangeListener(t,e),o=this.onTrackListener(t,e),d=this.onIceCandidateErrorListener(t,e);return i.addEventListener("icecandidate",n),i.addEventListener("signalingstatechange",a),i.addEventListener("connectionstatechange",s),i.addEventListener("track",o),i.addEventListener("icecandidateerror",d),i.addEventListener("iceconnectionstatechange",l),i.setListeners({iceCandidateListener:n,signalingStateChangeListener:a,connectionStateChangeListener:s,trackListener:o,iceCandidateErrorListener:d,iceConnectionStateChangeListener:l}),C.info(`[1371] [CallId: ${e.id}] Added Event Listeners to RTC Map: participantID: ${t.getFullId()}`,{color:"blue"}),e.activeSpeakerManager.addParticipant(t),t}joinToCall(e,t){return this.signalingClient.sendSignalMessage(Object.assign(Object.assign(Object.assign(Object.assign({mediaFlow:e.mediaFlow,callId:e.callId},e.sessionId&&{sessionId:e.sessionId}),{event:d.SignalEvent.JOIN,participants:e.participants}),(null==e?void 0:e.metadata)&&{metadata:e.metadata}),{joinOptions:e.joinOptions}),t)}sendRinging(e,t){return this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,sessionId:e.sessionId,event:d.SignalEvent.RINGING},(i=>i instanceof h.SceytCallException||i instanceof Error?(C.error(`[1389] [CallId: ${e.id}] SYNC RINGING failed message: ${i.message} code: ${i instanceof h.SceytCallException?i.code:""}`,{color:"red"}),void(null==t||t({error:(0,S.toCallException)(i)}))):i.event===d.SignalEvent.ERROR?(C.error(`[1393] [CallId: ${e.id}] SYNC RINGING failed message: ${i.error?`${i.error.message} code: ${i.error.code}`:""}`,{color:"red"}),void(null==t||t({error:(0,S.toCallException)(new Error("Failed to send ringing signal"))}))):(e.localParticipant.updateState(d.ParticipantState.Ringing,e.id),void e.emitParticipantStateChanged(e.localParticipant,d.ParticipantState.Ringing)))),{success:!0}}rejectCall(e,t,i){try{const n=this.activeCalls.find((t=>t.id===e.id));n&&(n.setState(d.CallState.Idle,"rejectCall"),n.localParticipant.updateState(d.ParticipantState.Declined,e.id)&&n.emitParticipantStateChanged(n.localParticipant,d.ParticipantState.Declined),n.localParticipant.updateConnectionState(d.ParticipantConnectionState.Idle,e.id)&&n.emitParticipantConnectionStateChanged(n.localParticipant,d.ParticipantConnectionState.Idle),this.closeTracksAndPeerConnections(n));const a=t=>t instanceof h.SceytCallException||t instanceof Error?(C.error(`[1420] [CallId: ${e.id}] SYNC DECLINE failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`,{color:"red"}),void(null==i||i({error:(0,S.toCallException)(t)}))):t.event===d.SignalEvent.ERROR?(C.error(`[1424] [CallId: ${e.id}] SYNC DECLINE failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`,{color:"red"}),void(null==i||i({error:(0,S.toCallException)(t.error||new Error("Failed to send decline signal"))}))):void 0;return this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,sessionId:e.sessionId,event:d.SignalEvent.DECLINE,metadata:Object.assign(Object.assign({},e.metadata),{reason:t||""})},a),{success:!0}}catch(t){return C.error(`[1432] [CallId: ${e.id}] Failed to reject call: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"}),{success:!1,error:(0,S.toCallException)(t)}}}closeTracksAndPeerConnections(e){e.localAudioTracks.forEach((e=>{e.stop()})),e.localVideoTracks.forEach((e=>{e.stop()})),e.participants.forEach((t=>{t.videoTracks.forEach((e=>{e.stop()})),t.audioTracks.forEach((e=>{e.stop()})),this.closePeerConnections(e.id,t.getFullId()),e.activeSpeakerManager.removeParticipant(t)})),e.localParticipant.videoTracks.forEach((e=>{e.stop()})),e.localParticipant.audioTracks.forEach((e=>{e.stop()})),e.mediaFlow===d.MediaFlow.SFU&&e.serverParticipant&&(e.serverParticipant.videoTracks.forEach((e=>{e.stop()})),e.serverParticipant.audioTracks.forEach((e=>{e.stop()})),this.closePeerConnections(e.id,e.serverParticipant.getFullId()))}closeCall(e){e.setState(d.CallState.Closed,"closeCall"),this.closeTracksAndPeerConnections(e);const t=this.activeCalls.findIndex((t=>t.id===e.id));this.activeCalls.splice(t,1),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls),delete this.callParticipantsRTCMap[e.id],C.info(`[1474] [CallId: ${e.id}] closed call and removed from active calls: callId: ${e.id}`,{color:"light-green"})}leaveCall(e,t=!0,i){const n=this.activeCalls.find((t=>t.id===e.id));if(n){this.signalingClient.cancelJoinIfPossible(e.id);const a=n.setState(d.CallState.Idle,`leaveCall: ${i}`);if(t&&a){const t=t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[1487] [CallId: ${e.id}] SYNC LEAVE failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`,{color:"red"}):t.event!==d.SignalEvent.ERROR||C.error(`[1491] [CallId: ${e.id}] SYNC LEAVE failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`,{color:"red"})};this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,sessionId:e.sessionId,event:d.SignalEvent.LEAVE},t)}this.closeTracksAndPeerConnections(n),delete this.callParticipantsRTCMap[n.id],n.localParticipant.updateState(d.ParticipantState.Left,e.id)&&n.emitParticipantStateChanged(n.localParticipant,d.ParticipantState.Left),n.localParticipant.setScreenSharing(!1,n),n.localParticipant.connectionState!==d.ParticipantConnectionState.Idle&&n.localParticipant.updateConnectionState(d.ParticipantConnectionState.Idle,e.id),n.participants.forEach((t=>{t.connectionState!==d.ParticipantConnectionState.Idle&&(t.updateConnectionState(d.ParticipantConnectionState.Idle,e.id),n.emitParticipantConnectionStateChanged(t,d.ParticipantConnectionState.Idle))})),e.sessionId||(this.activeCalls=this.activeCalls.filter((e=>e.id!=n.id))),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls)}}setRemoteDescription(e,t,i){var n;const a=null===(n=this.callParticipantsRTCMap[e])||void 0===n?void 0:n[t];return a?a.setRemoteDescription(i):(C.error(`[setRemoteDescription] [CallId: ${e}] No WebRTCClient found for participant ${t}`,{color:"red"}),Promise.reject(new Error(`No WebRTCClient found for participant ${t} in call ${e}`)))}changeVideoTracks(e,t,i,a){var l;return n(this,void 0,void 0,(function*(){if(C.info(`[1594] [CallId: ${e.id}], mediaFlow: ${e.mediaFlow}, changeVideoTracks ${i}, serverParticipant: ${(null===(l=e.serverParticipant)||void 0===l?void 0:l.id)||"null"}`,{color:"cyan"}),e.mediaFlow!==d.MediaFlow.SFU)for(let n=0;n<e.participants.length;n++){const l=e.participants[n];(l.id!==this.user.id||l.clientId!==this.clientId)&&l.clientId&&this.callParticipantsRTCMap[e.id]&&this.callParticipantsRTCMap[e.id][l.getFullId()]&&(yield this.callParticipantsRTCMap[e.id][l.getFullId()].enableVideoOnPeerConnection(i,t,!!a))}else this.callParticipantsRTCMap[e.id]&&this.callParticipantsRTCMap[e.id][e.id]&&(yield this.callParticipantsRTCMap[e.id][e.id].enableVideoOnPeerConnection(i,t,!!a))}))}changeAudioTracks(e,t,i){return n(this,void 0,void 0,(function*(){e.mediaFlow!==d.MediaFlow.SFU?e.participants.forEach((n=>{(n.id!==this.user.id||n.clientId!==this.clientId)&&this.callParticipantsRTCMap[e.id]&&this.callParticipantsRTCMap[e.id][n.getFullId()]&&(C.info(`[1561] [CallId: ${e.id}] Enabling audio on peer connection: ${n.getFullId()}`,{color:"cyan"}),this.callParticipantsRTCMap[e.id][n.getFullId()].enableAudioOnPeerConnection(i,t))})):(C.info(`[1565] [CallId: ${e.id}] Enabling audio on peer connection: ${e.id}`,{color:"cyan"}),yield this.callParticipantsRTCMap[e.id][e.id].enableAudioOnPeerConnection(i,t))}))}sendVideoEnabled(e,t,i){if(this.activeCalls.find((t=>t.id===e.id)))try{const n=t=>t instanceof h.SceytCallException||t instanceof Error?(C.error(`[1632] [CallId: ${e.id}] SYNC VIDEO_ON failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`),void(null==i||i({error:(0,S.toCallException)(t)}))):t.event===d.SignalEvent.ERROR?(C.error(`[1636] [CallId: ${e.id}] SYNC VIDEO_ON failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`),void(null==i||i({error:(0,S.toCallException)(t.error||t)}))):void 0;this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,event:t?d.SignalEvent.VIDEO_ON:d.SignalEvent.VIDEO_OFF,sessionId:e.sessionId},n)}catch(t){return C.error(`[1645] [CallId: ${e.id}] Failed to send video enabled signal: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"}),null==i||i({error:(0,S.toCallException)(t)}),!1}}sendScreenShare(e,t,i){return n(this,void 0,void 0,(function*(){const n=this.activeCalls.find((t=>t.id===e.id));try{if(n)return this.sendSignalScreenShare(e,t,i)}catch(t){return C.error(`[1668] [CallId: ${e.id}] Failed to send screen share signal: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"}),null==i||i({error:(0,S.toCallException)(t)}),!1}}))}sendAudioEnable(e,t,i){return n(this,void 0,void 0,(function*(){if(this.activeCalls.find((t=>t.id===e.id))){const a=a=>n(this,void 0,void 0,(function*(){try{if(a instanceof h.SceytCallException||a instanceof Error)return C.error(`[1704] [CallId: ${e.id}] SYNC HOLD failed message: ${a.message} code: ${a instanceof h.SceytCallException?a.code:""}`),void(null==i||i({error:(0,S.toCallException)(a)}));if(a.event===d.SignalEvent.ERROR)return C.error(`[1708] [CallId: ${e.id}] SYNC HOLD failed message: ${a.error?`${a.error.message} code: ${a.error.code}`:""}`),void(null==i||i({error:(0,S.toCallException)(a.error)}));if(e.mediaFlow!==d.MediaFlow.SFU)for(let i=0;i<e.participants.length;i++){const n=e.participants[i];(n.id!==this.user.id||n.clientId!==this.clientId)&&n.clientId&&this.callParticipantsRTCMap[e.id]&&this.callParticipantsRTCMap[e.id][n.getFullId()]&&(C.info(`[1712] [CallId: ${e.id}] Enabling audio on peer connection: ${n.getFullId()}`,{color:"cyan"}),yield this.callParticipantsRTCMap[e.id][n.getFullId()].enableAudioOnPeerConnection(t))}else this.callParticipantsRTCMap&&this.callParticipantsRTCMap[e.id]&&this.callParticipantsRTCMap[e.id][e.serverParticipant.getFullId()]&&(C.info(`[1712] [CallId: ${e.id}] Enabling audio on peer connection: ${e.serverParticipant.getFullId()}`,{color:"cyan"}),yield this.callParticipantsRTCMap[e.id][e.serverParticipant.getFullId()].enableAudioOnPeerConnection(t));e.localParticipant.audioTracks.forEach((e=>{e.enabled=!t}))}catch(t){C.error(`[1725] [CallId: ${e.id}] Failed to enable audio on peer connection: ${t instanceof Error?t.message:JSON.stringify(t)}`),null==i||i({error:(0,S.toCallException)(t)})}}));return this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,event:t?d.SignalEvent.MUTE:d.SignalEvent.UNMUTE,sessionId:e.sessionId},a)}}))}sendHold(e,t,i){if(this.activeCalls.find((t=>t.id===e.id))){const i=t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[1741] [CallId: ${e.id}] SYNC HOLD failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`):t.event!==d.SignalEvent.ERROR||C.error(`[1745] [CallId: ${e.id}] SYNC HOLD failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`)};return this.signalingClient.sendSignalMessage({mediaFlow:e.mediaFlow,callId:e.id,event:t?d.SignalEvent.HOLD:d.SignalEvent.UNHOLD,sessionId:e.sessionId},i)}}addTracksToPeerConnection(e,t,i=!0){var a,l;return n(this,void 0,void 0,(function*(){let n=e.localVideoTracks;const s=e.localAudioTracks,r=this.callParticipantsRTCMap[e.id][t];try{i?yield r.addTransceiverToPeerConnection(s[0],e.mediaFlow):yield r.setStreamsToTransceiver(s[0])}catch(t){C.warn(`[1766] [CallId: ${e.id}] Failed to add track to peer connection: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"})}n&&n.length>0||(n=(0,u.getEmptyVideoTrack)());try{i?yield r.addTransceiverToPeerConnection(n[0],e.mediaFlow):yield r.setStreamsToTransceiver(n[0])}catch(t){C.warn(`[1775] [CallId: ${e.id}] Failed to add track to peer connection: message: ${t instanceof Error?t.message:JSON.stringify(t)}`,{color:"red"})}e.videoEnabled&&r.enableVideoOnPeerConnection(e.videoEnabled,null===(a=e.localVideoTracks)||void 0===a?void 0:a[0]),e.muted||r.enableAudioOnPeerConnection(e.muted,null===(l=e.localAudioTracks)||void 0===l?void 0:l[0])}))}switchCallToSfu(e,t){try{const i=i=>{if(i instanceof h.SceytCallException||i instanceof Error)return C.error(`[1785] [CallId: ${e.id}] SYNC SWITCH_MEDIA_FLOW signal sent failed message: ${i.message} code: ${i instanceof h.SceytCallException?i.code:""}`),void(null==t||t({error:(0,S.toCallException)(i)}));if(i.event===d.SignalEvent.ERROR)return C.error(`[1789] [CallId: ${e.id}] SYNC SWITCH_MEDIA_FLOW signal sent failed message: ${i.error?`${i.error.message} code: ${i.error.code}`:""}`),void(null==t||t({error:(0,S.toCallException)(i)}));const n=new s.Participant(e.id);return e.setServerParticipant(n),e.participants.forEach((t=>{t.id===this.user.id&&t.clientId===this.clientId||t.updateConnectionState(d.ParticipantConnectionState.Idle,e.id),t.setShouldResetPeerConnection(!0)})),e.changeMediaFlow(d.MediaFlow.SFU),C.info(`[1818] [CallId: ${e.id}] Sending offer to server participant: ${n.getFullId()}`),this.sendOfferPeerToPeer(e,n,(t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[1805] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`):t.event!==d.SignalEvent.ERROR||C.error(`[1809] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`)})),!0};return this.signalingClient.sendSignalMessage({mediaFlow:d.MediaFlow.SFU,callId:e.id,event:d.SignalEvent.SWITCH_MEDIA_FLOW,sessionId:e.sessionId},i),C.info(`[1823] [CallId: ${e.id}] Switched call ${e.id} to SFU`,{color:"light-green"}),{success:!0}}catch(t){return C.error(`[1827] [CallId: ${e.id}] Failed to switch ${d.MediaFlow.SFU} message: ${t instanceof Error?t.message:JSON.stringify(t)}`),{success:!1,error:(0,S.toCallException)(t)}}}getCallById(e,t){return this.signalingClient.sendSignalMessage({callId:e,sessionId:t,event:d.SignalEvent.GET_CALL},(t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[1833] [CallId: ${e}] SYNC GET_CALL signal sent failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`):t.event!==d.SignalEvent.ERROR||C.error(`[1837] [CallId: ${e}] SYNC GET_CALL signal sent failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`)}),e)}getCalls(){return this.signalingClient.sendSignalMessage({callId:"",event:d.SignalEvent.GET_CALL},(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[1849] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`):e.event!==d.SignalEvent.ERROR?this.syncActiveCalls(e):C.error("[1853] [CallId: GLOBAL_LOGS] SYNC GET_CALL signal sent failed message: "+(e.error?`${e.error.message} code: ${e.error.code}`:""))}),"get_call")}createParticipants(e){let t=null,i=!1;return{participants:null==e?void 0:e.map((e=>{const n=new s.Participant(e.id,e.clientId);return n.setMuted(!!(null==e?void 0:e.muted)),n.setParticipantVideoEnabled(!!(null==e?void 0:e.videoEnabled)),n.setScreenSharing(!!(null==e?void 0:e.screenSharing)),n.setHold(!!(null==e?void 0:e.onHold)),(null==e?void 0:e.connectionState)&&(null==e?void 0:e.connectionState)>d.ParticipantConnectionState.Connected&&(null==e?void 0:e.id)!==this.user.id&&(null==e?void 0:e.clientId)!==this.clientId&&(n.connectionState=(null==e?void 0:e.connectionState)||d.ParticipantConnectionState.Idle),n.state=(null==e?void 0:e.state)||0,i=(null==e?void 0:e.isCallSilenced)||!1,(null==n?void 0:n.id)===this.user.id&&(null==n?void 0:n.clientId)===this.clientId&&(t=n),n})),localParticipant:t,isCallSilenced:i}}findOrCreateCall(e,t){var i;let n=new s.Participant(this.user.id,this.clientId),a=[],l=!1;if(t){const e=this.createParticipants(t);a=e.participants,l=e.isCallSilenced,e.localParticipant&&(n=e.localParticipant)}else a=null!==(i=e.participants)&&void 0!==i?i:[];let r=this.activeCalls.find((t=>t.id===e.id));return r?this.applyOptionsToExistingCall(r,e,t,a):r=this.initializeNewCall(e,n,a,l),{call:r}}initializeNewCall(e,t,i,n){var a,l,s,r,o;const d=e.id||(0,g.v4)();C.info(`[1869] [CallId: ${d}] Creating new call`,{color:"cyan"});const p=(0,u.makeFirstById)([...i,t],this.user.id,this.clientId),h=new c.Call({id:d,sessionId:e.sessionId,mediaFlow:e.mediaFlow,localParticipant:t,participants:p,metadata:e.metadata,createdBy:e.createdBy,chatClient:this.chatClient,isCallSilenced:n});return e.metadata&&h.setVideoCall("true"===e.metadata.videoCall),e.settings&&h.setSettings(e.settings),h.localAudioTracks=e.localAudioTracks||[],h.localVideoTracks=e.localVideoTracks||[],h.localParticipant.setAudioTracks(e.localAudioTracks||[],h),h.localParticipant.setVideoTracks(e.localVideoTracks||[],h),null!=(null===(a=e.audioSettings)||void 0===a?void 0:a.preferredAudioRoute)&&h.setAudioDeviceId(e.audioSettings.preferredAudioRoute),h.localParticipant.setMuted(!(null===(l=e.audioSettings)||void 0===l?void 0:l.publishAudio),h),h.setVideoEnabled(!!(null===(s=e.videoSettings)||void 0===s?void 0:s.publishVideo)),h.localParticipantVideoEnable(!!(null===(r=e.videoSettings)||void 0===r?void 0:r.publishVideo),void 0,!1,!1),h.localParticipant.setParticipantVideoEnabled(!!(null===(o=e.videoSettings)||void 0===o?void 0:o.publishVideo),h),this.activeCalls.push(h),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls),h}applyOptionsToExistingCall(e,t,i,n){var a,l;if(C.info(`[1911] [CallId: ${e.id}] Using existing call`,{color:"cyan"}),void 0!==t.mediaFlow&&e.changeMediaFlow(t.mediaFlow),t.sessionId&&e.setSessionId(t.sessionId),t.createdBy&&e.setCreatedBy(t.createdBy),t.settings&&e.setSettings(t.settings),t.metadata&&(e.metadata=t.metadata,e.setVideoCall("true"===t.metadata.videoCall)),t.participants&&!i){const i=new Set(e.participants.map((e=>e.id))),n=t.participants.filter((({id:e})=>!i.has(e)&&e!==this.user.id)).map((({id:e})=>new s.Participant(e)));n.length>0&&(e.participants=(0,u.makeFirstById)([...e.participants,...n],this.user.id,this.clientId),e.emitParticipantsAdded(n))}else e.participants=n;e.participants.some((e=>e.id===this.user.id&&e.clientId===this.clientId))||e.localParticipant.id!==this.user.id||e.localParticipant.clientId!==this.clientId||(e.participants=(0,u.makeFirstById)([...e.participants,e.localParticipant],this.user.id,this.clientId),e.emitParticipantsAdded([e.localParticipant])),(null===(a=t.localAudioTracks)||void 0===a?void 0:a.length)&&(e.localAudioTracks=t.localAudioTracks,e.localParticipant.setAudioTracks(t.localAudioTracks,e)),(null===(l=t.localVideoTracks)||void 0===l?void 0:l.length)&&(e.localVideoTracks=t.localVideoTracks,e.localParticipant.setVideoTracks(t.localVideoTracks,e)),t.audioSettings&&(null!=t.audioSettings.preferredAudioRoute&&e.setAudioDeviceId(t.audioSettings.preferredAudioRoute),e.setMuted(!t.audioSettings.publishAudio),e.localParticipant.setMuted(!t.audioSettings.publishAudio,e)),t.videoSettings&&(e.setVideoEnabled(!!t.videoSettings.publishVideo),e.localParticipantVideoEnable(!!t.videoSettings.publishVideo,void 0,!1,!1),e.localParticipant.setParticipantVideoEnabled(!!t.videoSettings.publishVideo,e))}processJoinAcknowledgment(e,t,i){var n,a,l,s;if(t.event===d.SignalEvent.ERROR)throw C.error(`[1955] [CallId: ${e.id}] Join failed: message: ${null===(n=t.error)||void 0===n?void 0:n.message} code: ${null===(a=t.error)||void 0===a?void 0:a.code}`),this.leaveCall(e,!0,"processJoinAcknowledgment"),(0,S.checkCode)((null===(l=t.error)||void 0===l?void 0:l.code)||0,null===(s=t.error)||void 0===s?void 0:s.message);if(t.event===d.SignalEvent.SUCCESS)return e.eventsQueue.forEach((e=>{e()})),e.eventsQueue.clear(),this.configureRTCServers(e,t,i),e;throw C.warn(`[1969] [CallId: ${e.id}] Unexpected join event: ${t.event}`),(0,S.checkCode)(4e3,`Unexpected event type: ${t.event}`)}configureRTCServers(e,t,i){var n;(null===(n=t.turnServers)||void 0===n?void 0:n.length)&&this.setRTCConfig(Object.assign(Object.assign({},e.mediaFlow===d.MediaFlow.SFU?{}:{iceServers:t.turnServers.map((e=>({urls:[`${e.url}?transport=tcp`,`${e.url}?transport=udp`],credential:e.password,username:e.username})))}),{bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"})),this.processRemoteParticipants(e,(null==t?void 0:t.participants)||[]),this.reconcileParticipants(e,t.participants||[]),e.mediaFlow===d.MediaFlow.SFU?this.setupSFUConnection(e,i,t):e.participants.forEach((t=>{e.mediaFlow===d.MediaFlow.P2P&&t.getFullId()!=e.localParticipant.getFullId()&&t.state===d.ParticipantState.Joined&&this.isPolitePeer(t.getFullId(),e.localParticipant.getFullId())&&(C.info(`[2008] [CallId: ${e.id}] Sending offer to participant: ${t.getFullId()}`),this.sendOfferPeerToPeer(e,t,(t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[2005] [CallId: ${e.id}] SYNC OFFER failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`):t.event!==d.SignalEvent.ERROR||C.error(`[2010] [CallId: ${e.id}] SYNC OFFER failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`)})))}))}setupSFUConnection(e,t,i){const n=new s.Participant(e.id);C.info(`[2005] [CallId: ${e.id}] [serverParticipant.id:${n.getFullId()}] Adding server participant to RTC map`,{color:"cyan"});try{e.setServerParticipant(n);const a=n=>{n instanceof h.SceytCallException||n instanceof Error?C.error(`[2011] [CallId: ${e.id}] SYNC OFFER failed message: ${n.message} code: ${n instanceof h.SceytCallException?n.code:""}`):(n.event===d.SignalEvent.ERROR&&C.error(`[2015] [CallId: ${e.id}] SYNC OFFER failed message: ${n.error?`${n.error.message} code: ${n.error.code}`:""}`),n.event!==d.SignalEvent.ERROR&&(C.info(`[2019] [CallId: ${e.id}] offerAck: ${JSON.stringify(n)}`,{color:"cyan"}),e.participants.forEach((n=>{var a;if(n.id===this.user.id&&n.clientId===this.clientId||!(null===(a=null==i?void 0:i.participants)||void 0===a?void 0:a.find((e=>e.id===n.id&&e.clientId===n.clientId&&e.connectionState===d.ParticipantConnectionState.Connected))))n.connectionState&&n.connectionState>d.ParticipantConnectionState.Connected&&n.id!==this.user.id&&n.clientId!==this.clientId&&n.getFullId()!=e.localParticipant.getFullId()&&(n.updateConnectionState(n.connectionState,e.id),e.emitParticipantConnectionStateChanged(n,n.connectionState));else{const a=t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[2023] [CallId: ${e.id}] SYNC CONNECT failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`):t.event!==d.SignalEvent.ERROR||C.error(`[2028] [CallId: ${e.id}] SYNC CONNECT failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`)};this.signalingClient.clearParticipantSignals(e.id,n.getFullId()),this.signalingClient.sendSignalMessage({mediaFlow:t,callId:e.id,event:d.SignalEvent.CONNECT,sessionId:i.sessionId,to:n.getFullId(),metadata:e.metadata},a)}}))))};C.info(`[2067] [CallId: ${e.id}] Sending offer to server participant: ${n.getFullId()}`),this.sendOfferPeerToPeer(e,n,a)}catch(t){throw C.error(`[2049] [CallId: ${e.id}] SFU setup error: message: ${t instanceof Error?t.message:JSON.stringify(t)}`),(0,S.toCallException)(t)}}processRemoteParticipants(e,t){t.length&&(t.forEach((t=>{let i=e.participants.find((e=>e.getFullId()===this.getParticipantId(t)));if(i||(i=e.participants.find((e=>e.id===t.id&&(e.clientId===t.clientId||!e.clientId))),i&&!i.clientId&&(i.clientId=t.clientId)),i||e.localParticipant.getFullId()===this.getParticipantId(t))i&&e.localParticipant.getFullId()!==this.getParticipantId(t)&&(i.presenter=!!t.presenter,i.setParticipantVideoEnabled(!!t.hasOwnProperty("videoEnabled")&&!!t.videoEnabled,e),i.setMuted(!!t.hasOwnProperty("muted")&&!!t.muted,e),i.setHold(!!t.hasOwnProperty("onHold")&&!!t.onHold,e),i.setScreenSharing(!!t.hasOwnProperty("screenSharing")&&!!t.screenSharing,e),i.state!=t.state&&void 0!==t.state&&(i.updateState(t.state||d.ParticipantState.Idle,e.id),e.emitParticipantStateChanged(i,t.state,"FromJoin")));else{const i=new s.Participant(t.id,t.clientId);i.updateState(t.state||d.ParticipantState.Idle,e.id),i.setParticipantVideoEnabled(!!t.hasOwnProperty("videoEnabled")&&!!t.videoEnabled,e),i.setMuted(!!t.hasOwnProperty("muted")&&!!t.muted,e),i.setHold(!!t.hasOwnProperty("onHold")&&!!t.onHold,e),i.setScreenSharing(!!t.hasOwnProperty("screenSharing")&&!!t.screenSharing,e),e.addParticipantToList(i),e.emitParticipantsAdded([i])}})),C.info(`[2098] [CallId: ${e.id}] Processed participants - Added and Updated`,{color:"cyan"}))}reconcileParticipants(e,t){if(!(null==t?void 0:t.length))return;const i=e.participants.filter((i=>(i.id!==e.localParticipant.id||i.clientId!==e.localParticipant.clientId)&&!t.some((e=>!(e.id!==i.id||e.clientId!==i.clientId&&e.clientId&&i.clientId)))));i.length&&(e.participants=e.participants.filter((e=>!i.includes(e))),e.emitParticipantsRemoved(i))}processJoinCall(e,t,i){e.mediaFlow!==d.MediaFlow.SFU&&e.localParticipant.updateConnectionState(d.ParticipantConnectionState.Connected,e.id);const n=t.mediaFlow||d.MediaFlow.P2P;e.setSessionId(t.sessionId),e.changeMediaFlow(n),e.localParticipant.updateState(d.ParticipantState.Joined,e.id),e.setState(d.CallState.Connected,i)?(e.emitParticipantStateChanged(e.localParticipant,d.ParticipantState.Joined),e.emitParticipantConnectionStateChanged(e.localParticipant,d.ParticipantConnectionState.Connected),this.processJoinAcknowledgment(e,t,n)):this.leaveCall(e,!0,"processJoinCall")}startCall(e,t,i){const a=t.mediaFlow,s=e.participants.filter((e=>!(e.id===this.user.id&&e.clientId===this.clientId))).map((e=>e.serialize()));e.mediaFlow!==d.MediaFlow.SFU&&e.localParticipant.updateConnectionState(d.ParticipantConnectionState.Connecting,e.id);const r=(t,r)=>{var o,c,u,p;if(e.state==d.CallState.Idle)return t.forEach((e=>{e.stop()})),void(null==i||i({error:(0,S.checkCode)(5002,"Call was ended before media setup completed")}));r&&r.length>0&&(e.localParticipant.setVideoTracks(r,e),e.localVideoTracks=r,e.setVideoDeviceId(r[0].getSettings().deviceId||null)),e.localParticipant.setAudioTracks(t,e),e.localAudioTracks=t,this.joinToCall({mediaFlow:a,callId:e.id,sessionId:e.sessionId,participants:s,metadata:e.metadata,joinOptions:{muted:e.muted,videoEnabled:e.videoEnabled,settings:Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==(null===(o=e.settings)||void 0===o?void 0:o.broadcastSettings)&&{broadcastSettings:e.settings.broadcastSettings}),void 0!==(null===(c=e.settings)||void 0===c?void 0:c.startsAt)&&{startsAt:l.default.fromNumber(e.settings.startsAt)}),void 0!==(null===(u=e.settings)||void 0===u?void 0:u.expiresAt)&&{expiresAt:l.default.fromNumber(e.settings.expiresAt)}),void 0!==(null===(p=e.settings)||void 0===p?void 0:p.persistent)&&{persistent:e.settings.persistent})}},(t=>n(this,void 0,void 0,(function*(){var n;return t instanceof h.SceytCallException||t instanceof Error?(C.error(`[2137] [CallId: ${e.id}] SYNC JOIN failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`),e.setState(d.CallState.Closed,"joinCall failed"),void(null==i||i({error:(0,S.toCallException)(t)}))):t.event===d.SignalEvent.ERROR?(C.error(`[2141] [CallId: ${e.id}] SYNC JOIN failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`),void(null==i||i({error:(0,S.checkCode)(5003,(null===(n=t.error)||void 0===n?void 0:n.message)||"Unknown error")}))):void this.processJoinCall(e,t,"from joinCall")}))))};return e.localAudioTracks&&e.localAudioTracks.length>0||e.localVideoTracks&&e.localVideoTracks.length>0?!(e.localAudioTracks&&e.localAudioTracks.length>0)&&e.localVideoTracks&&e.localVideoTracks.length>0?this.setupMediaStream(e).then((({audioTracks:e})=>{r(e,t.localVideoTracks||[])})):!e.localAudioTracks||e.localVideoTracks&&e.localVideoTracks.length>0?r(e.localAudioTracks||[],e.localVideoTracks||[]):r(t.localAudioTracks||[]):this.setupMediaStream(e).then((({audioTracks:e})=>{r(e)})),e}promoteFromPrepared(e,t){var i;const n=this.prepareCalls.findIndex((t=>t.id===e));if(-1===n)return;const a=this.prepareCalls[n];return this.prepareCalls.splice(n,1),this.activeCalls.push(a),t&&(this.updateCallMetadata(a,t),(null===(i=t.participants)||void 0===i?void 0:i.length)&&this.syncParticipants(a,t.participants)),this.callEvents.onOngoingCallsUpdated&&this.callEvents.onOngoingCallsUpdated(this.activeCalls),a}prepareCall(e,t,i){var n,a,l;try{const r=e||(0,g.v4)();C.info(`[2155] [CallId: ${e}] prepareCall, creating call object`,{color:"blue"});const o=this.activeCalls.find((t=>t.id===e));if(o)return{success:!0,data:o};const u=this.prepareCalls.find((t=>t.id===e));if(u)return this.applyCreateOptions(u,t),this.applyServerCall(u,i),{success:!0,data:u};const p=null!==(a=null!==(n=null==i?void 0:i.mediaFlow)&&void 0!==n?n:null==t?void 0:t.mediaFlow)&&void 0!==a?a:0,h=new s.Participant(this.user.id,this.clientId),v=new c.Call({id:r,sessionId:null==i?void 0:i.sessionId,mediaFlow:null!=p?p:d.MediaFlow.P2P,localParticipant:h,participants:[h],createdBy:null!==(l=null==i?void 0:i.createdBy)&&void 0!==l?l:this.user.id,chatClient:this.chatClient,isCallSilenced:!1});return this.applyCreateOptions(v,t),this.applyServerCall(v,i),this.prepareCalls.push(v),{success:!0,data:v}}catch(t){return C.error(`[2158] [CallId: ${e}] prepareCall failed: ${t.message||JSON.stringify(t)}`,{color:"red"}),{success:!1,error:(0,S.toCallException)(t)}}}prepareCallFromCallID(e){return n(this,void 0,void 0,(function*(){return new Promise((t=>{this.signalingClient.sendSignalMessage({event:d.SignalEvent.GET_CALL,callId:e},(i=>{var n,a,l,s;if(i instanceof h.SceytCallException||i instanceof Error)return C.error(`[2160] prepareCallFromCallID GET_CALL failed: ${i.message}`,{color:"red"}),void t({success:!1,error:(0,S.toCallException)(i)});if(i.event===d.SignalEvent.ERROR)return C.error(`[2161] prepareCallFromCallID GET_CALL failed: ${null===(n=i.error)||void 0===n?void 0:n.message}`,{color:"red"}),void t({success:!1,error:(0,S.checkCode)((null===(a=i.error)||void 0===a?void 0:a.code)||5e3,(null===(l=i.error)||void 0===l?void 0:l.message)||"GET_CALL failed")});const r=null===(s=i.calls)||void 0===s?void 0:s.find((t=>t.id===e));if(!r)return void t({success:!1,error:h.SceytCallException.BadRequest(4004,`Call ${e} not found`)});const o=this.prepareCall(e,{mediaFlow:r.mediaFlow},r);o.success&&o.data&&this.updateCallMetadata(o.data,r),t(o)}),"get_call")}))}))}joinCall(e,t,i){let n=null;try{C.info(`[2159] [CallId: ${e.id}] joinCall, start call`,{color:"blue"});const a={id:e.id,sessionId:e.sessionId||void 0,mediaFlow:e.mediaFlow,participants:e.participants.filter((({id:e})=>e!==this.user.id)),metadata:e.metadata,createdBy:e.createdBy,localAudioTracks:t.localAudioTracks,localVideoTracks:t.localVideoTracks,audioSettings:t.audioSettings,videoSettings:t.videoSettings},l=e.setState(d.CallState.Connecting,"joinCall");let s=this.promoteFromPrepared(e.id);if(s)this.applyOptionsToExistingCall(s,a,s.participants,s.participants);else{const{call:e}=this.findOrCreateCall(a);s=e}return l?(s.localParticipant.clientId=this.clientId,n=this.startCall(s,a,i),{success:!0,data:s}):{success:!1,error:(0,S.checkCode)(5001,`Failed to set call state from ${s.state} to connecting`)}}catch(e){return C.error(`[2173] [CallId: ${null==n?void 0:n.id}] Join call failed: ${e.message||JSON.stringify(e)}`,{color:"red"}),{success:!1,error:(0,S.toCallException)(e)}}}createCall(e,t){var i;try{C.info(`[2180] [CallId: ${e.id}] createCall, creating call link`,{color:"blue"});const n=e.settings;if(void 0!==(null==n?void 0:n.startsAt)&&void 0!==(null==n?void 0:n.expiresAt)&&n.startsAt>=n.expiresAt)return{success:!1,error:h.SceytCallException.BadRequest(4001,"startsAt must be before expiresAt")};const a=[...new Set(e.participants.filter((e=>!(e.id===this.user.id&&e.clientId===this.clientId))).map((e=>e.id)))],s=null!==(i=this.prepareCalls.find((t=>t.id===e.id)))&&void 0!==i?i:e,r=e=>{var i,n,a;return e instanceof h.SceytCallException||e instanceof Error?(C.error(`[2210] [CallId: ${s.id}] CREATE signal failed: ${e.message}`,{color:"red"}),void(null==t||t({error:(0,S.toCallException)(e)}))):e.event===d.SignalEvent.ERROR?(C.error(`[2219] [CallId: ${s.id}] CREATE signal failed: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"}),void(null==t||t({error:(0,S.checkCode)((null===(i=e.error)||void 0===i?void 0:i.code)||5e3,(null===(n=e.error)||void 0===n?void 0:n.message)||"Create call failed")}))):(C.info(`[2228] [CallId: ${s.id}] Call link created successfully`,{color:"blue"}),e.sessionId&&(this.promoteFromPrepared(s.id),s.setSessionId(e.sessionId),s.setIsCreatedRemotely(!0)),void((null===(a=e.participants)||void 0===a?void 0:a.length)&&this.reconcileParticipants(s,e.participants)))};return this.signalingClient.sendSignalMessage(Object.assign(Object.assign({event:d.SignalEvent.CREATE,callId:s.id,mediaFlow:s.mediaFlow,participants:a.map((e=>({id:e,clientId:""})))},s.metadata&&{metadata:s.metadata}),{settings:Object.assign(Object.assign(Object.assign({},void 0!==(null==n?void 0:n.startsAt)&&{startsAt:l.default.fromNumber(n.startsAt)}),void 0!==(null==n?void 0:n.expiresAt)&&{expiresAt:l.default.fromNumber(n.expiresAt)}),void 0!==(null==n?void 0:n.persistent)&&{persistent:n.persistent})}),r),{success:!0,data:s}}catch(t){return C.error(`[2238] [CallId: ${e.id}] createCall failed: ${t.message||JSON.stringify(t)}`,{color:"red"}),{success:!1,error:(0,S.toCallException)(t)}}}signalMessageToICall(e){const t=e.settings?Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e.settings.startsAt&&{startsAt:l.default.isLong(e.settings.startsAt)?e.settings.startsAt.toNumber():e.settings.startsAt}),void 0!==e.settings.expiresAt&&{expiresAt:l.default.isLong(e.settings.expiresAt)?e.settings.expiresAt.toNumber():e.settings.expiresAt}),void 0!==e.settings.persistent&&{persistent:e.settings.persistent}),void 0!==e.settings.broadcastOptions&&{broadcastSettings:e.settings.broadcastOptions}):void 0;return{id:e.callId,sessionId:e.sessionId,mediaFlow:e.mediaFlow,createdBy:e.createdBy,metadata:e.metadata||{},participants:e.participants||[],createdAt:l.default.isLong(e.createdAt)?e.createdAt.toNumber():e.createdAt,settings:t}}applyCreateOptions(e,t){if(!t)return;const i=t.videoCall?Object.assign(Object.assign({},t.metadata),{videoCall:"true"}):t.metadata;if(i&&(e.metadata=i),t.videoCall&&e.setVideoCall(!0),t.settings&&e.setSettings(t.settings),t.participantIds){const i=[...new Set(t.participantIds.filter((e=>e!==this.user.id)))],n=new Set(e.participants.map((e=>e.id))),a=i.filter((e=>!n.has(e))).map((e=>new s.Participant(e)));a.length>0&&(e.participants=(0,u.makeFirstById)([...e.participants,...a],this.user.id,this.clientId))}}applyServerCall(e,t){var i,n;t&&(t.sessionId&&e.setSessionId(t.sessionId),void 0!==t.mediaFlow&&(e.mediaFlow=t.mediaFlow),t.metadata&&(null===(i=Object.values(t.metadata))||void 0===i?void 0:i.length)&&(e.metadata=t.metadata),t.createdBy&&(e.createdBy=t.createdBy),t.settings&&e.setSettings(Object.assign(Object.assign(Object.assign({},t.settings),void 0!==t.settings.startsAt&&{startsAt:l.default.isLong(t.settings.startsAt)?t.settings.startsAt.toNumber():t.settings.startsAt}),void 0!==t.settings.expiresAt&&{expiresAt:l.default.isLong(t.settings.expiresAt)?t.settings.expiresAt.toNumber():t.settings.expiresAt})),(null===(n=t.participants)||void 0===n?void 0:n.length)&&this.syncParticipants(e,t.participants))}updateCallMetadata(e,t){var i,n;t.metadata&&(null===(i=Object.values(t.metadata))||void 0===i?void 0:i.length)&&(e.metadata=t.metadata||{}),e.createdBy=t.createdBy,e.sessionId=t.sessionId,e.id=t.id,e.setVideoCall("true"===(null===(n=e.metadata)||void 0===n?void 0:n.videoCall)),e.mediaFlow!==d.MediaFlow.SFU&&t.mediaFlow===d.MediaFlow.SFU&&e.changeMediaFlow(d.MediaFlow.SFU),t.settings&&e.setSettings(t.settings),C.info(`[2187] [CallId: ${e.id}] Updated call metadata for call ${e.id}`,{color:"light-blue"})}syncParticipants(e,t){C.info(`[2198] [CallId: ${e.id}] Syncing participants for call ${e.id}`,{color:"light-blue"}),e.participants=e.participants.filter((i=>{const n=t.find((e=>!(e.id!==i.id||e.clientId!==i.clientId&&e.clientId&&i.clientId)));return n||(C.info(`[2202] [CallId: ${e.id}] Removing participant ${i.id} who is no longer in the call`,{color:"light-blue"}),e.emitParticipantStateChanged(i,d.ParticipantState.Left),e.kickParticipantFromList(i,!1)),!!n})),C.info(`[2216] [CallId: ${e.id}] Syncing participants for call ${e.id}`,{color:"light-blue"});for(const i of t){const t=e.participants.find((e=>!(e.id!==i.id||e.clientId!==i.clientId&&i.clientId&&e.clientId)));if(C.info(`[2219] [CallId: ${e.id}] Syncing participants for call ${e.id}`,{color:"light-blue"}),t){if(t.clientId||(t.clientId=i.clientId),t.id===e.localParticipant.id&&t.clientId===e.localParticipant.clientId){i.state===d.ParticipantState.Joined&&e.localParticipant.state>d.ParticipantState.Joined&&this.leaveCall(e,!0,"syncParticipants");continue}t.state=i.state||d.ParticipantState.Idle,e.emitParticipantStateChanged(t,i.state||d.ParticipantState.Idle),t.state!==d.ParticipantState.Joined?t.getFullId()!==e.localParticipant.getFullId()&&(this.closePeerConnections(e.id,t.getFullId()),e.activeSpeakerManager.removeParticipant(t)):t.id!==e.localParticipant.id&&t.clientId!==e.localParticipant.clientId&&e.state===d.CallState.Connected&&this.handleNewParticipant(e,t),t.getFullId()===e.localParticipant.getFullId()&&(e.localParticipant=t),this.syncParticipantMediaState(e,t,i),C.info(`[2254] [CallId: ${e.id}] Syncing existing participants: ${t.getFullId()} for call ${e.id}`,{color:"light-blue"})}else{const t=new s.Participant(i.id,i.clientId);t.state=i.state||d.ParticipantState.Idle,e.addParticipantToList(t),this.syncParticipantMediaState(e,t,i),C.info(`[2263] [CallId: ${e.id}] Syncing no existing participants: ${t.getFullId()} for call ${e.id}`,{color:"light-blue"}),e.emitParticipantsAdded([t]),(e.mediaFlow!==d.MediaFlow.SFU&&i.state===d.ParticipantState.Joined||e.mediaFlow===d.MediaFlow.SFU&&i.connectionState===d.ParticipantConnectionState.Connected&&e.state===d.CallState.Connected)&&this.handleNewParticipant(e,t)}}}syncParticipantMediaState(e,t,i){if(t.getFullId()===i.id+(i.clientId?"/"+i.clientId:"")){const n=!!i.hasOwnProperty("muted")&&!!i.muted,a=!!i.hasOwnProperty("screenSharing")&&!!i.screenSharing,l=!!i.hasOwnProperty("videoEnabled")&&!!i.videoEnabled,s=!!i.hasOwnProperty("onHold")&&!!i.onHold,r=!!i.hasOwnProperty("isCallSilenced")&&!!i.isCallSilenced;n!==t.muted&&(C.info(`[2287] [CallId: ${e.id}] Participant ${t.getFullId()} audio state changed: ${t.muted} -> ${n}`,{color:"light-blue"}),t.setMuted(n,e)),l===t.videoEnabled||a||(C.info(`[2296] [CallId: ${e.id}] Participant ${t.getFullId()} video state changed: ${t.videoEnabled} -> ${l}`,{color:"light-blue"}),t.setParticipantVideoEnabled(l,e)),a!==t.screenSharing&&(C.info(`[2307] [CallId: ${e.id}] Participant ${t.getFullId()} screen sharing state changed: ${t.screenSharing} -> ${a}`,{color:"light-blue"}),t.setScreenSharing(a,e)),s!==t.onHold&&(C.info(`[2317] [CallId: ${e.id}] Participant ${t.getFullId()} hold state changed: ${t.onHold} -> ${s}`,{color:"light-blue"}),t.setHold(s,e)),t.getFullId()===e.localParticipant.getFullId()&&(C.info(`[2327] [CallId: ${e.id}] Participant ${t.getFullId()} ring allowed state changed: ${r}`,{color:"light-blue"}),e.setIsCallSilenced(r))}}handleNewParticipant(e,t){if(C.info(`[2333] [CallId: ${e.id}] Call media flow: ${e.mediaFlow}`,{color:"light-blue"}),e.mediaFlow!==d.MediaFlow.SFU){if(t.updateState(d.ParticipantState.Joined,e.id),e.emitParticipantStateChanged(t,d.ParticipantState.Joined),t.getFullId()!==e.localParticipant.getFullId()&&t.connectionState!==d.ParticipantConnectionState.Connected&&t.connectionState!==d.ParticipantConnectionState.Reconnecting){const i=t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[2341] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`,{color:"red"}):t.event!==d.SignalEvent.ERROR||C.error(`[2345] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`,{color:"red"})};C.info(`[2370] [CallId: ${e.id}] Sending offer to participant: ${t.getFullId()}`),e.localParticipant.state===d.ParticipantState.Joined&&e.mediaFlow===d.MediaFlow.P2P&&this.isPolitePeer(t.getFullId(),e.localParticipant.getFullId())?this.sendOfferPeerToPeer(e,t,i):e.localParticipant.state===d.ParticipantState.Joined&&(this.signalingClient.clearParticipantSignals(e.id,t.getFullId()),this.signalingClient.sendSignalMessage({to:t.getFullId(),mediaFlow:e.mediaFlow,callId:e.id,event:d.SignalEvent.CONNECT,sessionId:e.sessionId},i))}}else if(t.getFullId()!==e.localParticipant.getFullId()&&t.connectionState!==d.ParticipantConnectionState.Reconnecting){const i=t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[2354] [CallId: ${e.id}] SYNC CONNECT signal sent failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`,{color:"red"}):t.event!==d.SignalEvent.ERROR||C.error(`[2358] [CallId: ${e.id}] SYNC CONNECT signal sent failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`,{color:"red"})};this.signalingClient.clearParticipantSignals(e.id,t.getFullId()),this.signalingClient.sendSignalMessage({to:t.getFullId(),mediaFlow:e.mediaFlow,callId:e.id,event:d.SignalEvent.CONNECT,sessionId:e.sessionId},i)}}handleSessionRenewedSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(!t)return void C.warn(`[SessionRenewed] [CallId: ${e.callId}] No active call found`,{color:"red"});const i=e.sessionId;C.info(`[SessionRenewed] [CallId: ${t.id}] Session renewed: ${t.sessionId} -> ${i}`,{color:"cyan"}),t.setSessionId(i),t.emitSessionRenewed(i)}handleConnectSignal(e){const t=this.activeCalls.find((t=>t.id===e.callId));if(t){let i=t.participants.find((t=>t.getFullId()===e.from));i&&this.sendOfferPeerToPeer(t,i,(e=>{e instanceof h.SceytCallException||e instanceof Error?C.error(`[2417] [CallId: ${t.id}] SYNC OFFER signal sent failed message: ${e.message} code: ${e instanceof h.SceytCallException?e.code:""}`,{color:"red"}):e.event!==d.SignalEvent.ERROR||C.error(`[2421] [CallId: ${t.id}] SYNC OFFER signal sent failed message: ${e.error?`${e.error.message} code: ${e.error.code}`:""}`,{color:"red"})}))}}handleMediaFlowSwitch(e){C.info(`[2375] [CallId: ${e.id}] Switching call ${e.id} from P2P to SFU`,{color:"light-blue"});const t=new s.Participant(e.id);e.setServerParticipant(t),C.info(`[2395] [CallId: ${e.id}] Sending offer to server participant: ${t.getFullId()}`),this.sendOfferPeerToPeer(e,t,(t=>{t instanceof h.SceytCallException||t instanceof Error?C.error(`[2386] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.message} code: ${t instanceof h.SceytCallException?t.code:""}`,{color:"red"}):t.event!==d.SignalEvent.ERROR||C.error(`[2390] [CallId: ${e.id}] SYNC OFFER signal sent failed message: ${t.error?`${t.error.message} code: ${t.error.code}`:""}`,{color:"red"})})),e.participants.forEach((e=>{e.setShouldResetPeerConnection(!0)}))}}t.InternalCallHandler=f},787:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Participant=void 0;const n=i(578),a=i(758),l=i(645),s=(0,l.createLogger)("ParticipantState"),r=(0,l.createLogger)("ConnectionState");t.Participant=class{constructor(e,t){this.clientId="",this.muted=!1,this.onHold=!1,this.videoEnabled=!1,this.screenSharing=!1,this.presenter=!1,this.audioTracks=[],this.videoTracks=[],this.shouldResetPeerConnection=!1,this.state=n.ParticipantState.Idle,this.connectionState=n.ParticipantConnectionState.Idle;const i=e.split("/");this.id=i[0],this.clientId=t||i[1]||""}updateState(e,t){const i=new a.ParticipantStateMachine(this.id,t).updateState(e,this.state);return i&&(this.state=e,s.info(`[35] [CallId: ${t}] Updating state: ${e}, participantID: ${this.getFullId()}`,{color:"blue"})),i}updateConnectionState(e,t){const i=new a.ParticipantStateMachine(this.id,t).updateConnectionState(e,this.connectionState);return i&&(this.connectionState=e,r.info(`[45] [CallId: ${t}] Updating connection state: ${e}, participantID: ${this.getFullId()}`,{color:"blue"})),i}setShouldResetPeerConnection(e){this.shouldResetPeerConnection=e}setMuted(e,t){this.audioTracks.forEach((t=>{t.enabled=!e})),this.muted=e,t&&t.emitParticipantEvent(this,this.muted?"Mute":"Unmute")}setParticipantVideoEnabled(e,t){this.videoTracks.forEach((t=>{t.enabled=e})),this.videoEnabled=e,t&&t.emitParticipantEvent(this,this.videoEnabled?"VideoEnabled":"VideoDisabled")}setScreenSharing(e,t){this.videoTracks.forEach((t=>{t.enabled=e})),this.screenSharing=e,t&&t.emitParticipantEvent(this,this.screenSharing?"ScreenSharingStarted":"ScreenSharingStopped")}setPresenter(e){this.presenter=e}setAudioTracks(e,t){this.audioTracks=e,this.audioTracks.forEach((e=>{e.enabled=!this.muted})),t.emitAudioTrackAdded(this,e[0])}setVideoTracks(e,t){this.videoTracks=e,this.videoTracks.forEach((e=>{e.enabled=this.videoEnabled})),t.emitVideoTrackAdded(this,e[0])}setHold(e,t){this.onHold=e,t&&t.emitParticipantEvent(this,this.onHold?"Hold":"Unhold")}serialize(){return{id:this.id,clientId:this.clientId}}getFullId(){return this.id+(this.clientId?"/"+this.clientId:"")}}},816:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.QueryBuilder=void 0,t.QueryBuilder=class{constructor(){this.count=10}}},185:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RecentCallQueryBuilder=void 0;const n=i(578),a=i(650),l=i(816),s=i(343),r=i(228);class o extends l.QueryBuilder{constructor(){super(...arguments),this.order=n.CDRRequestOrder.ASC,this.count=10,this.participantCount=10,this.event=n.CDRRequestEvent.GET_RECENT_CALLS,this.direction=n.CDRRequestDirection.NEXT,this.setSessionIdList=e=>(this.sessionIdList=e,this),this.setEvent=e=>(this.event=e,this),this.setSessionId=e=>(this.sessionId=e,this),this.limit=e=>(this.count=e,this),this.setParticipantCount=e=>(this.participantCount=e,this),this.setOrder=e=>(this.order=e,this),this.setDirection=e=>(this.direction=e,this),this.build=()=>{const e=a.InternalCallHandler.getInstance();this.chatClient=e.chatClient;try{return new s.RecentCallQuery(this)}catch(e){throw(0,r.toCallException)(e)}}}}t.RecentCallQueryBuilder=o},343:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.RecentCallQuery=void 0;const a=i(578),l=i(645),s=i(228),r=(0,l.createLogger)("RecentCallQuery");t.RecentCallQuery=class{constructor(e){this.count=10,this.hasNext=!0,this.loading=!1,this.order=a.CDRRequestOrder.ASC,this.participantCount=10,this.event=a.CDRRequestEvent.GET_RECENT_CALLS,this.direction=a.CDRRequestDirection.NEXT,this.loadNextPage=()=>n(this,void 0,void 0,(function*(){if(this.loading)throw r.info("QUERY_IN_PROGRESS"),(0,s.checkCode)(5001,"QUERY_IN_PROGRESS");if(this.hasNext){this.loading=!0;const e=yield this.chatClient.sendCallDetailsRecord(Object.assign({event:this.event,order:this.order,limit:this.count,participantCount:this.participantCount,direction:this.direction},this.nextToken||this.sessionId?{position:Object.assign(Object.assign({},this.sessionId?{sessionId:this.sessionId}:{}),this.nextToken?{nextToken:this.nextToken}:{})}:{}));this.loading=!1;const{getRecentCallsResponse:{records:t,nextToken:i}}=e;return this.hasNext=!!i,this.nextToken=i,{records:t,hasNext:this.hasNext}}return{records:[],hasNext:this.hasNext}})),this.deleteCalls=()=>n(this,void 0,void 0,(function*(){var e;if(null===(e=this.sessionIdList)||void 0===e?void 0:e.length)return yield this.chatClient.sendCallDetailsRecord({event:a.CDRRequestEvent.DELETE_RECENT_CALLS,sessionIdList:{items:this.sessionIdList}})})),this.order=e.order,this.count=e.count,this.participantCount=e.participantCount,this.sessionId=e.sessionId,this.event=e.event,this.direction=e.direction,this.chatClient=e.chatClient,this.sessionIdList=e.sessionIdList}set limit(e){this.count=e}get limit(){return this.count}}},680:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSessionDescription=t.toSessionData=void 0;const n=i(578),a=i(645),l=i(19),s=(0,a.createLogger)("SignalingExtensions");t.toSessionData=function(e,t){const i=e.sdp.sdp||"",a=1e3*Date.now()+performance.now()%1*1e3;s.info(`[32] [CALL_TIME_TO_SESSION_DATA_START: ${a}]`,{color:"blue"});const r=l.SdpConverter.parseToSdpData(i,l.CODEC_NAME_TO_VIDEO_CODEC,t===n.MediaFlow.S2W?l.CODEC_NAME_TO_AUDIO_CODEC_S2W:l.CODEC_NAME_TO_AUDIO_CODEC),o=1e3*Date.now()+performance.now()%1*1e3;return s.info(`[35] [CALL_TIME_TO_SESSION_DATA_END: ${o}]`,{color:"blue"}),{id:e.sessionId,version:e.versionId,sdpData:r}},t.toSessionDescription=function(e,t){if(e.sdpData){const i=l.SdpConverter.reconstructFromSDPData(e.sdpData);return s.info(`[53] [CallId: ${e.id}] toSessionDescription in sdp-converter: sdp: ${i}`,{color:"blue"}),{type:t,sdp:i}}return s.error("SessionData has neither sdpData nor sdp field"),null}},19:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SdpConverter=t.CODEC_NAME_TO_AUDIO_CODEC_S2W=t.CODEC_NAME_TO_AUDIO_CODEC=t.CODEC_NAME_TO_VIDEO_CODEC=void 0;const n=i(645),a=i(228),l=i(799),s=(0,n.createLogger)("SdpConverter");t.CODEC_NAME_TO_VIDEO_CODEC=["vp8","rtx","red"],t.CODEC_NAME_TO_AUDIO_CODEC=["opus","red"],t.CODEC_NAME_TO_AUDIO_CODEC_S2W=["opus","red","pcmu","pcma"];class r{static parseToSdpData(e,i=t.CODEC_NAME_TO_VIDEO_CODEC,n=t.CODEC_NAME_TO_AUDIO_CODEC){var a,l,s;const o=[],d=e.split("\n").map((e=>e.trim())).filter((e=>e.length>0)),c=r.extractSessionId(d)||"",u=r.extractSessionVersion(d)||0,p=r.extractOriginAddress(d)||"127.0.0.1",g=(null===(a=d.find((e=>e.startsWith("s="))))||void 0===a?void 0:a.substring(2))||"-",h=(null===(l=d.find(((e,t)=>e.startsWith("c=")&&!r.inMediaSection(d,t))))||void 0===l?void 0:l.split(" ").slice(2)[0])||"",v=(null===(s=r.firstValueStartingWith(d,"a=msid-semantic:"))||void 0===s?void 0:s.trim())||"WMS",S=r.parseBundleGroup(d),C=d.findIndex((e=>e.startsWith("m="))),f=C>0?d.slice(0,C):d,I=r.firstValueStartingWith(f,"a=ice-ufrag:")||"",E=r.firstValueStartingWith(f,"a=ice-pwd:")||"",m=r.parseIceOptions(f),P=r.parseFingerprint(f),$=r.parseSetup(f),y=f.some((e=>"a=ice-lite"===e)),T=f.some((e=>"a=extmap-allow-mixed"===e));return{sessionId:c,sessionVersion:u,bundleGroup:S,iceUfrag:I,icePwd:E,iceOptions:m,fingerprint:P,setup:$,media:r.parseMediaSections(d,o,i,n),sessionName:g,originAddress:p,connectionAddress:h,msidSemantic:v,iceLite:y,extmapAllowMixed:T,stringPool:o}}static reconstructFromSDPData(e){var t,i,n,l,o,d;try{const c=[];if(c.push("v=0\r\n"),c.push(`o=- ${e.sessionId} ${e.sessionVersion} IN IP4 ${e.originAddress}\r\n`),c.push(`s=${e.sessionName}\r\n`),c.push("t=0 0\r\n"),(null===(i=null===(t=e.fingerprint)||void 0===t?void 0:t.hashValue)||void 0===i?void 0:i.length)>0&&c.push(`a=fingerprint:${r.fingerprintToString(e.fingerprint)}\r\n`),(null===(n=null==e?void 0:e.bundleGroup)||void 0===n?void 0:n.length)>0){const t=e.media.map((e=>e.mid)).join(" ");c.push(`a=group:BUNDLE ${t}\r\n`)}(null===(l=null==e?void 0:e.iceOptions)||void 0===l?void 0:l.length)>0&&c.push(`a=ice-options:${e.iceOptions.join(" ")}\r\n`),(null==e?void 0:e.extmapAllowMixed)&&c.push("a=extmap-allow-mixed\r\n"),(null===(o=null==e?void 0:e.msidSemantic)||void 0===o?void 0:o.length)>0&&c.push(`a=msid-semantic: ${e.msidSemantic}\r\n`),(null==e?void 0:e.iceLite)&&c.push("a=ice-lite\r\n"),null===(d=null==e?void 0:e.media)||void 0===d||d.forEach((t=>{r.buildMediaSection(c,t,e)}));const u=c.join("");if(s.debug(`Reconstructed SDP (${null==u?void 0:u.length} bytes)`),!(null==u?void 0:u.includes("m=")))throw(0,a.checkCode)(4e3,"Reconstructed SDP missing media lines");if(!(null==u?void 0:u.includes("a=ice-ufrag:"))&&!(null==u?void 0:u.includes("a=ice-pwd:")))throw(0,a.checkCode)(4e3,"Reconstructed SDP missing ICE credentials");return u}catch(e){throw s.error(`[647] [CallId: GLOBAL_LOGS] Failed to reconstruct SDP: ${e.message}`,{color:"red"}),s.error(e,{color:"red"}),(0,a.toCallException)(e)}}static extractSessionId(e){const t=e.find((e=>e.startsWith("o=")));return t&&t.split(" ")[1]||null}static extractSessionVersion(e){const t=e.find((e=>e.startsWith("o=")));if(!t)return null;const i=t.split(" "),n=parseInt(i[2]||"0",10);return isNaN(n)?null:n}static extractOriginAddress(e){const t=e.find((e=>e.startsWith("o=")));return t&&t.split(" ")[5]||null}static parseBundleGroup(e){const t=e.find((e=>e.startsWith("a=group:BUNDLE ")));return t?t.substring(15).split(" ").map((e=>parseInt(e,10))).filter((e=>!isNaN(e))):[]}static parseIceOptions(e){const t=e.find((e=>e.startsWith("a=ice-options:")));return t?t.substring(14).split(" "):[]}static parseFingerprint(e){var t;const i=e.find((e=>e.startsWith("a=fingerprint:")));if(i){const e=i.substring(14).split(" ",2);if(2===e.length){let i;switch(e[0].toLowerCase()){case"sha-256":default:i=l.HashFunction.SHA256;break;case"sha-1":i=l.HashFunction.SHA1;break;case"sha-384":i=l.HashFunction.SHA384;break;case"sha-512":i=l.HashFunction.SHA512;break;case"md5":i=l.HashFunction.MD5}const n=e[1].replace(/:/g,"");return{hashFunc:i,hashValue:new Uint8Array((null===(t=n.match(/.{1,2}/g))||void 0===t?void 0:t.map((e=>parseInt(e,16))))||[])}}}return{hashFunc:l.HashFunction.SHA256,hashValue:new Uint8Array(0)}}static parseSetup(e){const t=e.find((e=>e.startsWith("a=setup:")));switch(null==t?void 0:t.substring(8).toLowerCase()){case"active":return l.DTLSSetup.ACTIVE;case"passive":return l.DTLSSetup.PASSIVE;default:return l.DTLSSetup.ACTPASS}}static firstValueStartingWith(e,t){const i=e.find((e=>e.startsWith(t)));return i?i.substring(t.length):null}static inMediaSection(e,t){return e.map(((e,t)=>({line:e,index:t}))).filter((({line:e})=>e.startsWith("m="))).map((({index:e})=>e)).some((e=>e<t))}static parseMediaSections(e,t,i,n){const a=e.map(((e,t)=>({line:e,index:t}))).filter((({line:e})=>e.startsWith("m="))).map((({index:e})=>e));return a.map(((l,s)=>{const o=s<a.length-1?a[s+1]:e.length;return r.parseMediaSection(e.slice(l,o),t,i,n)})).filter((e=>null!==e))}static parseMediaSection(e,t,i,n){var a;try{const i=e[0].substring(2).split(" ");let n;switch(i[0].toLowerCase()){case"audio":n=l.MediaType.AUDIO;break;case"video":n=l.MediaType.VIDEO;break;default:n=l.MediaType.MEDIA_TYPE_UNSPECIFIED}if(n===l.MediaType.MEDIA_TYPE_UNSPECIFIED)return s.warn(`Skipping unknown media type: ${i[0]}`),null;const o=parseInt(i[1]||"9",10)||9,d=i.slice(3).map((e=>parseInt(e,10))).filter((e=>!isNaN(e))),c=r.firstValueStartingWith(e,"a=mid:")||"",u=r.parseDirection(e),p=r.firstValueStartingWith(e,"a=msid:"),[g,h,v]=r.parseMSID(p||null),S=e.some((e=>"a=rtcp-mux"===e)),C=e.some((e=>"a=rtcp-rsize"===e)),f=e.some((e=>"a=end-of-candidates"===e)),I=(null===(a=e.find((e=>e.startsWith("c="))))||void 0===a?void 0:a.split(" ")[2])||"",E=r.firstValueStartingWith(e,"a=rtcp:")||"",m=new Map,P=[];d.forEach((e=>{m.set(e,{codecName:{id:e,mapKey:0},fmtp:[],rtcpFeedbackIds:[]}),P.push(e)})),e.filter((e=>e.startsWith("a=rtpmap:"))).forEach((e=>{const t=e.substring(9).split(" ",2);if(2===t.length){const e=parseInt(t[0],10);if(!isNaN(e)){const i=t[1];r.dynamicCodecNames.set(e,i);const n=r.CODEC_NAME_TO_MAP_KEY.get(i)||0;if(m.has(e)){const t=m.get(e);m.set(e,{codecName:{id:e,mapKey:n},fmtp:t.fmtp,rtcpFeedbackIds:t.rtcpFeedbackIds})}}}})),e.filter((e=>e.startsWith("a=fmtp:"))).forEach((e=>{const t=e.substring(7).split(" ",2);if(2===t.length){const e=parseInt(t[0],10);if(!isNaN(e)&&m.has(e)){const i=r.parseFmtp(t[1]),n=m.get(e);m.set(e,{codecName:n.codecName,fmtp:i,rtcpFeedbackIds:n.rtcpFeedbackIds})}}})),e.filter((e=>e.startsWith("a=rtcp-fb:"))).forEach((e=>{const t=e.substring(10).split(" ");if(t.length>=2){const e=parseInt(t[0],10);if(!isNaN(e)){let i="";for(let e=1;e<t.length;e++)i+=t[e]+(e!==t.length-1?" ":"");const n=r.RTCP_FEEDBACK_STRING_TO_ID.get(i);if(void 0!==n&&m.has(e)){const t=m.get(e),i=[...t.rtcpFeedbackIds];i.includes(n)||i.push(n),m.set(e,{codecName:t.codecName,fmtp:t.fmtp,rtcpFeedbackIds:i})}}}}));const $=P.map((e=>m.get(e))).filter((e=>void 0!==e)),y=r.parseExtmaps(e),T=r.parseSsrcs(e),O=r.parseSsrcGroups(e),w=r.parseCandidates(e),b=r.firstValueStartingWith(e,"a=ice-ufrag:"),F=r.firstValueStartingWith(e,"a=ice-pwd:"),A=b?r.addToStringPool(t,b):0,R=F?r.addToStringPool(t,F):0,N=e.find((e=>e.startsWith("a=ice-options:"))),_=N?N.substring(14).split(" "):void 0,k=e.find((e=>e.startsWith("a=fingerprint:"))),M=k?r.parseFingerprint([k]):{hashFunc:l.HashFunction.SHA256,hashValue:new Uint8Array(0)},D=e.find((e=>e.startsWith("a=setup:")));return{type:n,mid:c,direction:u,msidStream:g,msidTrackLabel:h,msidTrackId:v,rtcpMux:S,rtcpRsize:C,extmaps:y,codecs:$,ssrcGroups:O,ssrcs:T,connectionAddress:I,candidates:w,endOfCandidates:f,rtcpAddress:E,iceUfragRef:A,icePwdRef:R,iceOptions:_,fingerprint:M,setup:D?r.parseSetup([D]):l.DTLSSetup.ACTPASS,port:o}}catch(e){return s.error(`[647] [CallId: GLOBAL_LOGS] Failed to parse media section: ${e.message}`,{color:"red"}),s.error(e,{color:"red"}),null}}static parseDirection(e){return e.some((e=>"a=sendrecv"===e))?l.MediaDirection.SENDRECV:e.some((e=>"a=sendonly"===e))?l.MediaDirection.SENDONLY:e.some((e=>"a=recvonly"===e))?l.MediaDirection.RECVONLY:e.some((e=>"a=inactive"===e))?l.MediaDirection.INACTIVE:l.MediaDirection.SENDRECV}static parseMSID(e){if(!e||0===e.trim().length)return["","",0];const t=e.split(" ",2);if(t.length<2)return[e,"",0];const i=t[0],n=t[1],a=n.lastIndexOf("_");if(a>0){const e=n.substring(a+1),t=parseInt(e,10);if(!isNaN(t))return[i,n.substring(0,a+1),t]}return[i,n,0]}static parseFmtp(e){if(0===e.trim().length)return[];const t=[];return e.split(";").forEach((e=>{const i=e.trim();if(0!==i.length)if(i.includes("=")){const e=i.split("=",2);t.push({key:e[0].trim(),value:e[1].trim()})}else t.push({key:"value",value:i})})),t}static parseExtmaps(e){return e.filter((e=>e.startsWith("a=extmap:"))).map((e=>{const t=e.substring(9).split(" ",2);if(2!==t.length)return null;const i=t[0].split("/")[0],n=parseInt(i,10);if(isNaN(n))return null;const a=t[1];return{id:n,mapKey:r.URI_TO_EXTMAP_ID.get(a)||0}})).filter((e=>null!==e))}static parseSsrcs(e){const t=new Map;return e.filter((e=>e.startsWith("a=ssrc:"))).forEach((e=>{const i=e.substring(7).split(" ");if(i.length>=2){const e=parseInt(i[0],10);if(isNaN(e))return;const n=e,a=t.get(n)||{};if(i[1].startsWith("cname:"))a.cname=i[1].substring(6);else if(i[1].startsWith("msid:")){let e="";for(let t=1;t<i.length;t++)e+=i[t].substring(1===t?5:0)+(i.length-1!==t?" ":"");a.msid=e}t.set(n,a)}})),Array.from(t.entries()).map((([e,t])=>({id:e,cname:t.cname||"",msid:t.msid||""})))}static parseSsrcGroups(e){return e.filter((e=>e.startsWith("a=ssrc-group:"))).map((e=>{const t=e.substring(13).split(" ");return t.length>=2?{semantics:t[0],ssrcs:t.slice(1).map((e=>parseInt(e,10))).filter((e=>!isNaN(e)))}:null})).filter((e=>null!==e))}static parseCandidates(e){return e.filter((e=>e.startsWith("a=candidate:"))).map((e=>r.parseCandidate(e.substring(12)))).filter((e=>null!==e))}static parseCandidate(e){const t=e.split(" ");if(t.length<8)return null;const i=parseInt(t[0],10);if(isNaN(i))return null;const n=parseInt(t[1],10);if(isNaN(n))return null;let a;switch(t[2].toLowerCase()){case"udp":default:a=l.IceCandidateProtocol.UDP;break;case"tcp":a=l.IceCandidateProtocol.TCP}const s=parseInt(t[3],10);if(isNaN(s))return null;const r=t[4].split("."),o=new Uint8Array(r.map((e=>parseInt(e,10)))),d=parseInt(t[5],10);if(isNaN(d))return null;let c;switch(t[7].toLowerCase()){case"host":default:c=l.IceCandidateType.HOST;break;case"srflx":c=l.IceCandidateType.SRFLX;break;case"prflx":c=l.IceCandidateType.PRFLX;break;case"relay":c=l.IceCandidateType.RELAY}let u=new Uint8Array(0),p=0,g=l.IceCandidateTcpType.ACTIVE,h=8;for(;h<t.length;){switch(t[h]){case"raddr":if(h+1<t.length){const e=t[++h];u=new Uint8Array(e.split(".").map((e=>parseInt(e,10))))}break;case"rport":h+1<t.length&&(p=parseInt(t[++h],10)||0);break;case"tcptype":if(h+1<t.length)switch(t[++h].toLowerCase()){case"active":default:g=l.IceCandidateTcpType.ACTIVE;break;case"passive":g=l.IceCandidateTcpType.PASSIVE;break;case"so":g=l.IceCandidateTcpType.SO}}h++}return{foundation:i,component:n,protocol:a,priority:s,ip:o,port:d,type:c,raddr:u,rport:p,tcptype:g}}static addToStringPool(e,t){if(0===t.length)return 0;const i=e.indexOf(t);return i>=0?i+1:(e.push(t),e.length)}static getFromStringPool(e,t){return 0===t||t>e.length?"":e[t-1]}static getCodecID(e){var t;return(null===(t=e.codecName)||void 0===t?void 0:t.id)||0}static getCodecName(e){if(!e.codecName)return null;const t=e.codecName;if(t.mapKey>0){const e=r.MAP_KEY_TO_CODEC_NAME.get(t.mapKey);if(e)return e}return r.dynamicCodecNames.get(t.id)||null}static filterVideoCodecs(e,t){if(0===t.length)return e;const i=[],n=new Set;return e.forEach((e=>{const a=r.getCodecName(e);if(!a)return;const l=a.split("/")[0];t.some((e=>e.toLowerCase()===l.toLowerCase()))&&(i.push(e),n.add(r.getCodecID(e)))})),e.forEach((e=>{const t=r.getCodecName(e);if(t&&t.toLowerCase().startsWith("rtx/")){const t=e.fmtp.find((e=>"apt"===e.key)),a=t?parseInt(t.value,10):null;null!==a&&!isNaN(a)&&n.has(a)&&i.push(e)}})),i}static buildMediaSection(e,t,i){var n,a,o,d,c,u,p,g,h,v;let S;switch(t.type){case l.MediaType.AUDIO:S="audio";break;case l.MediaType.VIDEO:S="video";break;case l.MediaType.MEDIA_TYPE_UNSPECIFIED:return void s.error("Cannot reconstruct MEDIA_TYPE_UNSPECIFIED")}const C=(null===(n=null==t?void 0:t.codecs)||void 0===n?void 0:n.map((e=>r.getCodecID(e).toString())).join(" "))||"";e.push(`m=${S} ${t.port} UDP/TLS/RTP/SAVPF ${C}\r\n`);const f=(null==t?void 0:t.connectionAddress)||(null==i?void 0:i.connectionAddress)||"0.0.0.0";e.push(`c=IN IP4 ${f}\r\n`),(null===(a=null==t?void 0:t.rtcpAddress)||void 0===a?void 0:a.length)>0&&e.push(`a=rtcp:${t.rtcpAddress}\r\n`);const I=(null==t?void 0:t.iceUfragRef)>0?r.getFromStringPool(null==i?void 0:i.stringPool,null==t?void 0:t.iceUfragRef):null==i?void 0:i.iceUfrag,E=(null==t?void 0:t.icePwdRef)>0?r.getFromStringPool(null==i?void 0:i.stringPool,null==t?void 0:t.icePwdRef):null==i?void 0:i.icePwd;I.length>0&&e.push(`a=ice-ufrag:${I}\r\n`),E.length>0&&e.push(`a=ice-pwd:${E}\r\n`);const m=(null==t?void 0:t.iceOptions)||(null==i?void 0:i.iceOptions);m.length>0&&e.push(`a=ice-options:${m.join(" ")}\r\n`);const P=(null===(d=null===(o=null==t?void 0:t.fingerprint)||void 0===o?void 0:o.hashValue)||void 0===d?void 0:d.length)>0?null==t?void 0:t.fingerprint:null==i?void 0:i.fingerprint;(null===(c=null==P?void 0:P.hashValue)||void 0===c?void 0:c.length)>0&&e.push(`a=fingerprint:${r.fingerprintToString(P)}\r\n`);const $=(null==t?void 0:t.setup)!==l.DTLSSetup.ACTPASS||(null==i?void 0:i.setup)===l.DTLSSetup.ACTPASS?t.setup:i.setup;e.push(`a=setup:${r.setupToString($)}\r\n`),e.push(`a=mid:${null==t?void 0:t.mid}\r\n`),null===(u=null==t?void 0:t.extmaps)||void 0===u||u.forEach((t=>{const i=r.EXTMAP_ID_TO_URI.get(t.mapKey)||`urn:ietf:params:rtp-hdrext:extension-${t.id}`;e.push(`a=extmap:${t.id} ${i}\r\n`)})),e.push(`a=${r.directionToString(null==t?void 0:t.direction)}\r\n`);const y=r.reconstructMSID(null==t?void 0:t.msidStream,null==t?void 0:t.msidTrackLabel,null==t?void 0:t.msidTrackId);(null==y?void 0:y.length)>0&&e.push(`a=msid:${y}\r\n`),(null==t?void 0:t.rtcpMux)&&e.push("a=rtcp-mux\r\n"),(null==t?void 0:t.rtcpRsize)&&e.push("a=rtcp-rsize\r\n"),null===(p=null==t?void 0:t.codecs)||void 0===p||p.forEach((t=>{var i,n;const a=r.getCodecID(t),l=r.getCodecName(t);if(l&&e.push(`a=rtpmap:${a} ${l}\r\n`),null===(i=null==t?void 0:t.rtcpFeedbackIds)||void 0===i||i.forEach((t=>{const i=r.RTCP_FEEDBACK_ID_TO_STRING.get(t);i&&e.push(`a=rtcp-fb:${a} ${i}\r\n`)})),(null===(n=null==t?void 0:t.fmtp)||void 0===n?void 0:n.length)>0){const i=r.reconstructFmtp(t.fmtp);e.push(`a=fmtp:${a} ${i}\r\n`)}})),null===(g=null==t?void 0:t.ssrcGroups)||void 0===g||g.forEach((t=>{const i=t.ssrcs.map((e=>(e>>>0).toString())).join(" ");e.push(`a=ssrc-group:${t.semantics} ${i}\r\n`)})),null===(h=null==t?void 0:t.ssrcs)||void 0===h||h.forEach((t=>{var i,n;const a=(t.id>>>0).toString();(null===(i=null==t?void 0:t.cname)||void 0===i?void 0:i.length)>0&&e.push(`a=ssrc:${a} cname:${t.cname}\r\n`),(null===(n=null==t?void 0:t.msid)||void 0===n?void 0:n.length)>0&&e.push(`a=ssrc:${a} msid:${t.msid}\r\n`)})),null===(v=null==t?void 0:t.candidates)||void 0===v||v.forEach((t=>{e.push(`a=candidate:${r.reconstructCandidate(t)}\r\n`)})),(null==t?void 0:t.endOfCandidates)&&e.push("a=end-of-candidates\r\n")}static reconstructMSID(e,t,i){return 0===e.length?"":0===t.length&&0===i?e:i>0&&t.length>0?`${e} ${t}${i}`:t.length>0?`${e} ${t}`:e}static reconstructFmtp(e){return e.map((e=>"value"===e.key?e.value:`${e.key}=${e.value}`)).join(";")}static fingerprintToString(e){let t;switch(e.hashFunc){case l.HashFunction.SHA256:t="sha-256";break;case l.HashFunction.SHA1:t="sha-1";break;case l.HashFunction.SHA384:t="sha-384";break;case l.HashFunction.SHA512:t="sha-512";break;case l.HashFunction.MD5:t="md5"}return`${t} ${Array.from(e.hashValue).map((e=>e.toString(16).padStart(2,"0").toUpperCase())).join(":")}`}static setupToString(e){switch(e){case l.DTLSSetup.ACTIVE:return"active";case l.DTLSSetup.PASSIVE:return"passive";case l.DTLSSetup.ACTPASS:return"actpass"}}static directionToString(e){switch(e){case l.MediaDirection.SENDONLY:return"sendonly";case l.MediaDirection.RECVONLY:return"recvonly";case l.MediaDirection.INACTIVE:return"inactive";default:return"sendrecv"}}static reconstructCandidate(e){const t=e.protocol===l.IceCandidateProtocol.UDP?"udp":"tcp";let i;switch(e.type){case l.IceCandidateType.HOST:i="host";break;case l.IceCandidateType.SRFLX:i="srflx";break;case l.IceCandidateType.PRFLX:i="prflx";break;case l.IceCandidateType.RELAY:i="relay"}const n=[e.foundation.toString(),e.component.toString(),t,e.priority.toString(),Array.from(e.ip).map((e=>(255&e).toString())).join("."),e.port.toString(),"typ",i];if(e.raddr.length>0){n.push("raddr");const t=Array.from(e.raddr).map((e=>(255&e).toString())).join(".");n.push(t)}if(e.rport>0&&(n.push("rport"),n.push(e.rport.toString())),"tcp"===t){let t;switch(e.tcptype){case l.IceCandidateTcpType.ACTIVE:t="active";break;case l.IceCandidateTcpType.PASSIVE:t="passive";break;case l.IceCandidateTcpType.SO:t="so"}n.push("tcptype"),n.push(t)}return n.join(" ")}}t.SdpConverter=r,r.EXTMAP_ID_TO_URI=new Map([[1,"urn:ietf:params:rtp-hdrext:toffset"],[2,"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"],[3,"urn:3gpp:video-orientation"],[4,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"],[5,"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"],[6,"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"],[7,"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"],[8,"http://www.webrtc.org/experiments/rtp-hdrext/color-space"],[9,"urn:ietf:params:rtp-hdrext:sdes:mid"],[10,"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"],[11,"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],[14,"urn:ietf:params:rtp-hdrext:ssrc-audio-level"],[15,"urn:ietf:params:rtp-hdrext:csrc-audio-level"]]),r.URI_TO_EXTMAP_ID=new Map(Array.from(r.EXTMAP_ID_TO_URI.entries()).map((([e,t])=>[t,e]))),r.RTCP_FEEDBACK_ID_TO_STRING=new Map([[1,"goog-remb"],[2,"transport-cc"],[3,"ccm fir"],[4,"nack"],[5,"nack pli"]]),r.RTCP_FEEDBACK_STRING_TO_ID=new Map(Array.from(r.RTCP_FEEDBACK_ID_TO_STRING.entries()).map((([e,t])=>[t,e]))),r.dynamicCodecNames=new Map,r.CODEC_NAME_TO_MAP_KEY=new Map([["VP8/90000",1],["VP9/90000",2],["AV1/90000",3],["H264/90000",4],["H265/90000",5],["rtx/90000",6],["red/90000",7],["ulpfec/90000",8],["opus/48000/2",9],["red/48000/2",10],["G722/8000",11],["G722/8000/1",11],["PCMU/8000",12],["PCMA/8000",13],["CN/8000",14],["telephone-event/48000",15],["telephone-event/8000",16],["telephone-event/8000/1",16],["ILBC/8000",17]]),r.MAP_KEY_TO_CODEC_NAME=new Map([[1,"VP8/90000"],[2,"VP9/90000"],[3,"AV1/90000"],[4,"H264/90000"],[5,"H265/90000"],[6,"rtx/90000"],[7,"red/90000"],[8,"ulpfec/90000"],[9,"opus/48000/2"],[10,"red/48000/2"],[11,"G722/8000"],[12,"PCMU/8000"],[13,"PCMA/8000"],[14,"CN/8000"],[15,"telephone-event/48000"],[16,"telephone-event/8000"],[17,"ILBC/8000"]])},799:(e,t)=>{"use strict";var i,n,a,l,s,r,o;Object.defineProperty(t,"__esModule",{value:!0}),t.IceCandidateTcpType=t.IceCandidateType=t.IceCandidateProtocol=t.MediaDirection=t.MediaType=t.DTLSSetup=t.HashFunction=void 0,function(e){e[e.SHA256=0]="SHA256",e[e.SHA1=1]="SHA1",e[e.SHA384=2]="SHA384",e[e.SHA512=3]="SHA512",e[e.MD5=4]="MD5"}(i||(t.HashFunction=i={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PASSIVE=1]="PASSIVE",e[e.ACTPASS=2]="ACTPASS"}(n||(t.DTLSSetup=n={})),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.MEDIA_TYPE_UNSPECIFIED=2]="MEDIA_TYPE_UNSPECIFIED"}(a||(t.MediaType=a={})),function(e){e[e.SENDRECV=0]="SENDRECV",e[e.SENDONLY=1]="SENDONLY",e[e.RECVONLY=2]="RECVONLY",e[e.INACTIVE=3]="INACTIVE"}(l||(t.MediaDirection=l={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP"}(s||(t.IceCandidateProtocol=s={})),function(e){e[e.HOST=0]="HOST",e[e.SRFLX=1]="SRFLX",e[e.PRFLX=2]="PRFLX",e[e.RELAY=3]="RELAY"}(r||(t.IceCandidateType=r={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PASSIVE=1]="PASSIVE",e[e.SO=2]="SO"}(o||(t.IceCandidateTcpType=o={}))},828:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.QueuedSignal=void 0;const n=i(795),a=i(429);t.QueuedSignal=class{constructor(e,t,i=n.SignalQueueStrategy.getSignalPriority(e),l=Date.now(),s=0,r=(0,a.v4)()){this.signal=e,this.callback=t,this.priority=i,this.timestamp=l,this.requeueCount=s,this.uniqueKey=r}get callId(){return this.signal.callId}compareTo(e){const t=e.priority-this.priority;return 0!==t?t:this.timestamp-e.timestamp}toString(){return`QueuedSignal(signal=${JSON.stringify(this.signal)}, timestamp=${this.timestamp}, priority=${this.priority}, requeueCount=${this.requeueCount}, uniqueKey=${this.uniqueKey})`}}},795:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignalQueueStrategy=t.SignalProcessingStrategy=void 0;const n=i(578),a=i(586),l=i(228);var s;!function(e){e[e.SEQUENTIAL=0]="SEQUENTIAL",e[e.IMMEDIATE=1]="IMMEDIATE"}(s||(t.SignalProcessingStrategy=s={}));class r{static getProcessingStrategy(e){return this.SEQUENTIAL_SIGNALS.has(e)?s.SEQUENTIAL:s.IMMEDIATE}static isSequentialSignal(e){return this.getProcessingStrategy(e)===s.SEQUENTIAL}static isImmediateSignal(e){return this.getProcessingStrategy(e)===s.IMMEDIATE}static getSignalPriorityValue(e){switch(e){case n.SignalEvent.JOIN:return 10;case n.SignalEvent.LEAVE:case n.SignalEvent.DECLINE:return 9;case n.SignalEvent.MEDIA_CONNECTED:return 8;case n.SignalEvent.OFFER:case n.SignalEvent.ANSWER:case n.SignalEvent.CONNECT:case n.SignalEvent.ICE:return 7;case n.SignalEvent.KICK:case n.SignalEvent.INVITE:case n.SignalEvent.RINGING:case n.SignalEvent.INFO:case n.SignalEvent.UPDATE:case n.SignalEvent.GET_CALL:case n.SignalEvent.SWITCH_MEDIA_FLOW:return 6;case n.SignalEvent.MUTE:case n.SignalEvent.UNMUTE:case n.SignalEvent.VIDEO_ON:case n.SignalEvent.VIDEO_OFF:case n.SignalEvent.HOLD:case n.SignalEvent.UNHOLD:case n.SignalEvent.SCREEN_SHARE_ON:case n.SignalEvent.SCREEN_SHARE_OFF:return 5;case n.SignalEvent.ERROR:case n.SignalEvent.SUCCESS:case n.SignalEvent.CLOSE:case n.SignalEvent.NO_ANSWER:throw(0,l.checkCode)(4e3,`SignalEvent ${e} should not be in queue`);default:return 0}}static getSignalPriority(e){if("number"!=typeof e.event)throw(0,l.checkCode)(4e3,`Signal event is not a number for signal: ${JSON.stringify(e)}`);return this.getSignalPriorityValue(e.event)}static getSignalLevel(e){switch(e.event){case n.SignalEvent.JOIN:case n.SignalEvent.LEAVE:case n.SignalEvent.DECLINE:return a.SignalLevel.GlobalBlocking;case n.SignalEvent.OFFER:case n.SignalEvent.ANSWER:case n.SignalEvent.ICE:case n.SignalEvent.CONNECT:return a.SignalLevel.ParticipantLevel;default:return a.SignalLevel.Immediate}}}t.SignalQueueStrategy=r,r.SEQUENTIAL_SIGNALS=new Set([n.SignalEvent.JOIN,n.SignalEvent.LEAVE,n.SignalEvent.DECLINE,n.SignalEvent.OFFER,n.SignalEvent.ANSWER,n.SignalEvent.CONNECT])},586:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.SignalingQueue=t.SignalLevel=void 0;const a=i(795),l=i(645),s=i(578),r=(0,l.createLogger)("SignalingQueue");var o;!function(e){e[e.GlobalBlocking=0]="GlobalBlocking",e[e.ParticipantLevel=1]="ParticipantLevel",e[e.Immediate=2]="Immediate"}(o||(t.SignalLevel=o={})),t.SignalingQueue=class{constructor(e,t,i){this.id=e,this.isTransportConnected=t,this.sender=i,this.globalBlockingSignals=[],this.immediateSignals=[],this.participantSignals=new Map,this.processingSignalJobs=new Map,this.participantJobs=new Map,this.sentSignals=new Set}getSignalKey(e,t){return`${t}_${e.event}_${e.callId}_${e.sessionId||""}`}addSignalToQueue(e){const t=this.getSignalKey(e.signal,e.uniqueKey);if(this.sentSignals.has(t))return void r.info(`[38] [CallId: ${e.signal.callId}] Signal already sent, skipping: ${s.SignalEvent[e.signal.event]}`);const i=a.SignalQueueStrategy.getSignalLevel(e.signal);switch(i){case o.GlobalBlocking:this.globalBlockingSignals.push(e);break;case o.ParticipantLevel:const t=e.signal.to||"";this.participantSignals.has(t)||this.participantSignals.set(t,[]),this.participantSignals.get(t).push(e);break;case o.Immediate:this.immediateSignals.push(e)}r.info(`[61] [CallId: ${e.signal.callId}] Add signal to queue ===> level: ${i}, signal Event: ${s.SignalEvent[e.signal.event]}, uniqueKey: ${e.uniqueKey}`),this.invalidateToSendSignalsIfNeeded()}removeSignalFromQueue(e){const t=this.getSignalKey(e.signal,e.uniqueKey);this.sentSignals.delete(t)}invalidateToSendSignalsIfNeeded(){this.isTransportConnected()?this.globalBlockingSignals.length>0?this.sendGlobalBlockingSignals():(this.sendParticipantSignals(),this.sendImmediateLevelSignals()):r.info(`[75] [CallId: ${this.id}] Connection is not established, skipping signal processing`)}triggerSignalProcessing(){this.invalidateToSendSignalsIfNeeded()}sendGlobalBlockingSignals(){return n(this,void 0,void 0,(function*(){if(!this.processingSignalJobs.get(o.GlobalBlocking)){this.processingSignalJobs.set(o.GlobalBlocking,!0);try{for(;this.isTransportConnected();){const e=this.globalBlockingSignals.shift();if(!e)break;const t=this.getSignalKey(e.signal,e.uniqueKey);this.sentSignals.has(t)?r.info(`[107] [CallId: ${this.id}] Global blocking signal already sent, skipping: ${s.SignalEvent[e.signal.event]}`):(r.info(`[111] [CallId: ${this.id}] Sending ${o.GlobalBlocking} level signal: ${s.SignalEvent[e.signal.event]}`),yield this.sendSignal(e),this.sentSignals.add(t))}}finally{this.processingSignalJobs.delete(o.GlobalBlocking),0===this.globalBlockingSignals.length&&(this.sendParticipantSignals(),this.sendImmediateLevelSignals())}}}))}sendImmediateLevelSignals(){return n(this,void 0,void 0,(function*(){if(!(this.globalBlockingSignals.length>0||this.processingSignalJobs.get(o.Immediate))){this.processingSignalJobs.set(o.Immediate,!0);try{for(;this.isTransportConnected()&&0===this.globalBlockingSignals.length;){const e=this.immediateSignals.shift();if(!e)break;const t=this.getSignalKey(e.signal,e.uniqueKey);this.sentSignals.has(t)?r.info(`[145] [CallId: ${this.id}] Immediate signal already sent, skipping: ${s.SignalEvent[e.signal.event]}`):(r.info(`[148] [CallId: ${this.id}] Sending ${o.Immediate} level signal: ${s.SignalEvent[e.signal.event]}`),yield this.sendSignal(e),this.sentSignals.add(t))}}finally{this.processingSignalJobs.delete(o.Immediate)}}}))}sendParticipantSignals(){if(!(this.globalBlockingSignals.length>0))for(const[e,t]of this.participantSignals.entries())t.length>0&&this.sendParticipantSignal(e,t)}sendParticipantSignal(e,t){return n(this,void 0,void 0,(function*(){if(!this.participantJobs.get(e)){this.participantJobs.set(e,!0);try{for(;this.isTransportConnected()&&0===this.globalBlockingSignals.length;){const i=t.shift();if(!i)break;const n=this.getSignalKey(i.signal,i.uniqueKey);this.sentSignals.has(n)?r.info(`[185] [CallId: ${this.id}] Participant signal already sent, skipping: ${s.SignalEvent[i.signal.event]}`):(r.info(`[188] [CallId: ${this.id}] Sending ${o.ParticipantLevel} level signal for identity ${e}: ${s.SignalEvent[i.signal.event]}`),yield this.sendSignal(i),this.sentSignals.add(n))}}finally{this.participantJobs.delete(e),0===t.length&&this.participantSignals.delete(e)}}}))}sendSignal(e){return n(this,void 0,void 0,(function*(){a.SignalQueueStrategy.getProcessingStrategy(e.signal.event)===a.SignalProcessingStrategy.SEQUENTIAL?yield this.sender(e):this.sender(e).catch((e=>{r.error(`[209] [CallId: ${this.id}] Error sending signal: ${e}`)}))}))}clearParticipantSignals(e){this.participantSignals.delete(e),this.participantJobs.delete(e),r.info(`[213] [CallId: ${this.id}] Cleared participant signals for identity: ${e}, queueId: ${this.id}`)}clearCallSignals(){this.globalBlockingSignals=[],this.immediateSignals=[],this.participantSignals.clear(),this.processingSignalJobs.clear(),this.participantJobs.clear(),this.sentSignals.clear(),r.info(`[227] [CallId: ${this.id}] Cleared all signals for queueId: ${this.id}`)}getGlobalBlockingSignals(){return this.globalBlockingSignals}}},786:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Signaling=void 0;const a=i(578),l=i(645),s=i(828),r=i(586),o=i(228),d=i(65),c=i(429),u=(0,l.createLogger)("Signaling");class p{constructor(e,t){this.signalingQueues=new Map,this.chatClient=e;const i=new this.chatClient.ChannelListener;i.onSignal=e=>{t(e)},this.chatClient.addChannelListener("call_listeners",i)}calculateRetryDelay(e){return Math.min(p.BASE_DELAY_MS*Math.pow(2,e),p.MAX_DELAY_MS)}handleRetry(e,t,i,a){var l;return n(this,void 0,void 0,(function*(){if(t>=p.MAX_RETRIES)throw u.error(`[45] [CallId: ${e.signal.callId}] Max retries exceeded for signal: ${JSON.stringify(e.signal)}`,{color:"red"}),(0,o.toCallException)(i);i instanceof d.SceytCallException&&!i.isResendable&&(u.error(`[49] [CallId: ${e.signal.callId}] Signal sending failed with non-resendable exception: ${i.message}`,{color:"red"}),null===(l=e.callback)||void 0===l||l.call(e,i),a.removeSignalFromQueue(e));const n=this.calculateRetryDelay(t);u.error(`[53] [CallId: ${e.signal.callId}] Sending signal failed with error: ${i.message}, but ChatClient is connected. Retrying in ${n}ms (attempt ${t+1}/${p.MAX_RETRIES})`,{color:"red"}),yield new Promise((e=>setTimeout(e,n)));try{const t=yield this.sendSignalSuspended(e);return u.info(`[64] [CallId: ${e.signal.callId}] Retry sending signal success: ${JSON.stringify(t)}`),t}catch(i){return u.error(`[67] [CallId: ${e.signal.callId}] Retry sending signal failed: ${i instanceof Error?i.message:String(i)}`),this.handleRetry(e,t+1,i instanceof Error?i:new Error(String(i)),a)}}))}sendSignalSuspended(e){return n(this,void 0,void 0,(function*(){try{u.info(`[78] [CallId: ${e.signal.callId}] Sending signal ${a.SignalEvent[e.signal.event]} to chat client: version: 132`);const t=yield this.chatClient.sendSignal(e.signal,132);if(null==t?void 0:t.error)throw(0,o.toCallException)(t.error);return(0,o.handleAck)(t)}catch(e){throw(0,o.toCallException)(e)}}))}sendSignalMessage(e,t,i){u.info(`[92] [CallId: ${e.callId}] Sending signal message request: ${a.SignalEvent[e.event]} uniqueKey: ${(0,c.v4)()} ${JSON.stringify(e)}`,{color:"yellow"});const l=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({mediaFlow:e.mediaFlow,callId:e.callId},e.sessionId&&{sessionId:e.sessionId}),{event:e.event}),e.sessionData&&{sessionData:e.sessionData}),e.to&&{to:e.to}),{participants:e.participants?e.participants:[]}),e.ice&&{ice:e.ice}),e.metadata?{metadata:e.metadata}:{metadata:{}}),e.joinOptions&&{joinOptions:e.joinOptions}),e.settings&&{settings:e.settings}),g=i||e.callId;let h=this.signalingQueues.get(g);h||(h=new r.SignalingQueue(g,(()=>"Connected"===this.chatClient.connectionState),(e=>n(this,void 0,void 0,(function*(){var t,i,n,l,r;try{const l=yield this.sendSignalSuspended(e);if(u.info(`[115] [CallId: ${e.signal.callId||"GLOBAL_LOGS"}] Sent signal message response: ${a.SignalEvent[e.signal.event]} uniqueKey: ${e.uniqueKey} ${JSON.stringify(l)}`,{color:"magenta"}),(null==l?void 0:l.event)===a.SignalEvent.ERROR)throw(0,o.checkCode)((null===(t=null==l?void 0:l.error)||void 0===t?void 0:t.code)||0,(null===(i=null==l?void 0:l.error)||void 0===i?void 0:i.message)||"Unknown error");return null===(n=e.callback)||void 0===n||n.call(e,l),null==h||h.removeSignalFromQueue(e),l}catch(t){if(u.error(`[125] [CallId: ${e.signal.callId||"GLOBAL_LOGS"}] Signal message error: ${a.SignalEvent[e.signal.event]} uniqueKey: ${e.uniqueKey} error: ${t instanceof Error?t.message:String(t)}, resendable: ${t instanceof d.SceytCallException&&t.isResendable}`,{color:"red"}),t instanceof d.SceytCallException&&t.isResendable){const i=e.requeueCount;i<p.REQUEUE_LIMIT?null==h||h.addSignalToQueue(new s.QueuedSignal(e.signal,e.callback,e.priority,e.timestamp,i+1,(0,c.v4)())):(u.error(`[140] [CallId: ${e.signal.callId||"GLOBAL_LOGS"}] Max requeue limit reached for signal: ${JSON.stringify(e.signal)}, will not requeue again. uniqueKey: ${e.uniqueKey}`,{color:"red"}),null===(l=e.callback)||void 0===l||l.call(e,t),null==h||h.removeSignalFromQueue(e))}const i=t instanceof d.SceytCallException?t:new Error(t instanceof Error?t.message:String(t));null===(r=e.callback)||void 0===r||r.call(e,i),null==h||h.removeSignalFromQueue(e)}})))),this.signalingQueues.set(g,h)),h.addSignalToQueue(new s.QueuedSignal(l,t,0,0,0,(0,c.v4)()))}clearCallSignals(e){const t=this.signalingQueues.get(e);t&&(t.clearCallSignals(),this.signalingQueues.delete(e))}clearParticipantSignals(e,t){const i=this.signalingQueues.get(e);i&&i.clearParticipantSignals(t)}cancelJoinIfPossible(e){const t=this.signalingQueues.get(e);return!!t&&!!t.getGlobalBlockingSignals().find((e=>e.signal.event==a.SignalEvent.JOIN))&&(t.clearCallSignals(),!0)}}t.Signaling=p,p.REQUEUE_LIMIT=10,p.MAX_RETRIES=10,p.BASE_DELAY_MS=1e3,p.MAX_DELAY_MS=8e3},342:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReceiveSignalValidator=void 0;const n=i(578),a=(0,i(645).createLogger)("ReceiveSignalValidator");class l{static canHandleSignal(e,t){const i=l.validateSignal(e,t.state,t.localParticipant);return i||a.warn(`Cannot handle signal ${e.event} in call state ${t.state} with local participant state ${t.localParticipant.state}`),i}static validateSignal(e,t,i){switch(e.event){case n.SignalEvent.JOIN:case n.SignalEvent.LEAVE:return!0;case n.SignalEvent.OFFER:case n.SignalEvent.ANSWER:return t===n.CallState.Connected;case n.SignalEvent.KICK:return!0;case n.SignalEvent.INVITE:return!e.participants||!e.participants.some((e=>e.id===i.id))||t===n.CallState.Idle;case n.SignalEvent.DECLINE:case n.SignalEvent.RINGING:case n.SignalEvent.INFO:case n.SignalEvent.UPDATE:case n.SignalEvent.CLOSE:return!0;case n.SignalEvent.ICE:return t===n.CallState.Connected;case n.SignalEvent.SWITCH_MEDIA_FLOW:case n.SignalEvent.NO_ANSWER:case n.SignalEvent.MUTE:case n.SignalEvent.UNMUTE:case n.SignalEvent.HOLD:case n.SignalEvent.UNHOLD:case n.SignalEvent.VIDEO_ON:case n.SignalEvent.VIDEO_OFF:case n.SignalEvent.SCREEN_SHARE_ON:case n.SignalEvent.SCREEN_SHARE_OFF:case n.SignalEvent.MEDIA_CONNECTED:case n.SignalEvent.CONNECT:case n.SignalEvent.GET_CALL:return!0;default:return a.warn(`Unknown signal event for handling: ${e.event}`),!1}}}t.ReceiveSignalValidator=l},771:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SendSignalValidator=void 0;const n=i(578),a=(0,i(645).createLogger)("SendSignalValidator");class l{canSendSignal(e,t){const i=l.validateSignalEvent(e.event,t.state);return i||a.warn(`Cannot send signal ${e.event} in call state ${t.state} with local participant state ${t.localParticipant.state}`),i}canSendSignalEvent(e,t){const i=l.validateSignalEvent(e,t.state);return i||a.warn(`Cannot send signal ${e} in call state ${t.state} with local participant state ${t.localParticipant.state}`),i}static validateSignalEvent(e,t){const i=t===n.CallState.Connected;switch(e){case n.SignalEvent.JOIN:return!0;case n.SignalEvent.LEAVE:return i;case n.SignalEvent.OFFER:case n.SignalEvent.ANSWER:case n.SignalEvent.CONNECT:case n.SignalEvent.KICK:case n.SignalEvent.INVITE:return t===n.CallState.Connected;case n.SignalEvent.DECLINE:return t===n.CallState.Idle;case n.SignalEvent.RINGING:return t===n.CallState.Idle||t===n.CallState.Connecting;case n.SignalEvent.INFO:case n.SignalEvent.UPDATE:return t===n.CallState.Connected;case n.SignalEvent.ICE:case n.SignalEvent.GET_CALL:return!0;case n.SignalEvent.SWITCH_MEDIA_FLOW:case n.SignalEvent.MEDIA_CONNECTED:return t===n.CallState.Connected;case n.SignalEvent.MUTE:case n.SignalEvent.UNMUTE:case n.SignalEvent.HOLD:case n.SignalEvent.UNHOLD:case n.SignalEvent.VIDEO_ON:case n.SignalEvent.VIDEO_OFF:return i;case n.SignalEvent.SCREEN_SHARE_ON:case n.SignalEvent.SCREEN_SHARE_OFF:return t===n.CallState.Connected;default:return a.warn(`Unknown signal event for sending: ${e}`),!1}}}t.SendSignalValidator=l},302:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReceiveSignalValidator=t.SendSignalValidator=void 0;var n=i(771);Object.defineProperty(t,"SendSignalValidator",{enumerable:!0,get:function(){return n.SendSignalValidator}});var a=i(342);Object.defineProperty(t,"ReceiveSignalValidator",{enumerable:!0,get:function(){return a.ReceiveSignalValidator}})},740:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VideoTrack=void 0,t.VideoTrack=class{constructor(e){this._enabled=!0,this.id=e.id,this.videoTrack=e}set enabled(e){this._enabled=e,this.videoTrack.enabled=e}get enabled(){return this._enabled}}},546:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,l){function s(e){try{o(n.next(e))}catch(e){l(e)}}function r(e){try{o(n.throw(e))}catch(e){l(e)}}function o(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,r)}o((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.WebRTCClient=void 0;const a=i(578),l=i(645),s=i(19),r=i(680),o=(0,l.createLogger)("WebRTCClient");t.WebRTCClient=class{constructor(e,t){this.listeners={},this.sessionId=null,this.version=null,this.iceQueueMap={},this.configuration=t,this.peerConnection=new RTCPeerConnection(this.configuration),this.callId=e}setSessionId(e){this.sessionId=e}getSessionId(){return this.sessionId||""}setVersion(e){this.version=e}getVersion(){return this.version||""}setListeners(e){o.info(`[18] [CallId: ${this.callId}] setListeners in webrtcClient: listeners`,{color:"blue"}),this.listeners=e}setConfiguration(e){o.info(`[21] [CallId: ${this.callId}] setConfiguration in webrtcClient: configuration: ${e}`,{color:"blue"}),this.configuration=e}getPreferredAudioCodecs(e){const t=RTCRtpReceiver.getCapabilities("audio");return t?t.codecs.filter((t=>{const i=t.mimeType.split("/")[1].toLowerCase();return e===a.MediaFlow.S2W?s.CODEC_NAME_TO_AUDIO_CODEC_S2W.includes(i):s.CODEC_NAME_TO_AUDIO_CODEC.includes(i)})):[]}getPreferredVideoCodecs(){const e=RTCRtpSender.getCapabilities("video");if(!e)return[];const t=[];return s.CODEC_NAME_TO_VIDEO_CODEC.forEach((i=>{const n=e.codecs.find((e=>e.mimeType.split("/")[1].toLowerCase()===i.toLowerCase()));n&&t.push(n)})),t}setPreferredCodecs(e,t,i){if("video"===t){o.info(`[74] [CallId: ${this.callId}] setPreferredCodecs: video, mediaFlow: ${e}`,{color:"blue"});const t=this.getPreferredVideoCodecs(),n=[];t.forEach((e=>{n.push({mimeType:e.mimeType,clockRate:e.clockRate,sdpFmtpLine:e.sdpFmtpLine,channels:e.channels})})),i.setCodecPreferences(n)}else if("audio"===t){o.info(`[88] [CallId: ${this.callId}] setPreferredCodecs: audio, mediaFlow: ${e}`,{color:"blue"});const t=this.getPreferredAudioCodecs(e),n=[];t.forEach((e=>{n.push({mimeType:e.mimeType,clockRate:e.clockRate,sdpFmtpLine:e.sdpFmtpLine||"",channels:e.channels||void 0})})),i.setCodecPreferences(n)}}addTransceiverToPeerConnection(e,t){return n(this,void 0,void 0,(function*(){o.info(`[56] [CallId: ${this.callId}] addTransceiverToPeerConnection in webrtcClient: track: ${null==e?void 0:e.kind}`,{color:"blue"}),this.peerConnection.addTransceiver(e,{direction:"sendrecv"});const i=this.peerConnection.getTransceivers().find((t=>{var i;return(null===(i=t.receiver.track)||void 0===i?void 0:i.kind)===(null==e?void 0:e.kind)}));if(i&&"video"===(null==e?void 0:e.kind)){this.setPreferredCodecs(t,"video",i);try{const e=i.sender.getParameters();e.encodings&&e.encodings.length>0&&(e.encodings.forEach((e=>{e.maxBitrate=5e5})),yield i.sender.setParameters(e),o.info(`[57] [CallId: ${this.callId}] addTransceiverToPeerConnection: Set video max bitrate to 500 kbps`,{color:"blue"}))}catch(e){o.warn(`[58] [CallId: ${this.callId}] addTransceiverToPeerConnection: Failed to set video bitrate: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"yellow"})}}else i&&"audio"===(null==e?void 0:e.kind)&&this.setPreferredCodecs(t,"audio",i)}))}setStreamsToTransceiver(e){var t,i;return n(this,void 0,void 0,(function*(){o.info(`[61] [CallId: ${this.callId}] setStreamsToTransceiver in webrtcClient: track: ${null==e?void 0:e.kind}`,{color:"blue"});const n=this.peerConnection.getTransceivers();o.info(`[62] [CallId: ${this.callId}] setStreamsToTransceiver: transceivers: ${n.length}`,{color:"blue"});const a=null==e?void 0:e.kind;let l=n.find((e=>{var t,i;const n=null===(t=e.receiver.track)||void 0===t?void 0:t.kind,l=null===(i=e.sender.track)||void 0===i?void 0:i.kind;return n===a||l===a}));if(o.info(`[63] [CallId: ${this.callId}] setStreamsToTransceiver: transceiver found: ${!!l}, receiver track: ${null===(t=null==l?void 0:l.receiver.track)||void 0===t?void 0:t.kind}, sender track: ${null===(i=null==l?void 0:l.sender.track)||void 0===i?void 0:i.kind}, current direction: ${null==l?void 0:l.direction}, mid: ${null==l?void 0:l.mid}`,{color:"blue"}),l){if(null!==l.sender.track)return void o.info(`[64] [CallId: ${this.callId}] setStreamsToTransceiver: Track already attached, skipping to avoid renegotiation`,{color:"blue"});e&&(e.enabled=!0),l.direction="sendrecv",yield l.sender.replaceTrack(e);const t=l.direction,i=l.sender.track,n=i?i.kind:"null";o.info(`[65] [CallId: ${this.callId}] setStreamsToTransceiver: Attached local ${a} track to transceiver, direction: ${t}, sender track: ${n}, track enabled: ${null==e?void 0:e.enabled}, track id: ${null==e?void 0:e.id}`,{color:"blue"}),i||o.error(`[66] [CallId: ${this.callId}] setStreamsToTransceiver: Failed to attach ${a} track - sender track is still null after replaceTrack`,{color:"red"})}else{const e=n.map((e=>{var t,i;return{mid:e.mid,receiverKind:(null===(t=e.receiver.track)||void 0===t?void 0:t.kind)||"null",senderKind:(null===(i=e.sender.track)||void 0===i?void 0:i.kind)||"null",direction:e.direction}}));o.warn(`[67] [CallId: ${this.callId}] setStreamsToTransceiver: No transceiver found for track kind: ${a}. Available transceivers: ${JSON.stringify(e)}`,{color:"yellow"})}}))}enableVideoOnPeerConnection(e,t,i=!1){return n(this,void 0,void 0,(function*(){o.info(`[27] [CallId: ${this.callId}] enableVideoOnPeerConnection in webrtcClient: enable: ${e}, kind: ${null==t?void 0:t.kind}`,{color:"blue"});const n=this.peerConnection.getTransceivers();for(let a=0;a<n.length;a++){const l=n[a];if(l.sender.track&&"video"===l.sender.track.kind){t?(t.enabled=e,yield l.sender.replaceTrack(t)):l.sender.track.enabled=e;const n=l.sender.getParameters();n.encodings&&n.encodings.length>0&&(n.encodings.forEach((e=>{e.maxBitrate=i?75e4:5e5})),yield l.sender.setParameters(n),o.info(`[184] [CallId: ${this.callId}] enableVideoOnPeerConnection: Set video max bitrate to ${i?75e4:5e5} kbps`,{color:"blue"}))}}}))}enableAudioOnPeerConnection(e,t){return n(this,void 0,void 0,(function*(){o.info(`[33] [CallId: ${this.callId}] enableAudioOnPeerConnection in webrtcClient: mute: ${e}, kind: ${null==t?void 0:t.kind}`,{color:"blue"});const i=this.peerConnection.getTransceivers();for(let n=0;n<i.length;n++){const a=i[n];a.sender.track&&"audio"===a.sender.track.kind&&(t?(t.enabled=!e,yield a.sender.replaceTrack(t)):a.sender.track.enabled=!e)}}))}createOffer(e,t,i){return n(this,void 0,void 0,(function*(){try{o.info(`[36] [CallId: ${this.callId}] createOffer in webrtcClient`,{color:"blue"});const n=yield this.peerConnection.createOffer({iceRestart:!0,offerToReceiveAudio:!0,offerToReceiveVideo:!0}),a=(0,r.toSessionData)({sdp:n,sessionId:e,versionId:t},i),l=(0,r.toSessionDescription)(a,"offer");return l?(yield this.setLocalDescription(l),a):(o.error(`[76] [CallId: ${this.callId}] createOffer in webrtcClient failed to convert session data to session description`,{color:"red"}),!1)}catch(e){return o.error(`[37] [CallId: ${this.callId}] createOffer in webrtcClient failed: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),!1}}))}createAnswer(e,t,i){return n(this,void 0,void 0,(function*(){try{o.info(`[75] [CallId: ${this.callId}] createAnswer in webrtcClient`,{color:"blue"});const n=yield this.peerConnection.createAnswer(),a=(0,r.toSessionData)({sdp:n,sessionId:e,versionId:t},i),l=(0,r.toSessionDescription)(a,"answer");return l?(yield this.setLocalDescription(l),a):(o.error(`[76] [CallId: ${this.callId}] createAnswer in webrtcClient failed to convert session data to session description`,{color:"red"}),!1)}catch(e){return o.error(`[70] [CallId: ${this.callId}] createAnswer in webrtcClient failed: ${e instanceof Error?e.message:JSON.stringify(e)}`,{color:"red"}),!1}}))}setLocalDescription(e){var t;return o.info(`[44] [CallId: ${this.callId}] setLocalDescription in webrtcClient: sdp sliced 50: ${null===(t=null==e?void 0:e.sdp)||void 0===t?void 0:t.slice(0,50)}...`,{color:"blue"}),this.peerConnection.setLocalDescription(e)}setRemoteDescription(e){var t;return o.info(`[48] [CallId: ${this.callId}] setRemoteDescription in webrtcClient: sdp sliced 50: ${null===(t=e.sdp)||void 0===t?void 0:t.slice(0,50)}...`,{color:"blue"}),this.peerConnection.setRemoteDescription(e)}getLocalSdpUfrag(){var e;const t=((null===(e=this.peerConnection.localDescription)||void 0===e?void 0:e.sdp)||"").match(/a=ice-ufrag:(\S+)/);return t?t[1]:null}getRemoteSdpUfrag(){var e;const t=((null===(e=this.peerConnection.remoteDescription)||void 0===e?void 0:e.sdp)||"").match(/a=ice-ufrag:(\S+)/);return t?t[1]:null}getIceCandidateUfrag(e){const t=e.match(/ufrag\s+(\S+)/);return t?t[1]:null}isUfragEqualsSdpUfrag(e){return{equals:this.getIceCandidateUfrag(e)===this.getRemoteSdpUfrag(),ufrag:this.getIceCandidateUfrag(e),sdpUfrag:this.getRemoteSdpUfrag()}}addIceCandidate(e,t){if(o.info(`[52] [CallId: ${this.callId}] addIceCandidate in webrtcClient: candidate: ${e.candidate}`,{color:"blue"}),e.candidate){const i=this.isUfragEqualsSdpUfrag(e.candidate);if(!i.equals)return this.iceQueueMap[t]||(this.iceQueueMap[t]={}),void(i.ufrag&&(this.iceQueueMap[t][i.ufrag]||(this.iceQueueMap[t][i.ufrag]=[]),this.iceQueueMap[t][i.ufrag].push(e)))}return this.peerConnection.addIceCandidate(e)}addEventListener(e,t){this.peerConnection.addEventListener(e,t)}removeEventListener(e,t){this.peerConnection.removeEventListener(e,t)}close(){o.info(`[56] [CallId: ${this.callId}] close in webrtcClient`,{color:"blue"}),this.peerConnection.close()}getConnectionStats(){return n(this,void 0,void 0,(function*(){return yield this.peerConnection.getStats()}))}}},297:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TypedEventEmitter=void 0,t.TypedEventEmitter=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var i;null===(i=this.listeners.get(e))||void 0===i||i.delete(t)}}emit(e,t){var i;null===(i=this.listeners.get(e))||void 0===i||i.forEach((i=>{try{i(t)}catch(t){console.error(`Error in event handler for "${String(e)}":`,t)}}))}off(e,t){var i;t?null===(i=this.listeners.get(e))||void 0===i||i.delete(t):this.listeners.delete(e)}removeAllListeners(){this.listeners.clear()}listenerCount(e){var t,i;return null!==(i=null===(t=this.listeners.get(e))||void 0===t?void 0:t.size)&&void 0!==i?i:0}}},578:(e,t)=>{"use strict";var i,n,a,l,s,r,o,d;Object.defineProperty(t,"__esModule",{value:!0}),t.CDRRequestDirection=t.CDRRequestEvent=t.CDRRequestOrder=t.MediaFlow=t.SignalEvent=t.CallState=t.ParticipantConnectionState=t.ParticipantState=void 0,function(e){e[e.Idle=0]="Idle",e[e.Ringing=1]="Ringing",e[e.Joined=2]="Joined",e[e.Left=3]="Left",e[e.Declined=4]="Declined",e[e.Kicked=5]="Kicked",e[e.NoAnswer=6]="NoAnswer"}(i||(t.ParticipantState=i={})),function(e){e[e.Idle=0]="Idle",e[e.Connecting=1]="Connecting",e[e.Connected=2]="Connected",e[e.Reconnecting=3]="Reconnecting",e[e.Disconnected=4]="Disconnected"}(n||(t.ParticipantConnectionState=n={})),function(e){e.Idle="idle",e.Connecting="connecting",e.Connected="connected",e.Closed="closed"}(a||(t.CallState=a={})),function(e){e[e.JOIN=0]="JOIN",e[e.LEAVE=1]="LEAVE",e[e.OFFER=2]="OFFER",e[e.ANSWER=3]="ANSWER",e[e.CONNECT=4]="CONNECT",e[e.ERROR=5]="ERROR",e[e.KICK=6]="KICK",e[e.SUCCESS=7]="SUCCESS",e[e.INVITE=8]="INVITE",e[e.DECLINE=9]="DECLINE",e[e.RINGING=10]="RINGING",e[e.INFO=11]="INFO",e[e.UPDATE=12]="UPDATE",e[e.CLOSE=13]="CLOSE",e[e.ICE=14]="ICE",e[e.GET_CALL=15]="GET_CALL",e[e.SWITCH_MEDIA_FLOW=16]="SWITCH_MEDIA_FLOW",e[e.NO_ANSWER=17]="NO_ANSWER",e[e.MEDIA_CONNECTED=18]="MEDIA_CONNECTED",e[e.MUTE=19]="MUTE",e[e.UNMUTE=20]="UNMUTE",e[e.HOLD=21]="HOLD",e[e.UNHOLD=22]="UNHOLD",e[e.VIDEO_ON=23]="VIDEO_ON",e[e.VIDEO_OFF=24]="VIDEO_OFF",e[e.SCREEN_SHARE_ON=25]="SCREEN_SHARE_ON",e[e.SCREEN_SHARE_OFF=26]="SCREEN_SHARE_OFF",e[e.CREATE=27]="CREATE",e[e.SESSION_RENEWED=28]="SESSION_RENEWED"}(l||(t.SignalEvent=l={})),function(e){e[e.P2P=0]="P2P",e[e.SFU=1]="SFU",e[e.S2W=2]="S2W"}(s||(t.MediaFlow=s={})),function(e){e[e.ASC=0]="ASC",e[e.DESC=1]="DESC"}(r||(t.CDRRequestOrder=r={})),function(e){e[e.GET_RECENT_CALLS=0]="GET_RECENT_CALLS",e[e.GET_CALLS_BY_SESSION_IDS=1]="GET_CALLS_BY_SESSION_IDS",e[e.DELETE_RECENT_CALLS=2]="DELETE_RECENT_CALLS"}(o||(t.CDRRequestEvent=o={})),function(e){e[e.NEXT=0]="NEXT",e[e.PREVIOUS=1]="PREVIOUS"}(d||(t.CDRRequestDirection=d={}))},489:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.makeFirstById=t.getEmptyVideoTrack=void 0,t.getEmptyVideoTrack=()=>{const e=document.createElement("canvas");return e.getContext("2d"),e.width=640,e.height=480,e.captureStream().getVideoTracks()},t.makeFirstById=(e,t,i)=>{const n=new Set,a=e.filter((e=>{const t=`${e.id}${e.clientId?`/${e.clientId}`:""}`;return!n.has(t)&&(n.add(t),!0)})),l=a.findIndex((e=>e.id===t&&(e.clientId===i||!e.clientId)));if(l>-1){const[e]=a.splice(l,1);a.unshift(e)}return a}},607:function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var a=Object.getOwnPropertyDescriptor(t,i);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,a)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),a=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});const l=i(838);a(i(838),t),t.default=l.SceytCallClient},838:function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var a=Object.getOwnPropertyDescriptor(t,i);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,a)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),a=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),t.CDRRequestDirection=t.CDRRequestEvent=t.CDRRequestOrder=t.ParticipantConnectionState=t.ParticipantState=t.CallState=t.MediaFlow=t.VideoTrack=t.AudioTrack=t.Participant=t.Call=void 0,a(i(271),t);var l=i(998);Object.defineProperty(t,"Call",{enumerable:!0,get:function(){return l.Call}});var s=i(787);Object.defineProperty(t,"Participant",{enumerable:!0,get:function(){return s.Participant}});var r=i(250);Object.defineProperty(t,"AudioTrack",{enumerable:!0,get:function(){return r.AudioTrack}});var o=i(740);Object.defineProperty(t,"VideoTrack",{enumerable:!0,get:function(){return o.VideoTrack}});var d=i(578);Object.defineProperty(t,"MediaFlow",{enumerable:!0,get:function(){return d.MediaFlow}}),Object.defineProperty(t,"CallState",{enumerable:!0,get:function(){return d.CallState}}),Object.defineProperty(t,"ParticipantState",{enumerable:!0,get:function(){return d.ParticipantState}}),Object.defineProperty(t,"ParticipantConnectionState",{enumerable:!0,get:function(){return d.ParticipantConnectionState}}),Object.defineProperty(t,"CDRRequestOrder",{enumerable:!0,get:function(){return d.CDRRequestOrder}}),Object.defineProperty(t,"CDRRequestEvent",{enumerable:!0,get:function(){return d.CDRRequestEvent}}),Object.defineProperty(t,"CDRRequestDirection",{enumerable:!0,get:function(){return d.CDRRequestDirection}}),a(i(645),t)},645:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createLogger=t.removeLogListener=t.addLogListener=void 0;const i={green:"[32m",blue:"[34m","light-green":"[34m","light-blue":"[34m",yellow:"[33m",magenta:"[35m",cyan:"[36m",reset:"[0m",orange:"[33m",red:"[31m",white:"[37m"},n=[];t.addLogListener=e=>{n.push(e)},t.removeLogListener=e=>{const t=n.indexOf(e);-1!==t&&n.splice(t,1)},t.createLogger=(e,t="white")=>{const a=`[SceytCallClient] ${e?`[${e}]`:""}:`,l=(e,l,s,r)=>{var o;const d=null!==(o=null==r?void 0:r.color)&&void 0!==o?o:t,c={level:e,message:l,prefix:a,args:s.filter((e=>!(null==e?void 0:e.color)&&!(null==e?void 0:e.time))),color:i[d],time:(null==r?void 0:r.time)||(new Date).toISOString()};n.forEach((e=>e(c)))};return{trace:(e,t)=>{l("trace",e,[],t)},debug:(e,t)=>{l("debug",e,[],t)},info:(e,t)=>{l("info",e,[],t)},warn:(e,t)=>{l("warn",e,[],t)},error:(e,t)=>{l("error",e,[],t)}}},t.default=(0,t.createLogger)("SceytCallClient")},429:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NIL",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(t,"parse",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(t,"v1",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(t,"v3",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(t,"v4",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(t,"v5",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(t,"validate",{enumerable:!0,get:function(){return d.default}}),Object.defineProperty(t,"version",{enumerable:!0,get:function(){return o.default}});var n=p(i(990)),a=p(i(237)),l=p(i(355)),s=p(i(764)),r=p(i(314)),o=p(i(464)),d=p(i(435)),c=p(i(8)),u=p(i(222));function p(e){return e&&e.__esModule?e:{default:e}}},163:(e,t)=>{"use strict";function i(e){return 14+(e+64>>>9<<4)+1}function n(e,t){const i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function a(e,t,i,a,l,s){return n((r=n(n(t,e),n(a,s)))<<(o=l)|r>>>32-o,i);var r,o}function l(e,t,i,n,l,s,r){return a(t&i|~t&n,e,t,l,s,r)}function s(e,t,i,n,l,s,r){return a(t&n|i&~n,e,t,l,s,r)}function r(e,t,i,n,l,s,r){return a(t^i^n,e,t,l,s,r)}function o(e,t,i,n,l,s,r){return a(i^(t|~n),e,t,l,s,r)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default=function(e){if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(let i=0;i<t.length;++i)e[i]=t.charCodeAt(i)}return function(e){const t=[],i=32*e.length,n="0123456789abcdef";for(let a=0;a<i;a+=8){const i=e[a>>5]>>>a%32&255,l=parseInt(n.charAt(i>>>4&15)+n.charAt(15&i),16);t.push(l)}return t}(function(e,t){e[t>>5]|=128<<t%32,e[i(t)-1]=t;let a=1732584193,d=-271733879,c=-1732584194,u=271733878;for(let t=0;t<e.length;t+=16){const i=a,p=d,g=c,h=u;a=l(a,d,c,u,e[t],7,-680876936),u=l(u,a,d,c,e[t+1],12,-389564586),c=l(c,u,a,d,e[t+2],17,606105819),d=l(d,c,u,a,e[t+3],22,-1044525330),a=l(a,d,c,u,e[t+4],7,-176418897),u=l(u,a,d,c,e[t+5],12,1200080426),c=l(c,u,a,d,e[t+6],17,-1473231341),d=l(d,c,u,a,e[t+7],22,-45705983),a=l(a,d,c,u,e[t+8],7,1770035416),u=l(u,a,d,c,e[t+9],12,-1958414417),c=l(c,u,a,d,e[t+10],17,-42063),d=l(d,c,u,a,e[t+11],22,-1990404162),a=l(a,d,c,u,e[t+12],7,1804603682),u=l(u,a,d,c,e[t+13],12,-40341101),c=l(c,u,a,d,e[t+14],17,-1502002290),d=l(d,c,u,a,e[t+15],22,1236535329),a=s(a,d,c,u,e[t+1],5,-165796510),u=s(u,a,d,c,e[t+6],9,-1069501632),c=s(c,u,a,d,e[t+11],14,643717713),d=s(d,c,u,a,e[t],20,-373897302),a=s(a,d,c,u,e[t+5],5,-701558691),u=s(u,a,d,c,e[t+10],9,38016083),c=s(c,u,a,d,e[t+15],14,-660478335),d=s(d,c,u,a,e[t+4],20,-405537848),a=s(a,d,c,u,e[t+9],5,568446438),u=s(u,a,d,c,e[t+14],9,-1019803690),c=s(c,u,a,d,e[t+3],14,-187363961),d=s(d,c,u,a,e[t+8],20,1163531501),a=s(a,d,c,u,e[t+13],5,-1444681467),u=s(u,a,d,c,e[t+2],9,-51403784),c=s(c,u,a,d,e[t+7],14,1735328473),d=s(d,c,u,a,e[t+12],20,-1926607734),a=r(a,d,c,u,e[t+5],4,-378558),u=r(u,a,d,c,e[t+8],11,-2022574463),c=r(c,u,a,d,e[t+11],16,1839030562),d=r(d,c,u,a,e[t+14],23,-35309556),a=r(a,d,c,u,e[t+1],4,-1530992060),u=r(u,a,d,c,e[t+4],11,1272893353),c=r(c,u,a,d,e[t+7],16,-155497632),d=r(d,c,u,a,e[t+10],23,-1094730640),a=r(a,d,c,u,e[t+13],4,681279174),u=r(u,a,d,c,e[t],11,-358537222),c=r(c,u,a,d,e[t+3],16,-722521979),d=r(d,c,u,a,e[t+6],23,76029189),a=r(a,d,c,u,e[t+9],4,-640364487),u=r(u,a,d,c,e[t+12],11,-421815835),c=r(c,u,a,d,e[t+15],16,530742520),d=r(d,c,u,a,e[t+2],23,-995338651),a=o(a,d,c,u,e[t],6,-198630844),u=o(u,a,d,c,e[t+7],10,1126891415),c=o(c,u,a,d,e[t+14],15,-1416354905),d=o(d,c,u,a,e[t+5],21,-57434055),a=o(a,d,c,u,e[t+12],6,1700485571),u=o(u,a,d,c,e[t+3],10,-1894986606),c=o(c,u,a,d,e[t+10],15,-1051523),d=o(d,c,u,a,e[t+1],21,-2054922799),a=o(a,d,c,u,e[t+8],6,1873313359),u=o(u,a,d,c,e[t+15],10,-30611744),c=o(c,u,a,d,e[t+6],15,-1560198380),d=o(d,c,u,a,e[t+13],21,1309151649),a=o(a,d,c,u,e[t+4],6,-145523070),u=o(u,a,d,c,e[t+11],10,-1120210379),c=o(c,u,a,d,e[t+2],15,718787259),d=o(d,c,u,a,e[t+9],21,-343485551),a=n(a,i),d=n(d,p),c=n(c,g),u=n(u,h)}return[a,d,c,u]}(function(e){if(0===e.length)return[];const t=8*e.length,n=new Uint32Array(i(t));for(let i=0;i<t;i+=8)n[i>>5]|=(255&e[i/8])<<i%32;return n}(e),8*e.length))}},790:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};t.default=i},314:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default="00000000-0000-0000-0000-000000000000"},222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,a=(n=i(435))&&n.__esModule?n:{default:n};t.default=function(e){if(!(0,a.default)(e))throw TypeError("Invalid UUID");let t;const i=new Uint8Array(16);return i[0]=(t=parseInt(e.slice(0,8),16))>>>24,i[1]=t>>>16&255,i[2]=t>>>8&255,i[3]=255&t,i[4]=(t=parseInt(e.slice(9,13),16))>>>8,i[5]=255&t,i[6]=(t=parseInt(e.slice(14,18),16))>>>8,i[7]=255&t,i[8]=(t=parseInt(e.slice(19,23),16))>>>8,i[9]=255&t,i[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,i[11]=t/4294967296&255,i[12]=t>>>24&255,i[13]=t>>>16&255,i[14]=t>>>8&255,i[15]=255&t,i}},58:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i},319:(e,t)=>{"use strict";let i;Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){if(!i&&(i="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!i))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(n)};const n=new Uint8Array(16)},757:(e,t)=>{"use strict";function i(e,t,i,n){switch(e){case 0:return t&i^~t&n;case 1:case 3:return t^i^n;case 2:return t&i^t&n^i&n}}function n(e,t){return e<<t|e>>>32-t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default=function(e){const t=[1518500249,1859775393,2400959708,3395469782],a=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=[];for(let i=0;i<t.length;++i)e.push(t.charCodeAt(i))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);const l=e.length/4+2,s=Math.ceil(l/16),r=new Array(s);for(let t=0;t<s;++t){const i=new Uint32Array(16);for(let n=0;n<16;++n)i[n]=e[64*t+4*n]<<24|e[64*t+4*n+1]<<16|e[64*t+4*n+2]<<8|e[64*t+4*n+3];r[t]=i}r[s-1][14]=8*(e.length-1)/Math.pow(2,32),r[s-1][14]=Math.floor(r[s-1][14]),r[s-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<s;++e){const l=new Uint32Array(80);for(let t=0;t<16;++t)l[t]=r[e][t];for(let e=16;e<80;++e)l[e]=n(l[e-3]^l[e-8]^l[e-14]^l[e-16],1);let s=a[0],o=a[1],d=a[2],c=a[3],u=a[4];for(let e=0;e<80;++e){const a=Math.floor(e/20),r=n(s,5)+i(a,o,d,c)+u+t[a]+l[e]>>>0;u=c,c=d,d=n(o,30)>>>0,o=s,s=r}a[0]=a[0]+s>>>0,a[1]=a[1]+o>>>0,a[2]=a[2]+d>>>0,a[3]=a[3]+c>>>0,a[4]=a[4]+u>>>0}return[a[0]>>24&255,a[0]>>16&255,a[0]>>8&255,255&a[0],a[1]>>24&255,a[1]>>16&255,a[1]>>8&255,255&a[1],a[2]>>24&255,a[2]>>16&255,a[2]>>8&255,255&a[2],a[3]>>24&255,a[3]>>16&255,a[3]>>8&255,255&a[3],a[4]>>24&255,a[4]>>16&255,a[4]>>8&255,255&a[4]]}},8:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.unsafeStringify=s;var n,a=(n=i(435))&&n.__esModule?n:{default:n};const l=[];for(let e=0;e<256;++e)l.push((e+256).toString(16).slice(1));function s(e,t=0){return l[e[t+0]]+l[e[t+1]]+l[e[t+2]]+l[e[t+3]]+"-"+l[e[t+4]]+l[e[t+5]]+"-"+l[e[t+6]]+l[e[t+7]]+"-"+l[e[t+8]]+l[e[t+9]]+"-"+l[e[t+10]]+l[e[t+11]]+l[e[t+12]]+l[e[t+13]]+l[e[t+14]]+l[e[t+15]]}t.default=function(e,t=0){const i=s(e,t);if(!(0,a.default)(i))throw TypeError("Stringified UUID is invalid");return i}},990:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,a=(n=i(319))&&n.__esModule?n:{default:n},l=i(8);let s,r,o=0,d=0;t.default=function(e,t,i){let n=t&&i||0;const c=t||new Array(16);let u=(e=e||{}).node||s,p=void 0!==e.clockseq?e.clockseq:r;if(null==u||null==p){const t=e.random||(e.rng||a.default)();null==u&&(u=s=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==p&&(p=r=16383&(t[6]<<8|t[7]))}let g=void 0!==e.msecs?e.msecs:Date.now(),h=void 0!==e.nsecs?e.nsecs:d+1;const v=g-o+(h-d)/1e4;if(v<0&&void 0===e.clockseq&&(p=p+1&16383),(v<0||g>o)&&void 0===e.nsecs&&(h=0),h>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");o=g,d=h,r=p,g+=122192928e5;const S=(1e4*(268435455&g)+h)%4294967296;c[n++]=S>>>24&255,c[n++]=S>>>16&255,c[n++]=S>>>8&255,c[n++]=255&S;const C=g/4294967296*1e4&268435455;c[n++]=C>>>8&255,c[n++]=255&C,c[n++]=C>>>24&15|16,c[n++]=C>>>16&255,c[n++]=p>>>8|128,c[n++]=255&p;for(let e=0;e<6;++e)c[n+e]=u[e];return t||(0,l.unsafeStringify)(c)}},237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=l(i(925)),a=l(i(163));function l(e){return e&&e.__esModule?e:{default:e}}var s=(0,n.default)("v3",48,a.default);t.default=s},925:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.URL=t.DNS=void 0,t.default=function(e,t,i){function n(e,n,s,r){var o;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));const t=[];for(let i=0;i<e.length;++i)t.push(e.charCodeAt(i));return t}(e)),"string"==typeof n&&(n=(0,l.default)(n)),16!==(null===(o=n)||void 0===o?void 0:o.length))throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let d=new Uint8Array(16+e.length);if(d.set(n),d.set(e,n.length),d=i(d),d[6]=15&d[6]|t,d[8]=63&d[8]|128,s){r=r||0;for(let e=0;e<16;++e)s[r+e]=d[e];return s}return(0,a.unsafeStringify)(d)}try{n.name=e}catch(e){}return n.DNS=s,n.URL=r,n};var n,a=i(8),l=(n=i(222))&&n.__esModule?n:{default:n};const s="6ba7b810-9dad-11d1-80b4-00c04fd430c8";t.DNS=s;const r="6ba7b811-9dad-11d1-80b4-00c04fd430c8";t.URL=r},355:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=s(i(790)),a=s(i(319)),l=i(8);function s(e){return e&&e.__esModule?e:{default:e}}t.default=function(e,t,i){if(n.default.randomUUID&&!t&&!e)return n.default.randomUUID();const s=(e=e||{}).random||(e.rng||a.default)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){i=i||0;for(let e=0;e<16;++e)t[i+e]=s[e];return t}return(0,l.unsafeStringify)(s)}},764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=l(i(925)),a=l(i(757));function l(e){return e&&e.__esModule?e:{default:e}}var s=(0,n.default)("v5",80,a.default);t.default=s},435:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,a=(n=i(58))&&n.__esModule?n:{default:n};t.default=function(e){return"string"==typeof e&&a.default.test(e)}},464:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,a=(n=i(435))&&n.__esModule?n:{default:n};t.default=function(e){if(!(0,a.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}},583:function(e,t){var i;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,i=function(){var e={};return function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function i(e,t,i){this.low=0|e,this.high=0|t,this.unsigned=!!i}function n(e){return!0===(e&&e.__isLong__)}function a(e){var t=Math.clz32(e&-e);return e?31-t:t}i.prototype.__isLong__,Object.defineProperty(i.prototype,"__isLong__",{value:!0}),i.isLong=n;var l={},s={};function r(e,t){var i,n,a;return t?(a=0<=(e>>>=0)&&e<256)&&(n=s[e])?n:(i=d(e,0,!0),a&&(s[e]=i),i):(a=-128<=(e|=0)&&e<128)&&(n=l[e])?n:(i=d(e,e<0?-1:0,!1),a&&(l[e]=i),i)}function o(e,t){if(isNaN(e))return t?f:C;if(t){if(e<0)return f;if(e>=h)return $}else{if(e<=-v)return y;if(e+1>=v)return P}return e<0?o(-e,t).neg():d(e%g|0,e/g|0,t)}function d(e,t,n){return new i(e,t,n)}i.fromInt=r,i.fromNumber=o,i.fromBits=d;var c=Math.pow;function u(e,t,i){if(0===e.length)throw Error("empty string");if("number"==typeof t?(i=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?f:C;if((i=i||10)<2||36<i)throw RangeError("radix");var n;if((n=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===n)return u(e.substring(1),t,i).neg();for(var a=o(c(i,8)),l=C,s=0;s<e.length;s+=8){var r=Math.min(8,e.length-s),d=parseInt(e.substring(s,s+r),i);if(r<8){var p=o(c(i,r));l=l.mul(p).add(o(d))}else l=(l=l.mul(a)).add(o(d))}return l.unsigned=t,l}function p(e,t){return"number"==typeof e?o(e,t):"string"==typeof e?u(e,t):d(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}i.fromString=u,i.fromValue=p;var g=4294967296,h=g*g,v=h/2,S=r(1<<24),C=r(0);i.ZERO=C;var f=r(0,!0);i.UZERO=f;var I=r(1);i.ONE=I;var E=r(1,!0);i.UONE=E;var m=r(-1);i.NEG_ONE=m;var P=d(-1,2147483647,!1);i.MAX_VALUE=P;var $=d(-1,-1,!0);i.MAX_UNSIGNED_VALUE=$;var y=d(0,-2147483648,!1);i.MIN_VALUE=y;var T=i.prototype;T.toInt=function(){return this.unsigned?this.low>>>0:this.low},T.toNumber=function(){return this.unsigned?(this.high>>>0)*g+(this.low>>>0):this.high*g+(this.low>>>0)},T.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(y)){var t=o(e),i=this.div(t),n=i.mul(t).sub(this);return i.toString(e)+n.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var a=o(c(e,6),this.unsigned),l=this,s="";;){var r=l.div(a),d=(l.sub(r.mul(a)).toInt()>>>0).toString(e);if((l=r).isZero())return d+s;for(;d.length<6;)d="0"+d;s=""+d+s}},T.getHighBits=function(){return this.high},T.getHighBitsUnsigned=function(){return this.high>>>0},T.getLowBits=function(){return this.low},T.getLowBitsUnsigned=function(){return this.low>>>0},T.getNumBitsAbs=function(){if(this.isNegative())return this.eq(y)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},T.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&-1===e&&!(0===this.low&&-2097152===this.high)},T.isZero=function(){return 0===this.high&&0===this.low},T.eqz=T.isZero,T.isNegative=function(){return!this.unsigned&&this.high<0},T.isPositive=function(){return this.unsigned||this.high>=0},T.isOdd=function(){return 1==(1&this.low)},T.isEven=function(){return 0==(1&this.low)},T.equals=function(e){return n(e)||(e=p(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},T.eq=T.equals,T.notEquals=function(e){return!this.eq(e)},T.neq=T.notEquals,T.ne=T.notEquals,T.lessThan=function(e){return this.comp(e)<0},T.lt=T.lessThan,T.lessThanOrEqual=function(e){return this.comp(e)<=0},T.lte=T.lessThanOrEqual,T.le=T.lessThanOrEqual,T.greaterThan=function(e){return this.comp(e)>0},T.gt=T.greaterThan,T.greaterThanOrEqual=function(e){return this.comp(e)>=0},T.gte=T.greaterThanOrEqual,T.ge=T.greaterThanOrEqual,T.compare=function(e){if(n(e)||(e=p(e)),this.eq(e))return 0;var t=this.isNegative(),i=e.isNegative();return t&&!i?-1:!t&&i?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},T.comp=T.compare,T.negate=function(){return!this.unsigned&&this.eq(y)?y:this.not().add(I)},T.neg=T.negate,T.add=function(e){n(e)||(e=p(e));var t=this.high>>>16,i=65535&this.high,a=this.low>>>16,l=65535&this.low,s=e.high>>>16,r=65535&e.high,o=e.low>>>16,c=0,u=0,g=0,h=0;return g+=(h+=l+(65535&e.low))>>>16,u+=(g+=a+o)>>>16,c+=(u+=i+r)>>>16,c+=t+s,d((g&=65535)<<16|(h&=65535),(c&=65535)<<16|(u&=65535),this.unsigned)},T.subtract=function(e){return n(e)||(e=p(e)),this.add(e.neg())},T.sub=T.subtract,T.multiply=function(e){if(this.isZero())return this;if(n(e)||(e=p(e)),t)return d(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return this.unsigned?f:C;if(this.eq(y))return e.isOdd()?y:C;if(e.eq(y))return this.isOdd()?y:C;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(S)&&e.lt(S))return o(this.toNumber()*e.toNumber(),this.unsigned);var i=this.high>>>16,a=65535&this.high,l=this.low>>>16,s=65535&this.low,r=e.high>>>16,c=65535&e.high,u=e.low>>>16,g=65535&e.low,h=0,v=0,I=0,E=0;return I+=(E+=s*g)>>>16,v+=(I+=l*g)>>>16,I&=65535,v+=(I+=s*u)>>>16,h+=(v+=a*g)>>>16,v&=65535,h+=(v+=l*u)>>>16,v&=65535,h+=(v+=s*c)>>>16,h+=i*g+a*u+l*c+s*r,d((I&=65535)<<16|(E&=65535),(h&=65535)<<16|(v&=65535),this.unsigned)},T.mul=T.multiply,T.divide=function(e){if(n(e)||(e=p(e)),e.isZero())throw Error("division by zero");var i,a,l;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?d((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?f:C;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return f;if(e.gt(this.shru(1)))return E;l=f}else{if(this.eq(y))return e.eq(I)||e.eq(m)?y:e.eq(y)?I:(i=this.shr(1).div(e).shl(1)).eq(C)?e.isNegative()?I:m:(a=this.sub(e.mul(i)),l=i.add(a.div(e)));if(e.eq(y))return this.unsigned?f:C;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();l=C}for(a=this;a.gte(e);){i=Math.max(1,Math.floor(a.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(i)/Math.LN2),r=s<=48?1:c(2,s-48),u=o(i),g=u.mul(e);g.isNegative()||g.gt(a);)g=(u=o(i-=r,this.unsigned)).mul(e);u.isZero()&&(u=I),l=l.add(u),a=a.sub(g)}return l},T.div=T.divide,T.modulo=function(e){return n(e)||(e=p(e)),t?d((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},T.mod=T.modulo,T.rem=T.modulo,T.not=function(){return d(~this.low,~this.high,this.unsigned)},T.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},T.clz=T.countLeadingZeros,T.countTrailingZeros=function(){return this.low?a(this.low):a(this.high)+32},T.ctz=T.countTrailingZeros,T.and=function(e){return n(e)||(e=p(e)),d(this.low&e.low,this.high&e.high,this.unsigned)},T.or=function(e){return n(e)||(e=p(e)),d(this.low|e.low,this.high|e.high,this.unsigned)},T.xor=function(e){return n(e)||(e=p(e)),d(this.low^e.low,this.high^e.high,this.unsigned)},T.shiftLeft=function(e){return n(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):d(0,this.low<<e-32,this.unsigned)},T.shl=T.shiftLeft,T.shiftRight=function(e){return n(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):d(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},T.shr=T.shiftRight,T.shiftRightUnsigned=function(e){return n(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):d(32===e?this.high:this.high>>>e-32,0,this.unsigned)},T.shru=T.shiftRightUnsigned,T.shr_u=T.shiftRightUnsigned,T.rotateLeft=function(e){var t;return n(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),d(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},T.rotl=T.rotateLeft,T.rotateRight=function(e){var t;return n(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),d(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},T.rotr=T.rotateRight,T.toSigned=function(){return this.unsigned?d(this.low,this.high,!1):this},T.toUnsigned=function(){return this.unsigned?this:d(this.low,this.high,!0)},T.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},T.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},T.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},i.fromBytes=function(e,t,n){return n?i.fromBytesLE(e,t):i.fromBytesBE(e,t)},i.fromBytesLE=function(e,t){return new i(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},i.fromBytesBE=function(e,t){return new i(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(i.fromBigInt=function(e,t){return d(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},i.fromValue=function(e,t){return"bigint"==typeof e?i.fromBigInt(e,t):p(e,t)},T.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e}),e.default=i}(e),function(e){return e.default||e}(e)}.apply(t,[]),void 0===i||(e.exports=i)}},t={},function i(n){var a=t[n];if(void 0!==a)return a.exports;var l=t[n]={exports:{}};return e[n].call(l.exports,l,l.exports,i),l.exports}(607);var e,t}));
|