sip-connector 20.6.0 → 20.6.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/dist/{@SipConnector-nmoTV9l_.js → @SipConnector-B4noAdXF.js} +2 -2
- package/dist/{@SipConnector-BVCkiu8l.cjs → @SipConnector-C09GtMW6.cjs} +1 -1
- package/dist/ConnectionManager/events.d.ts +2 -2
- package/dist/doMock.cjs +1 -1
- package/dist/doMock.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/package.json +5 -5
|
@@ -2707,8 +2707,8 @@ class xt extends q {
|
|
|
2707
2707
|
};
|
|
2708
2708
|
}
|
|
2709
2709
|
handleRegistrationFailed = (e) => {
|
|
2710
|
-
const
|
|
2711
|
-
this.toFailed(
|
|
2710
|
+
const t = e.response?.status_code ?? "Unknown", s = e.response?.reason_phrase ?? "Registration failed", i = new Error(`Registration failed: ${t} ${s}`);
|
|
2711
|
+
this.toFailed(i);
|
|
2712
2712
|
};
|
|
2713
2713
|
handleConnectFailed = (e) => {
|
|
2714
2714
|
this.toFailed(e instanceof Error ? e : void 0);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const J=require("debug"),I=require("events-constructor"),B=require("@krivega/cancelable-promise"),L=require("@krivega/timeout-requester"),z=require("repeated-calls"),N=require("xstate"),K=require("stack-promises");require("ua-parser-js");require("sequent-promises");const Je=require("lodash"),j="sip-connector",d=J(j),ze=()=>{J.enable(j)},Ke=()=>{J.enable(`-${j}`)},je="Error decline with 603",Ze=1006,et=n=>typeof n=="object"&&n!==null&&"code"in n&&n.code===Ze,tt=n=>n.message===je;var g=(n=>(n.CONTENT_TYPE="content-type",n.CONTENT_ENTER_ROOM="x-webrtc-enter-room",n.CONTENT_USE_LICENSE="X-WEBRTC-USE-LICENSE",n.PARTICIPANT_NAME="X-WEBRTC-PARTICIPANT-NAME",n.INPUT_CHANNELS="X-WEBRTC-INPUT-CHANNELS",n.OUTPUT_CHANNELS="X-WEBRTC-OUTPUT-CHANNELS",n.MAIN_CAM="X-WEBRTC-MAINCAM",n.MIC="X-WEBRTC-MIC",n.MEDIA_SYNC="X-WEBRTC-SYNC",n.MAIN_CAM_RESOLUTION="X-WEBRTC-MAINCAM-RESOLUTION",n.MEDIA_STATE="X-WEBRTC-MEDIA-STATE",n.MEDIA_TYPE="X-Vinteo-Media-Type",n.MAIN_CAM_STATE="X-Vinteo-MainCam-State",n.MIC_STATE="X-Vinteo-Mic-State",n.CONTENT_PARTICIPANT_STATE="X-WEBRTC-PARTSTATE",n.NOTIFY="X-VINTEO-NOTIFY",n.CONTENT_ENABLE_MEDIA_DEVICE="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",n.CONTENT_SHARE_STATE="x-webrtc-share-state",n.MUST_STOP_PRESENTATION_P2P="x-webrtc-share-state: YOUMUSTSTOPSENDCONTENT",n.START_PRESENTATION_P2P="x-webrtc-share-state: YOUCANRECEIVECONTENT",n.STOP_PRESENTATION_P2P="x-webrtc-share-state: CONTENTEND",n.STOP_PRESENTATION="x-webrtc-share-state: STOPPRESENTATION",n.START_PRESENTATION="x-webrtc-share-state: LETMESTARTPRESENTATION",n.ENABLE_MAIN_CAM="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM",n.AVAILABLE_INCOMING_BITRATE="X-WEBRTC-AVAILABLE-INCOMING-BITRATE",n.AUDIO_TRACK_COUNT="X-WEBRTC-AUDIO-TRACK-COUNT",n.VIDEO_TRACK_COUNT="X-WEBRTC-VIDEO-TRACK-COUNT",n.TRACKS_DIRECTION="X-WEBRTC-TRACKS-DIRECTION",n.AUDIO_ID="X-WEBRTC-AUDIOID",n))(g||{}),G=(n=>(n.AVAILABLE_SECOND_REMOTE_STREAM="YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="CONTENTEND",n.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",n))(G||{}),x=(n=>(n.SPECTATOR="SPECTATOR",n.PARTICIPANT="PARTICIPANT",n))(x||{}),y=(n=>(n.ENTER_ROOM="application/vinteo.webrtc.roomname",n.MIC="application/vinteo.webrtc.mic",n.USE_LICENSE="application/vinteo.webrtc.uselic",n.PARTICIPANT_STATE="application/vinteo.webrtc.partstate",n.NOTIFY="application/vinteo.webrtc.notify",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n))(y||{}),f=(n=>(n.CHANNELS="application/vinteo.webrtc.channels",n.MEDIA_STATE="application/vinteo.webrtc.mediastate",n.REFUSAL="application/vinteo.webrtc.refusal",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.STATS="application/vinteo.webrtc.stats",n))(f||{}),_=(n=>(n.PAUSE_MAIN_CAM="PAUSEMAINCAM",n.RESUME_MAIN_CAM="RESUMEMAINCAM",n.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",n.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",n.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",n))(_||{}),Q=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(Q||{}),Y=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(Y||{}),ge=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(ge||{}),l=(n=>(n.CHANNELS_NOTIFY="channels:notify",n.PARTICIPANT_ADDED_TO_LIST_MODERATORS="participant:added-to-list-moderators",n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS="participant:removed-from-list-moderators",n.PARTICIPANT_MOVE_REQUEST_TO_STREAM="participant:move-request-to-stream",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS="participant:move-request-to-spectators",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_SYNTHETIC="participant:move-request-to-spectators-synthetic",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_WITH_AUDIO_ID="participant:move-request-to-spectators-with-audio-id",n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS="participant:move-request-to-participants",n.PARTICIPATION_ACCEPTING_WORD_REQUEST="participation:accepting-word-request",n.PARTICIPATION_CANCELLING_WORD_REQUEST="participation:cancelling-word-request",n.WEBCAST_STARTED="webcast:started",n.WEBCAST_STOPPED="webcast:stopped",n.ACCOUNT_CHANGED="account:changed",n.ACCOUNT_DELETED="account:deleted",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="conference:participant-token-issued",n.CHANNELS="channels",n.ENTER_ROOM="enterRoom",n.SHARE_STATE="shareState",n.MAIN_CAM_CONTROL="main-cam-control",n.USE_LICENSE="useLicense",n.ADMIN_START_MAIN_CAM="admin-start-main-cam",n.ADMIN_STOP_MAIN_CAM="admin-stop-main-cam",n.ADMIN_START_MIC="admin-start-mic",n.ADMIN_STOP_MIC="admin-stop-mic",n.ADMIN_FORCE_SYNC_MEDIA_STATE="admin-force-sync-media-state",n.AVAILABLE_SECOND_REMOTE_STREAM="availableSecondRemoteStream",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="notAvailableSecondRemoteStream",n.MUST_STOP_PRESENTATION="mustStopPresentation",n.NEW_DTMF="newDTMF",n))(l||{});const ue=["participation:accepting-word-request","participation:cancelling-word-request","participant:move-request-to-stream","channels:notify","conference:participant-token-issued","account:changed","account:deleted","webcast:started","webcast:stopped","participant:added-to-list-moderators","participant:removed-from-list-moderators","participant:move-request-to-spectators","participant:move-request-to-spectators-synthetic","participant:move-request-to-spectators-with-audio-id","participant:move-request-to-participants","channels","enterRoom","shareState","main-cam-control","useLicense","admin-start-main-cam","admin-stop-main-cam","admin-start-mic","admin-stop-mic","admin-force-sync-media-state","availableSecondRemoteStream","notAvailableSecondRemoteStream","mustStopPresentation","newDTMF"],nt=()=>new I.TypedEvents(ue);var A=(n=>(n.CHANNELS="channels",n.WEBCAST_STARTED="WebcastStarted",n.WEBCAST_STOPPED="WebcastStopped",n.ACCOUNT_CHANGED="accountChanged",n.ACCOUNT_DELETED="accountDeleted",n.ADDED_TO_LIST_MODERATORS="addedToListModerators",n.REMOVED_FROM_LIST_MODERATORS="removedFromListModerators",n.ACCEPTING_WORD_REQUEST="ParticipationRequestAccepted",n.CANCELLING_WORD_REQUEST="ParticipationRequestRejected",n.MOVE_REQUEST_TO_STREAM="ParticipantMovedToWebcast",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="ConferenceParticipantTokenIssued",n))(A||{});class st{events;connectionManager;callManager;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.callManager=t,this.events=nt(),this.subscribe()}async waitChannels(){return this.wait(l.CHANNELS)}async waitSyncMediaState(){return this.wait(l.ADMIN_FORCE_SYNC_MEDIA_STATE)}async sendDTMF(e){return new Promise((t,s)=>{let i;try{i=this.getEstablishedRTCSessionProtected()}catch(r){s(r)}i&&(this.callManager.once("newDTMF",({originator:r})=>{r==="local"&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600}))})}async sendChannels({inputChannels:e,outputChannels:t}){const s=this.getEstablishedRTCSessionProtected(),i=`${g.INPUT_CHANNELS}: ${e}`,r=`${g.OUTPUT_CHANNELS}: ${t}`,a=[i,r];return s.sendInfo(f.CHANNELS,void 0,{extraHeaders:a})}async sendMediaState({cam:e,mic:t},s={}){const i=this.getEstablishedRTCSessionProtected(),r=`${g.MEDIA_STATE}: currentstate`,a=`${g.MAIN_CAM_STATE}: ${Number(e)}`,o=`${g.MIC_STATE}: ${Number(t)}`,c=[r,a,o];return i.sendInfo(f.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendStats({availableIncomingBitrate:e}){const t=this.getEstablishedRTCSessionProtected(),i=[`${g.AVAILABLE_INCOMING_BITRATE}: ${e}`];return t.sendInfo(f.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:i})}async sendRefusalToTurnOn(e,t={}){const s=this.getEstablishedRTCSessionProtected(),a=e==="mic"?0:1,c=[`${g.MEDIA_TYPE}: ${a}`];return s.sendInfo(f.REFUSAL,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendMustStopPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(f.SHARE_STATE,void 0,{extraHeaders:[g.MUST_STOP_PRESENTATION_P2P]})}async sendStoppedPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(f.SHARE_STATE,void 0,{extraHeaders:[g.STOP_PRESENTATION_P2P]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(f.SHARE_STATE,void 0,{extraHeaders:[g.STOP_PRESENTATION]})}async askPermissionToStartPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(f.SHARE_STATE,void 0,{extraHeaders:[g.START_PRESENTATION_P2P]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(f.SHARE_STATE,void 0,{extraHeaders:[g.START_PRESENTATION]})}async askPermissionToEnableCam(e={}){const t=this.getEstablishedRTCSessionProtected(),s=[g.ENABLE_MAIN_CAM];return t.sendInfo(f.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(i=>{if(tt(i))throw i})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}getEstablishedRTCSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};subscribe(){this.connectionManager.on("sipEvent",this.handleSipEvent),this.callManager.on("newInfo",this.handleNewInfo),this.callManager.on("newDTMF",e=>{this.events.trigger("newDTMF",e)})}handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{try{const t=e.getHeader(g.NOTIFY);if(t){const s=JSON.parse(t);this.handleNotify(s)}}catch(t){d("error parse notify",t)}};handleNotify=e=>{switch(e.cmd){case A.CHANNELS:{const t=e;this.triggerChannelsNotify(t);break}case A.WEBCAST_STARTED:{const t=e;this.triggerWebcastStartedNotify(t);break}case A.WEBCAST_STOPPED:{const t=e;this.triggerWebcastStoppedNotify(t);break}case A.ADDED_TO_LIST_MODERATORS:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case A.REMOVED_FROM_LIST_MODERATORS:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case A.ACCEPTING_WORD_REQUEST:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case A.CANCELLING_WORD_REQUEST:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case A.MOVE_REQUEST_TO_STREAM:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case A.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case A.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case A.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:d("unknown cmd",e)}};handleNewInfo=e=>{const{originator:t}=e;if(t!=="remote")return;const{request:s}=e,i=s,r=i.getHeader(g.CONTENT_TYPE);if(r!==void 0)switch(r){case y.ENTER_ROOM:{this.triggerEnterRoom(i),this.maybeTriggerChannels(i);break}case y.NOTIFY:{this.maybeHandleNotify(i);break}case y.SHARE_STATE:{this.triggerShareState(i);break}case y.MAIN_CAM:{this.triggerMainCamControl(i);break}case y.MIC:{this.triggerMicControl(i);break}case y.USE_LICENSE:{this.triggerUseLicense(i);break}case y.PARTICIPANT_STATE:{this.maybeTriggerParticipantMoveRequest(i);break}}};triggerChannelsNotify=e=>{const t=e.input,s=e.output,i={inputChannels:t,outputChannels:s};this.events.trigger(l.CHANNELS_NOTIFY,i)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(l.WEBCAST_STARTED,s)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(l.WEBCAST_STOPPED,s)};triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(l.PARTICIPANT_ADDED_TO_LIST_MODERATORS,t)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(l.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,t)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(l.PARTICIPATION_ACCEPTING_WORD_REQUEST,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(l.PARTICIPATION_CANCELLING_WORD_REQUEST,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_STREAM,t)};triggerAccountChangedNotify=()=>{this.events.trigger(l.ACCOUNT_CHANGED,{})};triggerAccountDeletedNotify=()=>{this.events.trigger(l.ACCOUNT_DELETED,{})};triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const i={conference:e,participant:t,jwt:s};this.events.trigger(l.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,i)};maybeTriggerChannels=e=>{const t=e.getHeader(g.INPUT_CHANNELS),s=e.getHeader(g.OUTPUT_CHANNELS);if(t&&s){const i={inputChannels:t,outputChannels:s};this.events.trigger(l.CHANNELS,i)}};triggerEnterRoom=e=>{const t=e.getHeader(g.CONTENT_ENTER_ROOM),s=e.getHeader(g.PARTICIPANT_NAME);this.events.trigger(l.ENTER_ROOM,{room:t,participantName:s})};triggerShareState=e=>{const t=e.getHeader(g.CONTENT_SHARE_STATE);if(t!==void 0)switch(t){case G.AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(l.AVAILABLE_SECOND_REMOTE_STREAM,{});break}case G.NOT_AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(l.NOT_AVAILABLE_SECOND_REMOTE_STREAM,{});break}case G.MUST_STOP_PRESENTATION:{this.events.trigger(l.MUST_STOP_PRESENTATION,{});break}}};maybeTriggerParticipantMoveRequest=e=>{const t=e.getHeader(g.CONTENT_PARTICIPANT_STATE),s=e.getHeader(g.AUDIO_ID);t===x.SPECTATOR&&(s?(this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_WITH_AUDIO_ID,{audioId:s}),this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,{isSynthetic:!1,audioId:s})):(this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_SYNTHETIC,{}),this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,{isSynthetic:!0}))),t===x.PARTICIPANT&&this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,{})};triggerMainCamControl=e=>{const t=e.getHeader(g.MAIN_CAM),s=e.getHeader(g.MEDIA_SYNC),i=s===Y.ADMIN_SYNC_FORCED;if(t===_.ADMIN_START_MAIN_CAM){this.events.trigger(l.ADMIN_START_MAIN_CAM,{isSyncForced:i});return}if(t===_.ADMIN_STOP_MAIN_CAM){this.events.trigger(l.ADMIN_STOP_MAIN_CAM,{isSyncForced:i});return}(t===_.RESUME_MAIN_CAM||t===_.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger(l.ADMIN_FORCE_SYNC_MEDIA_STATE,{isSyncForced:i});const r=e.getHeader(g.MAIN_CAM_RESOLUTION);this.events.trigger(l.MAIN_CAM_CONTROL,{mainCam:t,resolutionMainCam:r})};triggerMicControl=e=>{const t=e.getHeader(g.MIC),i=e.getHeader(g.MEDIA_SYNC)===Y.ADMIN_SYNC_FORCED;t===Q.ADMIN_START_MIC?this.events.trigger(l.ADMIN_START_MIC,{isSyncForced:i}):t===Q.ADMIN_STOP_MIC&&this.events.trigger(l.ADMIN_STOP_MIC,{isSyncForced:i})};triggerUseLicense=e=>{const t=e.getHeader(g.CONTENT_USE_LICENSE);this.events.trigger(l.USE_LICENSE,t)}}class q{actor;subscriptions=[];constructor(e){this.actor=N.createActor(e),this.actor.start()}get actorRef(){return this.actor}get state(){return this.getSnapshot().value}send(e){this.actor.send(e)}getSnapshot(){return this.actor.getSnapshot()}subscribe(e){const t=this.actor.subscribe(e);return this.addSubscription(t),t}stop(){this.subscriptions.forEach(e=>{e()}),this.subscriptions.length=0,this.actor.stop()}addSubscription(e){const t=typeof e=="function"?e:()=>{e.unsubscribe()};return this.subscriptions.push(t),t}}var Te=(n=>(n.IDLE="call:idle",n.CONNECTING="call:connecting",n.ACCEPTED="call:accepted",n.IN_CALL="call:inCall",n.ENDED="call:ended",n.FAILED="call:failed",n))(Te||{});const it=N.setup({types:{context:{},events:{}},actions:{rememberError:N.assign(({event:n})=>"error"in n&&n.error!==void 0?{lastError:n.error instanceof Error?n.error:new Error(JSON.stringify(n.error))}:{lastError:void 0}),resetError:N.assign({lastError:void 0})}}).createMachine({id:"call",initial:"call:idle",context:{},states:{"call:idle":{on:{"CALL.CONNECTING":{target:"call:connecting",actions:"resetError"}}},"call:connecting":{on:{"CALL.ACCEPTED":"call:accepted","CALL.ENDED":"call:ended","CALL.FAILED":{target:"call:failed",actions:"rememberError"}}},"call:accepted":{on:{"CALL.CONFIRMED":"call:inCall","CALL.ENDED":"call:ended","CALL.FAILED":{target:"call:failed",actions:"rememberError"}}},"call:inCall":{on:{"CALL.ENDED":"call:ended","CALL.FAILED":{target:"call:failed",actions:"rememberError"}}},"call:ended":{on:{"CALL.RESET":{target:"call:idle",actions:"resetError"},"CALL.CONNECTING":{target:"call:connecting",actions:"resetError"}}},"call:failed":{on:{"CALL.RESET":{target:"call:idle",actions:"resetError"},"CALL.CONNECTING":{target:"call:connecting",actions:"resetError"},"CALL.ENDED":{target:"call:ended",actions:"resetError"}}}}});class rt extends q{constructor(e){super(it),this.subscribeToEvents(e)}get isIdle(){return this.state==="call:idle"}get isConnecting(){return this.state==="call:connecting"}get isAccepted(){return this.state==="call:accepted"}get isInCall(){return this.state==="call:inCall"}get isEnded(){return this.state==="call:ended"}get isFailed(){return this.state==="call:failed"}get isActive(){return this.isAccepted||this.isInCall}get isPending(){return this.isConnecting}get lastError(){return this.getSnapshot().context.lastError}reset(){this.send({type:"CALL.RESET"})}send(e){if(!this.getSnapshot().can(e)){console.warn(`[CallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeToEvents(e){this.addSubscription(e.on("connecting",()=>{this.send({type:"CALL.CONNECTING"})})),this.addSubscription(e.on("accepted",()=>{this.send({type:"CALL.ACCEPTED"})})),this.addSubscription(e.on("confirmed",()=>{this.send({type:"CALL.CONFIRMED"})})),this.addSubscription(e.on("ended",()=>{this.send({type:"CALL.ENDED"})})),this.addSubscription(e.on("failed",t=>{this.send({type:"CALL.FAILED",error:t})}))}}var S=(n=>(n.PEER_CONNECTION="peerconnection",n.CONNECTING="connecting",n.SENDING="sending",n.PROGRESS="progress",n.ACCEPTED="accepted",n.CONFIRMED="confirmed",n.ENDED="ended",n.FAILED="failed",n.NEW_DTMF="newDTMF",n.NEW_INFO="newInfo",n.HOLD="hold",n.UNHOLD="unhold",n.MUTED="muted",n.UNMUTED="unmuted",n.REINVITE="reinvite",n.UPDATE="update",n.REFER="refer",n.REPLACES="replaces",n.SDP="sdp",n.ICE_CANDIDATE="icecandidate",n.GET_USER_MEDIA_FAILED="getusermediafailed",n.PEER_CONNECTION_CREATE_OFFER_FAILED="peerconnection:createofferfailed",n.PEER_CONNECTION_CREATE_ANSWER_FAILED="peerconnection:createanswerfailed",n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED="peerconnection:setlocaldescriptionfailed",n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED="peerconnection:setremotedescriptionfailed",n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n.PEER_CONNECTION_CONFIRMED="peerconnection:confirmed",n.PEER_CONNECTION_ONTRACK="peerconnection:ontrack",n.ENDED_FROM_SERVER="ended:fromserver",n.CALL_STATUS_CHANGED="call-status-changed",n.REMOTE_STREAMS_CHANGED="remote-streams-changed",n))(S||{}),Ee=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(Ee||{});const Se=["peerconnection","connecting","sending","progress","accepted","confirmed","ended","failed","hold","unhold","muted","unmuted","newInfo","newDTMF","presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed","reinvite","update","refer","replaces","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed"],at=["peerconnection:confirmed","peerconnection:ontrack","ended:fromserver","call-status-changed","remote-streams-changed"],pe=[...Se,...at],ot=()=>new I.TypedEvents(pe),ct=(n,e)=>{n.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},k=(n,{directionVideo:e,directionAudio:t,contentHint:s}={})=>{if(!n||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:n.getAudioTracks(),r=e==="recvonly"?[]:n.getVideoTracks(),a=[...i,...r],o=new MediaStream(a);return o.getTracks=()=>[...o.getAudioTracks(),...o.getVideoTracks()],s&&s!=="none"&&ct(o,s),o};var Z=(n=>(n.BYE="Terminated",n.WEBRTC_ERROR="WebRTC Error",n.CANCELED="Canceled",n.REQUEST_TIMEOUT="Request Timeout",n.REJECTED="Rejected",n.REDIRECTED="Redirected",n.UNAVAILABLE="Unavailable",n.NOT_FOUND="Not Found",n.ADDRESS_INCOMPLETE="Address Incomplete",n.INCOMPATIBLE_SDP="Incompatible SDP",n.BAD_MEDIA_DESCRIPTION="Bad Media Description",n))(Z||{});class dt{events;rtcSession;disposers=new Set;onReset;constructor(e,{onReset:t}){this.events=e,this.onReset=t,e.on(S.FAILED,this.handleEnded),e.on(S.ENDED,this.handleEnded)}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}getEstablishedRTCSession=()=>this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0;async renegotiate(){if(this.rtcSession===void 0)throw new Error("No rtcSession established");return this.rtcSession.renegotiate()}startCall=async(e,t,{number:s,mediaStream:i,extraHeaders:r=[],iceServers:a,directionVideo:o,directionAudio:c,contentHint:h,offerToReceiveAudio:E=!0,offerToReceiveVideo:u=!0,degradationPreference:T,sendEncodings:m,onAddedTransceiver:O})=>new Promise((R,D)=>{this.handleCall().then(R).catch(H=>{D(H)}),this.rtcSession=e.call(t(s),{mediaStream:k(i,{directionVideo:o,directionAudio:c,contentHint:h}),pcConfig:{iceServers:a},rtcOfferConstraints:{offerToReceiveAudio:E,offerToReceiveVideo:u},eventHandlers:this.events.triggers,extraHeaders:r,directionVideo:o,directionAudio:c,degradationPreference:T,sendEncodings:m,onAddedTransceiver:O})});async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:Z.CANCELED}).finally(()=>{this.reset()});this.reset()}answerToIncomingCall=async(e,{mediaStream:t,extraHeaders:s=[],iceServers:i,directionVideo:r,directionAudio:a,offerToReceiveAudio:o,offerToReceiveVideo:c,contentHint:h,degradationPreference:E,sendEncodings:u,onAddedTransceiver:T})=>new Promise((m,O)=>{try{this.rtcSession=e,this.subscribeToSessionEvents(e),this.handleCall().then(m).catch(R=>{O(R)}),e.answer({pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:o,offerToReceiveVideo:c},mediaStream:k(t,{directionVideo:r,directionAudio:a,contentHint:h}),extraHeaders:s,directionVideo:r,directionAudio:a,degradationPreference:E,sendEncodings:u,onAddedTransceiver:T})}catch(R){O(R)}});async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=t??{},i=k(e,{contentHint:s});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}async restartIce(e){if(!this.rtcSession)throw new Error("No rtcSession established");return this.rtcSession.restartIce(e)}handleCall=async()=>new Promise((e,t)=>{const s=()=>{this.events.on(S.PEER_CONNECTION,h),this.events.on(S.CONFIRMED,E)},i=()=>{this.events.off(S.PEER_CONNECTION,h),this.events.off(S.CONFIRMED,E)},r=()=>{this.events.on(S.FAILED,o),this.events.on(S.ENDED,o)},a=()=>{this.events.off(S.FAILED,o),this.events.off(S.ENDED,o)},o=u=>{i(),a(),t(u)};let c;const h=({peerconnection:u})=>{c=u;const T=m=>{this.events.trigger(S.PEER_CONNECTION_ONTRACK,m)};u.addEventListener("track",T),this.disposers.add(()=>{u.removeEventListener("track",T)})},E=()=>{c!==void 0&&this.events.trigger(S.PEER_CONNECTION_CONFIRMED,c),i(),a(),e(c)};s(),r()});subscribeToSessionEvents(e){this.events.eachTriggers((t,s)=>{const i=Se.find(r=>r===s);i&&(e.on(i,t),this.disposers.add(()=>{e.off(i,t)}))})}unsubscribeFromSessionEvents(){this.disposers.forEach(e=>{e()}),this.disposers.clear()}handleEnded=e=>{const{originator:t}=e;t==="remote"&&this.events.trigger(S.ENDED_FROM_SERVER,e),this.reset()};reset=()=>{delete this.rtcSession,this.unsubscribeFromSessionEvents(),this.onReset()}}class ht{config;tools;connection;constructor(e,t){this.config=e,this.tools=t,this.connection=new RTCPeerConnection(e.pcConfig),this.addTransceivers()}get settings(){return this.config}get peerConnection(){return this.connection}close(){this.connection.close()}async call(e){const t=this.waitForTracks(),s=await this.createOffer(),i=await this.tools.sendOffer({conferenceNumber:e,quality:this.config.quality,audioChannel:this.config.audioChannel},s);await this.setRemoteDescription(i),await t}async createOffer(){const e=await this.connection.createOffer();return await this.connection.setLocalDescription(e),e}async setRemoteDescription(e){return this.connection.setRemoteDescription(e)}async waitForTracks(){return new Promise(e=>{const t=new Set,s=i=>{const{track:r}=i;t.add(r.kind),t.has("audio")&&t.has("video")&&(this.connection.removeEventListener("track",s),e())};this.connection.addEventListener("track",s)})}addTransceivers(){this.addRecvOnlyTransceiver("audio"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video")}addRecvOnlyTransceiver(e){const t={direction:"recvonly"};return this.connection.addTransceiver(e,t)}}const Ce=n=>n.getSettings(),lt=(n,e)=>{const t=Ce(n);let s=e;s??=n.label;let i=t?.msid;return i??=s,i??=n.id,i},gt=(n,e)=>{const t=Ce(n);let s=e;return s??=t?.msid,s??=n.label,(s&&s.length>0?s:void 0)??n.id};class se{participantGroups=new Map;trackToGroup=new Map;trackDisposers=new Map;get mainStream(){const e=this.getStreams(),[t]=e;return t}reset(){this.participantGroups.clear(),this.trackToGroup.clear(),this.trackDisposers.forEach(e=>{e()}),this.trackDisposers.clear()}addTrack(e,{onRemoved:t,streamHint:s}={}){const i=gt(e,s),r=lt(e,s);if(this.trackToGroup.has(e.id))return{isAdded:!1};const a=this.getParticipantGroups(i);let o=a.get(r);o||(o={participantId:i,groupId:r,stream:new MediaStream,trackIds:new Set},a.set(r,o)),o.stream.addTrack(e),o.trackIds.add(e.id),this.trackToGroup.set(e.id,{participantId:i,groupId:r});const c=()=>{this.disposeTrackListener(e.id),this.removeTrack(e.id)&&t?.({trackId:e.id,participantId:i})};return e.addEventListener("ended",c),this.trackDisposers.set(e.id,()=>{e.removeEventListener("ended",c)}),{isAdded:!0,participantId:i}}removeTrack(e){this.disposeTrackListener(e);const t=this.trackToGroup.get(e);if(!t)return!1;const{participantId:s,groupId:i}=t,r=this.participantGroups.get(s),a=r?.get(i);if(!a)return this.trackToGroup.delete(e),!1;const o=a.stream.getTracks().find(c=>c.id===e);return o&&a.stream.removeTrack(o),a.trackIds.delete(e),this.trackToGroup.delete(e),a.trackIds.size===0&&(r?.delete(i),r?.size===0&&this.participantGroups.delete(s)),!0}removeStaleTracks(e,t){const s=this.participantGroups.get(e);if(!s)return!1;let i=!1;return[...s.values()].forEach(a=>{[...a.trackIds].filter(c=>!t.includes(c)).forEach(c=>{const h=this.removeTrack(c);i||=h})}),i}getStreams(e){if(e!==void 0){const t=this.participantGroups.get(e);return t?[...t.values()].map(s=>s.stream):[]}return[...this.participantGroups.values()].flatMap(t=>[...t.values()]).map(t=>t.stream)}disposeTrackListener(e){const t=this.trackDisposers.get(e);t&&(t(),this.trackDisposers.delete(e))}getParticipantGroups(e){const t=this.participantGroups.get(e);if(t)return t;const s=new Map;return this.participantGroups.set(e,s),s}}const V={type:"participant"},ut={type:"spectator_synthetic"},Tt=n=>({type:"spectator",recvParams:n});class b{role=V;mainManager;recvManager;onRoleChanged;constructor({mainManager:e,recvManager:t},s){this.mainManager=e,this.recvManager=t,this.onRoleChanged=s}static hasParticipant(e){return e.type==="participant"}static hasSpectatorSynthetic(e){return e.type==="spectator_synthetic"}static hasSpectator(e){return e.type==="spectator"}getRole(){return this.role}setCallRoleParticipant(){this.changeRole(V)}setCallRoleSpectatorSynthetic(){this.changeRole(ut)}setCallRoleSpectator(e){this.changeRole(Tt(e))}changeRole(e){const t=this.role;if(t.type!==e.type){this.setRole(e);return}b.hasSpectator(e)&&b.hasSpectator(t)&&t.recvParams.audioId!==e.recvParams.audioId&&this.setRole(e)}reset(){this.role=V,this.recvManager.reset()}getActiveManager(){return this.hasSpectator()?this.recvManager:this.mainManager}hasParticipant(){return b.hasParticipant(this.role)}hasSpectatorSynthetic(){return b.hasSpectatorSynthetic(this.role)}hasSpectator(){return b.hasSpectator(this.role)}setRole(e){const t=this.role;this.role=e,this.onRoleChanged?.({previous:t,next:e})}}const ie=n=>n.streams[0]?.id;class Et{events;callStateMachine;isPendingCall=!1;isPendingAnswer=!1;rtcSession;conferenceStateManager;mainRemoteStreamsManager=new se;recvRemoteStreamsManager=new se;roleManager=new b({mainManager:this.mainRemoteStreamsManager,recvManager:this.recvRemoteStreamsManager},e=>{this.onRoleChanged(e)});mcuSession;recvSession;disposeRecvSessionTrackListener;constructor(e){this.conferenceStateManager=e,this.events=ot(),this.mcuSession=new dt(this.events,{onReset:this.reset}),this.callStateMachine=new rt(this.events),this.subscribeCallStatusChange(),this.subscribeMcuRemoteTrackEvents()}get callActor(){return this.callStateMachine.actorRef}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.mcuSession.connection}get isCallActive(){return this.mcuSession.isCallActive}getEstablishedRTCSession=()=>this.mcuSession.getEstablishedRTCSession();on(e,t){return this.events.on(e,t)}onRace(e,t){return this.events.onRace(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}startCall=async(e,t,s)=>(this.isPendingCall=!0,this.conferenceStateManager.updateState({number:s.number,answer:!1}),this.mcuSession.startCall(e,t,s).finally(()=>{this.isPendingCall=!1}));async endCall(){return this.mcuSession.endCall()}async renegotiate(){return this.mcuSession.renegotiate()}answerToIncomingCall=async(e,t)=>{this.isPendingAnswer=!0;const s=e();return this.conferenceStateManager.updateState({answer:!0,number:s.remote_identity.uri.user}),this.mcuSession.answerToIncomingCall(s,t).finally(()=>{this.isPendingAnswer=!1})};getMainStream(){return this.getActiveStreamsManager().mainStream}getRemoteStreams(){return this.getActiveStreamsManager().getStreams()}setCallRoleParticipant(){this.roleManager.setCallRoleParticipant()}setCallRoleSpectatorSynthetic(){this.roleManager.setCallRoleSpectatorSynthetic()}setCallRoleSpectator(e){this.roleManager.setCallRoleSpectator(e)}async replaceMediaStream(e,t){return this.mcuSession.replaceMediaStream(e,t)}async restartIce(e){return this.mcuSession.restartIce(e)}reset=()=>{this.mainRemoteStreamsManager.reset(),this.conferenceStateManager.updateState({number:void 0,answer:!1}),this.roleManager.reset(),this.stopRecvSession()};subscribeCallStatusChange(){let{isCallActive:e}=this;const{ACCEPTED:t,CONFIRMED:s,ENDED:i,FAILED:r}=S;this.onRace([t,s,i,r],()=>{e=this.maybeTriggerCallStatus(e)})}maybeTriggerCallStatus(e){const t=this.isCallActive;return t!==e&&this.events.trigger(S.CALL_STATUS_CHANGED,{isCallActive:t}),t}subscribeMcuRemoteTrackEvents(){this.on(S.PEER_CONNECTION_ONTRACK,e=>{this.addRemoteTrack(this.mainRemoteStreamsManager,e.track,ie(e))})}addRemoteTrack(e,t,s){const i=e.addTrack(t,{streamHint:s,onRemoved:r=>{this.emitRemoteStreamsChanged(e,"removed",{trackId:r.trackId,participantId:r.participantId})}});i.isAdded&&this.emitRemoteStreamsChanged(e,"added",{trackId:t.id,participantId:i.participantId})}emitRemoteStreamsChanged(e,t,{trackId:s,participantId:i}){const r=this.getActiveStreamsManager();if(e!==r)return;const a=[...r.getStreams()];this.events.trigger(S.REMOTE_STREAMS_CHANGED,{participantId:i,changeType:t,trackId:s,streams:a})}getActiveStreamsManager(){return this.roleManager.getActiveManager()}attachRecvSessionTracks(e){const{peerConnection:t}=e,s=i=>{this.addRemoteTrack(this.recvRemoteStreamsManager,i.track,ie(i))};t.addEventListener("track",s),this.disposeRecvSessionTrackListener=()=>{t.removeEventListener("track",s)}}startRecvSession(e,t){const s=this.conferenceStateManager.getNumber();if(s===void 0)return;this.stopRecvSession();const i={quality:"high",audioChannel:e},r=new ht(i,{sendOffer:t});this.recvSession=r,this.recvRemoteStreamsManager.reset(),this.attachRecvSessionTracks(r),r.call(s).catch(()=>{this.stopRecvSession()})}stopRecvSession(){this.recvSession?.close(),this.recvSession=void 0,this.disposeRecvSessionTrackListener?.(),this.disposeRecvSessionTrackListener=void 0,this.recvRemoteStreamsManager.reset()}onRoleChanged=({previous:e,next:t})=>{if(b.hasSpectator(e)&&!b.hasSpectator(t)&&this.stopRecvSession(),b.hasSpectator(t)){const s=t.recvParams;this.startRecvSession(s.audioId,s.sendOffer)}}}const St=(n,e)=>(n.degradationPreference=e.degradationPreference,n),pt=(n,e)=>{n.encodings??=[];for(let t=n.encodings.length;t<e;t+=1)n.encodings.push({});return n},me=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,Ct=me(),mt=(n,e)=>{if(Ct(n,e))return n},Nt=(n,e)=>{const t=n.maxBitrate,s=mt(e,t);return s!==void 0&&(n.maxBitrate=s),n},Ne=1,Rt=me(Ne),At=(n,e)=>{const t=n===void 0?void 0:Math.max(n,Ne);if(t!==void 0&&Rt(t,e))return t},It=(n,e)=>{const t=n.scaleResolutionDownBy,s=At(e,t);return s!==void 0&&(n.scaleResolutionDownBy=s),n},ft=(n,e)=>{const t=e.encodings?.length??0;return pt(n,t),n.encodings.forEach((s,i)=>{const r=(e?.encodings??[])[i],a=r?.maxBitrate,o=r?.scaleResolutionDownBy;Nt(s,a),It(s,o)}),n},vt=(n,e)=>{if(n.codecs?.length!==e.codecs?.length)return!0;for(let t=0;t<(n.codecs?.length??0);t++)if(JSON.stringify(n.codecs[t])!==JSON.stringify(e.codecs[t]))return!0;if(n.headerExtensions?.length!==e.headerExtensions?.length)return!0;for(let t=0;t<(n.headerExtensions?.length??0);t++)if(JSON.stringify(n.headerExtensions[t])!==JSON.stringify(e.headerExtensions[t]))return!0;if(n.encodings?.length!==e.encodings?.length)return!0;for(let t=0;t<(n.encodings?.length??0);t++)if(JSON.stringify(n.encodings[t])!==JSON.stringify(e.encodings[t]))return!0;return n.rtcp?.cname!==e.rtcp?.cname||n.rtcp?.reducedSize!==e.rtcp?.reducedSize||n.degradationPreference!==e.degradationPreference},Re=async(n,e)=>{const t=n.getParameters(),s=JSON.parse(JSON.stringify(t));ft(t,e),St(t,e);const i=vt(s,t);return i&&await n.setParameters(t),{parameters:t,isChanged:i}},ee=async(n,e,t)=>{const{isChanged:s,parameters:i}=await Re(n,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return s&&t&&t(i),{isChanged:s,parameters:i}},Mt=(n,e)=>n.find(t=>t.track!==null&&e.getTracks().includes(t.track)),_t=async(n,e,t)=>{const s=Mt(n,e);if(s)return ee(s,{maxBitrate:t})};var P=(n=>(n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n))(P||{});const Ae=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],bt=()=>new I.TypedEvents(Ae);var Ie=(n=>(n.IDLE="presentation:idle",n.STARTING="presentation:starting",n.ACTIVE="presentation:active",n.STOPPING="presentation:stopping",n.FAILED="presentation:failed",n))(Ie||{});const Ot=N.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("PresentationStateMachine state changed",e.state)},setError:N.assign(({event:n})=>"error"in n&&n.error!==void 0?{lastError:n.error instanceof Error?n.error:new Error(JSON.stringify(n.error))}:{lastError:void 0}),clearError:N.assign({lastError:void 0})}}).createMachine({id:"presentation",initial:"presentation:idle",context:{},states:{"presentation:idle":{entry:{type:"logStateChange",params:{state:"presentation:idle"}},on:{"SCREEN.STARTING":{target:"presentation:starting",actions:["clearError",{type:"logTransition",params:{from:"presentation:idle",to:"presentation:starting",event:"SCREEN.STARTING"}}]}}},"presentation:starting":{entry:{type:"logStateChange",params:{state:"presentation:starting"}},on:{"SCREEN.STARTED":{target:"presentation:active",actions:{type:"logTransition",params:{from:"presentation:starting",to:"presentation:active",event:"SCREEN.STARTED"}}},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:active":{entry:{type:"logStateChange",params:{state:"presentation:active"}},on:{"SCREEN.ENDING":{target:"presentation:stopping",actions:{type:"logTransition",params:{from:"presentation:active",to:"presentation:stopping",event:"SCREEN.ENDING"}}},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:stopping":{entry:{type:"logStateChange",params:{state:"presentation:stopping"}},on:{"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:failed":{entry:{type:"logStateChange",params:{state:"presentation:failed"}},on:{"SCREEN.STARTING":{target:"presentation:starting",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:starting",event:"SCREEN.STARTING"}}]},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"PRESENTATION.RESET":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:idle",event:"PRESENTATION.RESET"}}]}}}}});class Pt extends q{constructor(e){super(Ot),this.subscribeCallEvents(e)}get isIdle(){return this.state==="presentation:idle"}get isStarting(){return this.state==="presentation:starting"}get isActive(){return this.state==="presentation:active"}get isStopping(){return this.state==="presentation:stopping"}get isFailed(){return this.state==="presentation:failed"}get isPending(){return this.isStarting||this.isStopping}get isActiveOrPending(){return this.isActive||this.isPending}get lastError(){return this.getSnapshot().context.lastError}reset(){this.send({type:"PRESENTATION.RESET"})}send(e){if(!this.getSnapshot().can(e)){console.warn(`[PresentationStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeCallEvents(e){this.addSubscription(e.on(S.START_PRESENTATION,()=>{this.send({type:"SCREEN.STARTING"})})),this.addSubscription(e.on(S.STARTED_PRESENTATION,()=>{this.send({type:"SCREEN.STARTED"})})),this.addSubscription(e.on(S.END_PRESENTATION,()=>{this.send({type:"SCREEN.ENDING"})})),this.addSubscription(e.on(S.ENDED_PRESENTATION,()=>{this.send({type:"SCREEN.ENDED"})})),this.addSubscription(e.on(S.FAILED_PRESENTATION,t=>{this.send({type:"SCREEN.FAILED",error:t})})),this.addSubscription(e.on(S.ENDED,()=>{this.send({type:"CALL.ENDED"})})),this.addSubscription(e.on(S.FAILED,t=>{this.send({type:"CALL.FAILED",error:t})}))}}const yt=1,Dt=n=>z.hasCanceledError(n);class wt{events;presentationStateMachine;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;maxBitrate;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e,maxBitrate:t}){this.callManager=e,this.maxBitrate=t,this.events=bt(),this.presentationStateMachine=new Pt(this.callManager.events),this.subscribe()}get presentationActor(){return this.presentationStateMachine.actorRef}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}get isPresentationInProcess(){return!!this.streamPresentationCurrent||this.isPendingPresentation}async startPresentation(e,t,{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a}={},o){const c=this.getRtcSessionProtected();if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return this.sendPresentationWithDuplicatedCalls(e,{rtcSession:c,stream:t,presentationOptions:{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a},options:o})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve(void 0);this.promisePendingStartPresentation&&await this.promisePendingStartPresentation.catch(()=>{});const i=this.callManager.getEstablishedRTCSession();return i&&t?s=e().then(async()=>i.stopPresentation(t)).catch(r=>{const a=r instanceof Error?r:new Error(String(r));throw this.events.trigger(P.FAILED_PRESENTATION,a),r}):t&&this.events.trigger(P.ENDED_PRESENTATION,t),this.promisePendingStopPresentation=s,s.finally(()=>{this.resetPresentation()})}async updatePresentation(e,t,{contentHint:s,sendEncodings:i,onAddedTransceiver:r}={}){const a=this.getRtcSessionProtected();if(!this.streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this.sendPresentation(e,a,t,{contentHint:s,isNeedReinvite:!1,sendEncodings:i,onAddedTransceiver:r}).then(async o=>(await this.setMaxBitrate(),o))}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.stopRepeatedCalls()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("presentation:start",e=>{this.events.trigger(P.START_PRESENTATION,e)}),this.callManager.on("presentation:started",e=>{this.events.trigger(P.STARTED_PRESENTATION,e)}),this.callManager.on("presentation:end",e=>{this.events.trigger(P.END_PRESENTATION,e)}),this.callManager.on("presentation:ended",e=>{this.events.trigger(P.ENDED_PRESENTATION,e)}),this.callManager.on("presentation:failed",e=>{this.events.trigger(P.FAILED_PRESENTATION,e)}),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded)}async sendPresentationWithDuplicatedCalls(e,{rtcSession:t,stream:s,presentationOptions:i,options:r={callLimit:yt}}){const a=async()=>this.sendPresentation(e,t,s,i),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=z.repeatedCallsAsync({targetFunction:a,isComplete:o,isRejectAsValid:!0,...r}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}async sendPresentation(e,t,s,{isNeedReinvite:i=!0,contentHint:r="detail",degradationPreference:a,sendEncodings:o,onAddedTransceiver:c}){const h=k(s,{contentHint:r});if(h===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=h;const E=e().then(async()=>t.startPresentation(h,i,{degradationPreference:a,sendEncodings:o,onAddedTransceiver:c})).then(this.setMaxBitrate).then(()=>s).catch(u=>{this.removeStreamPresentationCurrent();const T=u instanceof Error?u:new Error(String(u));throw this.events.trigger(P.FAILED_PRESENTATION,T),u});return this.promisePendingStartPresentation=E,E.finally(()=>{this.promisePendingStartPresentation=void 0})}setMaxBitrate=async()=>{const{connection:e}=this.callManager,{streamPresentationCurrent:t}=this,{maxBitrate:s}=this;if(!e||!t||s===void 0)return;const i=e.getSenders();await _t(i,t,s)};getRtcSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};handleEnded=()=>{this.reset()};reset(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}}class Lt{data;getUa;constructor(e){this.getUa=e.getUa}isConfigured(){return this.getUa()!==void 0}get(){if(this.data!==void 0)return{...this.data}}set(e){if(e===void 0){this.data=void 0;return}this.data={...e}}update(e,t){if(this.data===void 0)throw new Error("data is not exist");this.data[e]=t}clear(){this.data=void 0}isRegister(){return this.data?.register===!0}getSipServerIp(){return this.data?.sipServerIp}getSipServerUrl(){return this.data?.sipServerUrl}getDisplayName(){return this.data?.displayName}getUser(){return this.data?.user}getPassword(){return this.data?.password}isRegisterEnabled(){return this.data?.register===!0}}var p=(n=>(n.CONNECTING="connecting",n.CONNECTED="connected",n.DISCONNECTED="disconnected",n.DISCONNECTING="disconnecting",n.NEW_RTC_SESSION="newRTCSession",n.REGISTERED="registered",n.UNREGISTERED="unregistered",n.REGISTRATION_FAILED="registrationFailed",n.NEW_MESSAGE="newMessage",n.SIP_EVENT="sipEvent",n.CONNECT_STARTED="connect-started",n.CONNECT_SUCCEEDED="connect-succeeded",n.CONNECT_FAILED="connect-failed",n.CONNECT_PARAMETERS_RESOLVE_SUCCESS="connect-parameters-resolve-success",n.CONNECT_PARAMETERS_RESOLVE_FAILED="connect-parameters-resolve-failed",n.CONNECTED_WITH_CONFIGURATION="connected-with-configuration",n))(p||{});const fe=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],Ut=["disconnecting","connect-started","connect-succeeded","connect-failed","connect-parameters-resolve-success","connect-parameters-resolve-failed","connected-with-configuration"],ve=[...fe,...Ut],Ft=()=>new I.TypedEvents(ve);function kt(n){return e=>`sip:${e}@${n}`}const Bt=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,Me=n=>n.trim().replaceAll(" ","_"),$t=Bt(1e5,99999999),Gt=3;class qt{cancelableConnectWithRepeatedCalls;JsSIP;events;uaFactory;stateMachine;registrationManager;getUa;setUa;getConnectionConfiguration;setConnectionConfiguration;updateConnectionConfiguration;setGetUri;setSocket;constructor(e){this.JsSIP=e.JsSIP,this.events=e.events,this.uaFactory=e.uaFactory,this.stateMachine=e.stateMachine,this.registrationManager=e.registrationManager,this.getUa=e.getUa,this.setUa=e.setUa,this.getConnectionConfiguration=e.getConnectionConfiguration,this.setConnectionConfiguration=e.setConnectionConfiguration,this.updateConnectionConfiguration=e.updateConnectionConfiguration,this.setGetUri=e.setGetUri,this.setSocket=e.setSocket,this.proxyEvents()}connect=async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t));set=async({displayName:e})=>new Promise((t,s)=>{const i=this.getUa();if(!i){s(new Error("this.ua is not initialized"));return}let r=!1;const a=this.getConnectionConfiguration();e!==void 0&&e!==a?.displayName&&(r=i.set("display_name",Me(e)),this.updateConnectionConfiguration("displayName",e));const o=r;o?t(o):s(new Error("nothing changed"))});disconnect=async()=>{this.events.trigger(p.DISCONNECTING,{});const e=new Promise(s=>{this.events.once(p.DISCONNECTED,()=>{s()})}),t=this.getUa();return t?t.stop():this.events.trigger(p.DISCONNECTED,{socket:{},error:!1}),e.finally(()=>{t?.removeAllListeners(),this.setUa(void 0),this.stateMachine.reset()})};cancelRequests(){this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{callLimit:t=Gt}={})=>{const s=async()=>this.connectInner(e),i=r=>{const c=this.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),h=r!=null&&!et(r);return c||h};return this.stateMachine.startConnect(),this.cancelableConnectWithRepeatedCalls=z.repeatedCallsAsync({targetFunction:s,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(r=>{if("ua"in r&&r.ua instanceof this.JsSIP.UA)return r;throw r})};hasEqualConnectionConfiguration(e){const{configuration:t}=this.uaFactory.createConfiguration(e),i=this.getUa()?.configuration;return i?i.password===t.password&&i.register===t.register&&i.uri.toString()===t.uri&&i.display_name===t.display_name&&i.user_agent===t.user_agent&&i.sockets===t.sockets&&i.session_timers===t.session_timers&&i.register_expires===t.register_expires&&i.connection_recovery_min_interval===t.connection_recovery_min_interval&&i.connection_recovery_max_interval===t.connection_recovery_max_interval:!1}connectInner=async e=>this.initUa(e).then(async()=>this.start()).then(t=>{const s=this.getConnectionConfiguration();if(s===void 0)throw new Error("connectionConfiguration has not defined");return{...s,ua:t}});initUa=async({user:e,password:t,sipServerIp:s,sipServerUrl:i,remoteAddress:r,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:h,userAgent:E,displayName:u="",register:T=!1,extraHeaders:m=[]})=>{this.stateMachine.startInitUa(),this.setConnectionConfiguration({sipServerIp:s,sipServerUrl:i,displayName:u,register:T,user:e,password:t}),this.getUa()&&await this.disconnect();const{ua:R,helpers:D}=this.uaFactory.createUAWithConfiguration({user:e,password:t,sipServerIp:s,sipServerUrl:i,displayName:u,register:T,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:h,userAgent:E,remoteAddress:r,extraHeaders:m},this.events);return this.setUa(R),this.setGetUri(D.getUri),this.setSocket(D.socket),R};start=async()=>new Promise((e,t)=>{const s=this.getUa();if(!s){t(new Error("this.ua is not initialized"));return}let i;i=((c,h)=>{if(this.getConnectionConfiguration()?.register===!0)return this.registrationManager.subscribeToStartEvents(c,h);const u=p.CONNECTED,T=[p.DISCONNECTED];return this.events.on(u,c),T.forEach(m=>{this.events.on(m,h)}),()=>{this.events.off(u,c),T.forEach(m=>{this.events.off(m,h)})}})(()=>{i?.(),e(s)},c=>{i?.(),t(c)}),s.start()});cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}proxyEvents(){this.events.on(p.CONNECTED,()=>{const e=this.getConnectionConfiguration(),t=this.getUa();e!==void 0&&t!==void 0&&this.events.trigger(p.CONNECTED_WITH_CONFIGURATION,{...e,ua:t})})}}var _e=(n=>(n.IDLE="connection:idle",n.PREPARING="connection:preparing",n.CONNECTING="connection:connecting",n.CONNECTED="connection:connected",n.REGISTERED="connection:registered",n.ESTABLISHED="connection:established",n.DISCONNECTED="connection:disconnected",n.FAILED="connection:failed",n))(_e||{}),be=(n=>(n.START_CONNECT="START_CONNECT",n.START_INIT_UA="START_INIT_UA",n.UA_CONNECTED="UA_CONNECTED",n.UA_REGISTERED="UA_REGISTERED",n.UA_UNREGISTERED="UA_UNREGISTERED",n.UA_DISCONNECTED="UA_DISCONNECTED",n.CONNECTION_FAILED="CONNECTION_FAILED",n.RESET="RESET",n))(be||{});const Ht=Object.values(be),Vt=N.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("ConnectionStateMachine state changed",e.state)},setError:N.assign({error:({event:n})=>{if(n.type==="CONNECTION_FAILED"&&"error"in n)return n.error}}),clearError:N.assign({error:()=>{}})}}).createMachine({id:"connection",initial:"connection:idle",context:{},states:{"connection:idle":{entry:{type:"logStateChange",params:{state:"connection:idle"}},on:{START_CONNECT:{target:"connection:preparing",actions:{type:"logTransition",params:{from:"connection:idle",to:"connection:preparing",event:"START_CONNECT"}}}}},"connection:preparing":{entry:{type:"logStateChange",params:{state:"connection:preparing"}},on:{START_INIT_UA:{target:"connection:connecting",actions:{type:"logTransition",params:{from:"connection:preparing",to:"connection:connecting",event:"START_INIT_UA"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:preparing",to:"connection:disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"connection:failed",actions:[{type:"logTransition",params:{from:"connection:preparing",to:"connection:failed",event:"CONNECTION_FAILED"}},{type:"setError"}]}}},"connection:connecting":{entry:{type:"logStateChange",params:{state:"connection:connecting"}},on:{UA_CONNECTED:{target:"connection:connected",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:connected",event:"UA_CONNECTED"}}},UA_REGISTERED:{target:"connection:registered",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"connection:failed",actions:[{type:"logTransition",params:{from:"connection:connecting",to:"connection:failed",event:"CONNECTION_FAILED"}},{type:"setError"}]}}},"connection:connected":{entry:{type:"logStateChange",params:{state:"connection:connected"}},always:{target:"connection:established",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:established",event:"always"}}},on:{UA_REGISTERED:{target:"connection:registered",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:registered":{entry:{type:"logStateChange",params:{state:"connection:registered"}},always:{target:"connection:established",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:established",event:"always"}}},on:{UA_UNREGISTERED:{target:"connection:connected",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:connected",event:"UA_UNREGISTERED"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:established":{entry:{type:"logStateChange",params:{state:"connection:established"}},on:{UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:established",to:"connection:disconnected",event:"UA_DISCONNECTED"}}},RESET:{target:"connection:idle",actions:{type:"logTransition",params:{from:"connection:established",to:"connection:idle",event:"RESET"}}}}},"connection:disconnected":{entry:{type:"logStateChange",params:{state:"connection:disconnected"}},on:{RESET:{target:"connection:idle",actions:{type:"logTransition",params:{from:"connection:disconnected",to:"connection:idle",event:"RESET"}}},START_CONNECT:{target:"connection:preparing",actions:{type:"logTransition",params:{from:"connection:disconnected",to:"connection:preparing",event:"START_CONNECT"}}}}},"connection:failed":{entry:{type:"logStateChange",params:{state:"connection:failed"}},on:{RESET:{target:"connection:idle",actions:[{type:"logTransition",params:{from:"connection:failed",to:"connection:idle",event:"RESET"}},{type:"clearError"}]},START_CONNECT:{target:"connection:preparing",actions:[{type:"logTransition",params:{from:"connection:failed",to:"connection:preparing",event:"START_CONNECT"}},{type:"clearError"}]}}}}});class Wt extends q{stateChangeListeners=new Set;events;unsubscribeFromEvents;constructor(e){super(Vt),this.events=e,this.addSubscription(this.subscribe(t=>{const s=t.value;this.stateChangeListeners.forEach(i=>{i(s)})})),this.subscribeToEvents()}get isIdle(){return this.hasState("connection:idle")}get isPreparing(){return this.hasState("connection:preparing")}get isConnecting(){return this.hasState("connection:connecting")}get isConnected(){return this.hasState("connection:connected")}get isRegistered(){return this.hasState("connection:registered")}get isEstablished(){return this.hasState("connection:established")}get isDisconnected(){return this.hasState("connection:disconnected")}get isFailed(){return this.hasState("connection:failed")}get error(){return this.getSnapshot().context.error}get isPending(){return this.isPreparing||this.isConnecting}get isPendingConnect(){return this.isPreparing}get isPendingInitUa(){return this.isConnecting}get isActiveConnection(){return this.isEstablished||this.isConnected||this.isRegistered}startConnect(){this.toStartConnect()}startInitUa(){this.toStartInitUa()}reset(){this.toIdle()}destroy(){this.stateChangeListeners.clear(),this.unsubscribeFromEvents?.(),this.stop()}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}canTransition(e){return this.getSnapshot().can({type:e})}getValidEvents(){return Ht.filter(e=>this.canTransition(e))}hasState(e){return this.getSnapshot().matches(e)}sendEvent(e){if(!this.getSnapshot().can(e)){d(`Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}this.send(e)}toStartConnect=()=>{this.sendEvent({type:"START_CONNECT"})};toStartInitUa=()=>{this.sendEvent({type:"START_INIT_UA"})};toConnected=()=>{this.sendEvent({type:"UA_CONNECTED"})};toRegistered=()=>{this.sendEvent({type:"UA_REGISTERED"})};toUnregistered=()=>{this.sendEvent({type:"UA_UNREGISTERED"})};toDisconnected=()=>{this.sendEvent({type:"UA_DISCONNECTED"})};toFailed=e=>{this.sendEvent({type:"CONNECTION_FAILED",error:e})};toIdle=()=>{this.sendEvent({type:"RESET"})};subscribeToEvents(){this.events.on("connected",this.toConnected),this.events.on("registered",this.toRegistered),this.events.on("unregistered",this.toUnregistered),this.events.on("disconnected",this.toDisconnected),this.events.on("registrationFailed",this.handleRegistrationFailed),this.events.on("connect-failed",this.handleConnectFailed),this.unsubscribeFromEvents=()=>{this.events.off("connected",this.toConnected),this.events.off("registered",this.toRegistered),this.events.off("unregistered",this.toUnregistered),this.events.off("disconnected",this.toDisconnected),this.events.off("registrationFailed",this.handleRegistrationFailed),this.events.off("connect-failed",this.handleConnectFailed)}}handleRegistrationFailed=e=>{const{response:t}=e,s=t.status_code||"Unknown",i=t.reason_phrase||"Registration failed",r=new Error(`Registration failed: ${s} ${i}`);this.toFailed(r)};handleConnectFailed=e=>{this.toFailed(e instanceof Error?e:void 0)}}class xt{events;getUaProtected;constructor(e){this.events=e.events,this.getUaProtected=e.getUaProtected}async register(){const e=this.getUaProtected();return new Promise((t,s)=>{e.on(p.REGISTERED,t),e.on(p.REGISTRATION_FAILED,s),e.register()})}async unregister(){const e=this.getUaProtected();return new Promise(t=>{e.on(p.UNREGISTERED,t),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){d("tryRegister",e)}return this.register()}subscribeToStartEvents(e,t){const s=p.REGISTERED,i=[p.REGISTRATION_FAILED,p.DISCONNECTED];return this.events.on(s,e),i.forEach(r=>{this.events.on(r,t)}),()=>{this.events.off(s,e),i.forEach(r=>{this.events.off(r,t)})}}}class Qt{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,t,s){const i=this.getUaProtected();return new Promise((r,a)=>{try{i.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{r()},failed:a}})}catch(o){a(o)}})}async ping(e,t){const i=this.getUaProtected().configuration.uri;return this.sendOptions(i,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerIp:s,sipServerUrl:i,remoteAddress:r,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:h}=this.uaFactory.createConfiguration({sipServerUrl:i,displayName:t,userAgent:e,sipServerIp:s}),E=this.uaFactory.createUA({...h,remoteAddress:r,extraHeaders:a}),u=()=>{const m=new Error("Telephony is not available");c(m)};E.once(p.DISCONNECTED,u);const T=()=>{E.removeAllListeners(),E.once(p.DISCONNECTED,()=>{o()}),E.stop()};E.once(p.CONNECTED,T),E.start()})}}const Yt=n=>{const e=[];return n!==void 0&&n!==""&&e.push(`X-Vinteo-Remote: ${n}`),e};class w{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateParametersConnection({register:e,password:t,user:s,sipServerIp:i,sipServerUrl:r}){if(!i)throw new Error("sipServerIp is required");if(!r)throw new Error("sipServerUrl is required");if(e&&(t===void 0||t===""))throw new Error("password is required for authorized connection");if(e&&(s===void 0||s===""))throw new Error("user is required for authorized connection")}static resolveAuthorizationUser(e,t){return e&&t!==void 0&&t.trim()!==""?t.trim():`${$t()}`}static buildExtraHeaders(e,t){const s=e!==void 0&&e!==""?Yt(e):[];return t===void 0?s:[...s,...t]}createConfiguration({user:e,password:t,sipServerUrl:s,displayName:i="",sipServerIp:r,register:a=!1,sessionTimers:o=!1,registerExpires:c=300,connectionRecoveryMinInterval:h=2,connectionRecoveryMaxInterval:E=6,userAgent:u}){w.validateParametersConnection({register:a,password:t,user:e,sipServerIp:r,sipServerUrl:s});const T=w.resolveAuthorizationUser(a,e),m=kt(r),O=m(T),R=new this.JsSIP.WebSocketInterface(`wss://${s}/webrtc/wss/`);return{configuration:{password:t,register:a,uri:O,display_name:Me(i),user_agent:u,sdpSemantics:"unified-plan",sockets:[R],session_timers:o,register_expires:c,connection_recovery_min_interval:h,connection_recovery_max_interval:E},helpers:{socket:R,getUri:m}}}createUA({remoteAddress:e,extraHeaders:t,...s}){const i=new this.JsSIP.UA(s),r=w.buildExtraHeaders(e,t);return r.length>0&&i.registrator().setExtraHeaders(r),i}createUAWithConfiguration(e,t){const{configuration:s,helpers:i}=this.createConfiguration(e),r=this.createUA({...s,remoteAddress:e.remoteAddress,extraHeaders:e.extraHeaders});return t.eachTriggers((a,o)=>{const c=fe.find(h=>h===o);c&&r.on(c,a)}),{ua:r,helpers:i}}}const Oe="Not ready for connection",Pe=n=>n instanceof Error&&n.message===Oe,Xt=()=>new Error(Oe),Jt=async n=>typeof n=="function"?n():n;class zt{events;ua;socket;uaFactory;registrationManager;stateMachine;connectionFlow;sipOperations;configurationManager;JsSIP;constructor({JsSIP:e}){this.JsSIP=e,this.events=Ft(),this.uaFactory=new w(e),this.registrationManager=new xt({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new Wt(this.events),this.configurationManager=new Lt({getUa:this.getUa}),this.sipOperations=new Qt({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new qt({JsSIP:this.JsSIP,events:this.events,uaFactory:this.uaFactory,stateMachine:this.stateMachine,registrationManager:this.registrationManager,getUa:this.getUa,getConnectionConfiguration:this.getConnectionConfiguration,setConnectionConfiguration:t=>{this.configurationManager.set(t)},updateConnectionConfiguration:(t,s)=>{this.configurationManager.update(t,s)},setUa:t=>{this.ua=t},setGetUri:t=>{this.getUri=t},setSocket:t=>{this.socket=t}})}get requested(){return this.stateMachine.isPending}get isPendingConnect(){return this.stateMachine.isPendingConnect}get isPendingInitUa(){return this.stateMachine.isPendingInitUa}get isIdle(){return this.stateMachine.isIdle}get isDisconnected(){return this.stateMachine.isDisconnected}get isFailed(){return this.stateMachine.isFailed}get connectionActor(){return this.stateMachine.actorRef}get connectionState(){return this.stateMachine.state}get isRegistered(){return w.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.configurationManager.isRegister()}connect=async(e,t)=>this.disconnect().catch(s=>{d("connect: disconnect error",s)}).then(async()=>this.connectWithProcessError(e,t));set=async({displayName:e})=>this.connectionFlow.set({displayName:e});disconnect=async()=>{if(this.isConfigured())return this.connectionFlow.disconnect()};async register(){return this.registrationManager.register()}async unregister(){return this.registrationManager.unregister()}tryRegister=async()=>this.registrationManager.tryRegister();sendOptions=async(e,t,s)=>this.sipOperations.sendOptions(e,t,s);ping=async(e,t)=>this.sipOperations.ping(e,t);checkTelephony=async e=>this.sipOperations.checkTelephony(e);on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}isConfigured(){return this.configurationManager.isConfigured()}getConnectionConfiguration=()=>this.configurationManager.get();destroy(){this.stateMachine.destroy()}getUri=e=>e;getUaProtected=()=>{if(!this.ua)throw new Error("UA not initialized");return this.ua};getUa=()=>this.ua;connectWithProcessError=async(e,t)=>{if(!(t?.hasReadyForConnection?.()??!0))throw Xt();return this.processConnect(e,t).catch(async i=>{const r=i;return this.disconnect().then(()=>{throw r}).catch(()=>{throw r})})};processConnect=async(e,t)=>(this.events.trigger(p.CONNECT_STARTED,{}),Jt(e).then(s=>(this.events.trigger(p.CONNECT_PARAMETERS_RESOLVE_SUCCESS,s),s)).catch(s=>{throw this.events.trigger(p.CONNECT_PARAMETERS_RESOLVE_FAILED,s),s}).then(async s=>this.connectionFlow.connect(s,t)).then(s=>(this.events.trigger(p.CONNECT_SUCCEEDED,{...s}),s)).catch(s=>{const i=s??new Error("Failed to connect to server");throw this.events.trigger(p.CONNECT_FAILED,i),i}))}class Kt{connectionManager;stackPromises=K.createStackPromises({noRunIsNotActual:!0});constructor({connectionManager:e}){this.connectionManager=e}connect=async(...e)=>this.stackPromises.run(async()=>this.connectionManager.connect(...e));disconnect=async()=>this.stackPromises.run(async()=>this.connectionManager.disconnect());stop(){this.stackPromises.stop()}}const re=0,jt=30;class Zt{countInner=re;initialCount=re;limitInner=jt;isInProgress=!1;onStatusChange;constructor({onStatusChange:e}){this.onStatusChange=e}get count(){return this.countInner}get limit(){return this.limitInner}get isAttemptInProgress(){return this.isInProgress}hasLimitReached(){return this.countInner>=this.limitInner}startAttempt(){this.isInProgress||(this.isInProgress=!0,this.onStatusChange({isInProgress:this.isInProgress}))}finishAttempt(){this.isInProgress&&(this.isInProgress=!1,this.onStatusChange({isInProgress:this.isInProgress}))}increment(){this.count<this.limit&&(this.countInner+=1)}reset(){this.countInner=this.initialCount,this.finishAttempt()}}class en{connectionManager;interval;checkTelephonyByTimeout=void 0;cancelableBeforeRequest=void 0;constructor({connectionManager:e,interval:t}){this.connectionManager=e,this.interval=t}start({onBeforeRequest:e,onSuccessRequest:t,onFailRequest:s}){this.stop(),this.cancelableBeforeRequest=new B.CancelableRequest(e),this.checkTelephonyByTimeout=L.resolveRequesterByTimeout({isDontStopOnFail:!0,requestInterval:this.interval,request:async()=>{if(!this.cancelableBeforeRequest)throw new Error("cancelableBeforeRequest is not defined");const i=await this.cancelableBeforeRequest.request();return this.connectionManager.checkTelephony(i)}}),this.checkTelephonyByTimeout.start(void 0,{onFailRequest:s,onSuccessRequest:()=>{this.stop(),t()}})}stop(){this.checkTelephonyByTimeout?.stop(),this.checkTelephonyByTimeout=void 0,this.cancelableBeforeRequest?.cancelRequest(),this.cancelableBeforeRequest=void 0}}var v=(n=>(n.BEFORE_ATTEMPT="before-attempt",n.SUCCESS="success",n.FAILED_ALL_ATTEMPTS="failed-all-attempts",n.CANCELLED_ATTEMPTS="cancelled-attempts",n.CHANGED_ATTEMPT_STATUS="changed-attempt-status",n.STOP_ATTEMPTS_BY_ERROR="stop-attempts-by-error",n.LIMIT_REACHED_ATTEMPTS="limit-reached-attempts",n))(v||{});const ye=["before-attempt","success","failed-all-attempts","cancelled-attempts","changed-attempt-status","stop-attempts-by-error","limit-reached-attempts"],tn=()=>new I.TypedEvents(ye);class te{callManager;disposers=[];constructor({callManager:e}){this.callManager=e}subscribe(e){this.unsubscribe(),this.disposers.push(this.callManager.on("call-status-changed",()=>{this.handleCallStatusChange(e)})),this.handleCallStatusChange(e)}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[]}handleCallStatusChange({onActive:e,onInactive:t}){this.callManager.isCallActive?e?.():t()}}const nn=15e3,sn=2;class rn{connectionManager;pingServerByTimeoutWithFailCalls;constructor({connectionManager:e}){this.connectionManager=e,this.pingServerByTimeoutWithFailCalls=L.requesterByTimeoutsWithFailCalls(sn,{whenPossibleRequest:async()=>{},requestInterval:nn,request:async()=>(d("ping"),this.connectionManager.ping().then(()=>{d("ping success")}))})}start({onFailRequest:e}){this.pingServerByTimeoutWithFailCalls.start(void 0,{onFailRequest:e}).catch(d)}stop(){this.pingServerByTimeoutWithFailCalls.stop()}}class an{pingServerRequester;notActiveCallSubscriber;constructor({connectionManager:e,callManager:t}){this.pingServerRequester=new rn({connectionManager:e}),this.notActiveCallSubscriber=new te({callManager:t})}start({onFailRequest:e}){d("start"),this.notActiveCallSubscriber.subscribe({onActive:()=>{this.pingServerRequester.stop()},onInactive:()=>{this.pingServerRequester.start({onFailRequest:e})}})}stop(){d("stop"),this.pingServerRequester.stop(),this.unsubscribeCallStatusChange()}unsubscribeCallStatusChange(){this.notActiveCallSubscriber.unsubscribe()}}class on{connectionManager;isRegistrationFailed=!1;disposers=[];notActiveCallSubscriber;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.notActiveCallSubscriber=new te({callManager:t})}subscribe(e){this.unsubscribe(),this.disposers.push(this.connectionManager.on("registrationFailed",()=>{this.setIsRegistrationFailed()})),this.notActiveCallSubscriber.subscribe({onInactive:()=>{this.isRegistrationFailed&&e()}}),this.disposers.push(()=>{this.notActiveCallSubscriber.unsubscribe()})}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[],this.resetIsRegistrationFailed()}setIsRegistrationFailed(){this.isRegistrationFailed=!0}resetIsRegistrationFailed(){this.isRegistrationFailed=!1}}const cn=3e3,dn=15e3,ae={LIMIT_REACHED:"Limit reached",FAILED_TO_RECONNECT:"Failed to reconnect"},hn=async()=>{},ln=n=>!0;class gn{events;connectionManager;connectionQueueManager;checkTelephonyRequester;pingServerIfNotActiveCallRequester;registrationFailedOutOfCallSubscriber;attemptsState;delayBetweenAttempts;cancelableRequestBeforeRetry;onBeforeRetry;canRetryOnError;networkInterfacesSubscriber;resumeFromSleepModeSubscriber;notActiveCallSubscriber;constructor({connectionQueueManager:e,connectionManager:t,callManager:s},i){const r=i?.onBeforeRetry??hn,a=i?.canRetryOnError??ln;this.connectionQueueManager=e,this.connectionManager=t,this.onBeforeRetry=r,this.canRetryOnError=a,this.networkInterfacesSubscriber=i?.networkInterfacesSubscriber,this.resumeFromSleepModeSubscriber=i?.resumeFromSleepModeSubscriber,this.events=tn(),this.checkTelephonyRequester=new en({connectionManager:t,interval:i?.checkTelephonyRequestInterval??dn}),this.pingServerIfNotActiveCallRequester=new an({connectionManager:t,callManager:s}),this.registrationFailedOutOfCallSubscriber=new on({connectionManager:t,callManager:s}),this.attemptsState=new Zt({onStatusChange:this.emitStatusChange}),this.cancelableRequestBeforeRetry=new B.CancelableRequest(r),this.delayBetweenAttempts=new L.DelayRequester(i?.timeoutBetweenAttempts??cn),this.notActiveCallSubscriber=new te({callManager:s})}start(e){d("auto connector start"),this.restartConnectionAttempts(e),this.subscribeToNotActiveCall(e)}stop(){d("auto connector stop"),this.unsubscribeFromNotActiveCall(),this.unsubscribeFromHardwareTriggers(),this.stopConnectionFlow().catch(e=>{d("auto connector stop from stop method: error",e)})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}restartConnectionAttempts(e){d("auto connector restart connection attempts"),this.stopConnectionFlow().then(async()=>this.attemptConnection(e)).catch(t=>{d("auto connector failed to restart connection attempts:",t)})}async stopConnectionFlow(){d("stopConnectionFlow"),this.stopAttempts(),this.stopConnectTriggers(),await this.connectionQueueManager.disconnect()}stopAttempts(){this.attemptsState.isAttemptInProgress&&this.connectionQueueManager.stop(),this.delayBetweenAttempts.cancelRequest(),this.cancelableRequestBeforeRetry.cancelRequest(),this.attemptsState.reset()}stopConnectTriggers(){d("stopConnectTriggers"),this.stopPingRequester(),this.checkTelephonyRequester.stop(),this.registrationFailedOutOfCallSubscriber.unsubscribe()}startCheckTelephony(e){d("startCheckTelephony"),this.checkTelephonyRequester.start({onBeforeRequest:async()=>(await this.onBeforeRetry(),e.getParameters()),onSuccessRequest:()=>{d("startCheckTelephony: onSuccessRequest"),this.connectIfDisconnected(e)},onFailRequest:t=>{d("startCheckTelephony: onFailRequest",t.message)}})}async attemptConnection(e){if(d("attemptConnection: attempts.count",this.attemptsState.count),this.events.trigger(v.BEFORE_ATTEMPT,{}),this.stopConnectTriggers(),this.attemptsState.hasLimitReached()){d("attemptConnection: limit reached"),this.handleLimitReached(e);return}return this.attemptsState.startAttempt(),this.attemptsState.increment(),this.executeConnectionAttempt(e)}async executeConnectionAttempt(e){try{await this.connectionQueueManager.connect(e.getParameters,e.options),d("executeConnectionAttempt: success"),this.handleSucceededAttempt(e)}catch(t){this.handleConnectionError(t,e)}}handleConnectionError(e,t){if(Pe(e)){this.attemptsState.finishAttempt(),this.events.trigger(v.STOP_ATTEMPTS_BY_ERROR,e);return}if(!this.canRetryOnError(e)){d("executeConnectionAttempt: error does not allow retry",e),this.attemptsState.finishAttempt(),this.events.trigger(v.STOP_ATTEMPTS_BY_ERROR,e);return}if(K.isPromiseIsNotActualError(e)){d("executeConnectionAttempt: not actual error",e),this.attemptsState.finishAttempt(),this.events.trigger(v.CANCELLED_ATTEMPTS,e);return}d("executeConnectionAttempt: error",e),this.scheduleReconnect(t)}handleLimitReached(e){this.attemptsState.finishAttempt(),this.events.trigger(v.LIMIT_REACHED_ATTEMPTS,new Error(ae.LIMIT_REACHED)),this.startCheckTelephony(e)}handleSucceededAttempt(e){d("handleSucceededAttempt"),this.subscribeToConnectTriggers(e),this.events.trigger(v.SUCCESS)}subscribeToConnectTriggers(e){this.startPingRequester(e),this.registrationFailedOutOfCallSubscriber.subscribe(()=>{d("registrationFailedOutOfCallListener callback"),this.restartConnectionAttempts(e)})}subscribeToNotActiveCall(e){this.notActiveCallSubscriber.subscribe({onActive:()=>{d("subscribeToNotActiveCall onActive"),this.unsubscribeFromHardwareTriggers()},onInactive:()=>{d("subscribeToNotActiveCall onInactive"),this.subscribeToHardwareTriggers(e)}})}unsubscribeFromNotActiveCall(){this.notActiveCallSubscriber.unsubscribe()}subscribeToHardwareTriggers(e){this.unsubscribeFromHardwareTriggers(),d("subscribeToHardwareTriggers"),this.networkInterfacesSubscriber?.subscribe({onChange:()=>{d("networkInterfacesSubscriber onChange"),this.restartConnectionAttempts(e)},onUnavailable:()=>{d("networkInterfacesSubscriber onUnavailable"),this.stopConnectionFlow().catch(t=>{d("auto connector stop from networkInterfacesSubscriber onUnavailable: error",t)})}}),this.resumeFromSleepModeSubscriber?.subscribe({onResume:()=>{d("resumeFromSleepModeSubscriber onResume"),this.restartConnectionAttempts(e)}})}unsubscribeFromHardwareTriggers(){d("unsubscribeFromHardwareTriggers"),this.networkInterfacesSubscriber?.unsubscribe(),this.resumeFromSleepModeSubscriber?.unsubscribe()}stopPingRequester(){this.pingServerIfNotActiveCallRequester.stop()}startPingRequester(e){this.pingServerIfNotActiveCallRequester.start({onFailRequest:()=>{d("pingRequester: onFailRequest"),this.restartConnectionAttempts(e)}})}connectIfDisconnected(e){const t=this.isConnectionUnavailable();d("connectIfDisconnected: isUnavailable",t),t?this.restartConnectionAttempts(e):(this.stopConnectTriggers(),this.events.trigger(v.SUCCESS))}scheduleReconnect(e){d("scheduleReconnect"),this.delayBetweenAttempts.request().then(async()=>(d("scheduleReconnect: delayBetweenAttempts success"),this.cancelableRequestBeforeRetry.request())).then(async()=>(d("scheduleReconnect: onBeforeRetry success"),this.attemptConnection(e))).catch(t=>{const s=t instanceof Error?t:new Error(ae.FAILED_TO_RECONNECT);this.attemptsState.finishAttempt(),B.isCanceledError(t)||L.hasCanceledError(t)?this.events.trigger(v.CANCELLED_ATTEMPTS,s):this.events.trigger(v.FAILED_ALL_ATTEMPTS,s),d("scheduleReconnect: error",t)})}isConnectionUnavailable(){const{isFailed:e,isDisconnected:t,isIdle:s}=this.connectionManager;return e||t||s}emitStatusChange=({isInProgress:e})=>{this.events.trigger(v.CHANGED_ATTEMPT_STATUS,{isInProgress:e})}}var X=(n=>(n.STATE_CHANGED="state-changed",n.STATE_RESET="state-reset",n))(X||{});const De=["state-changed","state-reset"],un=()=>new I.TypedEvents(De);class Tn{events;state={};constructor(){this.events=un()}getState(){return{...this.state}}updateState(e){const t={...this.state};this.state={...this.state,...e},this.events.trigger(X.STATE_CHANGED,{previous:t,current:this.state,updates:e})}reset(){this.state={},this.events.trigger(X.STATE_RESET,{})}getToken(){return this.state.token}getRoom(){return this.state.room}getParticipantName(){return this.state.participantName}getChannels(){return this.state.channels}getConference(){return this.state.conference}getParticipant(){return this.state.participant}getNumber(){return this.state.number}getAnswer(){return this.state.answer}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t)}}var F=(n=>(n.RINGING="ringing",n.DECLINED_INCOMING_CALL="declinedIncomingCall",n.TERMINATED_INCOMING_CALL="terminatedIncomingCall",n.FAILED_INCOMING_CALL="failedIncomingCall",n))(F||{});const we=["ringing","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],En=()=>new I.TypedEvents(we);var Le=(n=>(n.IDLE="incoming:idle",n.RINGING="incoming:ringing",n.CONSUMED="incoming:consumed",n.DECLINED="incoming:declined",n.TERMINATED="incoming:terminated",n.FAILED="incoming:failed",n))(Le||{});const Sn=N.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("IncomingCallStateMachine state changed",e.state)},rememberIncoming:N.assign(({event:n})=>{const{data:e}=n;return{remoteCallerData:e,lastReason:void 0}}),rememberReason:N.assign(({event:n,context:e})=>n.type==="INCOMING.CONSUMED"?{remoteCallerData:e.remoteCallerData,lastReason:"incoming:consumed"}:n.type==="INCOMING.DECLINED"?{remoteCallerData:n.data,lastReason:"incoming:declined"}:n.type==="INCOMING.TERMINATED"?{remoteCallerData:n.data,lastReason:"incoming:terminated"}:{remoteCallerData:n.data,lastReason:"incoming:failed"}),clearIncoming:N.assign(()=>({remoteCallerData:void 0,lastReason:void 0}))}}).createMachine({id:"incoming",initial:"incoming:idle",context:{},states:{"incoming:idle":{entry:{type:"logStateChange",params:{state:"incoming:idle"}},on:{"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:idle",to:"incoming:ringing",event:"INCOMING.RINGING"}}]},"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:idle",to:"incoming:idle",event:"INCOMING.CLEAR"}}]}}},"incoming:ringing":{entry:{type:"logStateChange",params:{state:"incoming:ringing"}},on:{"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:ringing",event:"INCOMING.RINGING"}}]},"INCOMING.CONSUMED":{target:"incoming:consumed",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:consumed",event:"INCOMING.CONSUMED"}}]},"INCOMING.DECLINED":{target:"incoming:declined",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:declined",event:"INCOMING.DECLINED"}}]},"INCOMING.TERMINATED":{target:"incoming:terminated",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:terminated",event:"INCOMING.TERMINATED"}}]},"INCOMING.FAILED":{target:"incoming:failed",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:failed",event:"INCOMING.FAILED"}}]},"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:idle",event:"INCOMING.CLEAR"}}]}}},"incoming:consumed":{entry:{type:"logStateChange",params:{state:"incoming:consumed"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:consumed",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:consumed",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:declined":{entry:{type:"logStateChange",params:{state:"incoming:declined"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:declined",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:declined",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:terminated":{entry:{type:"logStateChange",params:{state:"incoming:terminated"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:terminated",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:terminated",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:failed":{entry:{type:"logStateChange",params:{state:"incoming:failed"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:failed",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:failed",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}}}});class pn extends q{constructor({incomingEvents:e,connectionEvents:t}){super(Sn),this.subscribeIncomingEvents(e),this.subscribeConnectionEvents(t)}get isIdle(){return this.state==="incoming:idle"}get isRinging(){return this.state==="incoming:ringing"}get isConsumed(){return this.state==="incoming:consumed"}get isDeclined(){return this.state==="incoming:declined"}get isTerminated(){return this.state==="incoming:terminated"}get isFailed(){return this.state==="incoming:failed"}get isActive(){return this.isRinging}get isFinished(){return this.isConsumed||this.isDeclined||this.isTerminated||this.isFailed}get remoteCallerData(){return this.getSnapshot().context.remoteCallerData}get lastReason(){return this.getSnapshot().context.lastReason}reset(){this.send({type:"INCOMING.CLEAR"})}send(e){if(!this.getSnapshot().can(e)){console.warn(`[IncomingCallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}toConsumed(){this.send({type:"INCOMING.CONSUMED"})}subscribeIncomingEvents(e){this.addSubscription(e.on("ringing",t=>{this.send({type:"INCOMING.RINGING",data:t})})),this.addSubscription(e.on("declinedIncomingCall",t=>{this.send({type:"INCOMING.DECLINED",data:t})})),this.addSubscription(e.on("terminatedIncomingCall",t=>{this.send({type:"INCOMING.TERMINATED",data:t})})),this.addSubscription(e.on("failedIncomingCall",t=>{this.send({type:"INCOMING.FAILED",data:t})}))}subscribeConnectionEvents(e){this.addSubscription(e.on(p.DISCONNECTED,()=>{this.toClearIncoming()})),this.addSubscription(e.on(p.REGISTRATION_FAILED,()=>{this.toClearIncoming()})),this.addSubscription(e.on(p.CONNECT_FAILED,()=>{this.toClearIncoming()}))}toClearIncoming(){this.send({type:"INCOMING.CLEAR"})}}const Cn=486,mn=487;class Nn{events;incomingStateMachine;incomingRTCSession;connectionManager;constructor(e){this.connectionManager=e,this.events=En(),this.incomingStateMachine=new pn({incomingEvents:this.events,connectionEvents:this.connectionManager.events}),this.start()}get incomingActor(){return this.incomingStateMachine.actorRef}get remoteCallerData(){return{displayName:this.incomingRTCSession?.remote_identity.display_name,host:this.incomingRTCSession?.remote_identity.uri.host,incomingNumber:this.incomingRTCSession?.remote_identity.uri.user,rtcSession:this.incomingRTCSession}}get isAvailableIncomingCall(){return!!this.incomingRTCSession}start(){this.subscribe()}stop(){this.unsubscribe(),this.removeIncomingSession()}getIncomingRTCSession=()=>{const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e};extractIncomingRTCSession=()=>{const e=this.getIncomingRTCSession();return this.incomingStateMachine.toConsumed(),this.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=mn}={}){return new Promise((t,s)=>{try{const i=this.getIncomingRTCSession(),r=this.remoteCallerData;this.removeIncomingSession(),this.events.trigger(F.DECLINED_INCOMING_CALL,r),i.terminate({status_code:e}),t()}catch(i){s(i)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:Cn})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.connectionManager.on("newRTCSession",this.handleNewRTCSession)}unsubscribe(){this.connectionManager.off("newRTCSession",this.handleNewRTCSession)}handleNewRTCSession=({originator:e,session:t})=>{e==="remote"&&this.setIncomingSession(t)};setIncomingSession(e){this.incomingRTCSession=e;const t=this.remoteCallerData;e.on("failed",s=>{this.removeIncomingSession(),s.originator==="local"?this.events.trigger(F.TERMINATED_INCOMING_CALL,t):this.events.trigger(F.FAILED_INCOMING_CALL,t)}),this.events.trigger(F.RINGING,t)}removeIncomingSession(){delete this.incomingRTCSession}}var Ue=(n=>(n.SNAPSHOT_CHANGED="snapshot-changed",n))(Ue||{});const Fe=["snapshot-changed"],Rn=()=>new I.TypedEvents(Fe),An=(n,e)=>Object.is(n,e),oe=n=>({connection:n.connection.getSnapshot(),call:n.call.getSnapshot(),incoming:n.incoming.getSnapshot(),presentation:n.presentation.getSnapshot()});class In{events;actors;currentSnapshot;subscribers=new Set;actorSubscriptions=[];constructor(e){this.events=Rn(),this.actors={connection:e.connectionManager.connectionActor,call:e.callManager.callActor,incoming:e.incomingCallManager.incomingActor,presentation:e.presentationManager.presentationActor},this.currentSnapshot=oe(this.actors),this.actorSubscriptions.push(this.actors.connection.subscribe(this.notifySubscribers),this.actors.call.subscribe(this.notifySubscribers),this.actors.incoming.subscribe(this.notifySubscribers),this.actors.presentation.subscribe(this.notifySubscribers))}getSnapshot(){return this.currentSnapshot}subscribe(e,t,s){const i=typeof t=="function",r=i?e:E=>E,a=i?t:e,o=(i?s:void 0)??An,c=r(this.currentSnapshot),h={selector:r,listener:a,equals:o,current:c};return this.subscribers.add(h),()=>{this.subscribers.delete(h)}}stop(){this.subscribers.clear(),this.actorSubscriptions.forEach(e=>{e.unsubscribe()})}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}notifySubscribers=()=>{const e=this.currentSnapshot;this.currentSnapshot=oe(this.actors);for(const t of this.subscribers){const s=t.selector(this.currentSnapshot);t.equals(t.current,s)||(t.current=s,t.listener(s))}this.events.trigger(Ue.SNAPSHOT_CHANGED,{previous:e,current:this.currentSnapshot})}}const U=1e3;var C=(n=>(n.INBOUND_RTP="inbound-rtp",n.REMOTE_OUTBOUND_RTP="remote-outbound-rtp",n.MEDIA_SOURCE="media-source",n.OUTBOUND_RTP="outbound-rtp",n.REMOTE_INBOUND_RTP="remote-inbound-rtp",n.CODEC="codec",n.CANDIDATE_PAIR="candidate-pair",n.CERTIFICATE="certificate",n.TRANSPORT="transport",n.LOCAL_CANDIDATE="local-candidate",n.REMOTE_CANDIDATE="remote-candidate",n))(C||{});const ke=["collected"],fn=()=>new I.TypedEvents(ke),vn="api/v2/rtp2webrtc/offer",Be=async({serverUrl:n,conferenceNumber:e,quality:t,audio:s,offer:i,token:r})=>{const a=new URL(`https://${n.replace(/\/$/,"")}/${vn}/${encodeURIComponent(e)}`);a.searchParams.set("quality",t),a.searchParams.set("audio",String(s));const o={"Content-Type":"application/json"};r!==void 0&&r!==""&&(o.Authorization=`Bearer ${r}`);const c=await fetch(a.toString(),{method:"POST",headers:o,credentials:"same-origin",body:JSON.stringify(i)});if(!c.ok)throw new Error(`sendOffer failed with status ${c.status}`);const h=await c.json();return{type:h.type,sdp:h.sdp,toJSON(){return h}}},ce=()=>"performance"in window?performance.now():Date.now(),$=n=>[...n.keys()].reduce((e,t)=>{const s=n.get(t);return s===void 0?e:{...e,[s.type]:s}},{}),Mn=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=$(n);return{outboundRtp:e[C.OUTBOUND_RTP],codec:e[C.CODEC],mediaSource:e[C.MEDIA_SOURCE],remoteInboundRtp:e[C.REMOTE_INBOUND_RTP]}},de=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=$(n);return{outboundRtp:e[C.OUTBOUND_RTP],codec:e[C.CODEC],mediaSource:e[C.MEDIA_SOURCE],remoteInboundRtp:e[C.REMOTE_INBOUND_RTP]}},he=({videoReceiversStats:n,synchronizationSourcesVideo:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,synchronizationSources:e};const t=$(n);return{inboundRtp:t[C.INBOUND_RTP],codec:t[C.CODEC],synchronizationSources:e}},_n=({audioReceiverStats:n,synchronizationSourcesAudio:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:e};const t=$(n);return{inboundRtp:t[C.INBOUND_RTP],codec:t[C.CODEC],remoteOutboundRtp:t[C.REMOTE_OUTBOUND_RTP],synchronizationSources:e}},$e=n=>{if(!n)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};const e=$(n);return{candidatePair:e[C.CANDIDATE_PAIR],certificate:e[C.CERTIFICATE],localCandidate:e[C.LOCAL_CANDIDATE],remoteCandidate:e[C.REMOTE_CANDIDATE],transport:e[C.TRANSPORT]}},bn=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t})=>({video:de(e),secondVideo:de(t),audio:Mn(n),additional:$e(n??e??t)}),On=({audioReceiverStats:n,videoReceiverFirstStats:e,videoReceiverSecondStats:t,synchronizationSources:s})=>({video:he({videoReceiversStats:e,synchronizationSourcesVideo:s.video}),secondVideo:he({videoReceiversStats:t,synchronizationSourcesVideo:s.video}),audio:_n({audioReceiverStats:n,synchronizationSourcesAudio:s.audio}),additional:$e(n??e??t)}),Pn=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t,audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a})=>{const o=bn({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t}),c=On({audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a});return{outbound:o,inbound:c}},yn=async n=>{const e="audio",t="video",s=n.getSenders(),i=s.find(T=>T.track?.kind===e),r=s.filter(T=>T.track?.kind===t),a=n.getReceivers(),o=a.find(T=>T.track.kind===e),c=a.filter(T=>T.track.kind===t),h={trackIdentifier:o?.track.id,item:o?.getSynchronizationSources()[0]},E={trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},u={audio:h,video:E};return Promise.all([i?.getStats()??Promise.resolve(void 0),r[0]?.getStats()??Promise.resolve(void 0),r[1]?.getStats()??Promise.resolve(void 0),o?.getStats()??Promise.resolve(void 0),c[0]?.getStats()??Promise.resolve(void 0),c[1]?.getStats()??Promise.resolve(void 0)]).then(T=>{const[m,O,R,D,H,Xe]=T;return{synchronizationSources:u,audioSenderStats:m,videoSenderFirstStats:O,videoSenderSecondStats:R,audioReceiverStats:D,videoReceiverFirstStats:H,videoReceiverSecondStats:Xe}})},Dn=n=>{d(String(n))};class Ge{events;setTimeoutRequest;requesterAllStatistics=new B.CancelableRequest(yn);constructor(){this.events=fn(),this.setTimeoutRequest=new L.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:t=U,onError:s=Dn}={}){this.stop(),this.setTimeoutRequest.request(()=>{this.collectStatistics(e,{onError:s})},t)}stop(){this.setTimeoutRequest.cancelRequest(),this.requesterAllStatistics.cancelRequest()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}collectStatistics=(e,{onError:t})=>{const s=ce();this.requesterAllStatistics.request(e).then(i=>{this.events.trigger("collected",Pn(i));const a=ce()-s;let o=U;a>48?o=U*4:a>32?o=U*3:a>16&&(o=U*2),this.start(e,{onError:t,interval:o})}).catch(i=>{t&&t(i)})}}const wn=500;class Ln{statsPeerConnection;availableStats;previousAvailableStats;callManager;apiManager;constructor({callManager:e,apiManager:t}){this.callManager=e,this.apiManager=t,this.statsPeerConnection=new Ge,this.subscribe()}get events(){return this.statsPeerConnection.events}get availableIncomingBitrate(){return this.availableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get isInvalidInboundFrames(){return this.isEmptyInboundFrames&&this.isReceivingPackets}get isEmptyInboundFrames(){return!this.isFramesReceived||!this.isFramesDecoded}get previousAvailableIncomingBitrate(){return this.previousAvailableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get previousInboundRtp(){return this.previousAvailableStats?.inbound.video.inboundRtp}get previousFramesReceived(){return this.previousInboundRtp?.framesReceived}get previousFramesDecoded(){return this.previousInboundRtp?.framesDecoded}get inboundRtp(){return this.availableStats?.inbound.video.inboundRtp}get framesReceived(){return this.inboundRtp?.framesReceived}get framesDecoded(){return this.inboundRtp?.framesDecoded}get isFramesReceived(){const e=this.framesReceived!==void 0&&this.framesReceived>0,t=this.framesReceived!==this.previousFramesReceived;return e&&t}get isFramesDecoded(){const e=this.framesDecoded!==void 0&&this.framesDecoded>0,t=this.framesDecoded!==this.previousFramesDecoded;return e&&t}get packetsReceived(){return this.inboundRtp?.packetsReceived}get previousPacketsReceived(){return this.previousInboundRtp?.packetsReceived}get isReceivingPackets(){const e=this.packetsReceived!==void 0&&this.packetsReceived>=wn,t=this.packetsReceived!==this.previousPacketsReceived;return e&&t}on(e,t){return this.statsPeerConnection.on(e,t)}once(e,t){return this.statsPeerConnection.once(e,t)}onceRace(e,t){return this.statsPeerConnection.onceRace(e,t)}async wait(e){return this.statsPeerConnection.wait(e)}off(e,t){this.statsPeerConnection.off(e,t)}hasAvailableIncomingBitrateChangedQuarter(){const e=this.previousAvailableIncomingBitrate,t=this.availableIncomingBitrate;return e===void 0||t===void 0?!1:e===0?t>0:Math.abs(t-e)/e>=.25}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleStarted),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded),this.statsPeerConnection.on("collected",this.handleStatsCollected)}handleStatsCollected=e=>{this.previousAvailableStats=this.availableStats,this.availableStats=e,this.maybeSendStats()};handleStarted=e=>{this.statsPeerConnection.start(e)};handleEnded=()=>{this.statsPeerConnection.stop(),this.availableStats=void 0,this.previousAvailableStats=void 0};maybeSendStats(){this.availableIncomingBitrate!==void 0&&this.hasAvailableIncomingBitrateChangedQuarter()&&this.apiManager.sendStats({availableIncomingBitrate:this.availableIncomingBitrate}).catch(e=>{d("Failed to send stats",e)})}}const Un=(n,e)=>n.filter(s=>e.some(i=>i.clockRate===s.clockRate&&i.mimeType===s.mimeType&&i.channels===s.channels&&i.sdpFmtpLine===s.sdpFmtpLine)),Fn=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,i=t===null?[]:t.codecs;return Un(s,i)},kn=(n,e)=>e===void 0||e.length===0?n:n.sort((t,s)=>{const i=e.indexOf(t.mimeType),r=e.indexOf(s.mimeType),a=i===-1?Number.MAX_VALUE:i,o=r===-1?Number.MAX_VALUE:r;return a-o}),Bn=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),$n=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>{try{if(typeof n.setCodecPreferences=="function"&&n.sender.track?.kind==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const s=Fn("video"),i=Bn(s,t),r=kn(i,e);n.setCodecPreferences(r)}}catch(s){d("setCodecPreferences error",s)}},Gn=n=>[...n.keys()].map(e=>n.get(e)),qn=(n,e)=>Gn(n).find(t=>t?.type===e),qe=async n=>n.getStats().then(e=>qn(e,"codec")?.mimeType);class Hn{async getCodecFromSender(e){return await qe(e)??""}}class Vn{stackPromises=K.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{d("TaskQueue: error",e)})}}class Wn{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new Vn}async setEncodingsToSender(e,t){return this.taskQueue.add(async()=>ee(e,t,this.onSetParameters))}stop(){this.taskQueue.stop()}}const He=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),xn=1e6,M=n=>n*xn,Ve=M(.06),We=M(4),Qn=n=>n<=64?Ve:n<=128?M(.12):n<=256?M(.25):n<=384?M(.32):n<=426?M(.38):n<=640?M(.5):n<=848?M(.7):n<=1280?M(1):n<=1920?M(2):We,Yn="av1",Xn=n=>He(n,Yn),Jn=.6,ne=(n,e)=>Xn(e)?n*Jn:n,zn=n=>ne(Ve,n),Kn=n=>ne(We,n),le=(n,e)=>{const t=Qn(n);return ne(t,e)},W=1,jn=({videoTrack:n,targetSize:e})=>{const t=n.getSettings(),s=t.width,i=t.height,r=s===void 0?W:s/e.width,a=i===void 0?W:i/e.height;return Math.max(r,a,W)};class Zn{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:t,parametersSetter:s},i){this.senderFinder=e,this.codecProvider=t,this.parametersSetter=s,this.ignoreForCodec=i.ignoreForCodec}async balance(e,t){const s=e.getSenders(),i=this.senderFinder.findVideoSender(s);if(!i?.track)return{...this.resultNoChanged,sender:i};const r=await this.codecProvider.getCodecFromSender(i);if(He(r,this.ignoreForCodec))return{...this.resultNoChanged,sender:i};const{mainCam:a,resolutionMainCam:o}=t??{};return this.processSender({mainCam:a,resolutionMainCam:o},{sender:i,codec:r,videoTrack:i.track}).then(c=>({...c,sender:i}))}async processSender(e,t){const{mainCam:s,resolutionMainCam:i}=e;switch(s){case _.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(t);case _.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(t);case _.MAX_MAIN_CAM_RESOLUTION:return i!==void 0?this.setResolutionSender(i,t):this.setBitrateByTrackResolution(t);case _.ADMIN_STOP_MAIN_CAM:case _.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(t);default:return this.setBitrateByTrackResolution(t)}}async downgradeResolutionSender(e){const{sender:t,codec:s}=e,i={scaleResolutionDownBy:200,maxBitrate:zn(s)};return this.parametersSetter.setEncodingsToSender(t,i)}async setBitrateByTrackResolution(e){const{sender:t,videoTrack:s,codec:i}=e,a=s.getSettings().width,o=a===void 0?Kn(i):le(a,i);return this.parametersSetter.setEncodingsToSender(t,{scaleResolutionDownBy:1,maxBitrate:o})}async setResolutionSender(e,t){const[s,i]=e.split("x"),{sender:r,videoTrack:a,codec:o}=t,c={width:Number(s),height:Number(i)},h=jn({videoTrack:a,targetSize:c}),E=le(c.width,o),u={scaleResolutionDownBy:h,maxBitrate:E};return this.parametersSetter.setEncodingsToSender(r,u)}}const es=n=>n.find(e=>e.track?.kind==="video");class ts{findVideoSender(e){return es(e)}}class ns{currentSender;originalReplaceTrack;lastWidth;lastHeight;maxPollIntervalMs;currentPollIntervalMs;pollIntervalMs;setTimeoutRequest;constructor({pollIntervalMs:e=1e3,maxPollIntervalMs:t}){this.pollIntervalMs=e,this.maxPollIntervalMs=t??e*16,this.currentPollIntervalMs=this.pollIntervalMs,this.setTimeoutRequest=new L.SetTimeoutRequest}subscribe(e,t){if(!e){this.detachSender();return}this.currentSender!==e&&(this.detachSender(),this.attachSender(e,t))}unsubscribe(){this.detachSender()}attachSender(e,t){this.currentSender=e;const s=e.replaceTrack.bind(e);this.originalReplaceTrack=s,e.replaceTrack=async i=>{await s(i),this.attachTrack(t,i??void 0),t()},this.attachTrack(t,e.track)}detachSender(){this.currentSender&&this.originalReplaceTrack&&(this.currentSender.replaceTrack=this.originalReplaceTrack),this.originalReplaceTrack=void 0,this.currentSender=void 0,this.detachTrack()}attachTrack(e,t){if(this.detachTrack(),!t)return;const{width:s,height:i}=t.getSettings();this.lastWidth=s,this.lastHeight=i,this.currentPollIntervalMs=this.pollIntervalMs,this.schedulePoll(t,e)}schedulePoll(e,t){const s=()=>{const{width:i,height:r}=e.getSettings();i!==this.lastWidth||r!==this.lastHeight?(this.lastWidth=i,this.lastHeight=r,this.currentPollIntervalMs=this.pollIntervalMs,t()):this.currentPollIntervalMs=Math.min(this.currentPollIntervalMs*2,this.maxPollIntervalMs),this.setTimeoutRequest.request(s,this.currentPollIntervalMs)};this.setTimeoutRequest.request(s,this.currentPollIntervalMs)}detachTrack(){this.setTimeoutRequest.cancelRequest(),this.lastWidth=void 0,this.lastHeight=void 0}}class ss{apiManager;currentHandler;constructor(e){this.apiManager=e}subscribe(e){this.currentHandler=e,this.apiManager.on("main-cam-control",e)}unsubscribe(){this.currentHandler&&(this.apiManager.off("main-cam-control",this.currentHandler),this.currentHandler=void 0)}}class is{eventHandler;senderBalancer;parametersSetterWithQueue;getConnection;serverHeaders;trackMonitor;constructor(e,t,{ignoreForCodec:s,onSetParameters:i,pollIntervalMs:r}={}){this.getConnection=t,this.eventHandler=new ss(e),this.parametersSetterWithQueue=new Wn(i),this.senderBalancer=new Zn({senderFinder:new ts,codecProvider:new Hn,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:s}),this.trackMonitor=new ns({pollIntervalMs:r})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.parametersSetterWithQueue.stop(),this.reset()}reset(){delete this.serverHeaders,this.trackMonitor.unsubscribe()}async balance(){const e=this.getConnection();if(!e)throw new Error("connection is not exist");const t=await this.senderBalancer.balance(e,this.serverHeaders);return this.trackMonitor.subscribe(t.sender,()=>{this.balance().catch(s=>{d("balance on track change: error",s)})}),t}handleMainCamControl=e=>{this.serverHeaders=e,this.balance().catch(t=>{d("handleMainCamControl: error",t)})}}const xe=["balancing-scheduled","balancing-started","balancing-stopped","parameters-updated"],rs=()=>new I.TypedEvents(xe);class as{isBalancingActive=!1;events;callManager;balancingStartDelay;videoSendingBalancer;startBalancingTimer;constructor(e,t,s={}){this.events=rs(),this.callManager=e,this.balancingStartDelay=s.balancingStartDelay??1e4,this.videoSendingBalancer=new is(t,()=>e.connection,{...s,onSetParameters:i=>{this.events.trigger("parameters-updated",i),s.onSetParameters?.(i)}}),this.subscribe()}get isBalancingScheduled(){return this.startBalancingTimer!==void 0}async startBalancing(){this.isBalancingActive||(this.clearStartTimer(),await this.videoSendingBalancer.balance(),this.videoSendingBalancer.subscribe(),this.isBalancingActive=!0,this.events.trigger("balancing-started",{delay:this.balancingStartDelay}))}stopBalancing(){this.clearStartTimer(),this.videoSendingBalancer.unsubscribe(),this.isBalancingActive=!1,this.events.trigger("balancing-stopped",{})}async balance(){return this.videoSendingBalancer.balance()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleCallStarted),this.callManager.on("ended",this.handleCallEnded),this.callManager.on("failed",this.handleCallEnded)}handleCallStarted=()=>{this.scheduleBalancingStart()};handleCallEnded=()=>{this.stopBalancing()};scheduleBalancingStart(){this.clearStartTimer(),this.startBalancingTimer=setTimeout(()=>{this.startBalancingTimer=void 0,this.startBalancing().catch(e=>{d("startBalancing: error",e)})},this.balancingStartDelay),this.events.trigger("balancing-scheduled",{delay:this.balancingStartDelay})}clearStartTimer(){this.startBalancingTimer&&(clearTimeout(this.startBalancingTimer),this.startBalancingTimer=void 0)}}const Qe="no-inbound-frames",Ye=[Qe],os=()=>new I.TypedEvents(Ye);class cs{events;statsManager;callManager;constructor(e,t){this.statsManager=e,this.callManager=t,this.events=os(),this.subscribe()}get mainVideoTrack(){return this.callManager.getMainStream()?.getVideoTracks()[0]}get isMutedMainVideoTrack(){const{mainVideoTrack:e}=this;return e===void 0?!1:e.muted}on(e,t){return this.events.on(e,t)}handleStatsCollected=()=>{this.hasNoIncomingFrames()&&this.events.trigger(Qe,{})};hasNoIncomingFrames=()=>this.statsManager.isInvalidInboundFrames&&this.isMutedMainVideoTrack;subscribe(){this.statsManager.on("collected",this.handleStatsCollected)}}const ds=3e3;class hs{renegotiateRequester;renegotiateThrottled;callManager;constructor(e,t=ds){this.callManager=e,this.renegotiateRequester=new B.CancelableRequest(e.renegotiate.bind(e)),this.renegotiateThrottled=Je.throttle(this.requestRenegotiate.bind(this),t),this.subscribe()}recover(){d("trying to recover main stream"),this.renegotiateThrottled()}requestRenegotiate=()=>{if(d("trying to renegotiate"),this.renegotiateRequester.requested){d("previous renegotiate is not finished yet");return}this.renegotiateRequester.request().then(()=>{d("renegotiate has successful")}).catch(e=>{d("failed to renegotiate main media stream",e)})};subscribe(){this.callManager.on("ended",()=>{this.cancel()})}cancel(){d("cancel recover main stream"),this.renegotiateThrottled.cancel(),this.renegotiateRequester.cancelRequest()}}const ls=1e6,gs=ye.map(n=>`auto-connect:${n}`),us=ve.map(n=>`connection:${n}`),Ts=pe.map(n=>`call:${n}`),Es=De.map(n=>`conference-state:${n}`),Ss=ue.map(n=>`api:${n}`),ps=we.map(n=>`incoming-call:${n}`),Cs=Ae.map(n=>`presentation:${n}`),ms=ke.map(n=>`stats:${n}`),Ns=xe.map(n=>`video-balancer:${n}`),Rs=Ye.map(n=>`main-stream-health:${n}`),As=Fe.map(n=>`session:${n}`),Is=["disconnected-from-out-of-call","connected-with-configuration-from-out-of-call","stopped-presentation-by-server-command"],fs=[...gs,...us,...Ts,...Es,...Ss,...ps,...Cs,...ms,...Ns,...Rs,...As,...Is],vs=()=>new I.TypedEvents(fs);class Ms{events;connectionManager;connectionQueueManager;conferenceStateManager;callManager;autoConnectorManager;apiManager;incomingCallManager;presentationManager;statsManager;videoSendingBalancerManager;sessionManager;mainStreamHealthMonitor;mainStreamRecovery;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor({JsSIP:e},{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s,videoBalancerOptions:i,autoConnectorOptions:r}={}){this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=s,this.events=vs(),this.connectionManager=new zt({JsSIP:e}),this.connectionQueueManager=new Kt({connectionManager:this.connectionManager}),this.conferenceStateManager=new Tn,this.callManager=new Et(this.conferenceStateManager),this.apiManager=new st({connectionManager:this.connectionManager,callManager:this.callManager}),this.incomingCallManager=new Nn(this.connectionManager),this.presentationManager=new wt({callManager:this.callManager,maxBitrate:ls}),this.statsManager=new Ln({callManager:this.callManager,apiManager:this.apiManager}),this.autoConnectorManager=new gn({connectionQueueManager:this.connectionQueueManager,connectionManager:this.connectionManager,callManager:this.callManager},r),this.videoSendingBalancerManager=new as(this.callManager,this.apiManager,i),this.mainStreamHealthMonitor=new cs(this.statsManager,this.callManager),this.mainStreamRecovery=new hs(this.callManager),this.sessionManager=new In({connectionManager:this.connectionManager,callManager:this.callManager,incomingCallManager:this.incomingCallManager,presentationManager:this.presentationManager}),this.subscribe()}get requestedConnection(){return this.connectionManager.requested}get isPendingConnect(){return this.connectionManager.isPendingConnect}get isPendingInitUa(){return this.connectionManager.isPendingInitUa}get connectionState(){return this.connectionManager.connectionState}get isRegistered(){return this.connectionManager.isRegistered}get isRegisterConfig(){return this.connectionManager.isRegisterConfig}get socket(){return this.connectionManager.socket}get requestedCall(){return this.callManager.requested}get connection(){return this.callManager.connection}get isCallActive(){return this.callManager.isCallActive}get remoteCallerData(){return this.incomingCallManager.remoteCallerData}get isAvailableIncomingCall(){return this.incomingCallManager.isAvailableIncomingCall}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}connect=async(...e)=>this.connectionQueueManager.connect(...e);disconnect=async()=>this.connectionQueueManager.disconnect();register=async()=>this.connectionManager.register();unregister=async()=>this.connectionManager.unregister();tryRegister=async()=>this.connectionManager.tryRegister();set=async(...e)=>this.connectionManager.set(...e);sendOptions=async(e,t,s)=>this.connectionManager.sendOptions(e,t,s);ping=async(e,t)=>this.connectionManager.ping(e,t);checkTelephony=async e=>this.connectionManager.checkTelephony(e);isConfigured=()=>this.connectionManager.isConfigured();getConnectionConfiguration=()=>this.connectionManager.getConnectionConfiguration();getUri=e=>this.connectionManager.getUri(e);startAutoConnect=(...e)=>{this.autoConnectorManager.start(...e)};stopAutoConnect=()=>{this.autoConnectorManager.stop()};call=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.startCall(this.connectionManager.getUaProtected(),this.getUri,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};hangUp=async()=>this.callManager.endCall();answerToIncomingCall=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getCallConfiguration=()=>{const e=this.conferenceStateManager.getState();return{number:e.number,answer:e.answer}};getRemoteStreams=()=>this.callManager.getRemoteStreams();replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,t={}){const{isP2P:s,callLimit:i,onAddedTransceiver:r,...a}=t;return this.presentationManager.startPresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...a,onAddedTransceiver:this.resolveHandleAddTransceiver(r)},i===void 0?void 0:{callLimit:i})}async stopPresentation(e={}){const{isP2P:t}=e;return this.presentationManager.stopPresentation(async()=>{await(t===!0?this.apiManager.sendMustStopPresentationP2P():this.apiManager.sendStoppedPresentation())})}async updatePresentation(e,t={}){const{isP2P:s,onAddedTransceiver:i,...r}=t;return this.presentationManager.updatePresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...r,onAddedTransceiver:this.resolveHandleAddTransceiver(i)})}async waitChannels(...e){return this.apiManager.waitChannels(...e)}async waitSyncMediaState(...e){return this.apiManager.waitSyncMediaState(...e)}async sendDTMF(...e){return this.apiManager.sendDTMF(...e)}async sendChannels(...e){return this.apiManager.sendChannels(...e)}async sendMediaState(...e){return this.apiManager.sendMediaState(...e)}async sendRefusalToTurnOn(...e){return this.apiManager.sendRefusalToTurnOn(...e)}async sendRefusalToTurnOnMic(...e){return this.apiManager.sendRefusalToTurnOnMic(...e)}async sendRefusalToTurnOnCam(...e){return this.apiManager.sendRefusalToTurnOnCam(...e)}async sendMustStopPresentationP2P(...e){return this.apiManager.sendMustStopPresentationP2P(...e)}async sendStoppedPresentationP2P(...e){return this.apiManager.sendStoppedPresentationP2P(...e)}async sendStoppedPresentation(...e){return this.apiManager.sendStoppedPresentation(...e)}async askPermissionToStartPresentationP2P(...e){return this.apiManager.askPermissionToStartPresentationP2P(...e)}async askPermissionToStartPresentation(...e){return this.apiManager.askPermissionToStartPresentation(...e)}async askPermissionToEnableCam(...e){return this.apiManager.askPermissionToEnableCam(...e)}subscribeDisconnectedFromOutOfCall(){this.connectionManager.on("disconnected",()=>{this.isCallActive||this.events.trigger("disconnected-from-out-of-call",{})})}subscribeConnectedWithConfigurationFromOutOfCall(){this.connectionManager.on("connected-with-configuration",e=>{this.isCallActive||this.events.trigger("connected-with-configuration-from-out-of-call",e)})}mayBeStopPresentationAndNotify(){this.presentationManager.isPresentationInProcess&&(this.stopPresentation().catch(()=>{}),this.events.trigger("stopped-presentation-by-server-command",{}))}subscribeToApiEvents(){this.apiManager.on("participant:move-request-to-participants",()=>{this.callManager.setCallRoleParticipant()}),this.apiManager.on("participant:move-request-to-spectators-synthetic",()=>{this.callManager.setCallRoleSpectatorSynthetic(),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("participant:move-request-to-spectators-with-audio-id",({audioId:e})=>{this.callManager.setCallRoleSpectator({audioId:e,sendOffer:this.sendOffer}),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("mustStopPresentation",()=>{this.mayBeStopPresentationAndNotify()}),this.apiManager.on("enterRoom",({room:e,participantName:t})=>{this.conferenceStateManager.updateState({room:e,participantName:t})}),this.apiManager.on("conference:participant-token-issued",({jwt:e,conference:t,participant:s})=>{this.conferenceStateManager.updateState({token:e,conference:t,participant:s})}),this.apiManager.on("channels",e=>{this.conferenceStateManager.updateState({channels:e})})}sendOffer=async(e,t)=>{const i=this.connectionManager.getConnectionConfiguration()?.sipServerUrl;if(i===void 0)throw new Error("No sipServerUrl for sendOffer");const r=this.conferenceStateManager.getToken();return Be({serverUrl:i,offer:t,token:r,conferenceNumber:e.conferenceNumber,quality:e.quality,audio:e.audioChannel})};setCodecPreferences(e){$n(e,{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs})}subscribe(){this.bridgeEvents("auto-connect",this.autoConnectorManager),this.bridgeEvents("connection",this.connectionManager),this.bridgeEvents("call",this.callManager),this.bridgeEvents("conference-state",this.conferenceStateManager),this.bridgeEvents("api",this.apiManager),this.bridgeEvents("incoming-call",this.incomingCallManager),this.bridgeEvents("presentation",this.presentationManager),this.bridgeEvents("stats",this.statsManager),this.bridgeEvents("video-balancer",this.videoSendingBalancerManager),this.bridgeEvents("main-stream-health",this.mainStreamHealthMonitor),this.bridgeEvents("session",this.sessionManager),this.subscribeToApiEvents(),this.subscribeDisconnectedFromOutOfCall(),this.subscribeConnectedWithConfigurationFromOutOfCall(),this.subscribeToMainStreamHealthMonitorEvents()}subscribeToMainStreamHealthMonitorEvents(){this.mainStreamHealthMonitor.on("no-inbound-frames",()=>{this.mainStreamRecovery.recover()})}bridgeEvents=(e,t)=>{t.events.eachTriggers((s,i)=>{t.on(i,r=>{this.events.trigger(`${e}:${i}`,r)})})};resolveHandleAddTransceiver=e=>async(t,s,i)=>{this.setCodecPreferences(t),await e?.(t,s,i)}}exports.ECallCause=Z;exports.EState=_e;exports.EState$1=Te;exports.EState$2=Le;exports.EState$3=Ie;exports.EStatsTypes=C;exports.EUseLicense=ge;exports.Originator=Ee;exports.SipConnector=Ms;exports.StatsPeerConnection=Ge;exports.disableDebug=Ke;exports.enableDebug=ze;exports.getCodecFromSender=qe;exports.hasCanceledStartPresentationError=Dt;exports.hasNotReadyForConnectionError=Pe;exports.logger=d;exports.prepareMediaStream=k;exports.sendOffer=Be;exports.setEncodingsToSender=ee;exports.setParametersToSender=Re;
|
|
1
|
+
"use strict";const J=require("debug"),I=require("events-constructor"),B=require("@krivega/cancelable-promise"),L=require("@krivega/timeout-requester"),z=require("repeated-calls"),N=require("xstate"),K=require("stack-promises");require("ua-parser-js");require("sequent-promises");const Je=require("lodash"),j="sip-connector",d=J(j),ze=()=>{J.enable(j)},Ke=()=>{J.enable(`-${j}`)},je="Error decline with 603",Ze=1006,et=n=>typeof n=="object"&&n!==null&&"code"in n&&n.code===Ze,tt=n=>n.message===je;var g=(n=>(n.CONTENT_TYPE="content-type",n.CONTENT_ENTER_ROOM="x-webrtc-enter-room",n.CONTENT_USE_LICENSE="X-WEBRTC-USE-LICENSE",n.PARTICIPANT_NAME="X-WEBRTC-PARTICIPANT-NAME",n.INPUT_CHANNELS="X-WEBRTC-INPUT-CHANNELS",n.OUTPUT_CHANNELS="X-WEBRTC-OUTPUT-CHANNELS",n.MAIN_CAM="X-WEBRTC-MAINCAM",n.MIC="X-WEBRTC-MIC",n.MEDIA_SYNC="X-WEBRTC-SYNC",n.MAIN_CAM_RESOLUTION="X-WEBRTC-MAINCAM-RESOLUTION",n.MEDIA_STATE="X-WEBRTC-MEDIA-STATE",n.MEDIA_TYPE="X-Vinteo-Media-Type",n.MAIN_CAM_STATE="X-Vinteo-MainCam-State",n.MIC_STATE="X-Vinteo-Mic-State",n.CONTENT_PARTICIPANT_STATE="X-WEBRTC-PARTSTATE",n.NOTIFY="X-VINTEO-NOTIFY",n.CONTENT_ENABLE_MEDIA_DEVICE="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",n.CONTENT_SHARE_STATE="x-webrtc-share-state",n.MUST_STOP_PRESENTATION_P2P="x-webrtc-share-state: YOUMUSTSTOPSENDCONTENT",n.START_PRESENTATION_P2P="x-webrtc-share-state: YOUCANRECEIVECONTENT",n.STOP_PRESENTATION_P2P="x-webrtc-share-state: CONTENTEND",n.STOP_PRESENTATION="x-webrtc-share-state: STOPPRESENTATION",n.START_PRESENTATION="x-webrtc-share-state: LETMESTARTPRESENTATION",n.ENABLE_MAIN_CAM="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM",n.AVAILABLE_INCOMING_BITRATE="X-WEBRTC-AVAILABLE-INCOMING-BITRATE",n.AUDIO_TRACK_COUNT="X-WEBRTC-AUDIO-TRACK-COUNT",n.VIDEO_TRACK_COUNT="X-WEBRTC-VIDEO-TRACK-COUNT",n.TRACKS_DIRECTION="X-WEBRTC-TRACKS-DIRECTION",n.AUDIO_ID="X-WEBRTC-AUDIOID",n))(g||{}),G=(n=>(n.AVAILABLE_SECOND_REMOTE_STREAM="YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="CONTENTEND",n.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",n))(G||{}),x=(n=>(n.SPECTATOR="SPECTATOR",n.PARTICIPANT="PARTICIPANT",n))(x||{}),y=(n=>(n.ENTER_ROOM="application/vinteo.webrtc.roomname",n.MIC="application/vinteo.webrtc.mic",n.USE_LICENSE="application/vinteo.webrtc.uselic",n.PARTICIPANT_STATE="application/vinteo.webrtc.partstate",n.NOTIFY="application/vinteo.webrtc.notify",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n))(y||{}),f=(n=>(n.CHANNELS="application/vinteo.webrtc.channels",n.MEDIA_STATE="application/vinteo.webrtc.mediastate",n.REFUSAL="application/vinteo.webrtc.refusal",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.STATS="application/vinteo.webrtc.stats",n))(f||{}),_=(n=>(n.PAUSE_MAIN_CAM="PAUSEMAINCAM",n.RESUME_MAIN_CAM="RESUMEMAINCAM",n.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",n.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",n.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",n))(_||{}),Q=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(Q||{}),Y=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(Y||{}),ge=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(ge||{}),l=(n=>(n.CHANNELS_NOTIFY="channels:notify",n.PARTICIPANT_ADDED_TO_LIST_MODERATORS="participant:added-to-list-moderators",n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS="participant:removed-from-list-moderators",n.PARTICIPANT_MOVE_REQUEST_TO_STREAM="participant:move-request-to-stream",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS="participant:move-request-to-spectators",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_SYNTHETIC="participant:move-request-to-spectators-synthetic",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_WITH_AUDIO_ID="participant:move-request-to-spectators-with-audio-id",n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS="participant:move-request-to-participants",n.PARTICIPATION_ACCEPTING_WORD_REQUEST="participation:accepting-word-request",n.PARTICIPATION_CANCELLING_WORD_REQUEST="participation:cancelling-word-request",n.WEBCAST_STARTED="webcast:started",n.WEBCAST_STOPPED="webcast:stopped",n.ACCOUNT_CHANGED="account:changed",n.ACCOUNT_DELETED="account:deleted",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="conference:participant-token-issued",n.CHANNELS="channels",n.ENTER_ROOM="enterRoom",n.SHARE_STATE="shareState",n.MAIN_CAM_CONTROL="main-cam-control",n.USE_LICENSE="useLicense",n.ADMIN_START_MAIN_CAM="admin-start-main-cam",n.ADMIN_STOP_MAIN_CAM="admin-stop-main-cam",n.ADMIN_START_MIC="admin-start-mic",n.ADMIN_STOP_MIC="admin-stop-mic",n.ADMIN_FORCE_SYNC_MEDIA_STATE="admin-force-sync-media-state",n.AVAILABLE_SECOND_REMOTE_STREAM="availableSecondRemoteStream",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="notAvailableSecondRemoteStream",n.MUST_STOP_PRESENTATION="mustStopPresentation",n.NEW_DTMF="newDTMF",n))(l||{});const ue=["participation:accepting-word-request","participation:cancelling-word-request","participant:move-request-to-stream","channels:notify","conference:participant-token-issued","account:changed","account:deleted","webcast:started","webcast:stopped","participant:added-to-list-moderators","participant:removed-from-list-moderators","participant:move-request-to-spectators","participant:move-request-to-spectators-synthetic","participant:move-request-to-spectators-with-audio-id","participant:move-request-to-participants","channels","enterRoom","shareState","main-cam-control","useLicense","admin-start-main-cam","admin-stop-main-cam","admin-start-mic","admin-stop-mic","admin-force-sync-media-state","availableSecondRemoteStream","notAvailableSecondRemoteStream","mustStopPresentation","newDTMF"],nt=()=>new I.TypedEvents(ue);var A=(n=>(n.CHANNELS="channels",n.WEBCAST_STARTED="WebcastStarted",n.WEBCAST_STOPPED="WebcastStopped",n.ACCOUNT_CHANGED="accountChanged",n.ACCOUNT_DELETED="accountDeleted",n.ADDED_TO_LIST_MODERATORS="addedToListModerators",n.REMOVED_FROM_LIST_MODERATORS="removedFromListModerators",n.ACCEPTING_WORD_REQUEST="ParticipationRequestAccepted",n.CANCELLING_WORD_REQUEST="ParticipationRequestRejected",n.MOVE_REQUEST_TO_STREAM="ParticipantMovedToWebcast",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="ConferenceParticipantTokenIssued",n))(A||{});class st{events;connectionManager;callManager;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.callManager=t,this.events=nt(),this.subscribe()}async waitChannels(){return this.wait(l.CHANNELS)}async waitSyncMediaState(){return this.wait(l.ADMIN_FORCE_SYNC_MEDIA_STATE)}async sendDTMF(e){return new Promise((t,s)=>{let i;try{i=this.getEstablishedRTCSessionProtected()}catch(r){s(r)}i&&(this.callManager.once("newDTMF",({originator:r})=>{r==="local"&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600}))})}async sendChannels({inputChannels:e,outputChannels:t}){const s=this.getEstablishedRTCSessionProtected(),i=`${g.INPUT_CHANNELS}: ${e}`,r=`${g.OUTPUT_CHANNELS}: ${t}`,a=[i,r];return s.sendInfo(f.CHANNELS,void 0,{extraHeaders:a})}async sendMediaState({cam:e,mic:t},s={}){const i=this.getEstablishedRTCSessionProtected(),r=`${g.MEDIA_STATE}: currentstate`,a=`${g.MAIN_CAM_STATE}: ${Number(e)}`,o=`${g.MIC_STATE}: ${Number(t)}`,c=[r,a,o];return i.sendInfo(f.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendStats({availableIncomingBitrate:e}){const t=this.getEstablishedRTCSessionProtected(),i=[`${g.AVAILABLE_INCOMING_BITRATE}: ${e}`];return t.sendInfo(f.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:i})}async sendRefusalToTurnOn(e,t={}){const s=this.getEstablishedRTCSessionProtected(),a=e==="mic"?0:1,c=[`${g.MEDIA_TYPE}: ${a}`];return s.sendInfo(f.REFUSAL,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendMustStopPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(f.SHARE_STATE,void 0,{extraHeaders:[g.MUST_STOP_PRESENTATION_P2P]})}async sendStoppedPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(f.SHARE_STATE,void 0,{extraHeaders:[g.STOP_PRESENTATION_P2P]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(f.SHARE_STATE,void 0,{extraHeaders:[g.STOP_PRESENTATION]})}async askPermissionToStartPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(f.SHARE_STATE,void 0,{extraHeaders:[g.START_PRESENTATION_P2P]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(f.SHARE_STATE,void 0,{extraHeaders:[g.START_PRESENTATION]})}async askPermissionToEnableCam(e={}){const t=this.getEstablishedRTCSessionProtected(),s=[g.ENABLE_MAIN_CAM];return t.sendInfo(f.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(i=>{if(tt(i))throw i})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}getEstablishedRTCSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};subscribe(){this.connectionManager.on("sipEvent",this.handleSipEvent),this.callManager.on("newInfo",this.handleNewInfo),this.callManager.on("newDTMF",e=>{this.events.trigger("newDTMF",e)})}handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{try{const t=e.getHeader(g.NOTIFY);if(t){const s=JSON.parse(t);this.handleNotify(s)}}catch(t){d("error parse notify",t)}};handleNotify=e=>{switch(e.cmd){case A.CHANNELS:{const t=e;this.triggerChannelsNotify(t);break}case A.WEBCAST_STARTED:{const t=e;this.triggerWebcastStartedNotify(t);break}case A.WEBCAST_STOPPED:{const t=e;this.triggerWebcastStoppedNotify(t);break}case A.ADDED_TO_LIST_MODERATORS:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case A.REMOVED_FROM_LIST_MODERATORS:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case A.ACCEPTING_WORD_REQUEST:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case A.CANCELLING_WORD_REQUEST:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case A.MOVE_REQUEST_TO_STREAM:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case A.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case A.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case A.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:d("unknown cmd",e)}};handleNewInfo=e=>{const{originator:t}=e;if(t!=="remote")return;const{request:s}=e,i=s,r=i.getHeader(g.CONTENT_TYPE);if(r!==void 0)switch(r){case y.ENTER_ROOM:{this.triggerEnterRoom(i),this.maybeTriggerChannels(i);break}case y.NOTIFY:{this.maybeHandleNotify(i);break}case y.SHARE_STATE:{this.triggerShareState(i);break}case y.MAIN_CAM:{this.triggerMainCamControl(i);break}case y.MIC:{this.triggerMicControl(i);break}case y.USE_LICENSE:{this.triggerUseLicense(i);break}case y.PARTICIPANT_STATE:{this.maybeTriggerParticipantMoveRequest(i);break}}};triggerChannelsNotify=e=>{const t=e.input,s=e.output,i={inputChannels:t,outputChannels:s};this.events.trigger(l.CHANNELS_NOTIFY,i)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(l.WEBCAST_STARTED,s)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(l.WEBCAST_STOPPED,s)};triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(l.PARTICIPANT_ADDED_TO_LIST_MODERATORS,t)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(l.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,t)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(l.PARTICIPATION_ACCEPTING_WORD_REQUEST,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(l.PARTICIPATION_CANCELLING_WORD_REQUEST,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_STREAM,t)};triggerAccountChangedNotify=()=>{this.events.trigger(l.ACCOUNT_CHANGED,{})};triggerAccountDeletedNotify=()=>{this.events.trigger(l.ACCOUNT_DELETED,{})};triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const i={conference:e,participant:t,jwt:s};this.events.trigger(l.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,i)};maybeTriggerChannels=e=>{const t=e.getHeader(g.INPUT_CHANNELS),s=e.getHeader(g.OUTPUT_CHANNELS);if(t&&s){const i={inputChannels:t,outputChannels:s};this.events.trigger(l.CHANNELS,i)}};triggerEnterRoom=e=>{const t=e.getHeader(g.CONTENT_ENTER_ROOM),s=e.getHeader(g.PARTICIPANT_NAME);this.events.trigger(l.ENTER_ROOM,{room:t,participantName:s})};triggerShareState=e=>{const t=e.getHeader(g.CONTENT_SHARE_STATE);if(t!==void 0)switch(t){case G.AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(l.AVAILABLE_SECOND_REMOTE_STREAM,{});break}case G.NOT_AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(l.NOT_AVAILABLE_SECOND_REMOTE_STREAM,{});break}case G.MUST_STOP_PRESENTATION:{this.events.trigger(l.MUST_STOP_PRESENTATION,{});break}}};maybeTriggerParticipantMoveRequest=e=>{const t=e.getHeader(g.CONTENT_PARTICIPANT_STATE),s=e.getHeader(g.AUDIO_ID);t===x.SPECTATOR&&(s?(this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_WITH_AUDIO_ID,{audioId:s}),this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,{isSynthetic:!1,audioId:s})):(this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_SYNTHETIC,{}),this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,{isSynthetic:!0}))),t===x.PARTICIPANT&&this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,{})};triggerMainCamControl=e=>{const t=e.getHeader(g.MAIN_CAM),s=e.getHeader(g.MEDIA_SYNC),i=s===Y.ADMIN_SYNC_FORCED;if(t===_.ADMIN_START_MAIN_CAM){this.events.trigger(l.ADMIN_START_MAIN_CAM,{isSyncForced:i});return}if(t===_.ADMIN_STOP_MAIN_CAM){this.events.trigger(l.ADMIN_STOP_MAIN_CAM,{isSyncForced:i});return}(t===_.RESUME_MAIN_CAM||t===_.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger(l.ADMIN_FORCE_SYNC_MEDIA_STATE,{isSyncForced:i});const r=e.getHeader(g.MAIN_CAM_RESOLUTION);this.events.trigger(l.MAIN_CAM_CONTROL,{mainCam:t,resolutionMainCam:r})};triggerMicControl=e=>{const t=e.getHeader(g.MIC),i=e.getHeader(g.MEDIA_SYNC)===Y.ADMIN_SYNC_FORCED;t===Q.ADMIN_START_MIC?this.events.trigger(l.ADMIN_START_MIC,{isSyncForced:i}):t===Q.ADMIN_STOP_MIC&&this.events.trigger(l.ADMIN_STOP_MIC,{isSyncForced:i})};triggerUseLicense=e=>{const t=e.getHeader(g.CONTENT_USE_LICENSE);this.events.trigger(l.USE_LICENSE,t)}}class q{actor;subscriptions=[];constructor(e){this.actor=N.createActor(e),this.actor.start()}get actorRef(){return this.actor}get state(){return this.getSnapshot().value}send(e){this.actor.send(e)}getSnapshot(){return this.actor.getSnapshot()}subscribe(e){const t=this.actor.subscribe(e);return this.addSubscription(t),t}stop(){this.subscriptions.forEach(e=>{e()}),this.subscriptions.length=0,this.actor.stop()}addSubscription(e){const t=typeof e=="function"?e:()=>{e.unsubscribe()};return this.subscriptions.push(t),t}}var Te=(n=>(n.IDLE="call:idle",n.CONNECTING="call:connecting",n.ACCEPTED="call:accepted",n.IN_CALL="call:inCall",n.ENDED="call:ended",n.FAILED="call:failed",n))(Te||{});const it=N.setup({types:{context:{},events:{}},actions:{rememberError:N.assign(({event:n})=>"error"in n&&n.error!==void 0?{lastError:n.error instanceof Error?n.error:new Error(JSON.stringify(n.error))}:{lastError:void 0}),resetError:N.assign({lastError:void 0})}}).createMachine({id:"call",initial:"call:idle",context:{},states:{"call:idle":{on:{"CALL.CONNECTING":{target:"call:connecting",actions:"resetError"}}},"call:connecting":{on:{"CALL.ACCEPTED":"call:accepted","CALL.ENDED":"call:ended","CALL.FAILED":{target:"call:failed",actions:"rememberError"}}},"call:accepted":{on:{"CALL.CONFIRMED":"call:inCall","CALL.ENDED":"call:ended","CALL.FAILED":{target:"call:failed",actions:"rememberError"}}},"call:inCall":{on:{"CALL.ENDED":"call:ended","CALL.FAILED":{target:"call:failed",actions:"rememberError"}}},"call:ended":{on:{"CALL.RESET":{target:"call:idle",actions:"resetError"},"CALL.CONNECTING":{target:"call:connecting",actions:"resetError"}}},"call:failed":{on:{"CALL.RESET":{target:"call:idle",actions:"resetError"},"CALL.CONNECTING":{target:"call:connecting",actions:"resetError"},"CALL.ENDED":{target:"call:ended",actions:"resetError"}}}}});class rt extends q{constructor(e){super(it),this.subscribeToEvents(e)}get isIdle(){return this.state==="call:idle"}get isConnecting(){return this.state==="call:connecting"}get isAccepted(){return this.state==="call:accepted"}get isInCall(){return this.state==="call:inCall"}get isEnded(){return this.state==="call:ended"}get isFailed(){return this.state==="call:failed"}get isActive(){return this.isAccepted||this.isInCall}get isPending(){return this.isConnecting}get lastError(){return this.getSnapshot().context.lastError}reset(){this.send({type:"CALL.RESET"})}send(e){if(!this.getSnapshot().can(e)){console.warn(`[CallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeToEvents(e){this.addSubscription(e.on("connecting",()=>{this.send({type:"CALL.CONNECTING"})})),this.addSubscription(e.on("accepted",()=>{this.send({type:"CALL.ACCEPTED"})})),this.addSubscription(e.on("confirmed",()=>{this.send({type:"CALL.CONFIRMED"})})),this.addSubscription(e.on("ended",()=>{this.send({type:"CALL.ENDED"})})),this.addSubscription(e.on("failed",t=>{this.send({type:"CALL.FAILED",error:t})}))}}var S=(n=>(n.PEER_CONNECTION="peerconnection",n.CONNECTING="connecting",n.SENDING="sending",n.PROGRESS="progress",n.ACCEPTED="accepted",n.CONFIRMED="confirmed",n.ENDED="ended",n.FAILED="failed",n.NEW_DTMF="newDTMF",n.NEW_INFO="newInfo",n.HOLD="hold",n.UNHOLD="unhold",n.MUTED="muted",n.UNMUTED="unmuted",n.REINVITE="reinvite",n.UPDATE="update",n.REFER="refer",n.REPLACES="replaces",n.SDP="sdp",n.ICE_CANDIDATE="icecandidate",n.GET_USER_MEDIA_FAILED="getusermediafailed",n.PEER_CONNECTION_CREATE_OFFER_FAILED="peerconnection:createofferfailed",n.PEER_CONNECTION_CREATE_ANSWER_FAILED="peerconnection:createanswerfailed",n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED="peerconnection:setlocaldescriptionfailed",n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED="peerconnection:setremotedescriptionfailed",n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n.PEER_CONNECTION_CONFIRMED="peerconnection:confirmed",n.PEER_CONNECTION_ONTRACK="peerconnection:ontrack",n.ENDED_FROM_SERVER="ended:fromserver",n.CALL_STATUS_CHANGED="call-status-changed",n.REMOTE_STREAMS_CHANGED="remote-streams-changed",n))(S||{}),Ee=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(Ee||{});const Se=["peerconnection","connecting","sending","progress","accepted","confirmed","ended","failed","hold","unhold","muted","unmuted","newInfo","newDTMF","presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed","reinvite","update","refer","replaces","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed"],at=["peerconnection:confirmed","peerconnection:ontrack","ended:fromserver","call-status-changed","remote-streams-changed"],pe=[...Se,...at],ot=()=>new I.TypedEvents(pe),ct=(n,e)=>{n.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},k=(n,{directionVideo:e,directionAudio:t,contentHint:s}={})=>{if(!n||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:n.getAudioTracks(),r=e==="recvonly"?[]:n.getVideoTracks(),a=[...i,...r],o=new MediaStream(a);return o.getTracks=()=>[...o.getAudioTracks(),...o.getVideoTracks()],s&&s!=="none"&&ct(o,s),o};var Z=(n=>(n.BYE="Terminated",n.WEBRTC_ERROR="WebRTC Error",n.CANCELED="Canceled",n.REQUEST_TIMEOUT="Request Timeout",n.REJECTED="Rejected",n.REDIRECTED="Redirected",n.UNAVAILABLE="Unavailable",n.NOT_FOUND="Not Found",n.ADDRESS_INCOMPLETE="Address Incomplete",n.INCOMPATIBLE_SDP="Incompatible SDP",n.BAD_MEDIA_DESCRIPTION="Bad Media Description",n))(Z||{});class dt{events;rtcSession;disposers=new Set;onReset;constructor(e,{onReset:t}){this.events=e,this.onReset=t,e.on(S.FAILED,this.handleEnded),e.on(S.ENDED,this.handleEnded)}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}getEstablishedRTCSession=()=>this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0;async renegotiate(){if(this.rtcSession===void 0)throw new Error("No rtcSession established");return this.rtcSession.renegotiate()}startCall=async(e,t,{number:s,mediaStream:i,extraHeaders:r=[],iceServers:a,directionVideo:o,directionAudio:c,contentHint:h,offerToReceiveAudio:E=!0,offerToReceiveVideo:u=!0,degradationPreference:T,sendEncodings:m,onAddedTransceiver:O})=>new Promise((R,D)=>{this.handleCall().then(R).catch(H=>{D(H)}),this.rtcSession=e.call(t(s),{mediaStream:k(i,{directionVideo:o,directionAudio:c,contentHint:h}),pcConfig:{iceServers:a},rtcOfferConstraints:{offerToReceiveAudio:E,offerToReceiveVideo:u},eventHandlers:this.events.triggers,extraHeaders:r,directionVideo:o,directionAudio:c,degradationPreference:T,sendEncodings:m,onAddedTransceiver:O})});async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:Z.CANCELED}).finally(()=>{this.reset()});this.reset()}answerToIncomingCall=async(e,{mediaStream:t,extraHeaders:s=[],iceServers:i,directionVideo:r,directionAudio:a,offerToReceiveAudio:o,offerToReceiveVideo:c,contentHint:h,degradationPreference:E,sendEncodings:u,onAddedTransceiver:T})=>new Promise((m,O)=>{try{this.rtcSession=e,this.subscribeToSessionEvents(e),this.handleCall().then(m).catch(R=>{O(R)}),e.answer({pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:o,offerToReceiveVideo:c},mediaStream:k(t,{directionVideo:r,directionAudio:a,contentHint:h}),extraHeaders:s,directionVideo:r,directionAudio:a,degradationPreference:E,sendEncodings:u,onAddedTransceiver:T})}catch(R){O(R)}});async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=t??{},i=k(e,{contentHint:s});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}async restartIce(e){if(!this.rtcSession)throw new Error("No rtcSession established");return this.rtcSession.restartIce(e)}handleCall=async()=>new Promise((e,t)=>{const s=()=>{this.events.on(S.PEER_CONNECTION,h),this.events.on(S.CONFIRMED,E)},i=()=>{this.events.off(S.PEER_CONNECTION,h),this.events.off(S.CONFIRMED,E)},r=()=>{this.events.on(S.FAILED,o),this.events.on(S.ENDED,o)},a=()=>{this.events.off(S.FAILED,o),this.events.off(S.ENDED,o)},o=u=>{i(),a(),t(u)};let c;const h=({peerconnection:u})=>{c=u;const T=m=>{this.events.trigger(S.PEER_CONNECTION_ONTRACK,m)};u.addEventListener("track",T),this.disposers.add(()=>{u.removeEventListener("track",T)})},E=()=>{c!==void 0&&this.events.trigger(S.PEER_CONNECTION_CONFIRMED,c),i(),a(),e(c)};s(),r()});subscribeToSessionEvents(e){this.events.eachTriggers((t,s)=>{const i=Se.find(r=>r===s);i&&(e.on(i,t),this.disposers.add(()=>{e.off(i,t)}))})}unsubscribeFromSessionEvents(){this.disposers.forEach(e=>{e()}),this.disposers.clear()}handleEnded=e=>{const{originator:t}=e;t==="remote"&&this.events.trigger(S.ENDED_FROM_SERVER,e),this.reset()};reset=()=>{delete this.rtcSession,this.unsubscribeFromSessionEvents(),this.onReset()}}class ht{config;tools;connection;constructor(e,t){this.config=e,this.tools=t,this.connection=new RTCPeerConnection(e.pcConfig),this.addTransceivers()}get settings(){return this.config}get peerConnection(){return this.connection}close(){this.connection.close()}async call(e){const t=this.waitForTracks(),s=await this.createOffer(),i=await this.tools.sendOffer({conferenceNumber:e,quality:this.config.quality,audioChannel:this.config.audioChannel},s);await this.setRemoteDescription(i),await t}async createOffer(){const e=await this.connection.createOffer();return await this.connection.setLocalDescription(e),e}async setRemoteDescription(e){return this.connection.setRemoteDescription(e)}async waitForTracks(){return new Promise(e=>{const t=new Set,s=i=>{const{track:r}=i;t.add(r.kind),t.has("audio")&&t.has("video")&&(this.connection.removeEventListener("track",s),e())};this.connection.addEventListener("track",s)})}addTransceivers(){this.addRecvOnlyTransceiver("audio"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video")}addRecvOnlyTransceiver(e){const t={direction:"recvonly"};return this.connection.addTransceiver(e,t)}}const Ce=n=>n.getSettings(),lt=(n,e)=>{const t=Ce(n);let s=e;s??=n.label;let i=t?.msid;return i??=s,i??=n.id,i},gt=(n,e)=>{const t=Ce(n);let s=e;return s??=t?.msid,s??=n.label,(s&&s.length>0?s:void 0)??n.id};class se{participantGroups=new Map;trackToGroup=new Map;trackDisposers=new Map;get mainStream(){const e=this.getStreams(),[t]=e;return t}reset(){this.participantGroups.clear(),this.trackToGroup.clear(),this.trackDisposers.forEach(e=>{e()}),this.trackDisposers.clear()}addTrack(e,{onRemoved:t,streamHint:s}={}){const i=gt(e,s),r=lt(e,s);if(this.trackToGroup.has(e.id))return{isAdded:!1};const a=this.getParticipantGroups(i);let o=a.get(r);o||(o={participantId:i,groupId:r,stream:new MediaStream,trackIds:new Set},a.set(r,o)),o.stream.addTrack(e),o.trackIds.add(e.id),this.trackToGroup.set(e.id,{participantId:i,groupId:r});const c=()=>{this.disposeTrackListener(e.id),this.removeTrack(e.id)&&t?.({trackId:e.id,participantId:i})};return e.addEventListener("ended",c),this.trackDisposers.set(e.id,()=>{e.removeEventListener("ended",c)}),{isAdded:!0,participantId:i}}removeTrack(e){this.disposeTrackListener(e);const t=this.trackToGroup.get(e);if(!t)return!1;const{participantId:s,groupId:i}=t,r=this.participantGroups.get(s),a=r?.get(i);if(!a)return this.trackToGroup.delete(e),!1;const o=a.stream.getTracks().find(c=>c.id===e);return o&&a.stream.removeTrack(o),a.trackIds.delete(e),this.trackToGroup.delete(e),a.trackIds.size===0&&(r?.delete(i),r?.size===0&&this.participantGroups.delete(s)),!0}removeStaleTracks(e,t){const s=this.participantGroups.get(e);if(!s)return!1;let i=!1;return[...s.values()].forEach(a=>{[...a.trackIds].filter(c=>!t.includes(c)).forEach(c=>{const h=this.removeTrack(c);i||=h})}),i}getStreams(e){if(e!==void 0){const t=this.participantGroups.get(e);return t?[...t.values()].map(s=>s.stream):[]}return[...this.participantGroups.values()].flatMap(t=>[...t.values()]).map(t=>t.stream)}disposeTrackListener(e){const t=this.trackDisposers.get(e);t&&(t(),this.trackDisposers.delete(e))}getParticipantGroups(e){const t=this.participantGroups.get(e);if(t)return t;const s=new Map;return this.participantGroups.set(e,s),s}}const V={type:"participant"},ut={type:"spectator_synthetic"},Tt=n=>({type:"spectator",recvParams:n});class b{role=V;mainManager;recvManager;onRoleChanged;constructor({mainManager:e,recvManager:t},s){this.mainManager=e,this.recvManager=t,this.onRoleChanged=s}static hasParticipant(e){return e.type==="participant"}static hasSpectatorSynthetic(e){return e.type==="spectator_synthetic"}static hasSpectator(e){return e.type==="spectator"}getRole(){return this.role}setCallRoleParticipant(){this.changeRole(V)}setCallRoleSpectatorSynthetic(){this.changeRole(ut)}setCallRoleSpectator(e){this.changeRole(Tt(e))}changeRole(e){const t=this.role;if(t.type!==e.type){this.setRole(e);return}b.hasSpectator(e)&&b.hasSpectator(t)&&t.recvParams.audioId!==e.recvParams.audioId&&this.setRole(e)}reset(){this.role=V,this.recvManager.reset()}getActiveManager(){return this.hasSpectator()?this.recvManager:this.mainManager}hasParticipant(){return b.hasParticipant(this.role)}hasSpectatorSynthetic(){return b.hasSpectatorSynthetic(this.role)}hasSpectator(){return b.hasSpectator(this.role)}setRole(e){const t=this.role;this.role=e,this.onRoleChanged?.({previous:t,next:e})}}const ie=n=>n.streams[0]?.id;class Et{events;callStateMachine;isPendingCall=!1;isPendingAnswer=!1;rtcSession;conferenceStateManager;mainRemoteStreamsManager=new se;recvRemoteStreamsManager=new se;roleManager=new b({mainManager:this.mainRemoteStreamsManager,recvManager:this.recvRemoteStreamsManager},e=>{this.onRoleChanged(e)});mcuSession;recvSession;disposeRecvSessionTrackListener;constructor(e){this.conferenceStateManager=e,this.events=ot(),this.mcuSession=new dt(this.events,{onReset:this.reset}),this.callStateMachine=new rt(this.events),this.subscribeCallStatusChange(),this.subscribeMcuRemoteTrackEvents()}get callActor(){return this.callStateMachine.actorRef}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.mcuSession.connection}get isCallActive(){return this.mcuSession.isCallActive}getEstablishedRTCSession=()=>this.mcuSession.getEstablishedRTCSession();on(e,t){return this.events.on(e,t)}onRace(e,t){return this.events.onRace(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}startCall=async(e,t,s)=>(this.isPendingCall=!0,this.conferenceStateManager.updateState({number:s.number,answer:!1}),this.mcuSession.startCall(e,t,s).finally(()=>{this.isPendingCall=!1}));async endCall(){return this.mcuSession.endCall()}async renegotiate(){return this.mcuSession.renegotiate()}answerToIncomingCall=async(e,t)=>{this.isPendingAnswer=!0;const s=e();return this.conferenceStateManager.updateState({answer:!0,number:s.remote_identity.uri.user}),this.mcuSession.answerToIncomingCall(s,t).finally(()=>{this.isPendingAnswer=!1})};getMainStream(){return this.getActiveStreamsManager().mainStream}getRemoteStreams(){return this.getActiveStreamsManager().getStreams()}setCallRoleParticipant(){this.roleManager.setCallRoleParticipant()}setCallRoleSpectatorSynthetic(){this.roleManager.setCallRoleSpectatorSynthetic()}setCallRoleSpectator(e){this.roleManager.setCallRoleSpectator(e)}async replaceMediaStream(e,t){return this.mcuSession.replaceMediaStream(e,t)}async restartIce(e){return this.mcuSession.restartIce(e)}reset=()=>{this.mainRemoteStreamsManager.reset(),this.conferenceStateManager.updateState({number:void 0,answer:!1}),this.roleManager.reset(),this.stopRecvSession()};subscribeCallStatusChange(){let{isCallActive:e}=this;const{ACCEPTED:t,CONFIRMED:s,ENDED:i,FAILED:r}=S;this.onRace([t,s,i,r],()=>{e=this.maybeTriggerCallStatus(e)})}maybeTriggerCallStatus(e){const t=this.isCallActive;return t!==e&&this.events.trigger(S.CALL_STATUS_CHANGED,{isCallActive:t}),t}subscribeMcuRemoteTrackEvents(){this.on(S.PEER_CONNECTION_ONTRACK,e=>{this.addRemoteTrack(this.mainRemoteStreamsManager,e.track,ie(e))})}addRemoteTrack(e,t,s){const i=e.addTrack(t,{streamHint:s,onRemoved:r=>{this.emitRemoteStreamsChanged(e,"removed",{trackId:r.trackId,participantId:r.participantId})}});i.isAdded&&this.emitRemoteStreamsChanged(e,"added",{trackId:t.id,participantId:i.participantId})}emitRemoteStreamsChanged(e,t,{trackId:s,participantId:i}){const r=this.getActiveStreamsManager();if(e!==r)return;const a=[...r.getStreams()];this.events.trigger(S.REMOTE_STREAMS_CHANGED,{participantId:i,changeType:t,trackId:s,streams:a})}getActiveStreamsManager(){return this.roleManager.getActiveManager()}attachRecvSessionTracks(e){const{peerConnection:t}=e,s=i=>{this.addRemoteTrack(this.recvRemoteStreamsManager,i.track,ie(i))};t.addEventListener("track",s),this.disposeRecvSessionTrackListener=()=>{t.removeEventListener("track",s)}}startRecvSession(e,t){const s=this.conferenceStateManager.getNumber();if(s===void 0)return;this.stopRecvSession();const i={quality:"high",audioChannel:e},r=new ht(i,{sendOffer:t});this.recvSession=r,this.recvRemoteStreamsManager.reset(),this.attachRecvSessionTracks(r),r.call(s).catch(()=>{this.stopRecvSession()})}stopRecvSession(){this.recvSession?.close(),this.recvSession=void 0,this.disposeRecvSessionTrackListener?.(),this.disposeRecvSessionTrackListener=void 0,this.recvRemoteStreamsManager.reset()}onRoleChanged=({previous:e,next:t})=>{if(b.hasSpectator(e)&&!b.hasSpectator(t)&&this.stopRecvSession(),b.hasSpectator(t)){const s=t.recvParams;this.startRecvSession(s.audioId,s.sendOffer)}}}const St=(n,e)=>(n.degradationPreference=e.degradationPreference,n),pt=(n,e)=>{n.encodings??=[];for(let t=n.encodings.length;t<e;t+=1)n.encodings.push({});return n},me=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,Ct=me(),mt=(n,e)=>{if(Ct(n,e))return n},Nt=(n,e)=>{const t=n.maxBitrate,s=mt(e,t);return s!==void 0&&(n.maxBitrate=s),n},Ne=1,Rt=me(Ne),At=(n,e)=>{const t=n===void 0?void 0:Math.max(n,Ne);if(t!==void 0&&Rt(t,e))return t},It=(n,e)=>{const t=n.scaleResolutionDownBy,s=At(e,t);return s!==void 0&&(n.scaleResolutionDownBy=s),n},ft=(n,e)=>{const t=e.encodings?.length??0;return pt(n,t),n.encodings.forEach((s,i)=>{const r=(e?.encodings??[])[i],a=r?.maxBitrate,o=r?.scaleResolutionDownBy;Nt(s,a),It(s,o)}),n},vt=(n,e)=>{if(n.codecs?.length!==e.codecs?.length)return!0;for(let t=0;t<(n.codecs?.length??0);t++)if(JSON.stringify(n.codecs[t])!==JSON.stringify(e.codecs[t]))return!0;if(n.headerExtensions?.length!==e.headerExtensions?.length)return!0;for(let t=0;t<(n.headerExtensions?.length??0);t++)if(JSON.stringify(n.headerExtensions[t])!==JSON.stringify(e.headerExtensions[t]))return!0;if(n.encodings?.length!==e.encodings?.length)return!0;for(let t=0;t<(n.encodings?.length??0);t++)if(JSON.stringify(n.encodings[t])!==JSON.stringify(e.encodings[t]))return!0;return n.rtcp?.cname!==e.rtcp?.cname||n.rtcp?.reducedSize!==e.rtcp?.reducedSize||n.degradationPreference!==e.degradationPreference},Re=async(n,e)=>{const t=n.getParameters(),s=JSON.parse(JSON.stringify(t));ft(t,e),St(t,e);const i=vt(s,t);return i&&await n.setParameters(t),{parameters:t,isChanged:i}},ee=async(n,e,t)=>{const{isChanged:s,parameters:i}=await Re(n,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return s&&t&&t(i),{isChanged:s,parameters:i}},Mt=(n,e)=>n.find(t=>t.track!==null&&e.getTracks().includes(t.track)),_t=async(n,e,t)=>{const s=Mt(n,e);if(s)return ee(s,{maxBitrate:t})};var P=(n=>(n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n))(P||{});const Ae=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],bt=()=>new I.TypedEvents(Ae);var Ie=(n=>(n.IDLE="presentation:idle",n.STARTING="presentation:starting",n.ACTIVE="presentation:active",n.STOPPING="presentation:stopping",n.FAILED="presentation:failed",n))(Ie||{});const Ot=N.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("PresentationStateMachine state changed",e.state)},setError:N.assign(({event:n})=>"error"in n&&n.error!==void 0?{lastError:n.error instanceof Error?n.error:new Error(JSON.stringify(n.error))}:{lastError:void 0}),clearError:N.assign({lastError:void 0})}}).createMachine({id:"presentation",initial:"presentation:idle",context:{},states:{"presentation:idle":{entry:{type:"logStateChange",params:{state:"presentation:idle"}},on:{"SCREEN.STARTING":{target:"presentation:starting",actions:["clearError",{type:"logTransition",params:{from:"presentation:idle",to:"presentation:starting",event:"SCREEN.STARTING"}}]}}},"presentation:starting":{entry:{type:"logStateChange",params:{state:"presentation:starting"}},on:{"SCREEN.STARTED":{target:"presentation:active",actions:{type:"logTransition",params:{from:"presentation:starting",to:"presentation:active",event:"SCREEN.STARTED"}}},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:active":{entry:{type:"logStateChange",params:{state:"presentation:active"}},on:{"SCREEN.ENDING":{target:"presentation:stopping",actions:{type:"logTransition",params:{from:"presentation:active",to:"presentation:stopping",event:"SCREEN.ENDING"}}},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:stopping":{entry:{type:"logStateChange",params:{state:"presentation:stopping"}},on:{"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:failed":{entry:{type:"logStateChange",params:{state:"presentation:failed"}},on:{"SCREEN.STARTING":{target:"presentation:starting",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:starting",event:"SCREEN.STARTING"}}]},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"PRESENTATION.RESET":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:idle",event:"PRESENTATION.RESET"}}]}}}}});class Pt extends q{constructor(e){super(Ot),this.subscribeCallEvents(e)}get isIdle(){return this.state==="presentation:idle"}get isStarting(){return this.state==="presentation:starting"}get isActive(){return this.state==="presentation:active"}get isStopping(){return this.state==="presentation:stopping"}get isFailed(){return this.state==="presentation:failed"}get isPending(){return this.isStarting||this.isStopping}get isActiveOrPending(){return this.isActive||this.isPending}get lastError(){return this.getSnapshot().context.lastError}reset(){this.send({type:"PRESENTATION.RESET"})}send(e){if(!this.getSnapshot().can(e)){console.warn(`[PresentationStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeCallEvents(e){this.addSubscription(e.on(S.START_PRESENTATION,()=>{this.send({type:"SCREEN.STARTING"})})),this.addSubscription(e.on(S.STARTED_PRESENTATION,()=>{this.send({type:"SCREEN.STARTED"})})),this.addSubscription(e.on(S.END_PRESENTATION,()=>{this.send({type:"SCREEN.ENDING"})})),this.addSubscription(e.on(S.ENDED_PRESENTATION,()=>{this.send({type:"SCREEN.ENDED"})})),this.addSubscription(e.on(S.FAILED_PRESENTATION,t=>{this.send({type:"SCREEN.FAILED",error:t})})),this.addSubscription(e.on(S.ENDED,()=>{this.send({type:"CALL.ENDED"})})),this.addSubscription(e.on(S.FAILED,t=>{this.send({type:"CALL.FAILED",error:t})}))}}const yt=1,Dt=n=>z.hasCanceledError(n);class wt{events;presentationStateMachine;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;maxBitrate;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e,maxBitrate:t}){this.callManager=e,this.maxBitrate=t,this.events=bt(),this.presentationStateMachine=new Pt(this.callManager.events),this.subscribe()}get presentationActor(){return this.presentationStateMachine.actorRef}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}get isPresentationInProcess(){return!!this.streamPresentationCurrent||this.isPendingPresentation}async startPresentation(e,t,{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a}={},o){const c=this.getRtcSessionProtected();if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return this.sendPresentationWithDuplicatedCalls(e,{rtcSession:c,stream:t,presentationOptions:{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a},options:o})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve(void 0);this.promisePendingStartPresentation&&await this.promisePendingStartPresentation.catch(()=>{});const i=this.callManager.getEstablishedRTCSession();return i&&t?s=e().then(async()=>i.stopPresentation(t)).catch(r=>{const a=r instanceof Error?r:new Error(String(r));throw this.events.trigger(P.FAILED_PRESENTATION,a),r}):t&&this.events.trigger(P.ENDED_PRESENTATION,t),this.promisePendingStopPresentation=s,s.finally(()=>{this.resetPresentation()})}async updatePresentation(e,t,{contentHint:s,sendEncodings:i,onAddedTransceiver:r}={}){const a=this.getRtcSessionProtected();if(!this.streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this.sendPresentation(e,a,t,{contentHint:s,isNeedReinvite:!1,sendEncodings:i,onAddedTransceiver:r}).then(async o=>(await this.setMaxBitrate(),o))}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.stopRepeatedCalls()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("presentation:start",e=>{this.events.trigger(P.START_PRESENTATION,e)}),this.callManager.on("presentation:started",e=>{this.events.trigger(P.STARTED_PRESENTATION,e)}),this.callManager.on("presentation:end",e=>{this.events.trigger(P.END_PRESENTATION,e)}),this.callManager.on("presentation:ended",e=>{this.events.trigger(P.ENDED_PRESENTATION,e)}),this.callManager.on("presentation:failed",e=>{this.events.trigger(P.FAILED_PRESENTATION,e)}),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded)}async sendPresentationWithDuplicatedCalls(e,{rtcSession:t,stream:s,presentationOptions:i,options:r={callLimit:yt}}){const a=async()=>this.sendPresentation(e,t,s,i),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=z.repeatedCallsAsync({targetFunction:a,isComplete:o,isRejectAsValid:!0,...r}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}async sendPresentation(e,t,s,{isNeedReinvite:i=!0,contentHint:r="detail",degradationPreference:a,sendEncodings:o,onAddedTransceiver:c}){const h=k(s,{contentHint:r});if(h===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=h;const E=e().then(async()=>t.startPresentation(h,i,{degradationPreference:a,sendEncodings:o,onAddedTransceiver:c})).then(this.setMaxBitrate).then(()=>s).catch(u=>{this.removeStreamPresentationCurrent();const T=u instanceof Error?u:new Error(String(u));throw this.events.trigger(P.FAILED_PRESENTATION,T),u});return this.promisePendingStartPresentation=E,E.finally(()=>{this.promisePendingStartPresentation=void 0})}setMaxBitrate=async()=>{const{connection:e}=this.callManager,{streamPresentationCurrent:t}=this,{maxBitrate:s}=this;if(!e||!t||s===void 0)return;const i=e.getSenders();await _t(i,t,s)};getRtcSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};handleEnded=()=>{this.reset()};reset(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}}class Lt{data;getUa;constructor(e){this.getUa=e.getUa}isConfigured(){return this.getUa()!==void 0}get(){if(this.data!==void 0)return{...this.data}}set(e){if(e===void 0){this.data=void 0;return}this.data={...e}}update(e,t){if(this.data===void 0)throw new Error("data is not exist");this.data[e]=t}clear(){this.data=void 0}isRegister(){return this.data?.register===!0}getSipServerIp(){return this.data?.sipServerIp}getSipServerUrl(){return this.data?.sipServerUrl}getDisplayName(){return this.data?.displayName}getUser(){return this.data?.user}getPassword(){return this.data?.password}isRegisterEnabled(){return this.data?.register===!0}}var p=(n=>(n.CONNECTING="connecting",n.CONNECTED="connected",n.DISCONNECTED="disconnected",n.DISCONNECTING="disconnecting",n.NEW_RTC_SESSION="newRTCSession",n.REGISTERED="registered",n.UNREGISTERED="unregistered",n.REGISTRATION_FAILED="registrationFailed",n.NEW_MESSAGE="newMessage",n.SIP_EVENT="sipEvent",n.CONNECT_STARTED="connect-started",n.CONNECT_SUCCEEDED="connect-succeeded",n.CONNECT_FAILED="connect-failed",n.CONNECT_PARAMETERS_RESOLVE_SUCCESS="connect-parameters-resolve-success",n.CONNECT_PARAMETERS_RESOLVE_FAILED="connect-parameters-resolve-failed",n.CONNECTED_WITH_CONFIGURATION="connected-with-configuration",n))(p||{});const fe=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],Ut=["disconnecting","connect-started","connect-succeeded","connect-failed","connect-parameters-resolve-success","connect-parameters-resolve-failed","connected-with-configuration"],ve=[...fe,...Ut],Ft=()=>new I.TypedEvents(ve);function kt(n){return e=>`sip:${e}@${n}`}const Bt=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,Me=n=>n.trim().replaceAll(" ","_"),$t=Bt(1e5,99999999),Gt=3;class qt{cancelableConnectWithRepeatedCalls;JsSIP;events;uaFactory;stateMachine;registrationManager;getUa;setUa;getConnectionConfiguration;setConnectionConfiguration;updateConnectionConfiguration;setGetUri;setSocket;constructor(e){this.JsSIP=e.JsSIP,this.events=e.events,this.uaFactory=e.uaFactory,this.stateMachine=e.stateMachine,this.registrationManager=e.registrationManager,this.getUa=e.getUa,this.setUa=e.setUa,this.getConnectionConfiguration=e.getConnectionConfiguration,this.setConnectionConfiguration=e.setConnectionConfiguration,this.updateConnectionConfiguration=e.updateConnectionConfiguration,this.setGetUri=e.setGetUri,this.setSocket=e.setSocket,this.proxyEvents()}connect=async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t));set=async({displayName:e})=>new Promise((t,s)=>{const i=this.getUa();if(!i){s(new Error("this.ua is not initialized"));return}let r=!1;const a=this.getConnectionConfiguration();e!==void 0&&e!==a?.displayName&&(r=i.set("display_name",Me(e)),this.updateConnectionConfiguration("displayName",e));const o=r;o?t(o):s(new Error("nothing changed"))});disconnect=async()=>{this.events.trigger(p.DISCONNECTING,{});const e=new Promise(s=>{this.events.once(p.DISCONNECTED,()=>{s()})}),t=this.getUa();return t?t.stop():this.events.trigger(p.DISCONNECTED,{socket:{},error:!1}),e.finally(()=>{t?.removeAllListeners(),this.setUa(void 0),this.stateMachine.reset()})};cancelRequests(){this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{callLimit:t=Gt}={})=>{const s=async()=>this.connectInner(e),i=r=>{const c=this.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),h=r!=null&&!et(r);return c||h};return this.stateMachine.startConnect(),this.cancelableConnectWithRepeatedCalls=z.repeatedCallsAsync({targetFunction:s,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(r=>{if("ua"in r&&r.ua instanceof this.JsSIP.UA)return r;throw r})};hasEqualConnectionConfiguration(e){const{configuration:t}=this.uaFactory.createConfiguration(e),i=this.getUa()?.configuration;return i?i.password===t.password&&i.register===t.register&&i.uri.toString()===t.uri&&i.display_name===t.display_name&&i.user_agent===t.user_agent&&i.sockets===t.sockets&&i.session_timers===t.session_timers&&i.register_expires===t.register_expires&&i.connection_recovery_min_interval===t.connection_recovery_min_interval&&i.connection_recovery_max_interval===t.connection_recovery_max_interval:!1}connectInner=async e=>this.initUa(e).then(async()=>this.start()).then(t=>{const s=this.getConnectionConfiguration();if(s===void 0)throw new Error("connectionConfiguration has not defined");return{...s,ua:t}});initUa=async({user:e,password:t,sipServerIp:s,sipServerUrl:i,remoteAddress:r,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:h,userAgent:E,displayName:u="",register:T=!1,extraHeaders:m=[]})=>{this.stateMachine.startInitUa(),this.setConnectionConfiguration({sipServerIp:s,sipServerUrl:i,displayName:u,register:T,user:e,password:t}),this.getUa()&&await this.disconnect();const{ua:R,helpers:D}=this.uaFactory.createUAWithConfiguration({user:e,password:t,sipServerIp:s,sipServerUrl:i,displayName:u,register:T,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:h,userAgent:E,remoteAddress:r,extraHeaders:m},this.events);return this.setUa(R),this.setGetUri(D.getUri),this.setSocket(D.socket),R};start=async()=>new Promise((e,t)=>{const s=this.getUa();if(!s){t(new Error("this.ua is not initialized"));return}let i;i=((c,h)=>{if(this.getConnectionConfiguration()?.register===!0)return this.registrationManager.subscribeToStartEvents(c,h);const u=p.CONNECTED,T=[p.DISCONNECTED];return this.events.on(u,c),T.forEach(m=>{this.events.on(m,h)}),()=>{this.events.off(u,c),T.forEach(m=>{this.events.off(m,h)})}})(()=>{i?.(),e(s)},c=>{i?.(),t(c)}),s.start()});cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}proxyEvents(){this.events.on(p.CONNECTED,()=>{const e=this.getConnectionConfiguration(),t=this.getUa();e!==void 0&&t!==void 0&&this.events.trigger(p.CONNECTED_WITH_CONFIGURATION,{...e,ua:t})})}}var _e=(n=>(n.IDLE="connection:idle",n.PREPARING="connection:preparing",n.CONNECTING="connection:connecting",n.CONNECTED="connection:connected",n.REGISTERED="connection:registered",n.ESTABLISHED="connection:established",n.DISCONNECTED="connection:disconnected",n.FAILED="connection:failed",n))(_e||{}),be=(n=>(n.START_CONNECT="START_CONNECT",n.START_INIT_UA="START_INIT_UA",n.UA_CONNECTED="UA_CONNECTED",n.UA_REGISTERED="UA_REGISTERED",n.UA_UNREGISTERED="UA_UNREGISTERED",n.UA_DISCONNECTED="UA_DISCONNECTED",n.CONNECTION_FAILED="CONNECTION_FAILED",n.RESET="RESET",n))(be||{});const Ht=Object.values(be),Vt=N.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("ConnectionStateMachine state changed",e.state)},setError:N.assign({error:({event:n})=>{if(n.type==="CONNECTION_FAILED"&&"error"in n)return n.error}}),clearError:N.assign({error:()=>{}})}}).createMachine({id:"connection",initial:"connection:idle",context:{},states:{"connection:idle":{entry:{type:"logStateChange",params:{state:"connection:idle"}},on:{START_CONNECT:{target:"connection:preparing",actions:{type:"logTransition",params:{from:"connection:idle",to:"connection:preparing",event:"START_CONNECT"}}}}},"connection:preparing":{entry:{type:"logStateChange",params:{state:"connection:preparing"}},on:{START_INIT_UA:{target:"connection:connecting",actions:{type:"logTransition",params:{from:"connection:preparing",to:"connection:connecting",event:"START_INIT_UA"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:preparing",to:"connection:disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"connection:failed",actions:[{type:"logTransition",params:{from:"connection:preparing",to:"connection:failed",event:"CONNECTION_FAILED"}},{type:"setError"}]}}},"connection:connecting":{entry:{type:"logStateChange",params:{state:"connection:connecting"}},on:{UA_CONNECTED:{target:"connection:connected",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:connected",event:"UA_CONNECTED"}}},UA_REGISTERED:{target:"connection:registered",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"connection:failed",actions:[{type:"logTransition",params:{from:"connection:connecting",to:"connection:failed",event:"CONNECTION_FAILED"}},{type:"setError"}]}}},"connection:connected":{entry:{type:"logStateChange",params:{state:"connection:connected"}},always:{target:"connection:established",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:established",event:"always"}}},on:{UA_REGISTERED:{target:"connection:registered",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:registered":{entry:{type:"logStateChange",params:{state:"connection:registered"}},always:{target:"connection:established",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:established",event:"always"}}},on:{UA_UNREGISTERED:{target:"connection:connected",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:connected",event:"UA_UNREGISTERED"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:established":{entry:{type:"logStateChange",params:{state:"connection:established"}},on:{UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:established",to:"connection:disconnected",event:"UA_DISCONNECTED"}}},RESET:{target:"connection:idle",actions:{type:"logTransition",params:{from:"connection:established",to:"connection:idle",event:"RESET"}}}}},"connection:disconnected":{entry:{type:"logStateChange",params:{state:"connection:disconnected"}},on:{RESET:{target:"connection:idle",actions:{type:"logTransition",params:{from:"connection:disconnected",to:"connection:idle",event:"RESET"}}},START_CONNECT:{target:"connection:preparing",actions:{type:"logTransition",params:{from:"connection:disconnected",to:"connection:preparing",event:"START_CONNECT"}}}}},"connection:failed":{entry:{type:"logStateChange",params:{state:"connection:failed"}},on:{RESET:{target:"connection:idle",actions:[{type:"logTransition",params:{from:"connection:failed",to:"connection:idle",event:"RESET"}},{type:"clearError"}]},START_CONNECT:{target:"connection:preparing",actions:[{type:"logTransition",params:{from:"connection:failed",to:"connection:preparing",event:"START_CONNECT"}},{type:"clearError"}]}}}}});class Wt extends q{stateChangeListeners=new Set;events;unsubscribeFromEvents;constructor(e){super(Vt),this.events=e,this.addSubscription(this.subscribe(t=>{const s=t.value;this.stateChangeListeners.forEach(i=>{i(s)})})),this.subscribeToEvents()}get isIdle(){return this.hasState("connection:idle")}get isPreparing(){return this.hasState("connection:preparing")}get isConnecting(){return this.hasState("connection:connecting")}get isConnected(){return this.hasState("connection:connected")}get isRegistered(){return this.hasState("connection:registered")}get isEstablished(){return this.hasState("connection:established")}get isDisconnected(){return this.hasState("connection:disconnected")}get isFailed(){return this.hasState("connection:failed")}get error(){return this.getSnapshot().context.error}get isPending(){return this.isPreparing||this.isConnecting}get isPendingConnect(){return this.isPreparing}get isPendingInitUa(){return this.isConnecting}get isActiveConnection(){return this.isEstablished||this.isConnected||this.isRegistered}startConnect(){this.toStartConnect()}startInitUa(){this.toStartInitUa()}reset(){this.toIdle()}destroy(){this.stateChangeListeners.clear(),this.unsubscribeFromEvents?.(),this.stop()}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}canTransition(e){return this.getSnapshot().can({type:e})}getValidEvents(){return Ht.filter(e=>this.canTransition(e))}hasState(e){return this.getSnapshot().matches(e)}sendEvent(e){if(!this.getSnapshot().can(e)){d(`Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}this.send(e)}toStartConnect=()=>{this.sendEvent({type:"START_CONNECT"})};toStartInitUa=()=>{this.sendEvent({type:"START_INIT_UA"})};toConnected=()=>{this.sendEvent({type:"UA_CONNECTED"})};toRegistered=()=>{this.sendEvent({type:"UA_REGISTERED"})};toUnregistered=()=>{this.sendEvent({type:"UA_UNREGISTERED"})};toDisconnected=()=>{this.sendEvent({type:"UA_DISCONNECTED"})};toFailed=e=>{this.sendEvent({type:"CONNECTION_FAILED",error:e})};toIdle=()=>{this.sendEvent({type:"RESET"})};subscribeToEvents(){this.events.on("connected",this.toConnected),this.events.on("registered",this.toRegistered),this.events.on("unregistered",this.toUnregistered),this.events.on("disconnected",this.toDisconnected),this.events.on("registrationFailed",this.handleRegistrationFailed),this.events.on("connect-failed",this.handleConnectFailed),this.unsubscribeFromEvents=()=>{this.events.off("connected",this.toConnected),this.events.off("registered",this.toRegistered),this.events.off("unregistered",this.toUnregistered),this.events.off("disconnected",this.toDisconnected),this.events.off("registrationFailed",this.handleRegistrationFailed),this.events.off("connect-failed",this.handleConnectFailed)}}handleRegistrationFailed=e=>{const t=e.response?.status_code??"Unknown",s=e.response?.reason_phrase??"Registration failed",i=new Error(`Registration failed: ${t} ${s}`);this.toFailed(i)};handleConnectFailed=e=>{this.toFailed(e instanceof Error?e:void 0)}}class xt{events;getUaProtected;constructor(e){this.events=e.events,this.getUaProtected=e.getUaProtected}async register(){const e=this.getUaProtected();return new Promise((t,s)=>{e.on(p.REGISTERED,t),e.on(p.REGISTRATION_FAILED,s),e.register()})}async unregister(){const e=this.getUaProtected();return new Promise(t=>{e.on(p.UNREGISTERED,t),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){d("tryRegister",e)}return this.register()}subscribeToStartEvents(e,t){const s=p.REGISTERED,i=[p.REGISTRATION_FAILED,p.DISCONNECTED];return this.events.on(s,e),i.forEach(r=>{this.events.on(r,t)}),()=>{this.events.off(s,e),i.forEach(r=>{this.events.off(r,t)})}}}class Qt{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,t,s){const i=this.getUaProtected();return new Promise((r,a)=>{try{i.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{r()},failed:a}})}catch(o){a(o)}})}async ping(e,t){const i=this.getUaProtected().configuration.uri;return this.sendOptions(i,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerIp:s,sipServerUrl:i,remoteAddress:r,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:h}=this.uaFactory.createConfiguration({sipServerUrl:i,displayName:t,userAgent:e,sipServerIp:s}),E=this.uaFactory.createUA({...h,remoteAddress:r,extraHeaders:a}),u=()=>{const m=new Error("Telephony is not available");c(m)};E.once(p.DISCONNECTED,u);const T=()=>{E.removeAllListeners(),E.once(p.DISCONNECTED,()=>{o()}),E.stop()};E.once(p.CONNECTED,T),E.start()})}}const Yt=n=>{const e=[];return n!==void 0&&n!==""&&e.push(`X-Vinteo-Remote: ${n}`),e};class w{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateParametersConnection({register:e,password:t,user:s,sipServerIp:i,sipServerUrl:r}){if(!i)throw new Error("sipServerIp is required");if(!r)throw new Error("sipServerUrl is required");if(e&&(t===void 0||t===""))throw new Error("password is required for authorized connection");if(e&&(s===void 0||s===""))throw new Error("user is required for authorized connection")}static resolveAuthorizationUser(e,t){return e&&t!==void 0&&t.trim()!==""?t.trim():`${$t()}`}static buildExtraHeaders(e,t){const s=e!==void 0&&e!==""?Yt(e):[];return t===void 0?s:[...s,...t]}createConfiguration({user:e,password:t,sipServerUrl:s,displayName:i="",sipServerIp:r,register:a=!1,sessionTimers:o=!1,registerExpires:c=300,connectionRecoveryMinInterval:h=2,connectionRecoveryMaxInterval:E=6,userAgent:u}){w.validateParametersConnection({register:a,password:t,user:e,sipServerIp:r,sipServerUrl:s});const T=w.resolveAuthorizationUser(a,e),m=kt(r),O=m(T),R=new this.JsSIP.WebSocketInterface(`wss://${s}/webrtc/wss/`);return{configuration:{password:t,register:a,uri:O,display_name:Me(i),user_agent:u,sdpSemantics:"unified-plan",sockets:[R],session_timers:o,register_expires:c,connection_recovery_min_interval:h,connection_recovery_max_interval:E},helpers:{socket:R,getUri:m}}}createUA({remoteAddress:e,extraHeaders:t,...s}){const i=new this.JsSIP.UA(s),r=w.buildExtraHeaders(e,t);return r.length>0&&i.registrator().setExtraHeaders(r),i}createUAWithConfiguration(e,t){const{configuration:s,helpers:i}=this.createConfiguration(e),r=this.createUA({...s,remoteAddress:e.remoteAddress,extraHeaders:e.extraHeaders});return t.eachTriggers((a,o)=>{const c=fe.find(h=>h===o);c&&r.on(c,a)}),{ua:r,helpers:i}}}const Oe="Not ready for connection",Pe=n=>n instanceof Error&&n.message===Oe,Xt=()=>new Error(Oe),Jt=async n=>typeof n=="function"?n():n;class zt{events;ua;socket;uaFactory;registrationManager;stateMachine;connectionFlow;sipOperations;configurationManager;JsSIP;constructor({JsSIP:e}){this.JsSIP=e,this.events=Ft(),this.uaFactory=new w(e),this.registrationManager=new xt({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new Wt(this.events),this.configurationManager=new Lt({getUa:this.getUa}),this.sipOperations=new Qt({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new qt({JsSIP:this.JsSIP,events:this.events,uaFactory:this.uaFactory,stateMachine:this.stateMachine,registrationManager:this.registrationManager,getUa:this.getUa,getConnectionConfiguration:this.getConnectionConfiguration,setConnectionConfiguration:t=>{this.configurationManager.set(t)},updateConnectionConfiguration:(t,s)=>{this.configurationManager.update(t,s)},setUa:t=>{this.ua=t},setGetUri:t=>{this.getUri=t},setSocket:t=>{this.socket=t}})}get requested(){return this.stateMachine.isPending}get isPendingConnect(){return this.stateMachine.isPendingConnect}get isPendingInitUa(){return this.stateMachine.isPendingInitUa}get isIdle(){return this.stateMachine.isIdle}get isDisconnected(){return this.stateMachine.isDisconnected}get isFailed(){return this.stateMachine.isFailed}get connectionActor(){return this.stateMachine.actorRef}get connectionState(){return this.stateMachine.state}get isRegistered(){return w.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.configurationManager.isRegister()}connect=async(e,t)=>this.disconnect().catch(s=>{d("connect: disconnect error",s)}).then(async()=>this.connectWithProcessError(e,t));set=async({displayName:e})=>this.connectionFlow.set({displayName:e});disconnect=async()=>{if(this.isConfigured())return this.connectionFlow.disconnect()};async register(){return this.registrationManager.register()}async unregister(){return this.registrationManager.unregister()}tryRegister=async()=>this.registrationManager.tryRegister();sendOptions=async(e,t,s)=>this.sipOperations.sendOptions(e,t,s);ping=async(e,t)=>this.sipOperations.ping(e,t);checkTelephony=async e=>this.sipOperations.checkTelephony(e);on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}isConfigured(){return this.configurationManager.isConfigured()}getConnectionConfiguration=()=>this.configurationManager.get();destroy(){this.stateMachine.destroy()}getUri=e=>e;getUaProtected=()=>{if(!this.ua)throw new Error("UA not initialized");return this.ua};getUa=()=>this.ua;connectWithProcessError=async(e,t)=>{if(!(t?.hasReadyForConnection?.()??!0))throw Xt();return this.processConnect(e,t).catch(async i=>{const r=i;return this.disconnect().then(()=>{throw r}).catch(()=>{throw r})})};processConnect=async(e,t)=>(this.events.trigger(p.CONNECT_STARTED,{}),Jt(e).then(s=>(this.events.trigger(p.CONNECT_PARAMETERS_RESOLVE_SUCCESS,s),s)).catch(s=>{throw this.events.trigger(p.CONNECT_PARAMETERS_RESOLVE_FAILED,s),s}).then(async s=>this.connectionFlow.connect(s,t)).then(s=>(this.events.trigger(p.CONNECT_SUCCEEDED,{...s}),s)).catch(s=>{const i=s??new Error("Failed to connect to server");throw this.events.trigger(p.CONNECT_FAILED,i),i}))}class Kt{connectionManager;stackPromises=K.createStackPromises({noRunIsNotActual:!0});constructor({connectionManager:e}){this.connectionManager=e}connect=async(...e)=>this.stackPromises.run(async()=>this.connectionManager.connect(...e));disconnect=async()=>this.stackPromises.run(async()=>this.connectionManager.disconnect());stop(){this.stackPromises.stop()}}const re=0,jt=30;class Zt{countInner=re;initialCount=re;limitInner=jt;isInProgress=!1;onStatusChange;constructor({onStatusChange:e}){this.onStatusChange=e}get count(){return this.countInner}get limit(){return this.limitInner}get isAttemptInProgress(){return this.isInProgress}hasLimitReached(){return this.countInner>=this.limitInner}startAttempt(){this.isInProgress||(this.isInProgress=!0,this.onStatusChange({isInProgress:this.isInProgress}))}finishAttempt(){this.isInProgress&&(this.isInProgress=!1,this.onStatusChange({isInProgress:this.isInProgress}))}increment(){this.count<this.limit&&(this.countInner+=1)}reset(){this.countInner=this.initialCount,this.finishAttempt()}}class en{connectionManager;interval;checkTelephonyByTimeout=void 0;cancelableBeforeRequest=void 0;constructor({connectionManager:e,interval:t}){this.connectionManager=e,this.interval=t}start({onBeforeRequest:e,onSuccessRequest:t,onFailRequest:s}){this.stop(),this.cancelableBeforeRequest=new B.CancelableRequest(e),this.checkTelephonyByTimeout=L.resolveRequesterByTimeout({isDontStopOnFail:!0,requestInterval:this.interval,request:async()=>{if(!this.cancelableBeforeRequest)throw new Error("cancelableBeforeRequest is not defined");const i=await this.cancelableBeforeRequest.request();return this.connectionManager.checkTelephony(i)}}),this.checkTelephonyByTimeout.start(void 0,{onFailRequest:s,onSuccessRequest:()=>{this.stop(),t()}})}stop(){this.checkTelephonyByTimeout?.stop(),this.checkTelephonyByTimeout=void 0,this.cancelableBeforeRequest?.cancelRequest(),this.cancelableBeforeRequest=void 0}}var v=(n=>(n.BEFORE_ATTEMPT="before-attempt",n.SUCCESS="success",n.FAILED_ALL_ATTEMPTS="failed-all-attempts",n.CANCELLED_ATTEMPTS="cancelled-attempts",n.CHANGED_ATTEMPT_STATUS="changed-attempt-status",n.STOP_ATTEMPTS_BY_ERROR="stop-attempts-by-error",n.LIMIT_REACHED_ATTEMPTS="limit-reached-attempts",n))(v||{});const ye=["before-attempt","success","failed-all-attempts","cancelled-attempts","changed-attempt-status","stop-attempts-by-error","limit-reached-attempts"],tn=()=>new I.TypedEvents(ye);class te{callManager;disposers=[];constructor({callManager:e}){this.callManager=e}subscribe(e){this.unsubscribe(),this.disposers.push(this.callManager.on("call-status-changed",()=>{this.handleCallStatusChange(e)})),this.handleCallStatusChange(e)}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[]}handleCallStatusChange({onActive:e,onInactive:t}){this.callManager.isCallActive?e?.():t()}}const nn=15e3,sn=2;class rn{connectionManager;pingServerByTimeoutWithFailCalls;constructor({connectionManager:e}){this.connectionManager=e,this.pingServerByTimeoutWithFailCalls=L.requesterByTimeoutsWithFailCalls(sn,{whenPossibleRequest:async()=>{},requestInterval:nn,request:async()=>(d("ping"),this.connectionManager.ping().then(()=>{d("ping success")}))})}start({onFailRequest:e}){this.pingServerByTimeoutWithFailCalls.start(void 0,{onFailRequest:e}).catch(d)}stop(){this.pingServerByTimeoutWithFailCalls.stop()}}class an{pingServerRequester;notActiveCallSubscriber;constructor({connectionManager:e,callManager:t}){this.pingServerRequester=new rn({connectionManager:e}),this.notActiveCallSubscriber=new te({callManager:t})}start({onFailRequest:e}){d("start"),this.notActiveCallSubscriber.subscribe({onActive:()=>{this.pingServerRequester.stop()},onInactive:()=>{this.pingServerRequester.start({onFailRequest:e})}})}stop(){d("stop"),this.pingServerRequester.stop(),this.unsubscribeCallStatusChange()}unsubscribeCallStatusChange(){this.notActiveCallSubscriber.unsubscribe()}}class on{connectionManager;isRegistrationFailed=!1;disposers=[];notActiveCallSubscriber;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.notActiveCallSubscriber=new te({callManager:t})}subscribe(e){this.unsubscribe(),this.disposers.push(this.connectionManager.on("registrationFailed",()=>{this.setIsRegistrationFailed()})),this.notActiveCallSubscriber.subscribe({onInactive:()=>{this.isRegistrationFailed&&e()}}),this.disposers.push(()=>{this.notActiveCallSubscriber.unsubscribe()})}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[],this.resetIsRegistrationFailed()}setIsRegistrationFailed(){this.isRegistrationFailed=!0}resetIsRegistrationFailed(){this.isRegistrationFailed=!1}}const cn=3e3,dn=15e3,ae={LIMIT_REACHED:"Limit reached",FAILED_TO_RECONNECT:"Failed to reconnect"},hn=async()=>{},ln=n=>!0;class gn{events;connectionManager;connectionQueueManager;checkTelephonyRequester;pingServerIfNotActiveCallRequester;registrationFailedOutOfCallSubscriber;attemptsState;delayBetweenAttempts;cancelableRequestBeforeRetry;onBeforeRetry;canRetryOnError;networkInterfacesSubscriber;resumeFromSleepModeSubscriber;notActiveCallSubscriber;constructor({connectionQueueManager:e,connectionManager:t,callManager:s},i){const r=i?.onBeforeRetry??hn,a=i?.canRetryOnError??ln;this.connectionQueueManager=e,this.connectionManager=t,this.onBeforeRetry=r,this.canRetryOnError=a,this.networkInterfacesSubscriber=i?.networkInterfacesSubscriber,this.resumeFromSleepModeSubscriber=i?.resumeFromSleepModeSubscriber,this.events=tn(),this.checkTelephonyRequester=new en({connectionManager:t,interval:i?.checkTelephonyRequestInterval??dn}),this.pingServerIfNotActiveCallRequester=new an({connectionManager:t,callManager:s}),this.registrationFailedOutOfCallSubscriber=new on({connectionManager:t,callManager:s}),this.attemptsState=new Zt({onStatusChange:this.emitStatusChange}),this.cancelableRequestBeforeRetry=new B.CancelableRequest(r),this.delayBetweenAttempts=new L.DelayRequester(i?.timeoutBetweenAttempts??cn),this.notActiveCallSubscriber=new te({callManager:s})}start(e){d("auto connector start"),this.restartConnectionAttempts(e),this.subscribeToNotActiveCall(e)}stop(){d("auto connector stop"),this.unsubscribeFromNotActiveCall(),this.unsubscribeFromHardwareTriggers(),this.stopConnectionFlow().catch(e=>{d("auto connector stop from stop method: error",e)})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}restartConnectionAttempts(e){d("auto connector restart connection attempts"),this.stopConnectionFlow().then(async()=>this.attemptConnection(e)).catch(t=>{d("auto connector failed to restart connection attempts:",t)})}async stopConnectionFlow(){d("stopConnectionFlow"),this.stopAttempts(),this.stopConnectTriggers(),await this.connectionQueueManager.disconnect()}stopAttempts(){this.attemptsState.isAttemptInProgress&&this.connectionQueueManager.stop(),this.delayBetweenAttempts.cancelRequest(),this.cancelableRequestBeforeRetry.cancelRequest(),this.attemptsState.reset()}stopConnectTriggers(){d("stopConnectTriggers"),this.stopPingRequester(),this.checkTelephonyRequester.stop(),this.registrationFailedOutOfCallSubscriber.unsubscribe()}startCheckTelephony(e){d("startCheckTelephony"),this.checkTelephonyRequester.start({onBeforeRequest:async()=>(await this.onBeforeRetry(),e.getParameters()),onSuccessRequest:()=>{d("startCheckTelephony: onSuccessRequest"),this.connectIfDisconnected(e)},onFailRequest:t=>{d("startCheckTelephony: onFailRequest",t.message)}})}async attemptConnection(e){if(d("attemptConnection: attempts.count",this.attemptsState.count),this.events.trigger(v.BEFORE_ATTEMPT,{}),this.stopConnectTriggers(),this.attemptsState.hasLimitReached()){d("attemptConnection: limit reached"),this.handleLimitReached(e);return}return this.attemptsState.startAttempt(),this.attemptsState.increment(),this.executeConnectionAttempt(e)}async executeConnectionAttempt(e){try{await this.connectionQueueManager.connect(e.getParameters,e.options),d("executeConnectionAttempt: success"),this.handleSucceededAttempt(e)}catch(t){this.handleConnectionError(t,e)}}handleConnectionError(e,t){if(Pe(e)){this.attemptsState.finishAttempt(),this.events.trigger(v.STOP_ATTEMPTS_BY_ERROR,e);return}if(!this.canRetryOnError(e)){d("executeConnectionAttempt: error does not allow retry",e),this.attemptsState.finishAttempt(),this.events.trigger(v.STOP_ATTEMPTS_BY_ERROR,e);return}if(K.isPromiseIsNotActualError(e)){d("executeConnectionAttempt: not actual error",e),this.attemptsState.finishAttempt(),this.events.trigger(v.CANCELLED_ATTEMPTS,e);return}d("executeConnectionAttempt: error",e),this.scheduleReconnect(t)}handleLimitReached(e){this.attemptsState.finishAttempt(),this.events.trigger(v.LIMIT_REACHED_ATTEMPTS,new Error(ae.LIMIT_REACHED)),this.startCheckTelephony(e)}handleSucceededAttempt(e){d("handleSucceededAttempt"),this.subscribeToConnectTriggers(e),this.events.trigger(v.SUCCESS)}subscribeToConnectTriggers(e){this.startPingRequester(e),this.registrationFailedOutOfCallSubscriber.subscribe(()=>{d("registrationFailedOutOfCallListener callback"),this.restartConnectionAttempts(e)})}subscribeToNotActiveCall(e){this.notActiveCallSubscriber.subscribe({onActive:()=>{d("subscribeToNotActiveCall onActive"),this.unsubscribeFromHardwareTriggers()},onInactive:()=>{d("subscribeToNotActiveCall onInactive"),this.subscribeToHardwareTriggers(e)}})}unsubscribeFromNotActiveCall(){this.notActiveCallSubscriber.unsubscribe()}subscribeToHardwareTriggers(e){this.unsubscribeFromHardwareTriggers(),d("subscribeToHardwareTriggers"),this.networkInterfacesSubscriber?.subscribe({onChange:()=>{d("networkInterfacesSubscriber onChange"),this.restartConnectionAttempts(e)},onUnavailable:()=>{d("networkInterfacesSubscriber onUnavailable"),this.stopConnectionFlow().catch(t=>{d("auto connector stop from networkInterfacesSubscriber onUnavailable: error",t)})}}),this.resumeFromSleepModeSubscriber?.subscribe({onResume:()=>{d("resumeFromSleepModeSubscriber onResume"),this.restartConnectionAttempts(e)}})}unsubscribeFromHardwareTriggers(){d("unsubscribeFromHardwareTriggers"),this.networkInterfacesSubscriber?.unsubscribe(),this.resumeFromSleepModeSubscriber?.unsubscribe()}stopPingRequester(){this.pingServerIfNotActiveCallRequester.stop()}startPingRequester(e){this.pingServerIfNotActiveCallRequester.start({onFailRequest:()=>{d("pingRequester: onFailRequest"),this.restartConnectionAttempts(e)}})}connectIfDisconnected(e){const t=this.isConnectionUnavailable();d("connectIfDisconnected: isUnavailable",t),t?this.restartConnectionAttempts(e):(this.stopConnectTriggers(),this.events.trigger(v.SUCCESS))}scheduleReconnect(e){d("scheduleReconnect"),this.delayBetweenAttempts.request().then(async()=>(d("scheduleReconnect: delayBetweenAttempts success"),this.cancelableRequestBeforeRetry.request())).then(async()=>(d("scheduleReconnect: onBeforeRetry success"),this.attemptConnection(e))).catch(t=>{const s=t instanceof Error?t:new Error(ae.FAILED_TO_RECONNECT);this.attemptsState.finishAttempt(),B.isCanceledError(t)||L.hasCanceledError(t)?this.events.trigger(v.CANCELLED_ATTEMPTS,s):this.events.trigger(v.FAILED_ALL_ATTEMPTS,s),d("scheduleReconnect: error",t)})}isConnectionUnavailable(){const{isFailed:e,isDisconnected:t,isIdle:s}=this.connectionManager;return e||t||s}emitStatusChange=({isInProgress:e})=>{this.events.trigger(v.CHANGED_ATTEMPT_STATUS,{isInProgress:e})}}var X=(n=>(n.STATE_CHANGED="state-changed",n.STATE_RESET="state-reset",n))(X||{});const De=["state-changed","state-reset"],un=()=>new I.TypedEvents(De);class Tn{events;state={};constructor(){this.events=un()}getState(){return{...this.state}}updateState(e){const t={...this.state};this.state={...this.state,...e},this.events.trigger(X.STATE_CHANGED,{previous:t,current:this.state,updates:e})}reset(){this.state={},this.events.trigger(X.STATE_RESET,{})}getToken(){return this.state.token}getRoom(){return this.state.room}getParticipantName(){return this.state.participantName}getChannels(){return this.state.channels}getConference(){return this.state.conference}getParticipant(){return this.state.participant}getNumber(){return this.state.number}getAnswer(){return this.state.answer}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t)}}var F=(n=>(n.RINGING="ringing",n.DECLINED_INCOMING_CALL="declinedIncomingCall",n.TERMINATED_INCOMING_CALL="terminatedIncomingCall",n.FAILED_INCOMING_CALL="failedIncomingCall",n))(F||{});const we=["ringing","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],En=()=>new I.TypedEvents(we);var Le=(n=>(n.IDLE="incoming:idle",n.RINGING="incoming:ringing",n.CONSUMED="incoming:consumed",n.DECLINED="incoming:declined",n.TERMINATED="incoming:terminated",n.FAILED="incoming:failed",n))(Le||{});const Sn=N.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("IncomingCallStateMachine state changed",e.state)},rememberIncoming:N.assign(({event:n})=>{const{data:e}=n;return{remoteCallerData:e,lastReason:void 0}}),rememberReason:N.assign(({event:n,context:e})=>n.type==="INCOMING.CONSUMED"?{remoteCallerData:e.remoteCallerData,lastReason:"incoming:consumed"}:n.type==="INCOMING.DECLINED"?{remoteCallerData:n.data,lastReason:"incoming:declined"}:n.type==="INCOMING.TERMINATED"?{remoteCallerData:n.data,lastReason:"incoming:terminated"}:{remoteCallerData:n.data,lastReason:"incoming:failed"}),clearIncoming:N.assign(()=>({remoteCallerData:void 0,lastReason:void 0}))}}).createMachine({id:"incoming",initial:"incoming:idle",context:{},states:{"incoming:idle":{entry:{type:"logStateChange",params:{state:"incoming:idle"}},on:{"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:idle",to:"incoming:ringing",event:"INCOMING.RINGING"}}]},"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:idle",to:"incoming:idle",event:"INCOMING.CLEAR"}}]}}},"incoming:ringing":{entry:{type:"logStateChange",params:{state:"incoming:ringing"}},on:{"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:ringing",event:"INCOMING.RINGING"}}]},"INCOMING.CONSUMED":{target:"incoming:consumed",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:consumed",event:"INCOMING.CONSUMED"}}]},"INCOMING.DECLINED":{target:"incoming:declined",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:declined",event:"INCOMING.DECLINED"}}]},"INCOMING.TERMINATED":{target:"incoming:terminated",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:terminated",event:"INCOMING.TERMINATED"}}]},"INCOMING.FAILED":{target:"incoming:failed",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:failed",event:"INCOMING.FAILED"}}]},"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:idle",event:"INCOMING.CLEAR"}}]}}},"incoming:consumed":{entry:{type:"logStateChange",params:{state:"incoming:consumed"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:consumed",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:consumed",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:declined":{entry:{type:"logStateChange",params:{state:"incoming:declined"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:declined",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:declined",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:terminated":{entry:{type:"logStateChange",params:{state:"incoming:terminated"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:terminated",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:terminated",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:failed":{entry:{type:"logStateChange",params:{state:"incoming:failed"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:failed",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:failed",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}}}});class pn extends q{constructor({incomingEvents:e,connectionEvents:t}){super(Sn),this.subscribeIncomingEvents(e),this.subscribeConnectionEvents(t)}get isIdle(){return this.state==="incoming:idle"}get isRinging(){return this.state==="incoming:ringing"}get isConsumed(){return this.state==="incoming:consumed"}get isDeclined(){return this.state==="incoming:declined"}get isTerminated(){return this.state==="incoming:terminated"}get isFailed(){return this.state==="incoming:failed"}get isActive(){return this.isRinging}get isFinished(){return this.isConsumed||this.isDeclined||this.isTerminated||this.isFailed}get remoteCallerData(){return this.getSnapshot().context.remoteCallerData}get lastReason(){return this.getSnapshot().context.lastReason}reset(){this.send({type:"INCOMING.CLEAR"})}send(e){if(!this.getSnapshot().can(e)){console.warn(`[IncomingCallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}toConsumed(){this.send({type:"INCOMING.CONSUMED"})}subscribeIncomingEvents(e){this.addSubscription(e.on("ringing",t=>{this.send({type:"INCOMING.RINGING",data:t})})),this.addSubscription(e.on("declinedIncomingCall",t=>{this.send({type:"INCOMING.DECLINED",data:t})})),this.addSubscription(e.on("terminatedIncomingCall",t=>{this.send({type:"INCOMING.TERMINATED",data:t})})),this.addSubscription(e.on("failedIncomingCall",t=>{this.send({type:"INCOMING.FAILED",data:t})}))}subscribeConnectionEvents(e){this.addSubscription(e.on(p.DISCONNECTED,()=>{this.toClearIncoming()})),this.addSubscription(e.on(p.REGISTRATION_FAILED,()=>{this.toClearIncoming()})),this.addSubscription(e.on(p.CONNECT_FAILED,()=>{this.toClearIncoming()}))}toClearIncoming(){this.send({type:"INCOMING.CLEAR"})}}const Cn=486,mn=487;class Nn{events;incomingStateMachine;incomingRTCSession;connectionManager;constructor(e){this.connectionManager=e,this.events=En(),this.incomingStateMachine=new pn({incomingEvents:this.events,connectionEvents:this.connectionManager.events}),this.start()}get incomingActor(){return this.incomingStateMachine.actorRef}get remoteCallerData(){return{displayName:this.incomingRTCSession?.remote_identity.display_name,host:this.incomingRTCSession?.remote_identity.uri.host,incomingNumber:this.incomingRTCSession?.remote_identity.uri.user,rtcSession:this.incomingRTCSession}}get isAvailableIncomingCall(){return!!this.incomingRTCSession}start(){this.subscribe()}stop(){this.unsubscribe(),this.removeIncomingSession()}getIncomingRTCSession=()=>{const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e};extractIncomingRTCSession=()=>{const e=this.getIncomingRTCSession();return this.incomingStateMachine.toConsumed(),this.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=mn}={}){return new Promise((t,s)=>{try{const i=this.getIncomingRTCSession(),r=this.remoteCallerData;this.removeIncomingSession(),this.events.trigger(F.DECLINED_INCOMING_CALL,r),i.terminate({status_code:e}),t()}catch(i){s(i)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:Cn})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.connectionManager.on("newRTCSession",this.handleNewRTCSession)}unsubscribe(){this.connectionManager.off("newRTCSession",this.handleNewRTCSession)}handleNewRTCSession=({originator:e,session:t})=>{e==="remote"&&this.setIncomingSession(t)};setIncomingSession(e){this.incomingRTCSession=e;const t=this.remoteCallerData;e.on("failed",s=>{this.removeIncomingSession(),s.originator==="local"?this.events.trigger(F.TERMINATED_INCOMING_CALL,t):this.events.trigger(F.FAILED_INCOMING_CALL,t)}),this.events.trigger(F.RINGING,t)}removeIncomingSession(){delete this.incomingRTCSession}}var Ue=(n=>(n.SNAPSHOT_CHANGED="snapshot-changed",n))(Ue||{});const Fe=["snapshot-changed"],Rn=()=>new I.TypedEvents(Fe),An=(n,e)=>Object.is(n,e),oe=n=>({connection:n.connection.getSnapshot(),call:n.call.getSnapshot(),incoming:n.incoming.getSnapshot(),presentation:n.presentation.getSnapshot()});class In{events;actors;currentSnapshot;subscribers=new Set;actorSubscriptions=[];constructor(e){this.events=Rn(),this.actors={connection:e.connectionManager.connectionActor,call:e.callManager.callActor,incoming:e.incomingCallManager.incomingActor,presentation:e.presentationManager.presentationActor},this.currentSnapshot=oe(this.actors),this.actorSubscriptions.push(this.actors.connection.subscribe(this.notifySubscribers),this.actors.call.subscribe(this.notifySubscribers),this.actors.incoming.subscribe(this.notifySubscribers),this.actors.presentation.subscribe(this.notifySubscribers))}getSnapshot(){return this.currentSnapshot}subscribe(e,t,s){const i=typeof t=="function",r=i?e:E=>E,a=i?t:e,o=(i?s:void 0)??An,c=r(this.currentSnapshot),h={selector:r,listener:a,equals:o,current:c};return this.subscribers.add(h),()=>{this.subscribers.delete(h)}}stop(){this.subscribers.clear(),this.actorSubscriptions.forEach(e=>{e.unsubscribe()})}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}notifySubscribers=()=>{const e=this.currentSnapshot;this.currentSnapshot=oe(this.actors);for(const t of this.subscribers){const s=t.selector(this.currentSnapshot);t.equals(t.current,s)||(t.current=s,t.listener(s))}this.events.trigger(Ue.SNAPSHOT_CHANGED,{previous:e,current:this.currentSnapshot})}}const U=1e3;var C=(n=>(n.INBOUND_RTP="inbound-rtp",n.REMOTE_OUTBOUND_RTP="remote-outbound-rtp",n.MEDIA_SOURCE="media-source",n.OUTBOUND_RTP="outbound-rtp",n.REMOTE_INBOUND_RTP="remote-inbound-rtp",n.CODEC="codec",n.CANDIDATE_PAIR="candidate-pair",n.CERTIFICATE="certificate",n.TRANSPORT="transport",n.LOCAL_CANDIDATE="local-candidate",n.REMOTE_CANDIDATE="remote-candidate",n))(C||{});const ke=["collected"],fn=()=>new I.TypedEvents(ke),vn="api/v2/rtp2webrtc/offer",Be=async({serverUrl:n,conferenceNumber:e,quality:t,audio:s,offer:i,token:r})=>{const a=new URL(`https://${n.replace(/\/$/,"")}/${vn}/${encodeURIComponent(e)}`);a.searchParams.set("quality",t),a.searchParams.set("audio",String(s));const o={"Content-Type":"application/json"};r!==void 0&&r!==""&&(o.Authorization=`Bearer ${r}`);const c=await fetch(a.toString(),{method:"POST",headers:o,credentials:"same-origin",body:JSON.stringify(i)});if(!c.ok)throw new Error(`sendOffer failed with status ${c.status}`);const h=await c.json();return{type:h.type,sdp:h.sdp,toJSON(){return h}}},ce=()=>"performance"in window?performance.now():Date.now(),$=n=>[...n.keys()].reduce((e,t)=>{const s=n.get(t);return s===void 0?e:{...e,[s.type]:s}},{}),Mn=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=$(n);return{outboundRtp:e[C.OUTBOUND_RTP],codec:e[C.CODEC],mediaSource:e[C.MEDIA_SOURCE],remoteInboundRtp:e[C.REMOTE_INBOUND_RTP]}},de=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=$(n);return{outboundRtp:e[C.OUTBOUND_RTP],codec:e[C.CODEC],mediaSource:e[C.MEDIA_SOURCE],remoteInboundRtp:e[C.REMOTE_INBOUND_RTP]}},he=({videoReceiversStats:n,synchronizationSourcesVideo:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,synchronizationSources:e};const t=$(n);return{inboundRtp:t[C.INBOUND_RTP],codec:t[C.CODEC],synchronizationSources:e}},_n=({audioReceiverStats:n,synchronizationSourcesAudio:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:e};const t=$(n);return{inboundRtp:t[C.INBOUND_RTP],codec:t[C.CODEC],remoteOutboundRtp:t[C.REMOTE_OUTBOUND_RTP],synchronizationSources:e}},$e=n=>{if(!n)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};const e=$(n);return{candidatePair:e[C.CANDIDATE_PAIR],certificate:e[C.CERTIFICATE],localCandidate:e[C.LOCAL_CANDIDATE],remoteCandidate:e[C.REMOTE_CANDIDATE],transport:e[C.TRANSPORT]}},bn=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t})=>({video:de(e),secondVideo:de(t),audio:Mn(n),additional:$e(n??e??t)}),On=({audioReceiverStats:n,videoReceiverFirstStats:e,videoReceiverSecondStats:t,synchronizationSources:s})=>({video:he({videoReceiversStats:e,synchronizationSourcesVideo:s.video}),secondVideo:he({videoReceiversStats:t,synchronizationSourcesVideo:s.video}),audio:_n({audioReceiverStats:n,synchronizationSourcesAudio:s.audio}),additional:$e(n??e??t)}),Pn=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t,audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a})=>{const o=bn({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t}),c=On({audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a});return{outbound:o,inbound:c}},yn=async n=>{const e="audio",t="video",s=n.getSenders(),i=s.find(T=>T.track?.kind===e),r=s.filter(T=>T.track?.kind===t),a=n.getReceivers(),o=a.find(T=>T.track.kind===e),c=a.filter(T=>T.track.kind===t),h={trackIdentifier:o?.track.id,item:o?.getSynchronizationSources()[0]},E={trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},u={audio:h,video:E};return Promise.all([i?.getStats()??Promise.resolve(void 0),r[0]?.getStats()??Promise.resolve(void 0),r[1]?.getStats()??Promise.resolve(void 0),o?.getStats()??Promise.resolve(void 0),c[0]?.getStats()??Promise.resolve(void 0),c[1]?.getStats()??Promise.resolve(void 0)]).then(T=>{const[m,O,R,D,H,Xe]=T;return{synchronizationSources:u,audioSenderStats:m,videoSenderFirstStats:O,videoSenderSecondStats:R,audioReceiverStats:D,videoReceiverFirstStats:H,videoReceiverSecondStats:Xe}})},Dn=n=>{d(String(n))};class Ge{events;setTimeoutRequest;requesterAllStatistics=new B.CancelableRequest(yn);constructor(){this.events=fn(),this.setTimeoutRequest=new L.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:t=U,onError:s=Dn}={}){this.stop(),this.setTimeoutRequest.request(()=>{this.collectStatistics(e,{onError:s})},t)}stop(){this.setTimeoutRequest.cancelRequest(),this.requesterAllStatistics.cancelRequest()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}collectStatistics=(e,{onError:t})=>{const s=ce();this.requesterAllStatistics.request(e).then(i=>{this.events.trigger("collected",Pn(i));const a=ce()-s;let o=U;a>48?o=U*4:a>32?o=U*3:a>16&&(o=U*2),this.start(e,{onError:t,interval:o})}).catch(i=>{t&&t(i)})}}const wn=500;class Ln{statsPeerConnection;availableStats;previousAvailableStats;callManager;apiManager;constructor({callManager:e,apiManager:t}){this.callManager=e,this.apiManager=t,this.statsPeerConnection=new Ge,this.subscribe()}get events(){return this.statsPeerConnection.events}get availableIncomingBitrate(){return this.availableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get isInvalidInboundFrames(){return this.isEmptyInboundFrames&&this.isReceivingPackets}get isEmptyInboundFrames(){return!this.isFramesReceived||!this.isFramesDecoded}get previousAvailableIncomingBitrate(){return this.previousAvailableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get previousInboundRtp(){return this.previousAvailableStats?.inbound.video.inboundRtp}get previousFramesReceived(){return this.previousInboundRtp?.framesReceived}get previousFramesDecoded(){return this.previousInboundRtp?.framesDecoded}get inboundRtp(){return this.availableStats?.inbound.video.inboundRtp}get framesReceived(){return this.inboundRtp?.framesReceived}get framesDecoded(){return this.inboundRtp?.framesDecoded}get isFramesReceived(){const e=this.framesReceived!==void 0&&this.framesReceived>0,t=this.framesReceived!==this.previousFramesReceived;return e&&t}get isFramesDecoded(){const e=this.framesDecoded!==void 0&&this.framesDecoded>0,t=this.framesDecoded!==this.previousFramesDecoded;return e&&t}get packetsReceived(){return this.inboundRtp?.packetsReceived}get previousPacketsReceived(){return this.previousInboundRtp?.packetsReceived}get isReceivingPackets(){const e=this.packetsReceived!==void 0&&this.packetsReceived>=wn,t=this.packetsReceived!==this.previousPacketsReceived;return e&&t}on(e,t){return this.statsPeerConnection.on(e,t)}once(e,t){return this.statsPeerConnection.once(e,t)}onceRace(e,t){return this.statsPeerConnection.onceRace(e,t)}async wait(e){return this.statsPeerConnection.wait(e)}off(e,t){this.statsPeerConnection.off(e,t)}hasAvailableIncomingBitrateChangedQuarter(){const e=this.previousAvailableIncomingBitrate,t=this.availableIncomingBitrate;return e===void 0||t===void 0?!1:e===0?t>0:Math.abs(t-e)/e>=.25}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleStarted),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded),this.statsPeerConnection.on("collected",this.handleStatsCollected)}handleStatsCollected=e=>{this.previousAvailableStats=this.availableStats,this.availableStats=e,this.maybeSendStats()};handleStarted=e=>{this.statsPeerConnection.start(e)};handleEnded=()=>{this.statsPeerConnection.stop(),this.availableStats=void 0,this.previousAvailableStats=void 0};maybeSendStats(){this.availableIncomingBitrate!==void 0&&this.hasAvailableIncomingBitrateChangedQuarter()&&this.apiManager.sendStats({availableIncomingBitrate:this.availableIncomingBitrate}).catch(e=>{d("Failed to send stats",e)})}}const Un=(n,e)=>n.filter(s=>e.some(i=>i.clockRate===s.clockRate&&i.mimeType===s.mimeType&&i.channels===s.channels&&i.sdpFmtpLine===s.sdpFmtpLine)),Fn=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,i=t===null?[]:t.codecs;return Un(s,i)},kn=(n,e)=>e===void 0||e.length===0?n:n.sort((t,s)=>{const i=e.indexOf(t.mimeType),r=e.indexOf(s.mimeType),a=i===-1?Number.MAX_VALUE:i,o=r===-1?Number.MAX_VALUE:r;return a-o}),Bn=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),$n=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>{try{if(typeof n.setCodecPreferences=="function"&&n.sender.track?.kind==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const s=Fn("video"),i=Bn(s,t),r=kn(i,e);n.setCodecPreferences(r)}}catch(s){d("setCodecPreferences error",s)}},Gn=n=>[...n.keys()].map(e=>n.get(e)),qn=(n,e)=>Gn(n).find(t=>t?.type===e),qe=async n=>n.getStats().then(e=>qn(e,"codec")?.mimeType);class Hn{async getCodecFromSender(e){return await qe(e)??""}}class Vn{stackPromises=K.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{d("TaskQueue: error",e)})}}class Wn{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new Vn}async setEncodingsToSender(e,t){return this.taskQueue.add(async()=>ee(e,t,this.onSetParameters))}stop(){this.taskQueue.stop()}}const He=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),xn=1e6,M=n=>n*xn,Ve=M(.06),We=M(4),Qn=n=>n<=64?Ve:n<=128?M(.12):n<=256?M(.25):n<=384?M(.32):n<=426?M(.38):n<=640?M(.5):n<=848?M(.7):n<=1280?M(1):n<=1920?M(2):We,Yn="av1",Xn=n=>He(n,Yn),Jn=.6,ne=(n,e)=>Xn(e)?n*Jn:n,zn=n=>ne(Ve,n),Kn=n=>ne(We,n),le=(n,e)=>{const t=Qn(n);return ne(t,e)},W=1,jn=({videoTrack:n,targetSize:e})=>{const t=n.getSettings(),s=t.width,i=t.height,r=s===void 0?W:s/e.width,a=i===void 0?W:i/e.height;return Math.max(r,a,W)};class Zn{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:t,parametersSetter:s},i){this.senderFinder=e,this.codecProvider=t,this.parametersSetter=s,this.ignoreForCodec=i.ignoreForCodec}async balance(e,t){const s=e.getSenders(),i=this.senderFinder.findVideoSender(s);if(!i?.track)return{...this.resultNoChanged,sender:i};const r=await this.codecProvider.getCodecFromSender(i);if(He(r,this.ignoreForCodec))return{...this.resultNoChanged,sender:i};const{mainCam:a,resolutionMainCam:o}=t??{};return this.processSender({mainCam:a,resolutionMainCam:o},{sender:i,codec:r,videoTrack:i.track}).then(c=>({...c,sender:i}))}async processSender(e,t){const{mainCam:s,resolutionMainCam:i}=e;switch(s){case _.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(t);case _.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(t);case _.MAX_MAIN_CAM_RESOLUTION:return i!==void 0?this.setResolutionSender(i,t):this.setBitrateByTrackResolution(t);case _.ADMIN_STOP_MAIN_CAM:case _.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(t);default:return this.setBitrateByTrackResolution(t)}}async downgradeResolutionSender(e){const{sender:t,codec:s}=e,i={scaleResolutionDownBy:200,maxBitrate:zn(s)};return this.parametersSetter.setEncodingsToSender(t,i)}async setBitrateByTrackResolution(e){const{sender:t,videoTrack:s,codec:i}=e,a=s.getSettings().width,o=a===void 0?Kn(i):le(a,i);return this.parametersSetter.setEncodingsToSender(t,{scaleResolutionDownBy:1,maxBitrate:o})}async setResolutionSender(e,t){const[s,i]=e.split("x"),{sender:r,videoTrack:a,codec:o}=t,c={width:Number(s),height:Number(i)},h=jn({videoTrack:a,targetSize:c}),E=le(c.width,o),u={scaleResolutionDownBy:h,maxBitrate:E};return this.parametersSetter.setEncodingsToSender(r,u)}}const es=n=>n.find(e=>e.track?.kind==="video");class ts{findVideoSender(e){return es(e)}}class ns{currentSender;originalReplaceTrack;lastWidth;lastHeight;maxPollIntervalMs;currentPollIntervalMs;pollIntervalMs;setTimeoutRequest;constructor({pollIntervalMs:e=1e3,maxPollIntervalMs:t}){this.pollIntervalMs=e,this.maxPollIntervalMs=t??e*16,this.currentPollIntervalMs=this.pollIntervalMs,this.setTimeoutRequest=new L.SetTimeoutRequest}subscribe(e,t){if(!e){this.detachSender();return}this.currentSender!==e&&(this.detachSender(),this.attachSender(e,t))}unsubscribe(){this.detachSender()}attachSender(e,t){this.currentSender=e;const s=e.replaceTrack.bind(e);this.originalReplaceTrack=s,e.replaceTrack=async i=>{await s(i),this.attachTrack(t,i??void 0),t()},this.attachTrack(t,e.track)}detachSender(){this.currentSender&&this.originalReplaceTrack&&(this.currentSender.replaceTrack=this.originalReplaceTrack),this.originalReplaceTrack=void 0,this.currentSender=void 0,this.detachTrack()}attachTrack(e,t){if(this.detachTrack(),!t)return;const{width:s,height:i}=t.getSettings();this.lastWidth=s,this.lastHeight=i,this.currentPollIntervalMs=this.pollIntervalMs,this.schedulePoll(t,e)}schedulePoll(e,t){const s=()=>{const{width:i,height:r}=e.getSettings();i!==this.lastWidth||r!==this.lastHeight?(this.lastWidth=i,this.lastHeight=r,this.currentPollIntervalMs=this.pollIntervalMs,t()):this.currentPollIntervalMs=Math.min(this.currentPollIntervalMs*2,this.maxPollIntervalMs),this.setTimeoutRequest.request(s,this.currentPollIntervalMs)};this.setTimeoutRequest.request(s,this.currentPollIntervalMs)}detachTrack(){this.setTimeoutRequest.cancelRequest(),this.lastWidth=void 0,this.lastHeight=void 0}}class ss{apiManager;currentHandler;constructor(e){this.apiManager=e}subscribe(e){this.currentHandler=e,this.apiManager.on("main-cam-control",e)}unsubscribe(){this.currentHandler&&(this.apiManager.off("main-cam-control",this.currentHandler),this.currentHandler=void 0)}}class is{eventHandler;senderBalancer;parametersSetterWithQueue;getConnection;serverHeaders;trackMonitor;constructor(e,t,{ignoreForCodec:s,onSetParameters:i,pollIntervalMs:r}={}){this.getConnection=t,this.eventHandler=new ss(e),this.parametersSetterWithQueue=new Wn(i),this.senderBalancer=new Zn({senderFinder:new ts,codecProvider:new Hn,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:s}),this.trackMonitor=new ns({pollIntervalMs:r})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.parametersSetterWithQueue.stop(),this.reset()}reset(){delete this.serverHeaders,this.trackMonitor.unsubscribe()}async balance(){const e=this.getConnection();if(!e)throw new Error("connection is not exist");const t=await this.senderBalancer.balance(e,this.serverHeaders);return this.trackMonitor.subscribe(t.sender,()=>{this.balance().catch(s=>{d("balance on track change: error",s)})}),t}handleMainCamControl=e=>{this.serverHeaders=e,this.balance().catch(t=>{d("handleMainCamControl: error",t)})}}const xe=["balancing-scheduled","balancing-started","balancing-stopped","parameters-updated"],rs=()=>new I.TypedEvents(xe);class as{isBalancingActive=!1;events;callManager;balancingStartDelay;videoSendingBalancer;startBalancingTimer;constructor(e,t,s={}){this.events=rs(),this.callManager=e,this.balancingStartDelay=s.balancingStartDelay??1e4,this.videoSendingBalancer=new is(t,()=>e.connection,{...s,onSetParameters:i=>{this.events.trigger("parameters-updated",i),s.onSetParameters?.(i)}}),this.subscribe()}get isBalancingScheduled(){return this.startBalancingTimer!==void 0}async startBalancing(){this.isBalancingActive||(this.clearStartTimer(),await this.videoSendingBalancer.balance(),this.videoSendingBalancer.subscribe(),this.isBalancingActive=!0,this.events.trigger("balancing-started",{delay:this.balancingStartDelay}))}stopBalancing(){this.clearStartTimer(),this.videoSendingBalancer.unsubscribe(),this.isBalancingActive=!1,this.events.trigger("balancing-stopped",{})}async balance(){return this.videoSendingBalancer.balance()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleCallStarted),this.callManager.on("ended",this.handleCallEnded),this.callManager.on("failed",this.handleCallEnded)}handleCallStarted=()=>{this.scheduleBalancingStart()};handleCallEnded=()=>{this.stopBalancing()};scheduleBalancingStart(){this.clearStartTimer(),this.startBalancingTimer=setTimeout(()=>{this.startBalancingTimer=void 0,this.startBalancing().catch(e=>{d("startBalancing: error",e)})},this.balancingStartDelay),this.events.trigger("balancing-scheduled",{delay:this.balancingStartDelay})}clearStartTimer(){this.startBalancingTimer&&(clearTimeout(this.startBalancingTimer),this.startBalancingTimer=void 0)}}const Qe="no-inbound-frames",Ye=[Qe],os=()=>new I.TypedEvents(Ye);class cs{events;statsManager;callManager;constructor(e,t){this.statsManager=e,this.callManager=t,this.events=os(),this.subscribe()}get mainVideoTrack(){return this.callManager.getMainStream()?.getVideoTracks()[0]}get isMutedMainVideoTrack(){const{mainVideoTrack:e}=this;return e===void 0?!1:e.muted}on(e,t){return this.events.on(e,t)}handleStatsCollected=()=>{this.hasNoIncomingFrames()&&this.events.trigger(Qe,{})};hasNoIncomingFrames=()=>this.statsManager.isInvalidInboundFrames&&this.isMutedMainVideoTrack;subscribe(){this.statsManager.on("collected",this.handleStatsCollected)}}const ds=3e3;class hs{renegotiateRequester;renegotiateThrottled;callManager;constructor(e,t=ds){this.callManager=e,this.renegotiateRequester=new B.CancelableRequest(e.renegotiate.bind(e)),this.renegotiateThrottled=Je.throttle(this.requestRenegotiate.bind(this),t),this.subscribe()}recover(){d("trying to recover main stream"),this.renegotiateThrottled()}requestRenegotiate=()=>{if(d("trying to renegotiate"),this.renegotiateRequester.requested){d("previous renegotiate is not finished yet");return}this.renegotiateRequester.request().then(()=>{d("renegotiate has successful")}).catch(e=>{d("failed to renegotiate main media stream",e)})};subscribe(){this.callManager.on("ended",()=>{this.cancel()})}cancel(){d("cancel recover main stream"),this.renegotiateThrottled.cancel(),this.renegotiateRequester.cancelRequest()}}const ls=1e6,gs=ye.map(n=>`auto-connect:${n}`),us=ve.map(n=>`connection:${n}`),Ts=pe.map(n=>`call:${n}`),Es=De.map(n=>`conference-state:${n}`),Ss=ue.map(n=>`api:${n}`),ps=we.map(n=>`incoming-call:${n}`),Cs=Ae.map(n=>`presentation:${n}`),ms=ke.map(n=>`stats:${n}`),Ns=xe.map(n=>`video-balancer:${n}`),Rs=Ye.map(n=>`main-stream-health:${n}`),As=Fe.map(n=>`session:${n}`),Is=["disconnected-from-out-of-call","connected-with-configuration-from-out-of-call","stopped-presentation-by-server-command"],fs=[...gs,...us,...Ts,...Es,...Ss,...ps,...Cs,...ms,...Ns,...Rs,...As,...Is],vs=()=>new I.TypedEvents(fs);class Ms{events;connectionManager;connectionQueueManager;conferenceStateManager;callManager;autoConnectorManager;apiManager;incomingCallManager;presentationManager;statsManager;videoSendingBalancerManager;sessionManager;mainStreamHealthMonitor;mainStreamRecovery;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor({JsSIP:e},{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s,videoBalancerOptions:i,autoConnectorOptions:r}={}){this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=s,this.events=vs(),this.connectionManager=new zt({JsSIP:e}),this.connectionQueueManager=new Kt({connectionManager:this.connectionManager}),this.conferenceStateManager=new Tn,this.callManager=new Et(this.conferenceStateManager),this.apiManager=new st({connectionManager:this.connectionManager,callManager:this.callManager}),this.incomingCallManager=new Nn(this.connectionManager),this.presentationManager=new wt({callManager:this.callManager,maxBitrate:ls}),this.statsManager=new Ln({callManager:this.callManager,apiManager:this.apiManager}),this.autoConnectorManager=new gn({connectionQueueManager:this.connectionQueueManager,connectionManager:this.connectionManager,callManager:this.callManager},r),this.videoSendingBalancerManager=new as(this.callManager,this.apiManager,i),this.mainStreamHealthMonitor=new cs(this.statsManager,this.callManager),this.mainStreamRecovery=new hs(this.callManager),this.sessionManager=new In({connectionManager:this.connectionManager,callManager:this.callManager,incomingCallManager:this.incomingCallManager,presentationManager:this.presentationManager}),this.subscribe()}get requestedConnection(){return this.connectionManager.requested}get isPendingConnect(){return this.connectionManager.isPendingConnect}get isPendingInitUa(){return this.connectionManager.isPendingInitUa}get connectionState(){return this.connectionManager.connectionState}get isRegistered(){return this.connectionManager.isRegistered}get isRegisterConfig(){return this.connectionManager.isRegisterConfig}get socket(){return this.connectionManager.socket}get requestedCall(){return this.callManager.requested}get connection(){return this.callManager.connection}get isCallActive(){return this.callManager.isCallActive}get remoteCallerData(){return this.incomingCallManager.remoteCallerData}get isAvailableIncomingCall(){return this.incomingCallManager.isAvailableIncomingCall}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}connect=async(...e)=>this.connectionQueueManager.connect(...e);disconnect=async()=>this.connectionQueueManager.disconnect();register=async()=>this.connectionManager.register();unregister=async()=>this.connectionManager.unregister();tryRegister=async()=>this.connectionManager.tryRegister();set=async(...e)=>this.connectionManager.set(...e);sendOptions=async(e,t,s)=>this.connectionManager.sendOptions(e,t,s);ping=async(e,t)=>this.connectionManager.ping(e,t);checkTelephony=async e=>this.connectionManager.checkTelephony(e);isConfigured=()=>this.connectionManager.isConfigured();getConnectionConfiguration=()=>this.connectionManager.getConnectionConfiguration();getUri=e=>this.connectionManager.getUri(e);startAutoConnect=(...e)=>{this.autoConnectorManager.start(...e)};stopAutoConnect=()=>{this.autoConnectorManager.stop()};call=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.startCall(this.connectionManager.getUaProtected(),this.getUri,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};hangUp=async()=>this.callManager.endCall();answerToIncomingCall=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getCallConfiguration=()=>{const e=this.conferenceStateManager.getState();return{number:e.number,answer:e.answer}};getRemoteStreams=()=>this.callManager.getRemoteStreams();replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,t={}){const{isP2P:s,callLimit:i,onAddedTransceiver:r,...a}=t;return this.presentationManager.startPresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...a,onAddedTransceiver:this.resolveHandleAddTransceiver(r)},i===void 0?void 0:{callLimit:i})}async stopPresentation(e={}){const{isP2P:t}=e;return this.presentationManager.stopPresentation(async()=>{await(t===!0?this.apiManager.sendMustStopPresentationP2P():this.apiManager.sendStoppedPresentation())})}async updatePresentation(e,t={}){const{isP2P:s,onAddedTransceiver:i,...r}=t;return this.presentationManager.updatePresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...r,onAddedTransceiver:this.resolveHandleAddTransceiver(i)})}async waitChannels(...e){return this.apiManager.waitChannels(...e)}async waitSyncMediaState(...e){return this.apiManager.waitSyncMediaState(...e)}async sendDTMF(...e){return this.apiManager.sendDTMF(...e)}async sendChannels(...e){return this.apiManager.sendChannels(...e)}async sendMediaState(...e){return this.apiManager.sendMediaState(...e)}async sendRefusalToTurnOn(...e){return this.apiManager.sendRefusalToTurnOn(...e)}async sendRefusalToTurnOnMic(...e){return this.apiManager.sendRefusalToTurnOnMic(...e)}async sendRefusalToTurnOnCam(...e){return this.apiManager.sendRefusalToTurnOnCam(...e)}async sendMustStopPresentationP2P(...e){return this.apiManager.sendMustStopPresentationP2P(...e)}async sendStoppedPresentationP2P(...e){return this.apiManager.sendStoppedPresentationP2P(...e)}async sendStoppedPresentation(...e){return this.apiManager.sendStoppedPresentation(...e)}async askPermissionToStartPresentationP2P(...e){return this.apiManager.askPermissionToStartPresentationP2P(...e)}async askPermissionToStartPresentation(...e){return this.apiManager.askPermissionToStartPresentation(...e)}async askPermissionToEnableCam(...e){return this.apiManager.askPermissionToEnableCam(...e)}subscribeDisconnectedFromOutOfCall(){this.connectionManager.on("disconnected",()=>{this.isCallActive||this.events.trigger("disconnected-from-out-of-call",{})})}subscribeConnectedWithConfigurationFromOutOfCall(){this.connectionManager.on("connected-with-configuration",e=>{this.isCallActive||this.events.trigger("connected-with-configuration-from-out-of-call",e)})}mayBeStopPresentationAndNotify(){this.presentationManager.isPresentationInProcess&&(this.stopPresentation().catch(()=>{}),this.events.trigger("stopped-presentation-by-server-command",{}))}subscribeToApiEvents(){this.apiManager.on("participant:move-request-to-participants",()=>{this.callManager.setCallRoleParticipant()}),this.apiManager.on("participant:move-request-to-spectators-synthetic",()=>{this.callManager.setCallRoleSpectatorSynthetic(),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("participant:move-request-to-spectators-with-audio-id",({audioId:e})=>{this.callManager.setCallRoleSpectator({audioId:e,sendOffer:this.sendOffer}),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("mustStopPresentation",()=>{this.mayBeStopPresentationAndNotify()}),this.apiManager.on("enterRoom",({room:e,participantName:t})=>{this.conferenceStateManager.updateState({room:e,participantName:t})}),this.apiManager.on("conference:participant-token-issued",({jwt:e,conference:t,participant:s})=>{this.conferenceStateManager.updateState({token:e,conference:t,participant:s})}),this.apiManager.on("channels",e=>{this.conferenceStateManager.updateState({channels:e})})}sendOffer=async(e,t)=>{const i=this.connectionManager.getConnectionConfiguration()?.sipServerUrl;if(i===void 0)throw new Error("No sipServerUrl for sendOffer");const r=this.conferenceStateManager.getToken();return Be({serverUrl:i,offer:t,token:r,conferenceNumber:e.conferenceNumber,quality:e.quality,audio:e.audioChannel})};setCodecPreferences(e){$n(e,{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs})}subscribe(){this.bridgeEvents("auto-connect",this.autoConnectorManager),this.bridgeEvents("connection",this.connectionManager),this.bridgeEvents("call",this.callManager),this.bridgeEvents("conference-state",this.conferenceStateManager),this.bridgeEvents("api",this.apiManager),this.bridgeEvents("incoming-call",this.incomingCallManager),this.bridgeEvents("presentation",this.presentationManager),this.bridgeEvents("stats",this.statsManager),this.bridgeEvents("video-balancer",this.videoSendingBalancerManager),this.bridgeEvents("main-stream-health",this.mainStreamHealthMonitor),this.bridgeEvents("session",this.sessionManager),this.subscribeToApiEvents(),this.subscribeDisconnectedFromOutOfCall(),this.subscribeConnectedWithConfigurationFromOutOfCall(),this.subscribeToMainStreamHealthMonitorEvents()}subscribeToMainStreamHealthMonitorEvents(){this.mainStreamHealthMonitor.on("no-inbound-frames",()=>{this.mainStreamRecovery.recover()})}bridgeEvents=(e,t)=>{t.events.eachTriggers((s,i)=>{t.on(i,r=>{this.events.trigger(`${e}:${i}`,r)})})};resolveHandleAddTransceiver=e=>async(t,s,i)=>{this.setCodecPreferences(t),await e?.(t,s,i)}}exports.ECallCause=Z;exports.EState=_e;exports.EState$1=Te;exports.EState$2=Le;exports.EState$3=Ie;exports.EStatsTypes=C;exports.EUseLicense=ge;exports.Originator=Ee;exports.SipConnector=Ms;exports.StatsPeerConnection=Ge;exports.disableDebug=Ke;exports.enableDebug=ze;exports.getCodecFromSender=qe;exports.hasCanceledStartPresentationError=Dt;exports.hasNotReadyForConnectionError=Pe;exports.logger=d;exports.prepareMediaStream=k;exports.sendOffer=Be;exports.setEncodingsToSender=ee;exports.setParametersToSender=Re;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TypedEvents } from 'events-constructor';
|
|
2
|
-
import { ConnectedEvent, ConnectingEventUA, DisconnectEvent, IncomingMessageEvent, IncomingRequest, OutgoingMessageEvent, RegisteredEvent, RTCSessionEvent, UnRegisteredEvent } from '@krivega/jssip';
|
|
2
|
+
import { ConnectedEvent, ConnectingEventUA, DisconnectEvent, IncomingMessageEvent, IncomingRequest, OutgoingMessageEvent, RegisteredEvent, RTCSessionEvent, UnRegisteredEvent, RegistrationFailedEvent } from '@krivega/jssip';
|
|
3
3
|
import { TConnectionConfigurationWithUa, TParametersConnection } from './ConnectionFlow';
|
|
4
4
|
export declare enum EEvent {
|
|
5
5
|
CONNECTING = "connecting",
|
|
@@ -29,7 +29,7 @@ export type TEventMap = {
|
|
|
29
29
|
newRTCSession: RTCSessionEvent;
|
|
30
30
|
registered: RegisteredEvent;
|
|
31
31
|
unregistered: UnRegisteredEvent;
|
|
32
|
-
registrationFailed:
|
|
32
|
+
registrationFailed: RegistrationFailedEvent;
|
|
33
33
|
newMessage: IncomingMessageEvent | OutgoingMessageEvent;
|
|
34
34
|
sipEvent: {
|
|
35
35
|
event: unknown;
|
package/dist/doMock.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("node:events"),U=require("@krivega/jssip/lib/NameAddrHeader"),j=require("@krivega/jssip/lib/URI"),H=require("@krivega/jssip/lib/SIPMessage"),a=require("@krivega/jssip"),_=require("webrtc-mock"),v=require("events-constructor"),D=require("./@SipConnector-BVCkiu8l.cjs");class N extends H.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const q="incomingCall",G="declinedIncomingCall",x="failedIncomingCall",z="terminatedIncomingCall",y="connecting",Y="connected",B="disconnected",K="newRTCSession",J="registered",$="unregistered",Q="registrationFailed",X="newMessage",Z="sipEvent",ee="availableSecondRemoteStream",te="notAvailableSecondRemoteStream",re="mustStopPresentation",ne="shareState",oe="enterRoom",ie="useLicense",se="peerconnection:confirmed",ae="peerconnection:ontrack",ce="channels",de="channels:notify",Ee="ended:fromserver",he="main-cam-control",ue="admin-stop-main-cam",me="admin-start-main-cam",le="admin-stop-mic",pe="admin-start-mic",ge="admin-force-sync-media-state",_e="participant:added-to-list-moderators",Te="participant:removed-from-list-moderators",Ie="participant:move-request-to-stream",Se="participant:move-request-to-spectators",Ne="participant:move-request-to-participants",we="participation:accepting-word-request",Ce="participation:cancelling-word-request",fe="webcast:started",Re="webcast:stopped",Ae="account:changed",Me="account:deleted",Oe="conference:participant-token-issued",Pe="ended",ve="sending",De="reinvite",ye="replaces",Le="refer",Fe="progress",We="accepted",be="confirmed",ke="peerconnection",Ve="failed",Ue="muted",je="unmuted",He="newDTMF",qe="newInfo",Ge="hold",xe="unhold",ze="update",Ye="sdp",Be="icecandidate",Ke="getusermediafailed",Je="peerconnection:createofferfailed",$e="peerconnection:createanswerfailed",Qe="peerconnection:setlocaldescriptionfailed",Xe="peerconnection:setremotedescriptionfailed",Ze="presentation:start",et="presentation:started",tt="presentation:end",rt="presentation:ended",nt="presentation:failed",ot=[q,G,z,x,we,Ce,Ie,de,Oe,Ae,Me,fe,Re,_e,Te],L=[y,Y,B,K,J,$,Q,X,Z],it=[ee,te,re,ne,oe,ie,se,ae,ce,Ee,he,me,ue,le,pe,ge,Se,Ne],T=[Pe,y,ve,De,ye,Le,Fe,We,be,ke,Ve,Ue,je,He,qe,Ge,xe,ze,Ye,Be,Ke,Je,$e,Qe,Xe,Ze,et,tt,rt,nt];[...L,...ot];[...T,...it];class st{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};constructor({originator:e="local",eventHandlers:t,remoteIdentity:r}){this.originator=e,this.events=new v.Events(T),this.initEvents(t),this.remote_identity=r}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}set data(e){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(e){throw new Error("Method not implemented.")}terminate(e){throw new Error("Method not implemented.")}async sendInfo(e,t,r){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(e){throw new Error("Method not implemented.")}unmute(e){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(e,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}removeAllListeners(e){return console.warn("Method not implemented. Event:",e),this}setMaxListeners(e){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(e){throw new Error("Method not implemented.")}rawListeners(e){throw new Error("Method not implemented.")}emit(e,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){e&&Object.entries(e).forEach(([t,r])=>{this.on(t,r)})}on(e,t){return T.includes(e)&&this.events.on(e,t),this}trigger(e,t){this.events.trigger(e,t)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(e){return this.trigger("presentation:start",e),this.trigger("presentation:started",e),e}async stopPresentation(e){return this.trigger("presentation:end",e),this.trigger("presentation:ended",e),e}isEstablished(){return!0}}class R{stats=new Map().set("codec",{mimeType:"video/h264"});dtmf=null;track=null;transport=null;transform=null;parameters={encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}};parametersGets;constructor({track:e}={}){this.track=e??null}async getStats(){return this.stats}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class A{currentDirection="sendrecv";direction="sendrecv";mid=null;receiver;sender;stopped=!1;constructor(e){this.sender=e}setCodecPreferences(e){}stop(){}}class at extends EventTarget{senders=[];receivers=[];canTrickleIceCandidates;connectionState;currentLocalDescription;currentRemoteDescription;iceConnectionState;iceGatheringState;idpErrorInfo;idpLoginUrl;localDescription;onconnectionstatechange;ondatachannel;onicecandidate;onicecandidateerror=null;oniceconnectionstatechange;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;peerIdentity=void 0;pendingLocalDescription;pendingRemoteDescription;remoteDescription;sctp=null;signalingState;close=jest.fn();setLocalDescription=jest.fn(async e=>{});setRemoteDescription=jest.fn(async e=>{});addTransceiver=jest.fn((e,t)=>({}));createOffer=jest.fn(async(e,t,r)=>({type:"offer",sdp:"offer-sdp"}));constructor(e,t){super(),this.receivers=t?.map(r=>({track:r}))??[]}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(e){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(e){throw new Error("Method not implemented.")}setConfiguration(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=(e,...t)=>{const r=new R({track:e}),o=new A(r);return o.mid=e.kind==="audio"?"0":"1",this.senders.push(r),this.dispatchTrackInternal(e,...t),r};addTrackWithMid=(e,t)=>{const r=new R({track:e}),o=new A(r);return t===void 0?o.mid=e.kind==="audio"?"0":"1":o.mid=t,this.senders.push(r),this.dispatchTrackInternal(e),r};dispatchTrack(e){this.dispatchTrackInternal(new _.MediaStreamTrackMock(e))}dispatchTrackInternal(e,...t){const r=new Event("track");Object.defineProperty(r,"track",{value:e}),Object.defineProperty(r,"streams",{value:t.length===0?[new MediaStream([e])]:t}),this.dispatchEvent(r)}}function ct(n){const e=n.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const M=400,F="777",dt=n=>n.getVideoTracks().length>0;class s extends st{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;renegotiate=jest.fn(async()=>!0);answer=jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},M)});replaceMediaStream=jest.fn(async e=>{});_isReadyToReOffer=jest.fn(()=>!0);addTransceiver=jest.fn((e,t)=>({}));restartIce=jest.fn(async e=>!0);isEndedInner=!1;delayStartPresentation=0;timeoutStartPresentation;timeoutConnect;timeoutNewInfo;timeoutAccepted;timeoutConfirmed;constructor({eventHandlers:e,originator:t,remoteIdentity:r=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1"),delayStartPresentation:o=0}){super({originator:t,eventHandlers:e,remoteIdentity:r}),this.delayStartPresentation=o}static get C(){return a.SessionStatus}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=t}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}startPresentation=async e=>(s.countStartsPresentation+=1,new Promise((t,r)=>{this.timeoutStartPresentation=setTimeout(()=>{if(s.presentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.presentationError);return}if(s.startPresentationError&&s.countStartsPresentation<s.countStartPresentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.startPresentationError);return}t(super.startPresentation(e))},this.delayStartPresentation)}));stopPresentation=async e=>{if(s.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),s.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=_.createAudioMediaStreamTrackMock();t.id="mainaudio1";const r=[t];if(dt(e)){const c=_.createVideoMediaStreamTrackMock();c.id="mainvideo1",r.push(c)}this.connection=new at(void 0,r),this.trigger("peerconnection",{peerconnection:this.connection}),this.addStream(e)}connect(e,{mediaStream:t}={}){const r=ct(e);return this.initPeerconnection(t),this.timeoutConnect=setTimeout(()=>{e.includes(F)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:D.Originator.REMOTE,request:{getHeader:o=>o==="content-type"?"application/vinteo.webrtc.roomname":o==="x-webrtc-enter-room"?r:o==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),this.timeoutAccepted=setTimeout(()=>{this.trigger("accepted")},200),this.timeoutConfirmed=setTimeout(()=>{this.trigger("confirmed")},300))},M),this.connection}terminate({status_code:e,cause:t}={}){return this.status_code=e,this.trigger("ended",{status_code:e,cause:t,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:t}={}){this.terminate({status_code:e,cause:t})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}addStream(e,t="getTracks"){e[t]().forEach(r=>this.connection.addTrack(r,e))}forEachSenders(e){const t=this.connection.getSenders();for(const r of t)e(r);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t?.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{t?.kind==="video"&&(t.enabled=!e)})}mute(e){e.audio&&(this.mutedOptions.audio=!0,this.toggleMuteAudio(this.mutedOptions.audio)),e.video&&(this.mutedOptions.video=!0,this.toggleMuteVideo(this.mutedOptions.video)),this.onmute(e)}unmute(e){e.audio&&(this.mutedOptions.audio=!1),e.video&&(this.mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this.mutedOptions}onmute({audio:e,video:t}){this.trigger("muted",{audio:e,video:t})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(e){this.trigger("newInfo",e)}clear(){clearTimeout(this.timeoutStartPresentation),clearTimeout(this.timeoutConnect),clearTimeout(this.timeoutNewInfo),clearTimeout(this.timeoutAccepted),clearTimeout(this.timeoutConfirmed)}}class Et{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",I="PASSWORD_CORRECT_2",W="NAME_INCORRECT",h=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},O={status_code:200,reason_phrase:"OK"},P={status_code:401,reason_phrase:"Unauthorized"};class i{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:r,eventHandlers:o}=t;return this.session=new s({eventHandlers:o,originator:"local"}),this.session.connect(e,{mediaStream:r}),this.session});sendOptions=jest.fn((e,t,r)=>{console.log("sendOptions",e,t,r)});start=jest.fn(()=>{if(i.countStarts+=1,i.startError&&i.countStarts<i.countStartError){this.trigger("disconnected",i.startError);return}this.register()});stop=jest.fn(()=>{this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:g})},h):this.trigger("disconnected",{error:!0,socket:g})});removeAllListeners=jest.fn(()=>(this.events.removeEventHandlers(),this));once=jest.fn((e,t)=>(this.events.once(e,t),this));startedTimeout;stopedTimeout;session;isRegisteredInner;isConnectedInner;configuration;constructor(e){this.events=new v.Events(L);const[t,r]=e.uri.split(":"),[o,c]=r.split("@"),p={...e,uri:new a.URI(t,o,c)};this.configuration=p,this.registratorInner=new Et}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){i.startError=e,i.countStartError=t}static resetStartError(){i.startError=void 0,i.countStartError=Number.POSITIVE_INFINITY,i.countStarts=0}static setAvailableTelephony(){i.isAvailableTelephony=!0}static setNotAvailableTelephony(){i.isAvailableTelephony=!1}static reset(){i.resetStartError(),i.setAvailableTelephony()}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){this.session?.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:r}=this.configuration;t===!0&&r.user.includes(W)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:a.C.causes.REJECTED})},h)):!this.isRegistered()&&t===!0&&(e===d||e===I)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:O})},h)):t===!0&&e!==d&&e!==I&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:a.C.causes.REJECTED})},h)),i.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:O})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}}class ht{url;constructor(e){this.url=e}}class ut extends V.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const S="remote",mt=(n,e)=>{const t=new N(e),r={originator:S,request:t,info:new ut("","")};n.newInfo(r)},lt=(n,e)=>{const r={event:"sipEvent",request:new N(e)};n.newSipEvent(r)},pt=(n,{incomingNumber:e="1234",displayName:t,host:r})=>{const o=new s({originator:S,eventHandlers:{}}),c=new j("sip",e,r);o.remote_identity=new U(c,t);const p=new N([]);n.trigger("newRTCSession",{originator:S,session:o,request:p})},gt=(n,e)=>{e?n.trigger("failed",e):n.trigger("failed",n)},w={triggerNewInfo:mt,triggerNewSipEvent:lt,triggerIncomingSession:pt,triggerFailIncomingSession:gt,WebSocketInterface:ht,UA:i,C:{INVITE:"INVITE"}},u="user",E="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",_t=new w.WebSocketInterface(`wss://${C}/webrtc/wss/`),f={displayName:"DISPLAY_NAME",userAgent:"Chrome",sipServerIp:m,sipServerUrl:C},Tt={...f,displayName:"DISPLAY_NAME",register:!1},b={...f,user:u,password:d,register:!0},It={...b,displayName:E},St={...f,displayName:E,register:!1},l={session_timers:!1,sockets:[_t],user_agent:"Chrome",sdpSemantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},Nt={...l,password:d,uri:new a.URI("sip",u,m),display_name:"DISPLAY_NAME",register:!0},wt={...l,password:d,uri:new a.URI("sip",u,m),display_name:E,register:!0},Ct={...l,display_name:E,register:!1},ft={...l,display_name:"DISPLAY_NAME",register:!1},k="10.10.10.10",Rt=[`X-Vinteo-Remote: ${k}`],At=()=>new D.SipConnector({JsSIP:w});exports.FAILED_CONFERENCE_NUMBER=F;exports.JsSIP=w;exports.NAME_INCORRECT=W;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=I;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=b;exports.dataForConnectionWithAuthorizationWithDisplayName=It;exports.dataForConnectionWithoutAuthorization=St;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=Tt;exports.displayName=E;exports.doMockSipConnector=At;exports.extraHeadersRemoteAddress=Rt;exports.remoteAddress=k;exports.uaConfigurationWithAuthorization=Nt;exports.uaConfigurationWithAuthorizationWithDisplayName=wt;exports.uaConfigurationWithoutAuthorization=Ct;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ft;exports.user=u;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("node:events"),U=require("@krivega/jssip/lib/NameAddrHeader"),j=require("@krivega/jssip/lib/URI"),H=require("@krivega/jssip/lib/SIPMessage"),a=require("@krivega/jssip"),_=require("webrtc-mock"),v=require("events-constructor"),D=require("./@SipConnector-C09GtMW6.cjs");class N extends H.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const q="incomingCall",G="declinedIncomingCall",x="failedIncomingCall",z="terminatedIncomingCall",y="connecting",Y="connected",B="disconnected",K="newRTCSession",J="registered",$="unregistered",Q="registrationFailed",X="newMessage",Z="sipEvent",ee="availableSecondRemoteStream",te="notAvailableSecondRemoteStream",re="mustStopPresentation",ne="shareState",oe="enterRoom",ie="useLicense",se="peerconnection:confirmed",ae="peerconnection:ontrack",ce="channels",de="channels:notify",Ee="ended:fromserver",he="main-cam-control",ue="admin-stop-main-cam",me="admin-start-main-cam",le="admin-stop-mic",pe="admin-start-mic",ge="admin-force-sync-media-state",_e="participant:added-to-list-moderators",Te="participant:removed-from-list-moderators",Ie="participant:move-request-to-stream",Se="participant:move-request-to-spectators",Ne="participant:move-request-to-participants",we="participation:accepting-word-request",Ce="participation:cancelling-word-request",fe="webcast:started",Re="webcast:stopped",Ae="account:changed",Me="account:deleted",Oe="conference:participant-token-issued",Pe="ended",ve="sending",De="reinvite",ye="replaces",Le="refer",Fe="progress",We="accepted",be="confirmed",ke="peerconnection",Ve="failed",Ue="muted",je="unmuted",He="newDTMF",qe="newInfo",Ge="hold",xe="unhold",ze="update",Ye="sdp",Be="icecandidate",Ke="getusermediafailed",Je="peerconnection:createofferfailed",$e="peerconnection:createanswerfailed",Qe="peerconnection:setlocaldescriptionfailed",Xe="peerconnection:setremotedescriptionfailed",Ze="presentation:start",et="presentation:started",tt="presentation:end",rt="presentation:ended",nt="presentation:failed",ot=[q,G,z,x,we,Ce,Ie,de,Oe,Ae,Me,fe,Re,_e,Te],L=[y,Y,B,K,J,$,Q,X,Z],it=[ee,te,re,ne,oe,ie,se,ae,ce,Ee,he,me,ue,le,pe,ge,Se,Ne],T=[Pe,y,ve,De,ye,Le,Fe,We,be,ke,Ve,Ue,je,He,qe,Ge,xe,ze,Ye,Be,Ke,Je,$e,Qe,Xe,Ze,et,tt,rt,nt];[...L,...ot];[...T,...it];class st{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};constructor({originator:e="local",eventHandlers:t,remoteIdentity:r}){this.originator=e,this.events=new v.Events(T),this.initEvents(t),this.remote_identity=r}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}set data(e){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(e){throw new Error("Method not implemented.")}terminate(e){throw new Error("Method not implemented.")}async sendInfo(e,t,r){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(e){throw new Error("Method not implemented.")}unmute(e){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(e,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}removeAllListeners(e){return console.warn("Method not implemented. Event:",e),this}setMaxListeners(e){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(e){throw new Error("Method not implemented.")}rawListeners(e){throw new Error("Method not implemented.")}emit(e,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){e&&Object.entries(e).forEach(([t,r])=>{this.on(t,r)})}on(e,t){return T.includes(e)&&this.events.on(e,t),this}trigger(e,t){this.events.trigger(e,t)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(e){return this.trigger("presentation:start",e),this.trigger("presentation:started",e),e}async stopPresentation(e){return this.trigger("presentation:end",e),this.trigger("presentation:ended",e),e}isEstablished(){return!0}}class R{stats=new Map().set("codec",{mimeType:"video/h264"});dtmf=null;track=null;transport=null;transform=null;parameters={encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}};parametersGets;constructor({track:e}={}){this.track=e??null}async getStats(){return this.stats}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class A{currentDirection="sendrecv";direction="sendrecv";mid=null;receiver;sender;stopped=!1;constructor(e){this.sender=e}setCodecPreferences(e){}stop(){}}class at extends EventTarget{senders=[];receivers=[];canTrickleIceCandidates;connectionState;currentLocalDescription;currentRemoteDescription;iceConnectionState;iceGatheringState;idpErrorInfo;idpLoginUrl;localDescription;onconnectionstatechange;ondatachannel;onicecandidate;onicecandidateerror=null;oniceconnectionstatechange;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;peerIdentity=void 0;pendingLocalDescription;pendingRemoteDescription;remoteDescription;sctp=null;signalingState;close=jest.fn();setLocalDescription=jest.fn(async e=>{});setRemoteDescription=jest.fn(async e=>{});addTransceiver=jest.fn((e,t)=>({}));createOffer=jest.fn(async(e,t,r)=>({type:"offer",sdp:"offer-sdp"}));constructor(e,t){super(),this.receivers=t?.map(r=>({track:r}))??[]}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(e){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(e){throw new Error("Method not implemented.")}setConfiguration(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=(e,...t)=>{const r=new R({track:e}),o=new A(r);return o.mid=e.kind==="audio"?"0":"1",this.senders.push(r),this.dispatchTrackInternal(e,...t),r};addTrackWithMid=(e,t)=>{const r=new R({track:e}),o=new A(r);return t===void 0?o.mid=e.kind==="audio"?"0":"1":o.mid=t,this.senders.push(r),this.dispatchTrackInternal(e),r};dispatchTrack(e){this.dispatchTrackInternal(new _.MediaStreamTrackMock(e))}dispatchTrackInternal(e,...t){const r=new Event("track");Object.defineProperty(r,"track",{value:e}),Object.defineProperty(r,"streams",{value:t.length===0?[new MediaStream([e])]:t}),this.dispatchEvent(r)}}function ct(n){const e=n.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const M=400,F="777",dt=n=>n.getVideoTracks().length>0;class s extends st{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;renegotiate=jest.fn(async()=>!0);answer=jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},M)});replaceMediaStream=jest.fn(async e=>{});_isReadyToReOffer=jest.fn(()=>!0);addTransceiver=jest.fn((e,t)=>({}));restartIce=jest.fn(async e=>!0);isEndedInner=!1;delayStartPresentation=0;timeoutStartPresentation;timeoutConnect;timeoutNewInfo;timeoutAccepted;timeoutConfirmed;constructor({eventHandlers:e,originator:t,remoteIdentity:r=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1"),delayStartPresentation:o=0}){super({originator:t,eventHandlers:e,remoteIdentity:r}),this.delayStartPresentation=o}static get C(){return a.SessionStatus}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=t}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}startPresentation=async e=>(s.countStartsPresentation+=1,new Promise((t,r)=>{this.timeoutStartPresentation=setTimeout(()=>{if(s.presentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.presentationError);return}if(s.startPresentationError&&s.countStartsPresentation<s.countStartPresentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.startPresentationError);return}t(super.startPresentation(e))},this.delayStartPresentation)}));stopPresentation=async e=>{if(s.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),s.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=_.createAudioMediaStreamTrackMock();t.id="mainaudio1";const r=[t];if(dt(e)){const c=_.createVideoMediaStreamTrackMock();c.id="mainvideo1",r.push(c)}this.connection=new at(void 0,r),this.trigger("peerconnection",{peerconnection:this.connection}),this.addStream(e)}connect(e,{mediaStream:t}={}){const r=ct(e);return this.initPeerconnection(t),this.timeoutConnect=setTimeout(()=>{e.includes(F)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:D.Originator.REMOTE,request:{getHeader:o=>o==="content-type"?"application/vinteo.webrtc.roomname":o==="x-webrtc-enter-room"?r:o==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),this.timeoutAccepted=setTimeout(()=>{this.trigger("accepted")},200),this.timeoutConfirmed=setTimeout(()=>{this.trigger("confirmed")},300))},M),this.connection}terminate({status_code:e,cause:t}={}){return this.status_code=e,this.trigger("ended",{status_code:e,cause:t,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:t}={}){this.terminate({status_code:e,cause:t})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}addStream(e,t="getTracks"){e[t]().forEach(r=>this.connection.addTrack(r,e))}forEachSenders(e){const t=this.connection.getSenders();for(const r of t)e(r);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t?.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{t?.kind==="video"&&(t.enabled=!e)})}mute(e){e.audio&&(this.mutedOptions.audio=!0,this.toggleMuteAudio(this.mutedOptions.audio)),e.video&&(this.mutedOptions.video=!0,this.toggleMuteVideo(this.mutedOptions.video)),this.onmute(e)}unmute(e){e.audio&&(this.mutedOptions.audio=!1),e.video&&(this.mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this.mutedOptions}onmute({audio:e,video:t}){this.trigger("muted",{audio:e,video:t})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(e){this.trigger("newInfo",e)}clear(){clearTimeout(this.timeoutStartPresentation),clearTimeout(this.timeoutConnect),clearTimeout(this.timeoutNewInfo),clearTimeout(this.timeoutAccepted),clearTimeout(this.timeoutConfirmed)}}class Et{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",I="PASSWORD_CORRECT_2",W="NAME_INCORRECT",h=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},O={status_code:200,reason_phrase:"OK"},P={status_code:401,reason_phrase:"Unauthorized"};class i{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:r,eventHandlers:o}=t;return this.session=new s({eventHandlers:o,originator:"local"}),this.session.connect(e,{mediaStream:r}),this.session});sendOptions=jest.fn((e,t,r)=>{console.log("sendOptions",e,t,r)});start=jest.fn(()=>{if(i.countStarts+=1,i.startError&&i.countStarts<i.countStartError){this.trigger("disconnected",i.startError);return}this.register()});stop=jest.fn(()=>{this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:g})},h):this.trigger("disconnected",{error:!0,socket:g})});removeAllListeners=jest.fn(()=>(this.events.removeEventHandlers(),this));once=jest.fn((e,t)=>(this.events.once(e,t),this));startedTimeout;stopedTimeout;session;isRegisteredInner;isConnectedInner;configuration;constructor(e){this.events=new v.Events(L);const[t,r]=e.uri.split(":"),[o,c]=r.split("@"),p={...e,uri:new a.URI(t,o,c)};this.configuration=p,this.registratorInner=new Et}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){i.startError=e,i.countStartError=t}static resetStartError(){i.startError=void 0,i.countStartError=Number.POSITIVE_INFINITY,i.countStarts=0}static setAvailableTelephony(){i.isAvailableTelephony=!0}static setNotAvailableTelephony(){i.isAvailableTelephony=!1}static reset(){i.resetStartError(),i.setAvailableTelephony()}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){this.session?.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:r}=this.configuration;t===!0&&r.user.includes(W)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:a.C.causes.REJECTED})},h)):!this.isRegistered()&&t===!0&&(e===d||e===I)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:O})},h)):t===!0&&e!==d&&e!==I&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:a.C.causes.REJECTED})},h)),i.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:O})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}}class ht{url;constructor(e){this.url=e}}class ut extends V.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const S="remote",mt=(n,e)=>{const t=new N(e),r={originator:S,request:t,info:new ut("","")};n.newInfo(r)},lt=(n,e)=>{const r={event:"sipEvent",request:new N(e)};n.newSipEvent(r)},pt=(n,{incomingNumber:e="1234",displayName:t,host:r})=>{const o=new s({originator:S,eventHandlers:{}}),c=new j("sip",e,r);o.remote_identity=new U(c,t);const p=new N([]);n.trigger("newRTCSession",{originator:S,session:o,request:p})},gt=(n,e)=>{e?n.trigger("failed",e):n.trigger("failed",n)},w={triggerNewInfo:mt,triggerNewSipEvent:lt,triggerIncomingSession:pt,triggerFailIncomingSession:gt,WebSocketInterface:ht,UA:i,C:{INVITE:"INVITE"}},u="user",E="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",_t=new w.WebSocketInterface(`wss://${C}/webrtc/wss/`),f={displayName:"DISPLAY_NAME",userAgent:"Chrome",sipServerIp:m,sipServerUrl:C},Tt={...f,displayName:"DISPLAY_NAME",register:!1},b={...f,user:u,password:d,register:!0},It={...b,displayName:E},St={...f,displayName:E,register:!1},l={session_timers:!1,sockets:[_t],user_agent:"Chrome",sdpSemantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},Nt={...l,password:d,uri:new a.URI("sip",u,m),display_name:"DISPLAY_NAME",register:!0},wt={...l,password:d,uri:new a.URI("sip",u,m),display_name:E,register:!0},Ct={...l,display_name:E,register:!1},ft={...l,display_name:"DISPLAY_NAME",register:!1},k="10.10.10.10",Rt=[`X-Vinteo-Remote: ${k}`],At=()=>new D.SipConnector({JsSIP:w});exports.FAILED_CONFERENCE_NUMBER=F;exports.JsSIP=w;exports.NAME_INCORRECT=W;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=I;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=b;exports.dataForConnectionWithAuthorizationWithDisplayName=It;exports.dataForConnectionWithoutAuthorization=St;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=Tt;exports.displayName=E;exports.doMockSipConnector=At;exports.extraHeadersRemoteAddress=Rt;exports.remoteAddress=k;exports.uaConfigurationWithAuthorization=Nt;exports.uaConfigurationWithAuthorizationWithDisplayName=wt;exports.uaConfigurationWithoutAuthorization=Ct;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ft;exports.user=u;
|
package/dist/doMock.js
CHANGED
|
@@ -5,7 +5,7 @@ import { IncomingRequest as b } from "@krivega/jssip/lib/SIPMessage";
|
|
|
5
5
|
import { NameAddrHeader as V, URI as E, SessionStatus as W, C as N } from "@krivega/jssip";
|
|
6
6
|
import { MediaStreamTrackMock as j, createAudioMediaStreamTrackMock as U, createVideoMediaStreamTrackMock as G } from "webrtc-mock";
|
|
7
7
|
import { Events as O } from "events-constructor";
|
|
8
|
-
import { O as H, S as x } from "./@SipConnector-
|
|
8
|
+
import { O as H, S as x } from "./@SipConnector-B4noAdXF.js";
|
|
9
9
|
class T extends b {
|
|
10
10
|
headers;
|
|
11
11
|
constructor(e) {
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./@SipConnector-BVCkiu8l.cjs");require("events-constructor");const k=require("@krivega/cancelable-promise"),W=require("repeated-calls"),H=require("ts-debounce"),Y=require("ua-parser-js"),j=require("sequent-promises"),K=require("stack-promises"),X=e=>e instanceof Object&&("originator"in e||"cause"in e),J=e=>{if(k.isCanceledError(e))return!0;if(!X(e))return!1;const{originator:n,cause:r}=e;return typeof r=="string"?r===t.ECallCause.REQUEST_TIMEOUT||r===t.ECallCause.REJECTED||n==="local"&&(r===t.ECallCause.CANCELED||r===t.ECallCause.BYE):!1};var C=(e=>(e.DISCONNECTED="system:disconnected",e.CONNECTING="system:connecting",e.READY_TO_CALL="system:readyToCall",e.CALL_CONNECTING="system:callConnecting",e.CALL_ACTIVE="system:callActive",e.CONNECTION_FAILED="system:connectionFailed",e.CALL_FAILED="system:callFailed",e))(C||{});const V=e=>e.connection.value,F=e=>e.call.value,z=e=>e.incoming.value,Q=e=>{if(e.incoming.value!==t.EState$2.IDLE)return e.incoming.context.remoteCallerData},Z=e=>e.presentation.value,ee=e=>{const n=F(e);return n===t.EState$1.IN_CALL||n===t.EState$1.ACCEPTED},ne=e=>{const n=V(e),r=F(e);if(n===t.EState.IDLE||n===t.EState.DISCONNECTED)return C.DISCONNECTED;if(n===t.EState.FAILED)return C.CONNECTION_FAILED;if(n===t.EState.PREPARING||n===t.EState.CONNECTING||n===t.EState.CONNECTED||n===t.EState.REGISTERED)return C.CONNECTING;switch(r){case t.EState$1.IDLE:return C.READY_TO_CALL;case t.EState$1.CONNECTING:return C.CALL_CONNECTING;case t.EState$1.ACCEPTED:case t.EState$1.IN_CALL:return C.CALL_ACTIVE;case t.EState$1.ENDED:return C.READY_TO_CALL;case t.EState$1.FAILED:return C.CALL_FAILED;default:return C.READY_TO_CALL}},te={selectConnectionStatus:V,selectCallStatus:F,selectIncomingStatus:z,selectIncomingRemoteCaller:Q,selectPresentationStatus:Z,selectIsInCall:ee,selectSystemStatus:ne},re=()=>globalThis.process?.versions?.electron!==void 0,x=()=>{const e=new Y.UAParser,{name:n}=e.getBrowser(),r=re();return{isChrome:n==="Chrome"||r}},v=e=>{const{url:n,cause:r}=e;let o=n;return(r===t.ECallCause.BAD_MEDIA_DESCRIPTION||r===t.ECallCause.NOT_FOUND)&&(o=`${e.message.to.uri.user}@${e.message.to.uri.host}`),o};var B=(e=>(e.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",e.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",e.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",e.NOT_FOUND_ERROR="NOT_FOUND_ERROR",e.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",e.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",e))(B||{});const oe=new Error("Unknown error"),se=(e=oe)=>{const{cause:n,socket:r}=e;let o="CONNECT_SERVER_FAILED";switch(n){case"Forbidden":{o="WRONG_USER_OR_PASSWORD";break}case t.ECallCause.BAD_MEDIA_DESCRIPTION:{o="BAD_MEDIA_ERROR";break}case t.ECallCause.NOT_FOUND:{o="NOT_FOUND_ERROR";break}default:r!==void 0&&r._ws?.readyState===3?o="WS_CONNECTION_FAILED":v(e)!==void 0&&v(e)!==""&&(o="CONNECT_SERVER_FAILED_BY_LINK")}return o},ae=e=>{let n="";try{n=JSON.stringify(e)}catch(r){t.logger("failed to stringify message",r)}return n},ce=new Error("Unknown error"),ie=(e=ce)=>{const{code:n,cause:r,message:o}=e,a=v(e),s={code:"",cause:"",message:""};return typeof o=="object"&&o!==null?s.message=ae(o):o&&(s.message=String(o)),a!==void 0&&a!==""&&(s.link=a),n!==void 0&&n!==""&&(s.code=n),r!==void 0&&r!==""&&(s.cause=r),s},le=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:B,getLinkError:v,getTypeFromError:se,getValuesFromError:ie},Symbol.toStringTag,{value:"Module"})),ue=({sessionId:e,remoteAddress:n,isMutedAudio:r,isMutedVideo:o,isRegistered:a,isPresentationCall:s})=>{const c=[],l=r?"0":"1",g=o?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${g}`),(a===!1||a===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Session: ${e}`),s===!0&&c.push("X-Vinteo-Presentation-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Remote: ${n}`),c},Ce="[@*!|]",ge="_",de=e=>{let n=e;return n=n.replaceAll(new RegExp(Ce,"g"),ge),n},Se=({appName:e,appVersion:n,browserName:r,browserVersion:o})=>{const s=`${de(e)} ${n}`;return`ChromeNew - ${r===void 0?s:`${r} ${o}, ${s}`}`},Ee=({isUnifiedSdpSemantic:e,appVersion:n,browserName:r,browserVersion:o,appName:a})=>e?Se({appVersion:n,browserName:r,browserVersion:o,appName:a}):"Chrome",q="purgatory",D=e=>e===q,fe=e=>n=>[...n].map(o=>async()=>e(o)),me=async({accumulatedKeys:e,sendKey:n,canRunTask:r})=>{const a=fe(n)(e);return j.sequentPromises(a,r)},pe=e=>r=>(t.logger("onStartMainCam"),e.on("api:admin-start-main-cam",r)),he=e=>r=>(t.logger("onStartMic"),e.on("api:admin-start-mic",r)),Re=e=>r=>(t.logger("onStopMainCam"),e.on("api:admin-stop-main-cam",r)),Te=e=>r=>(t.logger("onStopMic"),e.on("api:admin-stop-mic",r)),Ne=({sipConnector:e})=>{const n=(u,d)=>({isSyncForced:S})=>{if(S===!0){u();return}d()},r=pe(e),o=Re(e),a=he(e),s=Te(e);let c,l,g,p;const N=({onStartMainCamForced:u,onStartMainCamNotForced:d,onStopMainCamForced:S,onStopMainCamNotForced:R,onStartMicForced:T,onStartMicNotForced:A,onStopMicForced:b,onStopMicNotForced:P})=>{const E=n(u,d);c=r(E);const f=n(S,R);l=o(f);const I=n(T,A);g=a(I);const m=n(b,P);p=s(m)},O=()=>{c?.(),l?.(),g?.(),p?.()};return{start:u=>{N(u)},stop:()=>{O()}}},Oe=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:q,createSyncMediaState:Ne,createUaParser:x,error:le,getExtraHeaders:ue,getUserAgent:Ee,hasPurgatory:D,prepareMediaStream:t.prepareMediaStream,sendDtmfAccumulated:me,sendOffer:t.sendOffer,setEncodingsToSender:t.setEncodingsToSender,setParametersToSender:t.setParametersToSender},Symbol.toStringTag,{value:"Module"})),_e=()=>x().isChrome,Ae=e=>{if(!k.isCanceledError(e)&&!W.hasCanceledError(e)&&!t.hasNotReadyForConnectionError(e))throw e;return{configuration:void 0,isSuccessful:!1}},be=({kind:e,readyState:n})=>e==="video"&&n==="live",w=(e,n,{onEnterPurgatory:r,onEnterConference:o})=>{D(e)?r&&r():o&&o({isSuccessProgressCall:n})},U=(e,n)=>{e(),n&&n()},$=(e,n,r)=>{throw e&&e(),n(),r},Pe=new Set(["on","once","onceRace","wait","off","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","startAutoConnect","stopAutoConnect","connection","isConfigured","isRegistered"]);class ve{on;once;onceRace;wait;off;sendDTMF;hangUp;declineToIncomingCall;sendChannels;checkTelephony;waitChannels;ping;startAutoConnect;stopAutoConnect;connection;isConfigured;isRegistered;sipConnector;constructor(n){return this.sipConnector=n,new Proxy(this,{get:(r,o,a)=>{if(typeof o=="string"&&Pe.has(o)&&o in this.sipConnector){const c=Reflect.get(this.sipConnector,o,this.sipConnector);return typeof c=="function"?c.bind(this.sipConnector):c}const s=Reflect.get(r,o,a);return typeof s=="function"?s.bind(r):s}})}connectToServer=async(n,r)=>this.sipConnector.connect(n,r).then(o=>(t.logger("connectToServer then"),{configuration:o,isSuccessful:!0})).catch(async o=>(t.logger("connectToServer catch: error",o),Ae(o)));callToServer=async n=>{const{conference:r,mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,degradationPreference:l,sendEncodings:g,offerToReceiveAudio:p,offerToReceiveVideo:N,directionVideo:O,directionAudio:_,onBeforeProgressCall:h,onSuccessProgressCall:u,onEnterPurgatory:d,onEnterConference:S,onFailProgressCall:R,onFinishProgressCall:T,onEndedCall:A,onAddedTransceiver:b}=n;t.logger("callToServer",n);const P=async()=>(t.logger("startCall"),this.sipConnector.call({mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,offerToReceiveAudio:p,offerToReceiveVideo:N,directionVideo:O,directionAudio:_,degradationPreference:l,onAddedTransceiver:b,sendEncodings:g,number:r}));let E=!1,f;const m=(t.logger("subscribeEnterConference: onEnterConference",S),this.sipConnector.on("api:enterRoom",({room:i})=>{t.logger("enterRoom",{_room:i,isSuccessProgressCall:E}),f=i,(d??S)&&w(f,E,{onEnterPurgatory:d,onEnterConference:S})})),M=i=>(t.logger("onSuccess"),E=!0,u&&u({isPurgatory:D(f)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{U(m,A)}),i),y=i=>(t.logger("onFail"),$(R,m,i)),L=()=>{t.logger("onFinish"),T&&T()};return t.logger("onBeforeProgressCall"),h&&h(r),P().then(M).catch(i=>y(i)).finally(L)};disconnectFromServer=async()=>this.sipConnector.disconnect().then(()=>(t.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(n=>(t.logger("disconnectFromServer: catch",n),{isSuccessful:!1}));answerToIncomingCall=async n=>{const{mediaStream:r,extraHeaders:o,iceServers:a,contentHint:s,degradationPreference:c,sendEncodings:l,offerToReceiveAudio:g,offerToReceiveVideo:p,directionVideo:N,directionAudio:O,onBeforeProgressCall:_,onSuccessProgressCall:h,onEnterPurgatory:u,onEnterConference:d,onFailProgressCall:S,onFinishProgressCall:R,onEndedCall:T,onAddedTransceiver:A}=n;t.logger("answerToIncomingCall",n);const b=async()=>this.sipConnector.answerToIncomingCall({mediaStream:r,extraHeaders:o,iceServers:a,contentHint:s,offerToReceiveAudio:g,offerToReceiveVideo:p,directionVideo:N,directionAudio:O,degradationPreference:c,onAddedTransceiver:A,sendEncodings:l}),P=()=>{const{remoteCallerData:i}=this.sipConnector;return i.incomingNumber};let E=!1,f;const m=(t.logger("subscribeEnterConference: onEnterConference",d),this.sipConnector.on("api:enterRoom",i=>{t.logger("enterRoom",{room:i.room,isSuccessProgressCall:E}),f=i.room,(u??d)&&w(f,E,{onEnterPurgatory:u,onEnterConference:d})})),M=i=>(t.logger("onSuccess"),E=!0,h&&h({isPurgatory:D(f)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{U(m,T)}),i),y=i=>(t.logger("onFail"),$(S,m,i)),L=()=>{t.logger("onFinish"),R&&R()};if(t.logger("onBeforeProgressCall"),_){const i=P();_(i)}return b().then(M).catch(i=>y(i)).finally(L)};updatePresentation=async({mediaStream:n,isP2P:r,contentHint:o,degradationPreference:a,sendEncodings:s,onAddedTransceiver:c})=>(t.logger("updatePresentation"),this.sipConnector.updatePresentation(n,{isP2P:r,contentHint:o,degradationPreference:a,onAddedTransceiver:c,sendEncodings:s}));startPresentation=async({mediaStream:n,isP2P:r,contentHint:o,degradationPreference:a,sendEncodings:s,callLimit:c,onAddedTransceiver:l})=>(t.logger("startPresentation"),this.sipConnector.startPresentation(n,{isP2P:r,contentHint:o,callLimit:c,degradationPreference:a,onAddedTransceiver:l,sendEncodings:s}));stopShareSipConnector=async({isP2P:n=!1}={})=>(t.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:n}).catch(r=>{t.logger(r)}));sendRefusalToTurnOnMic=async()=>{t.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(n=>{t.logger("sendRefusalToTurnOnMic: error",n)})};sendRefusalToTurnOnCam=async()=>{t.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(n=>{t.logger("sendRefusalToTurnOnCam: error",n)})};sendMediaState=async({isEnabledCam:n,isEnabledMic:r})=>{t.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:n,mic:r})};replaceMediaStream=async(n,{deleteExisting:r,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,sendEncodings:l,onAddedTransceiver:g})=>(t.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(n,{deleteExisting:r,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,onAddedTransceiver:g,sendEncodings:l}));askPermissionToEnableCam=async()=>{t.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam()};resolveHandleReadyRemoteStreamsDebounced=({onReadyRemoteStreams:n})=>H.debounce(()=>{const r=this.sipConnector.getRemoteStreams();t.logger("remoteStreams",r),n(r)},200);resolveHandleReadyRemoteStreams=({onReadyRemoteStreams:n})=>({track:r})=>{be(r)&&n()};getRemoteStreams=()=>(t.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams());onUseLicense=n=>(t.logger("onUseLicense"),this.sipConnector.on("api:useLicense",n));onMustStopPresentation=n=>(t.logger("onMustStopPresentation"),this.sipConnector.on("api:mustStopPresentation",n));onMoveToSpectators=n=>(t.logger("onMoveToSpectators"),this.sipConnector.on("api:participant:move-request-to-spectators",n));onMoveToParticipants=n=>(t.logger("onMoveToParticipants"),this.sipConnector.on("api:participant:move-request-to-participants",n));onStats=n=>(t.logger("onStats"),this.sipConnector.on("stats:collected",n));offStats=n=>{t.logger("offStats"),this.sipConnector.off("stats:collected",n)}}var G=(e=>(e.VP8="video/VP8",e.VP9="video/VP9",e.H264="video/H264",e.AV1="video/AV1",e.rtx="video/rtx",e.red="video/red",e.flexfec03="video/flexfec-03",e))(G||{});exports.ECallCause=t.ECallCause;exports.ECallStatus=t.EState$1;exports.EConnectionStatus=t.EState;exports.EIncomingStatus=t.EState$2;exports.EPresentationStatus=t.EState$3;exports.EStatsTypes=t.EStatsTypes;exports.EUseLicense=t.EUseLicense;exports.SipConnector=t.SipConnector;exports.StatsPeerConnection=t.StatsPeerConnection;exports.disableDebug=t.disableDebug;exports.enableDebug=t.enableDebug;exports.getCodecFromSender=t.getCodecFromSender;exports.hasCanceledStartPresentationError=t.hasCanceledStartPresentationError;Object.defineProperty(exports,"hasConnectionPromiseIsNotActualError",{enumerable:!0,get:()=>K.isPromiseIsNotActualError});exports.EMimeTypesVideoCodecs=G;exports.ESystemStatus=C;exports.SipConnectorFacade=ve;exports.hasAvailableStats=_e;exports.hasCanceledCallError=J;exports.sessionSelectors=te;exports.tools=Oe;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./@SipConnector-C09GtMW6.cjs");require("events-constructor");const k=require("@krivega/cancelable-promise"),W=require("repeated-calls"),H=require("ts-debounce"),Y=require("ua-parser-js"),j=require("sequent-promises"),K=require("stack-promises"),X=e=>e instanceof Object&&("originator"in e||"cause"in e),J=e=>{if(k.isCanceledError(e))return!0;if(!X(e))return!1;const{originator:n,cause:r}=e;return typeof r=="string"?r===t.ECallCause.REQUEST_TIMEOUT||r===t.ECallCause.REJECTED||n==="local"&&(r===t.ECallCause.CANCELED||r===t.ECallCause.BYE):!1};var C=(e=>(e.DISCONNECTED="system:disconnected",e.CONNECTING="system:connecting",e.READY_TO_CALL="system:readyToCall",e.CALL_CONNECTING="system:callConnecting",e.CALL_ACTIVE="system:callActive",e.CONNECTION_FAILED="system:connectionFailed",e.CALL_FAILED="system:callFailed",e))(C||{});const V=e=>e.connection.value,F=e=>e.call.value,z=e=>e.incoming.value,Q=e=>{if(e.incoming.value!==t.EState$2.IDLE)return e.incoming.context.remoteCallerData},Z=e=>e.presentation.value,ee=e=>{const n=F(e);return n===t.EState$1.IN_CALL||n===t.EState$1.ACCEPTED},ne=e=>{const n=V(e),r=F(e);if(n===t.EState.IDLE||n===t.EState.DISCONNECTED)return C.DISCONNECTED;if(n===t.EState.FAILED)return C.CONNECTION_FAILED;if(n===t.EState.PREPARING||n===t.EState.CONNECTING||n===t.EState.CONNECTED||n===t.EState.REGISTERED)return C.CONNECTING;switch(r){case t.EState$1.IDLE:return C.READY_TO_CALL;case t.EState$1.CONNECTING:return C.CALL_CONNECTING;case t.EState$1.ACCEPTED:case t.EState$1.IN_CALL:return C.CALL_ACTIVE;case t.EState$1.ENDED:return C.READY_TO_CALL;case t.EState$1.FAILED:return C.CALL_FAILED;default:return C.READY_TO_CALL}},te={selectConnectionStatus:V,selectCallStatus:F,selectIncomingStatus:z,selectIncomingRemoteCaller:Q,selectPresentationStatus:Z,selectIsInCall:ee,selectSystemStatus:ne},re=()=>globalThis.process?.versions?.electron!==void 0,x=()=>{const e=new Y.UAParser,{name:n}=e.getBrowser(),r=re();return{isChrome:n==="Chrome"||r}},v=e=>{const{url:n,cause:r}=e;let o=n;return(r===t.ECallCause.BAD_MEDIA_DESCRIPTION||r===t.ECallCause.NOT_FOUND)&&(o=`${e.message.to.uri.user}@${e.message.to.uri.host}`),o};var B=(e=>(e.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",e.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",e.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",e.NOT_FOUND_ERROR="NOT_FOUND_ERROR",e.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",e.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",e))(B||{});const oe=new Error("Unknown error"),se=(e=oe)=>{const{cause:n,socket:r}=e;let o="CONNECT_SERVER_FAILED";switch(n){case"Forbidden":{o="WRONG_USER_OR_PASSWORD";break}case t.ECallCause.BAD_MEDIA_DESCRIPTION:{o="BAD_MEDIA_ERROR";break}case t.ECallCause.NOT_FOUND:{o="NOT_FOUND_ERROR";break}default:r!==void 0&&r._ws?.readyState===3?o="WS_CONNECTION_FAILED":v(e)!==void 0&&v(e)!==""&&(o="CONNECT_SERVER_FAILED_BY_LINK")}return o},ae=e=>{let n="";try{n=JSON.stringify(e)}catch(r){t.logger("failed to stringify message",r)}return n},ce=new Error("Unknown error"),ie=(e=ce)=>{const{code:n,cause:r,message:o}=e,a=v(e),s={code:"",cause:"",message:""};return typeof o=="object"&&o!==null?s.message=ae(o):o&&(s.message=String(o)),a!==void 0&&a!==""&&(s.link=a),n!==void 0&&n!==""&&(s.code=n),r!==void 0&&r!==""&&(s.cause=r),s},le=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:B,getLinkError:v,getTypeFromError:se,getValuesFromError:ie},Symbol.toStringTag,{value:"Module"})),ue=({sessionId:e,remoteAddress:n,isMutedAudio:r,isMutedVideo:o,isRegistered:a,isPresentationCall:s})=>{const c=[],l=r?"0":"1",g=o?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${g}`),(a===!1||a===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Session: ${e}`),s===!0&&c.push("X-Vinteo-Presentation-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Remote: ${n}`),c},Ce="[@*!|]",ge="_",de=e=>{let n=e;return n=n.replaceAll(new RegExp(Ce,"g"),ge),n},Se=({appName:e,appVersion:n,browserName:r,browserVersion:o})=>{const s=`${de(e)} ${n}`;return`ChromeNew - ${r===void 0?s:`${r} ${o}, ${s}`}`},Ee=({isUnifiedSdpSemantic:e,appVersion:n,browserName:r,browserVersion:o,appName:a})=>e?Se({appVersion:n,browserName:r,browserVersion:o,appName:a}):"Chrome",q="purgatory",D=e=>e===q,fe=e=>n=>[...n].map(o=>async()=>e(o)),me=async({accumulatedKeys:e,sendKey:n,canRunTask:r})=>{const a=fe(n)(e);return j.sequentPromises(a,r)},pe=e=>r=>(t.logger("onStartMainCam"),e.on("api:admin-start-main-cam",r)),he=e=>r=>(t.logger("onStartMic"),e.on("api:admin-start-mic",r)),Re=e=>r=>(t.logger("onStopMainCam"),e.on("api:admin-stop-main-cam",r)),Te=e=>r=>(t.logger("onStopMic"),e.on("api:admin-stop-mic",r)),Ne=({sipConnector:e})=>{const n=(u,d)=>({isSyncForced:S})=>{if(S===!0){u();return}d()},r=pe(e),o=Re(e),a=he(e),s=Te(e);let c,l,g,p;const N=({onStartMainCamForced:u,onStartMainCamNotForced:d,onStopMainCamForced:S,onStopMainCamNotForced:R,onStartMicForced:T,onStartMicNotForced:A,onStopMicForced:b,onStopMicNotForced:P})=>{const E=n(u,d);c=r(E);const f=n(S,R);l=o(f);const I=n(T,A);g=a(I);const m=n(b,P);p=s(m)},O=()=>{c?.(),l?.(),g?.(),p?.()};return{start:u=>{N(u)},stop:()=>{O()}}},Oe=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:q,createSyncMediaState:Ne,createUaParser:x,error:le,getExtraHeaders:ue,getUserAgent:Ee,hasPurgatory:D,prepareMediaStream:t.prepareMediaStream,sendDtmfAccumulated:me,sendOffer:t.sendOffer,setEncodingsToSender:t.setEncodingsToSender,setParametersToSender:t.setParametersToSender},Symbol.toStringTag,{value:"Module"})),_e=()=>x().isChrome,Ae=e=>{if(!k.isCanceledError(e)&&!W.hasCanceledError(e)&&!t.hasNotReadyForConnectionError(e))throw e;return{configuration:void 0,isSuccessful:!1}},be=({kind:e,readyState:n})=>e==="video"&&n==="live",w=(e,n,{onEnterPurgatory:r,onEnterConference:o})=>{D(e)?r&&r():o&&o({isSuccessProgressCall:n})},U=(e,n)=>{e(),n&&n()},$=(e,n,r)=>{throw e&&e(),n(),r},Pe=new Set(["on","once","onceRace","wait","off","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","startAutoConnect","stopAutoConnect","connection","isConfigured","isRegistered"]);class ve{on;once;onceRace;wait;off;sendDTMF;hangUp;declineToIncomingCall;sendChannels;checkTelephony;waitChannels;ping;startAutoConnect;stopAutoConnect;connection;isConfigured;isRegistered;sipConnector;constructor(n){return this.sipConnector=n,new Proxy(this,{get:(r,o,a)=>{if(typeof o=="string"&&Pe.has(o)&&o in this.sipConnector){const c=Reflect.get(this.sipConnector,o,this.sipConnector);return typeof c=="function"?c.bind(this.sipConnector):c}const s=Reflect.get(r,o,a);return typeof s=="function"?s.bind(r):s}})}connectToServer=async(n,r)=>this.sipConnector.connect(n,r).then(o=>(t.logger("connectToServer then"),{configuration:o,isSuccessful:!0})).catch(async o=>(t.logger("connectToServer catch: error",o),Ae(o)));callToServer=async n=>{const{conference:r,mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,degradationPreference:l,sendEncodings:g,offerToReceiveAudio:p,offerToReceiveVideo:N,directionVideo:O,directionAudio:_,onBeforeProgressCall:h,onSuccessProgressCall:u,onEnterPurgatory:d,onEnterConference:S,onFailProgressCall:R,onFinishProgressCall:T,onEndedCall:A,onAddedTransceiver:b}=n;t.logger("callToServer",n);const P=async()=>(t.logger("startCall"),this.sipConnector.call({mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,offerToReceiveAudio:p,offerToReceiveVideo:N,directionVideo:O,directionAudio:_,degradationPreference:l,onAddedTransceiver:b,sendEncodings:g,number:r}));let E=!1,f;const m=(t.logger("subscribeEnterConference: onEnterConference",S),this.sipConnector.on("api:enterRoom",({room:i})=>{t.logger("enterRoom",{_room:i,isSuccessProgressCall:E}),f=i,(d??S)&&w(f,E,{onEnterPurgatory:d,onEnterConference:S})})),M=i=>(t.logger("onSuccess"),E=!0,u&&u({isPurgatory:D(f)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{U(m,A)}),i),y=i=>(t.logger("onFail"),$(R,m,i)),L=()=>{t.logger("onFinish"),T&&T()};return t.logger("onBeforeProgressCall"),h&&h(r),P().then(M).catch(i=>y(i)).finally(L)};disconnectFromServer=async()=>this.sipConnector.disconnect().then(()=>(t.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(n=>(t.logger("disconnectFromServer: catch",n),{isSuccessful:!1}));answerToIncomingCall=async n=>{const{mediaStream:r,extraHeaders:o,iceServers:a,contentHint:s,degradationPreference:c,sendEncodings:l,offerToReceiveAudio:g,offerToReceiveVideo:p,directionVideo:N,directionAudio:O,onBeforeProgressCall:_,onSuccessProgressCall:h,onEnterPurgatory:u,onEnterConference:d,onFailProgressCall:S,onFinishProgressCall:R,onEndedCall:T,onAddedTransceiver:A}=n;t.logger("answerToIncomingCall",n);const b=async()=>this.sipConnector.answerToIncomingCall({mediaStream:r,extraHeaders:o,iceServers:a,contentHint:s,offerToReceiveAudio:g,offerToReceiveVideo:p,directionVideo:N,directionAudio:O,degradationPreference:c,onAddedTransceiver:A,sendEncodings:l}),P=()=>{const{remoteCallerData:i}=this.sipConnector;return i.incomingNumber};let E=!1,f;const m=(t.logger("subscribeEnterConference: onEnterConference",d),this.sipConnector.on("api:enterRoom",i=>{t.logger("enterRoom",{room:i.room,isSuccessProgressCall:E}),f=i.room,(u??d)&&w(f,E,{onEnterPurgatory:u,onEnterConference:d})})),M=i=>(t.logger("onSuccess"),E=!0,h&&h({isPurgatory:D(f)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{U(m,T)}),i),y=i=>(t.logger("onFail"),$(S,m,i)),L=()=>{t.logger("onFinish"),R&&R()};if(t.logger("onBeforeProgressCall"),_){const i=P();_(i)}return b().then(M).catch(i=>y(i)).finally(L)};updatePresentation=async({mediaStream:n,isP2P:r,contentHint:o,degradationPreference:a,sendEncodings:s,onAddedTransceiver:c})=>(t.logger("updatePresentation"),this.sipConnector.updatePresentation(n,{isP2P:r,contentHint:o,degradationPreference:a,onAddedTransceiver:c,sendEncodings:s}));startPresentation=async({mediaStream:n,isP2P:r,contentHint:o,degradationPreference:a,sendEncodings:s,callLimit:c,onAddedTransceiver:l})=>(t.logger("startPresentation"),this.sipConnector.startPresentation(n,{isP2P:r,contentHint:o,callLimit:c,degradationPreference:a,onAddedTransceiver:l,sendEncodings:s}));stopShareSipConnector=async({isP2P:n=!1}={})=>(t.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:n}).catch(r=>{t.logger(r)}));sendRefusalToTurnOnMic=async()=>{t.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(n=>{t.logger("sendRefusalToTurnOnMic: error",n)})};sendRefusalToTurnOnCam=async()=>{t.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(n=>{t.logger("sendRefusalToTurnOnCam: error",n)})};sendMediaState=async({isEnabledCam:n,isEnabledMic:r})=>{t.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:n,mic:r})};replaceMediaStream=async(n,{deleteExisting:r,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,sendEncodings:l,onAddedTransceiver:g})=>(t.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(n,{deleteExisting:r,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,onAddedTransceiver:g,sendEncodings:l}));askPermissionToEnableCam=async()=>{t.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam()};resolveHandleReadyRemoteStreamsDebounced=({onReadyRemoteStreams:n})=>H.debounce(()=>{const r=this.sipConnector.getRemoteStreams();t.logger("remoteStreams",r),n(r)},200);resolveHandleReadyRemoteStreams=({onReadyRemoteStreams:n})=>({track:r})=>{be(r)&&n()};getRemoteStreams=()=>(t.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams());onUseLicense=n=>(t.logger("onUseLicense"),this.sipConnector.on("api:useLicense",n));onMustStopPresentation=n=>(t.logger("onMustStopPresentation"),this.sipConnector.on("api:mustStopPresentation",n));onMoveToSpectators=n=>(t.logger("onMoveToSpectators"),this.sipConnector.on("api:participant:move-request-to-spectators",n));onMoveToParticipants=n=>(t.logger("onMoveToParticipants"),this.sipConnector.on("api:participant:move-request-to-participants",n));onStats=n=>(t.logger("onStats"),this.sipConnector.on("stats:collected",n));offStats=n=>{t.logger("offStats"),this.sipConnector.off("stats:collected",n)}}var G=(e=>(e.VP8="video/VP8",e.VP9="video/VP9",e.H264="video/H264",e.AV1="video/AV1",e.rtx="video/rtx",e.red="video/red",e.flexfec03="video/flexfec-03",e))(G||{});exports.ECallCause=t.ECallCause;exports.ECallStatus=t.EState$1;exports.EConnectionStatus=t.EState;exports.EIncomingStatus=t.EState$2;exports.EPresentationStatus=t.EState$3;exports.EStatsTypes=t.EStatsTypes;exports.EUseLicense=t.EUseLicense;exports.SipConnector=t.SipConnector;exports.StatsPeerConnection=t.StatsPeerConnection;exports.disableDebug=t.disableDebug;exports.enableDebug=t.enableDebug;exports.getCodecFromSender=t.getCodecFromSender;exports.hasCanceledStartPresentationError=t.hasCanceledStartPresentationError;Object.defineProperty(exports,"hasConnectionPromiseIsNotActualError",{enumerable:!0,get:()=>K.isPromiseIsNotActualError});exports.EMimeTypesVideoCodecs=G;exports.ESystemStatus=C;exports.SipConnectorFacade=ve;exports.hasAvailableStats=_e;exports.hasCanceledCallError=J;exports.sessionSelectors=te;exports.tools=Oe;
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { E as h, a as R, b as p, c as j, l as r, p as K, s as X, d as q, e as z, h as J } from "./@SipConnector-
|
|
2
|
-
import { o as je, k as Ke, f as Xe, S as qe, m as ze, g as Je, i as Qe, n as Ze, j as en } from "./@SipConnector-
|
|
1
|
+
import { E as h, a as R, b as p, c as j, l as r, p as K, s as X, d as q, e as z, h as J } from "./@SipConnector-B4noAdXF.js";
|
|
2
|
+
import { o as je, k as Ke, f as Xe, S as qe, m as ze, g as Je, i as Qe, n as Ze, j as en } from "./@SipConnector-B4noAdXF.js";
|
|
3
3
|
import "events-constructor";
|
|
4
4
|
import { isCanceledError as B } from "@krivega/cancelable-promise";
|
|
5
5
|
import { hasCanceledError as Q } from "repeated-calls";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sip-connector",
|
|
3
|
-
"version": "20.6.
|
|
3
|
+
"version": "20.6.1",
|
|
4
4
|
"description": "Module for connect to Vinteo server",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"webrtc",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
65
|
"@krivega/cancelable-promise": "^1.1.4",
|
|
66
|
-
"@krivega/jssip": "^5.5.
|
|
66
|
+
"@krivega/jssip": "^5.5.1",
|
|
67
67
|
"@krivega/timeout-requester": "^1.0.0",
|
|
68
68
|
"debug": "^4.4.3",
|
|
69
69
|
"events-constructor": "^2.1.1",
|
|
@@ -81,7 +81,7 @@
|
|
|
81
81
|
"@commitlint/cli": "^20.3.1",
|
|
82
82
|
"@commitlint/config-conventional": "^20.3.1",
|
|
83
83
|
"@eslint/compat": "^2.0.1",
|
|
84
|
-
"@krivega/eslint-config": "^1.1.
|
|
84
|
+
"@krivega/eslint-config": "^1.1.7",
|
|
85
85
|
"@types/debug": "^4.1.12",
|
|
86
86
|
"@types/dom-mediacapture-transform": "^0.1.11",
|
|
87
87
|
"@types/jest": "^30.0.0",
|
|
@@ -94,7 +94,7 @@
|
|
|
94
94
|
"jest-extended": "^7.0.0",
|
|
95
95
|
"jest-junit": "^16.0.0",
|
|
96
96
|
"lint-staged": "^16.2.7",
|
|
97
|
-
"prettier": "^3.
|
|
97
|
+
"prettier": "^3.8.0",
|
|
98
98
|
"standard-version": "^9.5.0",
|
|
99
99
|
"ts-jest": "^29.4.6",
|
|
100
100
|
"ts-node": "^10.9.2",
|
|
@@ -107,7 +107,7 @@
|
|
|
107
107
|
},
|
|
108
108
|
"peerDependencies": {
|
|
109
109
|
"@krivega/cancelable-promise": "^1.1.4",
|
|
110
|
-
"@krivega/jssip": "^5.5.
|
|
110
|
+
"@krivega/jssip": "^5.5.1",
|
|
111
111
|
"@krivega/timeout-requester": "^1.0.0",
|
|
112
112
|
"debug": "^4.4.3",
|
|
113
113
|
"events-constructor": "^2.1.1",
|