sip-connector 15.2.0 → 15.3.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.
@@ -0,0 +1 @@
1
+ "use strict";const O=require("events-constructor"),ge=require("@krivega/cancelable-promise"),B=require("debug"),q=require("repeated-calls"),Q=require("xstate"),de=require("@krivega/timeout-requester");require("ua-parser-js");require("sequent-promises");var N=(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))(N||{}),w=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(w||{});const X=["peerconnection","connecting","sending","progress","accepted","confirmed","ended","failed","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"],Te=["peerconnection:confirmed","peerconnection:ontrack","ended:fromserver"],J=[...X,...Te],he=(n,e)=>{n.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},U=(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"&&he(o,s),o};function le(n){return e=>`sip:${e}@${n}`}const Ee=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,j=n=>n.trim().replaceAll(" ","_"),Se=Ee(1e5,99999999),ue=n=>n.some(t=>{const{kind:s}=t;return s==="video"});class Ce{isPendingCall=!1;isPendingAnswer=!1;rtcSession;remoteStreams={};events;callConfiguration={};constructor(e){this.events=e}}var G=(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))(G||{});class Ne{remoteStreams={};reset(){this.remoteStreams={}}generateStream(e,t){const{id:s}=e,i=this.remoteStreams[s]??new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this.remoteStreams[s]=i,i}generateAudioStream(e){const{id:t}=e,s=this.remoteStreams[t]??new MediaStream;return s.addTrack(e),this.remoteStreams[t]=s,s}generateStreams(e){const t=[];return e.forEach((s,i)=>{if(s.kind==="audio")return;const r=s,a=e[i-1];let o;a?.kind==="audio"&&(o=a);const c=this.generateStream(r,o);t.push(c)}),t}generateAudioStreams(e){return e.map(t=>this.generateAudioStream(t))}}class Ae extends Ce{remoteStreamsManager=new Ne;disposers=new Set;constructor(e){super(e),e.on(N.FAILED,this.handleEnded),e.on(N.ENDED,this.handleEnded)}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}get establishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}startCall=async(e,t,{number:s,mediaStream:i,extraHeaders:r=[],ontrack:a,iceServers:o,directionVideo:c,directionAudio:g,contentHint:l,offerToReceiveAudio:u=!0,offerToReceiveVideo:d=!0,sendEncodings:S,onAddedTransceiver:_})=>(this.isPendingCall=!0,new Promise((C,P)=>{this.callConfiguration.number=s,this.callConfiguration.answer=!1,this.handleCall({ontrack:a}).then(C).catch(D=>{P(D)}),this.rtcSession=e.call(t(s),{extraHeaders:r,mediaStream:U(i,{directionVideo:c,directionAudio:g,contentHint:l}),eventHandlers:this.events.triggers,directionVideo:c,directionAudio:g,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:u,offerToReceiveVideo:d},sendEncodings:S,onAddedTransceiver:_})}).finally(()=>{this.isPendingCall=!1}));async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:G.CANCELED}).finally(()=>{this.reset()});this.reset()}answerToIncomingCall=async(e,{mediaStream:t,ontrack:s,extraHeaders:i=[],iceServers:r,directionVideo:a,directionAudio:o,offerToReceiveAudio:c,offerToReceiveVideo:g,contentHint:l,sendEncodings:u,onAddedTransceiver:d})=>(this.isPendingAnswer=!0,new Promise((S,_)=>{try{const C=e();this.rtcSession=C,this.subscribeToSessionEvents(C),this.callConfiguration.answer=!0,this.callConfiguration.number=C.remote_identity.uri.user,this.handleCall({ontrack:s}).then(S).catch(D=>{_(D)});const P=U(t,{directionVideo:a,directionAudio:o,contentHint:l});C.answer({extraHeaders:i,directionVideo:a,directionAudio:o,mediaStream:P,pcConfig:{iceServers:r},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:g},sendEncodings:u,onAddedTransceiver:d})}catch(C){_(C)}}).finally(()=>{this.isPendingAnswer=!1}));getEstablishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}getCallConfiguration(){return{...this.callConfiguration}}getRemoteStreams(){if(!this.connection)return;const t=this.connection.getReceivers().map(({track:s})=>s);return ue(t)?this.remoteStreamsManager.generateStreams(t):this.remoteStreamsManager.generateAudioStreams(t)}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=t??{},i=U(e,{contentHint:s});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}handleCall=async({ontrack:e})=>new Promise((t,s)=>{const i=()=>{this.events.on(N.PEER_CONNECTION,l),this.events.on(N.CONFIRMED,u)},r=()=>{this.events.off(N.PEER_CONNECTION,l),this.events.off(N.CONFIRMED,u)},a=()=>{this.events.on(N.FAILED,c),this.events.on(N.ENDED,c)},o=()=>{this.events.off(N.FAILED,c),this.events.off(N.ENDED,c)},c=d=>{r(),o(),s(d)};let g;const l=({peerconnection:d})=>{g=d;const S=_=>{this.events.trigger(N.PEER_CONNECTION_ONTRACK,d),e&&e(_)};d.addEventListener("track",S),this.disposers.add(()=>{d.removeEventListener("track",S)})},u=()=>{g!==void 0&&this.events.trigger(N.PEER_CONNECTION_CONFIRMED,g),r(),o(),t(g)};i(),a()});subscribeToSessionEvents(e){this.events.eachTriggers((t,s)=>{const i=X.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===w.REMOTE&&this.events.trigger(N.ENDED_FROM_SERVER,e),this.reset()};reset=()=>{delete this.rtcSession,this.remoteStreamsManager.reset(),this.unsubscribeFromSessionEvents(),this.callConfiguration.number=void 0,this.callConfiguration.answer=!1}}class Re{events;strategy;constructor(e){this.events=new O.Events(J),this.strategy=e??new Ae(this.events)}get requested(){return this.strategy.requested}get connection(){return this.strategy.connection}get establishedRTCSession(){return this.strategy.establishedRTCSession}get isCallActive(){return this.strategy.isCallActive}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)}setStrategy(e){this.strategy=e}startCall=async(...e)=>this.strategy.startCall(...e);endCall=async()=>this.strategy.endCall();answerToIncomingCall=async(...e)=>this.strategy.answerToIncomingCall(...e);getEstablishedRTCSession=()=>this.strategy.getEstablishedRTCSession();getCallConfiguration=()=>this.strategy.getCallConfiguration();getRemoteStreams=()=>this.strategy.getRemoteStreams();replaceMediaStream=async(...e)=>this.strategy.replaceMediaStream(...e)}const H="sip-connector",p=B(H),_e=()=>{B.enable(H)},Ie=()=>{B.enable(`-${H}`)},Me="Error decline with 603",pe=1006,Pe=n=>typeof n=="object"&&n!==null&&"code"in n&&n.code===pe,me=n=>n.message===Me;var h=(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))(h||{}),F=(n=>(n.AVAILABLE_SECOND_REMOTE_STREAM="YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="CONTENTEND",n.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",n))(F||{}),$=(n=>(n.SPECTATOR="SPECTATOR",n.PARTICIPANT="PARTICIPANT",n.SPECTATOR_OVER_SFU="SPECTATOROVERSFU",n))($||{}),m=(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))(m||{}),I=(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))(I||{}),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))(f||{}),k=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(k||{}),W=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(W||{}),K=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(K||{}),T=(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_PARTICIPANTS="participant:move-request-to-participants",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_OVER_SFU="participant:move-request-to-spectators-over-sfu",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))(T||{});const Z=["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-participants","participant:move-request-to-spectators-over-sfu","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"];var R=(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))(R||{});class Oe{events;connectionManager;callManager;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.callManager=t,this.events=new O.Events(Z),this.subscribe()}async waitChannels(){return this.wait(T.CHANNELS)}async waitSyncMediaState(){return this.wait(T.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===w.LOCAL&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600}))})}async sendChannels({inputChannels:e,outputChannels:t}){const s=this.getEstablishedRTCSessionProtected(),i=`${h.INPUT_CHANNELS}: ${e}`,r=`${h.OUTPUT_CHANNELS}: ${t}`,a=[i,r];return s.sendInfo(I.CHANNELS,void 0,{extraHeaders:a})}async sendMediaState({cam:e,mic:t},s={}){const i=this.getEstablishedRTCSessionProtected(),r=`${h.MEDIA_STATE}: currentstate`,a=`${h.MAIN_CAM_STATE}: ${Number(e)}`,o=`${h.MIC_STATE}: ${Number(t)}`,c=[r,a,o];return i.sendInfo(I.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendStats({availableIncomingBitrate:e}){const t=this.getEstablishedRTCSessionProtected(),i=[`${h.AVAILABLE_INCOMING_BITRATE}: ${e}`];return t.sendInfo(I.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:i})}async sendRefusalToTurnOn(e,t={}){const s=this.getEstablishedRTCSessionProtected(),a=e==="mic"?0:1,c=[`${h.MEDIA_TYPE}: ${a}`];return s.sendInfo(I.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(I.SHARE_STATE,void 0,{extraHeaders:[h.MUST_STOP_PRESENTATION_P2P]})}async sendStoppedPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(I.SHARE_STATE,void 0,{extraHeaders:[h.STOP_PRESENTATION_P2P]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(I.SHARE_STATE,void 0,{extraHeaders:[h.STOP_PRESENTATION]})}async askPermissionToStartPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(I.SHARE_STATE,void 0,{extraHeaders:[h.START_PRESENTATION_P2P]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(I.SHARE_STATE,void 0,{extraHeaders:[h.START_PRESENTATION]})}async askPermissionToEnableCam(e={}){const t=this.getEstablishedRTCSessionProtected(),s=[h.ENABLE_MAIN_CAM];return t.sendInfo(I.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(i=>{if(me(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(h.NOTIFY);if(t){const s=JSON.parse(t);this.handleNotify(s)}}catch(t){p("error parse notify",t)}};handleNotify=e=>{switch(e.cmd){case R.CHANNELS:{const t=e;this.triggerChannelsNotify(t);break}case R.WEBCAST_STARTED:{const t=e;this.triggerWebcastStartedNotify(t);break}case R.WEBCAST_STOPPED:{const t=e;this.triggerWebcastStoppedNotify(t);break}case R.ADDED_TO_LIST_MODERATORS:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case R.REMOVED_FROM_LIST_MODERATORS:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case R.ACCEPTING_WORD_REQUEST:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case R.CANCELLING_WORD_REQUEST:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case R.MOVE_REQUEST_TO_STREAM:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case R.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case R.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case R.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:p("unknown cmd",e)}};handleNewInfo=e=>{const{originator:t}=e;if(t!==w.REMOTE)return;const{request:s}=e,i=s.getHeader(h.CONTENT_TYPE);if(i!==void 0)switch(i){case m.ENTER_ROOM:{this.triggerEnterRoom(s),this.maybeTriggerChannels(s);break}case m.NOTIFY:{this.maybeHandleNotify(s);break}case m.SHARE_STATE:{this.triggerShareState(s);break}case m.MAIN_CAM:{this.triggerMainCamControl(s);break}case m.MIC:{this.triggerMicControl(s);break}case m.USE_LICENSE:{this.triggerUseLicense(s);break}case m.PARTICIPANT_STATE:{this.maybeTriggerParticipantMoveRequest(s);break}}};triggerChannelsNotify=e=>{const t=e.input,s=e.output,i={inputChannels:t,outputChannels:s};this.events.trigger(T.CHANNELS_NOTIFY,i)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(T.WEBCAST_STARTED,s)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(T.WEBCAST_STOPPED,s)};triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(T.PARTICIPANT_ADDED_TO_LIST_MODERATORS,t)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(T.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,t)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(T.PARTICIPATION_ACCEPTING_WORD_REQUEST,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(T.PARTICIPATION_CANCELLING_WORD_REQUEST,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(T.PARTICIPANT_MOVE_REQUEST_TO_STREAM,t)};triggerAccountChangedNotify=()=>{this.events.trigger(T.ACCOUNT_CHANGED,void 0)};triggerAccountDeletedNotify=()=>{this.events.trigger(T.ACCOUNT_DELETED,void 0)};triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const i={conference:e,participant:t,jwt:s};this.events.trigger(T.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,i)};maybeTriggerChannels=e=>{const t=e.getHeader(h.INPUT_CHANNELS),s=e.getHeader(h.OUTPUT_CHANNELS);if(t&&s){const i={inputChannels:t,outputChannels:s};this.events.trigger(T.CHANNELS,i)}};triggerEnterRoom=e=>{const t=e.getHeader(h.CONTENT_ENTER_ROOM),s=e.getHeader(h.PARTICIPANT_NAME);this.events.trigger(T.ENTER_ROOM,{room:t,participantName:s})};triggerShareState=e=>{const t=e.getHeader(h.CONTENT_SHARE_STATE);if(t!==void 0)switch(t){case F.AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(T.AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case F.NOT_AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(T.NOT_AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case F.MUST_STOP_PRESENTATION:{this.events.trigger(T.MUST_STOP_PRESENTATION,void 0);break}}};maybeTriggerParticipantMoveRequest=e=>{const t=e.getHeader(h.CONTENT_PARTICIPANT_STATE);t===$.SPECTATOR&&this.events.trigger(T.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,void 0),t===$.PARTICIPANT&&this.events.trigger(T.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,void 0),t===$.SPECTATOR_OVER_SFU&&this.events.trigger(T.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_OVER_SFU,void 0)};triggerMainCamControl=e=>{const t=e.getHeader(h.MAIN_CAM),s=e.getHeader(h.MEDIA_SYNC),i=s===W.ADMIN_SYNC_FORCED;if(t===f.ADMIN_START_MAIN_CAM){this.events.trigger(T.ADMIN_START_MAIN_CAM,{isSyncForced:i});return}if(t===f.ADMIN_STOP_MAIN_CAM){this.events.trigger(T.ADMIN_STOP_MAIN_CAM,{isSyncForced:i});return}(t===f.RESUME_MAIN_CAM||t===f.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger(T.ADMIN_FORCE_SYNC_MEDIA_STATE,{isSyncForced:i});const r=e.getHeader(h.MAIN_CAM_RESOLUTION);this.events.trigger(T.MAIN_CAM_CONTROL,{mainCam:t,resolutionMainCam:r})};triggerMicControl=e=>{const t=e.getHeader(h.MIC),i=e.getHeader(h.MEDIA_SYNC)===W.ADMIN_SYNC_FORCED;t===k.ADMIN_START_MIC?this.events.trigger(T.ADMIN_START_MIC,{isSyncForced:i}):t===k.ADMIN_STOP_MIC&&this.events.trigger(T.ADMIN_STOP_MIC,{isSyncForced:i})};triggerUseLicense=e=>{const t=e.getHeader(h.CONTENT_USE_LICENSE);this.events.trigger(T.USE_LICENSE,t)}}var M=(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))(M||{});const ee=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],fe=1,ve=n=>q.hasCanceledError(n);class De{events;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e}){this.callManager=e,this.events=new O.Events(ee),this.subscribe()}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async startPresentation(e,t,{isNeedReinvite:s,maxBitrate:i,contentHint:r,sendEncodings:a,onAddedTransceiver:o}={},c){const g=this.getRtcSessionProtected();if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return this.sendPresentationWithDuplicatedCalls(e,{rtcSession:g,stream:t,presentationOptions:{isNeedReinvite:s,maxBitrate:i,contentHint:r,sendEncodings:a,onAddedTransceiver:o},options:c})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve(void 0);const i=this.callManager.getEstablishedRTCSession();return i&&t?s=e().then(async()=>i.stopPresentation(t)).catch(r=>{throw this.events.trigger(M.FAILED_PRESENTATION,r),r}):t&&this.events.trigger(M.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})}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.cancel()}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(M.START_PRESENTATION,e)}),this.callManager.on("presentation:started",e=>{this.events.trigger(M.STARTED_PRESENTATION,e)}),this.callManager.on("presentation:end",e=>{this.events.trigger(M.END_PRESENTATION,e)}),this.callManager.on("presentation:ended",e=>{this.events.trigger(M.ENDED_PRESENTATION,e)}),this.callManager.on("presentation:failed",e=>{this.events.trigger(M.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:fe}}){const a=async()=>this.sendPresentation(e,t,s,i),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=q.repeatedCallsAsync({targetFunction:a,isComplete:o,isRejectAsValid:!0,...r}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}async sendPresentation(e,t,s,{isNeedReinvite:i=!0,contentHint:r="detail",sendEncodings:a,onAddedTransceiver:o}){const c=U(s,{contentHint:r});if(c===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=c;const g=e().then(async()=>t.startPresentation(c,i,{sendEncodings:a,onAddedTransceiver:o})).then(()=>s).catch(l=>{throw this.removeStreamPresentationCurrent(),this.events.trigger(M.FAILED_PRESENTATION,l),l});return this.promisePendingStartPresentation=g,g.finally(()=>{this.promisePendingStartPresentation=void 0})}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 ye{data={};getUa;constructor(e){this.getUa=e.getUa}isConfigured(){return this.getUa()!==void 0}get(){return{...this.data}}set(e){this.data={...e}}update(e,t){this.data[e]=t}clear(){this.data={}}isRegister(){return this.data.register===!0}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 A=(n=>(n.CONNECTING="connecting",n.CONNECTED="connected",n.DISCONNECTED="disconnected",n.NEW_RTC_SESSION="newRTCSession",n.REGISTERED="registered",n.UNREGISTERED="unregistered",n.REGISTRATION_FAILED="registrationFailed",n.NEW_MESSAGE="newMessage",n.SIP_EVENT="sipEvent",n))(A||{});const te=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],ne=[...te],be=3;class Ue{cancelableConnectWithRepeatedCalls;JsSIP;events;uaFactory;stateMachine;registrationManager;getUa;setUa;getConnectionConfiguration;setConnectionConfiguration;updateConnectionConfiguration;setSipServerUrl;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.setSipServerUrl=e.setSipServerUrl,this.setSocket=e.setSocket}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",j(e)),this.updateConnectionConfiguration("displayName",e));const o=r;o?t(o):s(new Error("nothing changed"))});disconnect=async()=>{const e=new Promise(s=>{this.events.once(A.DISCONNECTED,()=>{s()})}),t=this.getUa();return t?t.stop():this.events.trigger(A.DISCONNECTED,void 0),e.finally(()=>{this.setUa(void 0),this.stateMachine.reset()})};cancelRequests(){this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{callLimit:t=be}={})=>{const s=async()=>this.connectInner(e),i=r=>{const c=this.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),g=r!=null&&!Pe(r);return c||g};return this.stateMachine.startConnect(),this.cancelableConnectWithRepeatedCalls=q.repeatedCallsAsync({targetFunction:s,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(r=>{if(r 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());initUa=async({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:i,remoteAddress:r,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:g,userAgent:l,displayName:u="",register:d=!1,extraHeaders:S=[]})=>{this.stateMachine.startInitUa(),this.setConnectionConfiguration({sipServerUrl:s,displayName:u,register:d,user:e,password:t}),this.getUa()&&await this.disconnect();const{ua:C,helpers:P}=this.uaFactory.createUAWithConfiguration({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:i,displayName:u,register:d,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:g,userAgent:l,remoteAddress:r,extraHeaders:S},this.events);return this.setUa(C),this.setSipServerUrl(P.getSipServerUrl),this.setSocket(P.socket),C};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,g)=>{if(this.getConnectionConfiguration().register===!0)return this.registrationManager.subscribeToStartEvents(c,g);const u=A.CONNECTED,d=[A.DISCONNECTED];return this.events.on(u,c),d.forEach(S=>{this.events.on(S,g)}),()=>{this.events.off(u,c),d.forEach(S=>{this.events.off(S,g)})}})(()=>{i?.(),e(s)},c=>{i?.(),t(c)}),s.start()});cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}}var se=(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))(se||{});const we=Q.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{p(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{p("ConnectionStateMachine state changed",e.state)}}}).createMachine({id:"connection",initial:"idle",context:{},states:{idle:{entry:{type:"logStateChange",params:{state:"idle"}},on:{START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"idle",to:"connecting",event:"START_CONNECT"}}}}},connecting:{entry:{type:"logStateChange",params:{state:"connecting"}},on:{START_INIT_UA:{target:"initializing",actions:{type:"logTransition",params:{from:"connecting",to:"initializing",event:"START_INIT_UA"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connecting",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connecting",to:"failed",event:"CONNECTION_FAILED"}}}}},initializing:{entry:{type:"logStateChange",params:{state:"initializing"}},on:{UA_CONNECTED:{target:"connected",actions:{type:"logTransition",params:{from:"initializing",to:"connected",event:"UA_CONNECTED"}}},UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"initializing",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"initializing",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"initializing",to:"failed",event:"CONNECTION_FAILED"}}}}},connected:{entry:{type:"logStateChange",params:{state:"connected"}},on:{UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"connected",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connected",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connected",to:"failed",event:"CONNECTION_FAILED"}}}}},registered:{entry:{type:"logStateChange",params:{state:"registered"}},on:{UA_UNREGISTERED:{target:"connected",actions:{type:"logTransition",params:{from:"registered",to:"connected",event:"UA_UNREGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"registered",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"registered",to:"failed",event:"CONNECTION_FAILED"}}}}},disconnected:{entry:{type:"logStateChange",params:{state:"disconnected"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"disconnected",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"disconnected",to:"connecting",event:"START_CONNECT"}}}}},failed:{entry:{type:"logStateChange",params:{state:"failed"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"failed",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"failed",to:"connecting",event:"START_CONNECT"}}}}}}});class Le{actor;stateChangeListeners=new Set;events;unsubscribeFromEvents;actorSubscription;constructor(e){this.events=e,this.actor=Q.createActor(we),this.actorSubscription=this.actor.subscribe(t=>{const s=t.value;this.stateChangeListeners.forEach(i=>{i(s)})}),this.actor.start(),this.subscribeToEvents()}get state(){return this.actor.getSnapshot().value}get isIdle(){return this.hasState("idle")}get isConnecting(){return this.hasState("connecting")}get isInitializing(){return this.hasState("initializing")}get isConnected(){return this.hasState("connected")}get isRegistered(){return this.hasState("registered")}get isDisconnected(){return this.hasState("disconnected")}get isFailed(){return this.hasState("failed")}get isPending(){return this.isConnecting||this.isInitializing}get isPendingConnect(){return this.isConnecting}get isPendingInitUa(){return this.isInitializing}get isActiveConnection(){return this.isConnected||this.isRegistered}startConnect(){this.toStartConnect()}startInitUa(){this.toStartInitUa()}reset(){this.toIdle()}destroy(){this.unsubscribeFromEvents?.(),this.actorSubscription?.unsubscribe(),this.actor.stop()}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}canTransition(e){return this.actor.getSnapshot().can({type:e})}getValidEvents(){return Object.values(se).filter(e=>this.canTransition(e))}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){const t=this.actor.getSnapshot(),s={type:e};if(!t.can(s)){p(`Invalid transition: ${s.type} from ${this.state}. Event cannot be processed in current state.`);return}this.actor.send(s)}toStartConnect=()=>{this.sendEvent("START_CONNECT")};toStartInitUa=()=>{this.sendEvent("START_INIT_UA")};toConnected=()=>{this.sendEvent("UA_CONNECTED")};toRegistered=()=>{this.sendEvent("UA_REGISTERED")};toUnregistered=()=>{this.sendEvent("UA_UNREGISTERED")};toDisconnected=()=>{this.sendEvent("UA_DISCONNECTED")};toFailed=()=>{this.sendEvent("CONNECTION_FAILED")};toIdle=()=>{this.sendEvent("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.toFailed),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.toFailed)}}}class Fe{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(A.REGISTERED,t),e.on(A.REGISTRATION_FAILED,s),e.register()})}async unregister(){const e=this.getUaProtected();return new Promise(t=>{e.on(A.UNREGISTERED,t),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){p("tryRegister",e)}return this.register()}subscribeToStartEvents(e,t){const s=A.REGISTERED,i=[A.REGISTRATION_FAILED,A.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 $e{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,sipServerUrl:s,sipWebSocketServerURL:i,remoteAddress:r,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:g}=this.uaFactory.createConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:s}),l=this.uaFactory.createUA({...g,remoteAddress:r,extraHeaders:a}),u=()=>{const S=new Error("Telephony is not available");c(S)};l.once(A.DISCONNECTED,u);const d=()=>{l.removeAllListeners(),l.once(A.DISCONNECTED,()=>{o()}),l.stop()};l.once(A.CONNECTED,d),l.start()})}}const ke=n=>{const e=[];return n!==void 0&&n!==""&&e.push(`X-Vinteo-Remote: ${n}`),e};class v{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateConfiguration({register:e,password:t,user:s,sipServerUrl:i,sipWebSocketServerURL:r}){if(!i)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL 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():`${Se()}`}static buildExtraHeaders(e,t){const s=e!==void 0&&e!==""?ke(e):[];return t===void 0?s:[...s,...t]}createConfiguration({user:e,password:t,sipWebSocketServerURL:s,displayName:i="",sipServerUrl:r,register:a=!1,sessionTimers:o=!1,registerExpires:c=300,connectionRecoveryMinInterval:g=2,connectionRecoveryMaxInterval:l=6,userAgent:u}){v.validateConfiguration({register:a,password:t,user:e,sipServerUrl:r,sipWebSocketServerURL:s});const d=v.resolveAuthorizationUser(a,e),S=le(r),_=S(d),C=new this.JsSIP.WebSocketInterface(s);return{configuration:{password:t,register:a,uri:_,display_name:j(i),user_agent:u,sdpSemantics:"unified-plan",sockets:[C],session_timers:o,register_expires:c,connection_recovery_min_interval:g,connection_recovery_max_interval:l},helpers:{socket:C,getSipServerUrl:S}}}createUA({remoteAddress:e,extraHeaders:t,...s}){const i=new this.JsSIP.UA(s),r=v.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=te.find(g=>g===o);c&&r.on(c,a)}),{ua:r,helpers:i}}}class We{events;ua;socket;uaFactory;registrationManager;stateMachine;connectionFlow;sipOperations;configurationManager;JsSIP;constructor({JsSIP:e}){this.JsSIP=e,this.events=new O.Events(ne),this.uaFactory=new v(e),this.registrationManager=new Fe({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new Le(this.events),this.configurationManager=new ye({getUa:this.getUa}),this.sipOperations=new $e({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new Ue({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},setSipServerUrl:t=>{this.getSipServerUrl=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 connectionState(){return this.stateMachine.state}get isRegistered(){return v.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.configurationManager.isRegister()}connect=async(e,t)=>this.connectionFlow.connect(e,t);set=async({displayName:e})=>this.connectionFlow.set({displayName:e});disconnect=async()=>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()}getSipServerUrl=e=>e;getUaProtected=()=>{if(!this.ua)throw new Error("UA not initialized");return this.ua};getUa=()=>this.ua}var b=(n=>(n.INCOMING_CALL="incomingCall",n.DECLINED_INCOMING_CALL="declinedIncomingCall",n.TERMINATED_INCOMING_CALL="terminatedIncomingCall",n.FAILED_INCOMING_CALL="failedIncomingCall",n))(b||{}),V=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(V||{});const ie=["incomingCall","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],Ve=486,Be=487;class qe{events;incomingRTCSession;connectionManager;constructor(e){this.connectionManager=e,this.events=new O.Events(ie),this.start()}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.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=Be}={}){return new Promise((t,s)=>{try{const i=this.getIncomingRTCSession(),r=this.remoteCallerData;this.removeIncomingSession(),this.events.trigger(b.DECLINED_INCOMING_CALL,r),i.terminate({status_code:e}),t()}catch(i){s(i)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:Ve})}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===V.REMOTE&&this.setIncomingSession(t)};setIncomingSession(e){this.incomingRTCSession=e;const t=this.remoteCallerData;e.on("failed",s=>{this.removeIncomingSession(),s.originator===V.LOCAL?this.events.trigger(b.TERMINATED_INCOMING_CALL,t):this.events.trigger(b.FAILED_INCOMING_CALL,t)}),this.events.trigger(b.INCOMING_CALL,t)}removeIncomingSession(){delete this.incomingRTCSession}}const y=1e3;var E=(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))(E||{});const re=["collected"],x=()=>"performance"in window?performance.now():Date.now(),L=n=>[...n.keys()].reduce((e,t)=>{const s=n.get(t);return s===void 0?e:{...e,[s.type]:s}},{}),Ge=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=L(n);return{outboundRtp:e[E.OUTBOUND_RTP],codec:e[E.CODEC],mediaSource:e[E.MEDIA_SOURCE],remoteInboundRtp:e[E.REMOTE_INBOUND_RTP]}},Y=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=L(n);return{outboundRtp:e[E.OUTBOUND_RTP],codec:e[E.CODEC],mediaSource:e[E.MEDIA_SOURCE],remoteInboundRtp:e[E.REMOTE_INBOUND_RTP]}},z=({videoReceiversStats:n,synchronizationSourcesVideo:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,synchronizationSources:e};const t=L(n);return{inboundRtp:t[E.INBOUND_RTP],codec:t[E.CODEC],synchronizationSources:e}},He=({audioReceiverStats:n,synchronizationSourcesAudio:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:e};const t=L(n);return{inboundRtp:t[E.INBOUND_RTP],codec:t[E.CODEC],remoteOutboundRtp:t[E.REMOTE_OUTBOUND_RTP],synchronizationSources:e}},ae=n=>{if(!n)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};const e=L(n);return{candidatePair:e[E.CANDIDATE_PAIR],certificate:e[E.CERTIFICATE],localCandidate:e[E.LOCAL_CANDIDATE],remoteCandidate:e[E.REMOTE_CANDIDATE],transport:e[E.TRANSPORT]}},xe=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t})=>({video:Y(e),secondVideo:Y(t),audio:Ge(n),additional:ae(n??e??t)}),Ye=({audioReceiverStats:n,videoReceiverFirstStats:e,videoReceiverSecondStats:t,synchronizationSources:s})=>({video:z({videoReceiversStats:e,synchronizationSourcesVideo:s.video}),secondVideo:z({videoReceiversStats:t,synchronizationSourcesVideo:s.video}),audio:He({audioReceiverStats:n,synchronizationSourcesAudio:s.audio}),additional:ae(n??e??t)}),ze=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t,audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a})=>{const o=xe({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t}),c=Ye({audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a});return{outbound:o,inbound:c}},Qe=async n=>{const e="audio",t="video",s=n.getSenders(),i=s.find(d=>d.track?.kind===e),r=s.filter(d=>d.track?.kind===t),a=n.getReceivers(),o=a.find(d=>d.track.kind===e),c=a.filter(d=>d.track.kind===t),g={trackIdentifier:o?.track.id,item:o?.getSynchronizationSources()[0]},l={trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},u={audio:g,video:l};return Promise.all([i?.getStats(),r[0]?.getStats(),r[1]?.getStats(),o?.getStats(),c[0]?.getStats(),c[1]?.getStats()]).then(d=>{const[S,_,C,P,D,ce]=d;return{synchronizationSources:u,audioSenderStats:S,videoSenderFirstStats:_,videoSenderSecondStats:C,audioReceiverStats:P,videoReceiverFirstStats:D,videoReceiverSecondStats:ce}})},Xe=n=>{p(String(n))};class oe{events;setTimeoutRequest;requesterAllStatistics=new ge.CancelableRequest(Qe);constructor(){this.events=new O.TypedEvents(re),this.setTimeoutRequest=new de.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:t=y,onError:s=Xe}={}){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=x();this.requesterAllStatistics.request(e).then(i=>{this.events.trigger("collected",ze(i));const a=x()-s;let o=y;a>48?o=y*4:a>32?o=y*3:a>16&&(o=y*2),this.start(e,{onError:t,interval:o})}).catch(i=>{t&&t(i)})}}class Je{availableIncomingBitrate;statsPeerConnection;callManager;apiManager;previousAvailableIncomingBitrate;constructor({callManager:e,apiManager:t}){this.callManager=e,this.apiManager=t,this.statsPeerConnection=new oe,this.subscribe()}get events(){return this.statsPeerConnection.events}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.previousAvailableIncomingBitrate=this.availableIncomingBitrate,this.availableIncomingBitrate=e.inbound.additional.candidatePair?.availableIncomingBitrate,this.maybeSendStats()};handleStarted=e=>{this.statsPeerConnection.start(e)};handleEnded=()=>{this.statsPeerConnection.stop(),this.availableIncomingBitrate=void 0,this.previousAvailableIncomingBitrate=void 0};maybeSendStats(){this.availableIncomingBitrate!==void 0&&this.hasAvailableIncomingBitrateChangedQuarter()&&this.apiManager.sendStats({availableIncomingBitrate:this.availableIncomingBitrate}).catch(e=>{p("Failed to send stats",e)})}}const je=ne.map(n=>`connection:${n}`),Ke=J.map(n=>`call:${n}`),Ze=Z.map(n=>`api:${n}`),et=ie.map(n=>`incoming-call:${n}`),tt=ee.map(n=>`presentation:${n}`),nt=re.map(n=>`stats:${n}`),st=[...je,...Ke,...Ze,...et,...tt,...nt];class it{events;connectionManager;callManager;apiManager;incomingCallManager;presentationManager;statsManager;constructor({JsSIP:e}){this.events=new O.Events(st),this.connectionManager=new We({JsSIP:e}),this.callManager=new Re,this.apiManager=new Oe({connectionManager:this.connectionManager,callManager:this.callManager}),this.incomingCallManager=new qe(this.connectionManager),this.presentationManager=new De({callManager:this.callManager}),this.statsManager=new Je({callManager:this.callManager,apiManager:this.apiManager}),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 establishedRTCSession(){return this.callManager.establishedRTCSession}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.connectionManager.connect(...e);set=async(...e)=>this.connectionManager.set(...e);disconnect=async()=>this.connectionManager.disconnect();register=async()=>this.connectionManager.register();unregister=async()=>this.connectionManager.unregister();tryRegister=async()=>this.connectionManager.tryRegister();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();getSipServerUrl=e=>this.connectionManager.getSipServerUrl(e);call=async e=>this.callManager.startCall(this.connectionManager.getUaProtected(),this.getSipServerUrl,e);hangUp=async()=>this.callManager.endCall();answerToIncomingCall=async e=>this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,e);declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getCallConfiguration=()=>this.callManager.getCallConfiguration();getRemoteStreams=()=>this.callManager.getRemoteStreams();replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,t={}){const{isP2P:s,callLimit:i,...r}=t;return this.presentationManager.startPresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,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,...i}=t;return this.presentationManager.updatePresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,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)}subscribe(){this.connectionManager.events.eachTriggers((e,t)=>{this.connectionManager.on(t,s=>{this.events.trigger(`connection:${t}`,s)})}),this.callManager.events.eachTriggers((e,t)=>{this.callManager.on(t,s=>{this.events.trigger(`call:${t}`,s)})}),this.apiManager.events.eachTriggers((e,t)=>{this.apiManager.on(t,s=>{this.events.trigger(`api:${t}`,s)})}),this.incomingCallManager.events.eachTriggers((e,t)=>{this.incomingCallManager.on(t,s=>{this.events.trigger(`incoming-call:${t}`,s)})}),this.presentationManager.events.eachTriggers((e,t)=>{this.presentationManager.on(t,s=>{this.events.trigger(`presentation:${t}`,s)})}),this.statsManager.events.eachTriggers((e,t)=>{this.statsManager.on(t,s=>{this.events.trigger(`stats:${t}`,s)})})}}exports.ECallCause=G;exports.EEventsMainCAM=f;exports.EStatsTypes=E;exports.EUseLicense=K;exports.Originator=w;exports.SipConnector=it;exports.StatsPeerConnection=oe;exports.disableDebug=Ie;exports.enableDebug=_e;exports.hasCanceledStartPresentationError=ve;exports.logger=p;exports.prepareMediaStream=U;
@@ -17,6 +17,9 @@ declare class ApiManager {
17
17
  sendDTMF(tone: number | string): Promise<void>;
18
18
  sendChannels({ inputChannels, outputChannels }: TChannels): Promise<void>;
19
19
  sendMediaState({ cam, mic }: TMediaState, options?: TOptionsInfoMediaState): Promise<void>;
20
+ sendStats({ availableIncomingBitrate, }: {
21
+ availableIncomingBitrate: number;
22
+ }): Promise<void>;
20
23
  sendRefusalToTurnOn(type: 'cam' | 'mic', options?: TOptionsInfoMediaState): Promise<void>;
21
24
  sendRefusalToTurnOnMic(options?: TOptionsInfoMediaState): Promise<void>;
22
25
  sendRefusalToTurnOnCam(options?: TOptionsInfoMediaState): Promise<void>;
@@ -22,7 +22,8 @@ export declare enum EHeader {
22
22
  STOP_PRESENTATION_P2P = "x-webrtc-share-state: CONTENTEND",
23
23
  STOP_PRESENTATION = "x-webrtc-share-state: STOPPRESENTATION",
24
24
  START_PRESENTATION = "x-webrtc-share-state: LETMESTARTPRESENTATION",
25
- ENABLE_MAIN_CAM = "X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM"
25
+ ENABLE_MAIN_CAM = "X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM",
26
+ AVAILABLE_INCOMING_BITRATE = "X-WEBRTC-AVAILABLE-INCOMING-BITRATE"
26
27
  }
27
28
  export declare enum EShareState {
28
29
  AVAILABLE_SECOND_REMOTE_STREAM = "YOUCANRECEIVECONTENT",
@@ -48,7 +49,8 @@ export declare enum EContentTypeSent {
48
49
  MEDIA_STATE = "application/vinteo.webrtc.mediastate",
49
50
  REFUSAL = "application/vinteo.webrtc.refusal",
50
51
  SHARE_STATE = "application/vinteo.webrtc.sharedesktop",
51
- MAIN_CAM = "application/vinteo.webrtc.maincam"
52
+ MAIN_CAM = "application/vinteo.webrtc.maincam",
53
+ STATS = "application/vinteo.webrtc.stats"
52
54
  }
53
55
  export declare enum EEventsMainCAM {
54
56
  PAUSE_MAIN_CAM = "PAUSEMAINCAM",
@@ -1,10 +1,15 @@
1
1
  import { StatsPeerConnection, TEventMap } from '../StatsPeerConnection';
2
+ import { ApiManager } from '../ApiManager';
2
3
  import { CallManager } from '../CallManager';
3
4
  declare class StatsManager {
5
+ availableIncomingBitrate: number | undefined;
4
6
  readonly statsPeerConnection: StatsPeerConnection;
5
7
  private readonly callManager;
6
- constructor({ callManager }: {
8
+ private readonly apiManager;
9
+ private previousAvailableIncomingBitrate;
10
+ constructor({ callManager, apiManager, }: {
7
11
  callManager: CallManager;
12
+ apiManager: ApiManager;
8
13
  });
9
14
  get events(): import('../StatsPeerConnection/eventNames').TEvents;
10
15
  on<T extends keyof TEventMap>(eventName: T, handler: (data: TEventMap[T]) => void): () => void;
@@ -12,8 +17,11 @@ declare class StatsManager {
12
17
  onceRace<T extends keyof TEventMap>(eventNames: T[], handler: (data: TEventMap[T], eventName: string) => void): () => void;
13
18
  wait<T extends keyof TEventMap>(eventName: T): Promise<TEventMap[T]>;
14
19
  off<T extends keyof TEventMap>(eventName: T, handler: (data: TEventMap[T]) => void): void;
20
+ hasAvailableIncomingBitrateChangedQuarter(): boolean;
15
21
  private subscribe;
22
+ private readonly handleStatsCollected;
16
23
  private readonly handleStarted;
17
24
  private readonly handleEnded;
25
+ private maybeSendStats;
18
26
  }
19
27
  export default StatsManager;
@@ -15,6 +15,6 @@ declare class StatsPeerConnection {
15
15
  onceRace<T extends keyof TEventMap>(eventNames: T[], handler: (data: TEventMap[T], eventName: string) => void): () => void;
16
16
  wait<T extends keyof TEventMap>(eventName: T): Promise<TEventMap[T]>;
17
17
  off<T extends keyof TEventMap>(eventName: T, handler: (data: TEventMap[T]) => void): void;
18
- private readonly resolveCollectStatistics;
18
+ private readonly collectStatistics;
19
19
  }
20
20
  export default StatsPeerConnection;
@@ -1,7 +1,7 @@
1
- import { TInbound, TOutbound } from '../typings';
1
+ import { TInboundStats, TOutboundStats } from '../types';
2
2
  export type TStats = {
3
- inbound: TInbound;
4
- outbound: TOutbound;
3
+ inbound: TInboundStats;
4
+ outbound: TOutboundStats;
5
5
  };
6
6
  export declare const statisticsMockBase: {
7
7
  outbound: {
@@ -1,9 +1,9 @@
1
1
  import { TypedEvents } from 'events-constructor';
2
- import { TInbound, TOutbound } from './typings';
2
+ import { TInboundStats, TOutboundStats } from './types';
3
3
  export type TEventMap = {
4
4
  collected: {
5
- outbound: TOutbound;
6
- inbound: TInbound;
5
+ outbound: TOutboundStats;
6
+ inbound: TInboundStats;
7
7
  };
8
8
  };
9
9
  export declare const EVENT_NAMES: readonly ["collected"];
@@ -1,4 +1,5 @@
1
1
  export { EStatsTypes } from './constants';
2
2
  export type { TEventMap } from './eventNames';
3
3
  export { default as StatsPeerConnection } from './StatsPeerConnection';
4
+ export type { TInboundStats, TOutboundStats } from './types';
4
5
  export { default as hasAvailableStats } from './utils/hasAvailableStats';
@@ -1,4 +1,4 @@
1
- import { TInbound, TOutbound, TSynchronizationSources } from './typings';
1
+ import { TInboundStats, TOutboundStats, TSynchronizationSources } from './types';
2
2
  declare const parseStatsReports: ({ audioSenderStats, videoSenderFirstStats, videoSenderSecondStats, audioReceiverStats, videoReceiverFirstStats, videoReceiverSecondStats, synchronizationSources, }: {
3
3
  audioSenderStats?: RTCStatsReport;
4
4
  videoSenderFirstStats?: RTCStatsReport;
@@ -8,7 +8,7 @@ declare const parseStatsReports: ({ audioSenderStats, videoSenderFirstStats, vid
8
8
  videoReceiverSecondStats?: RTCStatsReport;
9
9
  synchronizationSources: TSynchronizationSources;
10
10
  }) => {
11
- inbound: TInbound;
12
- outbound: TOutbound;
11
+ inbound: TInboundStats;
12
+ outbound: TOutboundStats;
13
13
  };
14
14
  export default parseStatsReports;
@@ -1,4 +1,4 @@
1
- import { TSynchronizationSources } from './typings';
1
+ import { TSynchronizationSources } from './types';
2
2
  declare const requestAllStatistics: (peerConnection: RTCPeerConnection) => Promise<{
3
3
  synchronizationSources: TSynchronizationSources;
4
4
  audioSenderStats: RTCStatsReport | undefined;
@@ -158,13 +158,13 @@ export type TInboundAudio = {
158
158
  remoteOutboundRtp?: TRemoteOutboundRtp;
159
159
  synchronizationSources?: TMedia;
160
160
  };
161
- export type TInbound = {
161
+ export type TInboundStats = {
162
162
  video: TInboundVideo;
163
163
  secondVideo: TInboundVideo;
164
164
  audio: TInboundAudio;
165
165
  additional: TAdditional;
166
166
  };
167
- export type TOutbound = {
167
+ export type TOutboundStats = {
168
168
  video: TOutboundVideo;
169
169
  secondVideo: TOutboundVideo;
170
170
  audio: TOutboundAudio;
package/dist/doMock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("node:events"),V=require("@krivega/jssip/lib/NameAddrHeader"),k=require("@krivega/jssip/lib/URI"),U=require("@krivega/jssip/lib/SIPMessage"),a=require("@krivega/jssip"),f=require("webrtc-mock"),S=require("events-constructor"),P=require("./@SipConnector-hpySQIBa.cjs");class N extends U.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const H="incomingCall",q="declinedIncomingCall",G="failedIncomingCall",x="terminatedIncomingCall",v="connecting",z="connected",j="disconnected",Y="newRTCSession",B="registered",K="unregistered",J="registrationFailed",$="newMessage",Q="sipEvent",X="availableSecondRemoteStream",Z="notAvailableSecondRemoteStream",ee="mustStopPresentation",te="shareState",re="enterRoom",ne="useLicense",oe="peerconnection:confirmed",se="peerconnection:ontrack",ie="channels",ae="channels:notify",ce="ended:fromserver",de="main-cam-control",Ee="admin-stop-main-cam",he="admin-start-main-cam",ue="admin-stop-mic",me="admin-start-mic",le="admin-force-sync-media-state",pe="participant:added-to-list-moderators",ge="participant:removed-from-list-moderators",_e="participant:move-request-to-stream",Te="participant:move-request-to-spectators",Ie="participant:move-request-to-participants",Se="participation:accepting-word-request",Ne="participation:cancelling-word-request",we="webcast:started",Ce="webcast:stopped",Re="account:changed",fe="account:deleted",Ae="conference:participant-token-issued",Me="ended",Oe="sending",Pe="reinvite",ve="replaces",De="refer",ye="progress",Le="accepted",Fe="confirmed",We="peerconnection",be="failed",Ve="muted",ke="unmuted",Ue="newDTMF",He="newInfo",qe="hold",Ge="unhold",xe="update",ze="sdp",je="icecandidate",Ye="getusermediafailed",Be="peerconnection:createofferfailed",Ke="peerconnection:createanswerfailed",Je="peerconnection:setlocaldescriptionfailed",$e="peerconnection:setremotedescriptionfailed",Qe="presentation:start",Xe="presentation:started",Ze="presentation:end",et="presentation:ended",tt="presentation:failed",rt=[H,q,x,G,Se,Ne,_e,ae,Ae,Re,fe,we,Ce,pe,ge],D=[v,z,j,Y,B,K,J,$,Q],nt=[X,Z,ee,te,re,ne,oe,se,ie,ce,de,he,Ee,ue,me,le,Te,Ie],_=[Me,v,Oe,Pe,ve,De,ye,Le,Fe,We,be,Ve,ke,Ue,He,qe,Ge,xe,ze,je,Ye,Be,Ke,Je,$e,Qe,Xe,Ze,et,tt];[...D,...rt];[..._,...nt];class ot{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};constructor({originator:e="local",eventHandlers:t,remoteIdentity:r}){this.originator=e,this.events=new S.Events(_),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 _.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 st{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.")}}const it=["track"];class at{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;events;constructor(e,t){this.events=new S.Events(it),this.receivers=t.map(r=>({track:r}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}addTransceiver(e,t){throw new Error("Method not implemented.")}close(){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.")}async createOffer(e,t,r){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.")}async setLocalDescription(e){throw new Error("Method not implemented.")}async setRemoteDescription(e){throw new Error("Method not implemented.")}addEventListener(e,t,r){this.events.on(e,t)}removeEventListener(e,t,r){this.events.off(e,t)}dispatchEvent(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=e=>{const t=new st({track:e});return this.senders.push(t),this.events.trigger("track",{track:e}),t}}function ct(n){const e=n.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const A=400,y="777",dt=n=>n.getVideoTracks().length>0;class i extends ot{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;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)},A)});replaceMediaStream=jest.fn(async e=>{});isEndedInner=!1;constructor({eventHandlers:e,originator:t,remoteIdentity:r=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1")}){super({originator:t,eventHandlers:e,remoteIdentity:r})}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=>{if(i.countStartsPresentation+=1,i.presentationError)throw this.trigger("presentation:start",e),this.trigger("presentation:failed",e),i.presentationError;if(i.startPresentationError&&i.countStartsPresentation<i.countStartPresentationError)throw this.trigger("presentation:start",e),this.trigger("presentation:failed",e),i.startPresentationError;return super.startPresentation(e)};stopPresentation=async e=>{if(i.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),i.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=f.createAudioMediaStreamTrackMock();t.id="mainaudio1";const r=[t];if(dt(e)){const c=f.createVideoMediaStreamTrackMock();c.id="mainvideo1",r.push(c)}this.connection=new at(void 0,r),this.addStream(e),this.trigger("peerconnection",{peerconnection:this.connection})}connect(e,{mediaStream:t}={}){const r=ct(e);return this.initPeerconnection(t),setTimeout(()=>{e.includes(y)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),setTimeout(()=>{this.newInfo({originator:P.Originator.REMOTE,request:{getHeader:s=>s==="content-type"?"application/vinteo.webrtc.roomname":s==="x-webrtc-enter-room"?r:s==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},A),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))}forEachSenders(e){const t=this.connection.getSenders();for(const r of t)e(r);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t&&t.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{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)}}class Et{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",T="PASSWORD_CORRECT_2",L="NAME_INCORRECT",h=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},M={status_code:200,reason_phrase:"OK"},O={status_code:401,reason_phrase:"Unauthorized"};class o{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:r,eventHandlers:s}=t;return this.session=new i({eventHandlers:s,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(o.countStarts+=1,o.startError&&o.countStarts<o.countStartError){this.trigger("disconnected",o.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 S.Events(D);const[t,r]=e.uri.split(":"),[s,c]=r.split("@"),p={...e,uri:new a.URI(t,s,c)};this.configuration=p,this.registratorInner=new Et}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){o.startError=e,o.countStartError=t}static resetStartError(){o.startError=void 0,o.countStartError=Number.POSITIVE_INFINITY,o.countStarts=0}static setAvailableTelephony(){o.isAvailableTelephony=!0}static setNotAvailableTelephony(){o.isAvailableTelephony=!1}static reset(){o.resetStartError(),o.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(L)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:O,cause:a.C.causes.REJECTED})},h)):!this.isRegistered()&&t===!0&&(e===d||e===T)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:M})},h)):t===!0&&e!==d&&e!==T&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:O,cause:a.C.causes.REJECTED})},h)),o.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:M})}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 b.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const I="remote",mt=(n,e)=>{const t=new N(e),r={originator:I,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 s=new i({originator:I,eventHandlers:{}}),c=new k("sip",e,r);s.remote_identity=new V(c,t);const p=new N([]);n.trigger("newRTCSession",{originator:I,session:s,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:o,C:{INVITE:"INVITE"}},u="user",E="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",_t=new w.WebSocketInterface(C),R={userAgent:"Chrome",sipServerUrl:m,sipWebSocketServerURL:C},Tt={...R},F={...R,user:u,password:d,register:!0},It={...F,displayName:E},St={...R,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:"",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},Rt={...l,display_name:"",register:!1},W="10.10.10.10",ft=[`X-Vinteo-Remote: ${W}`],At=()=>new P.SipConnector({JsSIP:w});exports.FAILED_CONFERENCE_NUMBER=y;exports.JsSIP=w;exports.NAME_INCORRECT=L;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=T;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=F;exports.dataForConnectionWithAuthorizationWithDisplayName=It;exports.dataForConnectionWithoutAuthorization=St;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=Tt;exports.displayName=E;exports.doMockSipConnector=At;exports.extraHeadersRemoteAddress=ft;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=Nt;exports.uaConfigurationWithAuthorizationWithDisplayName=wt;exports.uaConfigurationWithoutAuthorization=Ct;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=Rt;exports.user=u;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("node:events"),V=require("@krivega/jssip/lib/NameAddrHeader"),k=require("@krivega/jssip/lib/URI"),U=require("@krivega/jssip/lib/SIPMessage"),a=require("@krivega/jssip"),f=require("webrtc-mock"),S=require("events-constructor"),P=require("./@SipConnector-Bv3-Y4Rz.cjs");class N extends U.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const H="incomingCall",q="declinedIncomingCall",G="failedIncomingCall",x="terminatedIncomingCall",v="connecting",z="connected",j="disconnected",Y="newRTCSession",B="registered",K="unregistered",J="registrationFailed",$="newMessage",Q="sipEvent",X="availableSecondRemoteStream",Z="notAvailableSecondRemoteStream",ee="mustStopPresentation",te="shareState",re="enterRoom",ne="useLicense",oe="peerconnection:confirmed",se="peerconnection:ontrack",ie="channels",ae="channels:notify",ce="ended:fromserver",de="main-cam-control",Ee="admin-stop-main-cam",he="admin-start-main-cam",ue="admin-stop-mic",me="admin-start-mic",le="admin-force-sync-media-state",pe="participant:added-to-list-moderators",ge="participant:removed-from-list-moderators",_e="participant:move-request-to-stream",Te="participant:move-request-to-spectators",Ie="participant:move-request-to-participants",Se="participation:accepting-word-request",Ne="participation:cancelling-word-request",we="webcast:started",Ce="webcast:stopped",Re="account:changed",fe="account:deleted",Ae="conference:participant-token-issued",Me="ended",Oe="sending",Pe="reinvite",ve="replaces",De="refer",ye="progress",Le="accepted",Fe="confirmed",We="peerconnection",be="failed",Ve="muted",ke="unmuted",Ue="newDTMF",He="newInfo",qe="hold",Ge="unhold",xe="update",ze="sdp",je="icecandidate",Ye="getusermediafailed",Be="peerconnection:createofferfailed",Ke="peerconnection:createanswerfailed",Je="peerconnection:setlocaldescriptionfailed",$e="peerconnection:setremotedescriptionfailed",Qe="presentation:start",Xe="presentation:started",Ze="presentation:end",et="presentation:ended",tt="presentation:failed",rt=[H,q,x,G,Se,Ne,_e,ae,Ae,Re,fe,we,Ce,pe,ge],D=[v,z,j,Y,B,K,J,$,Q],nt=[X,Z,ee,te,re,ne,oe,se,ie,ce,de,he,Ee,ue,me,le,Te,Ie],_=[Me,v,Oe,Pe,ve,De,ye,Le,Fe,We,be,Ve,ke,Ue,He,qe,Ge,xe,ze,je,Ye,Be,Ke,Je,$e,Qe,Xe,Ze,et,tt];[...D,...rt];[..._,...nt];class ot{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};constructor({originator:e="local",eventHandlers:t,remoteIdentity:r}){this.originator=e,this.events=new S.Events(_),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 _.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 st{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.")}}const it=["track"];class at{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;events;constructor(e,t){this.events=new S.Events(it),this.receivers=t.map(r=>({track:r}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}addTransceiver(e,t){throw new Error("Method not implemented.")}close(){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.")}async createOffer(e,t,r){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.")}async setLocalDescription(e){throw new Error("Method not implemented.")}async setRemoteDescription(e){throw new Error("Method not implemented.")}addEventListener(e,t,r){this.events.on(e,t)}removeEventListener(e,t,r){this.events.off(e,t)}dispatchEvent(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=e=>{const t=new st({track:e});return this.senders.push(t),this.events.trigger("track",{track:e}),t}}function ct(n){const e=n.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const A=400,y="777",dt=n=>n.getVideoTracks().length>0;class i extends ot{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;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)},A)});replaceMediaStream=jest.fn(async e=>{});isEndedInner=!1;constructor({eventHandlers:e,originator:t,remoteIdentity:r=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1")}){super({originator:t,eventHandlers:e,remoteIdentity:r})}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=>{if(i.countStartsPresentation+=1,i.presentationError)throw this.trigger("presentation:start",e),this.trigger("presentation:failed",e),i.presentationError;if(i.startPresentationError&&i.countStartsPresentation<i.countStartPresentationError)throw this.trigger("presentation:start",e),this.trigger("presentation:failed",e),i.startPresentationError;return super.startPresentation(e)};stopPresentation=async e=>{if(i.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),i.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=f.createAudioMediaStreamTrackMock();t.id="mainaudio1";const r=[t];if(dt(e)){const c=f.createVideoMediaStreamTrackMock();c.id="mainvideo1",r.push(c)}this.connection=new at(void 0,r),this.addStream(e),this.trigger("peerconnection",{peerconnection:this.connection})}connect(e,{mediaStream:t}={}){const r=ct(e);return this.initPeerconnection(t),setTimeout(()=>{e.includes(y)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),setTimeout(()=>{this.newInfo({originator:P.Originator.REMOTE,request:{getHeader:s=>s==="content-type"?"application/vinteo.webrtc.roomname":s==="x-webrtc-enter-room"?r:s==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},A),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))}forEachSenders(e){const t=this.connection.getSenders();for(const r of t)e(r);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t&&t.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{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)}}class Et{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",T="PASSWORD_CORRECT_2",L="NAME_INCORRECT",h=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},M={status_code:200,reason_phrase:"OK"},O={status_code:401,reason_phrase:"Unauthorized"};class o{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:r,eventHandlers:s}=t;return this.session=new i({eventHandlers:s,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(o.countStarts+=1,o.startError&&o.countStarts<o.countStartError){this.trigger("disconnected",o.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 S.Events(D);const[t,r]=e.uri.split(":"),[s,c]=r.split("@"),p={...e,uri:new a.URI(t,s,c)};this.configuration=p,this.registratorInner=new Et}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){o.startError=e,o.countStartError=t}static resetStartError(){o.startError=void 0,o.countStartError=Number.POSITIVE_INFINITY,o.countStarts=0}static setAvailableTelephony(){o.isAvailableTelephony=!0}static setNotAvailableTelephony(){o.isAvailableTelephony=!1}static reset(){o.resetStartError(),o.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(L)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:O,cause:a.C.causes.REJECTED})},h)):!this.isRegistered()&&t===!0&&(e===d||e===T)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:M})},h)):t===!0&&e!==d&&e!==T&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:O,cause:a.C.causes.REJECTED})},h)),o.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:M})}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 b.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const I="remote",mt=(n,e)=>{const t=new N(e),r={originator:I,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 s=new i({originator:I,eventHandlers:{}}),c=new k("sip",e,r);s.remote_identity=new V(c,t);const p=new N([]);n.trigger("newRTCSession",{originator:I,session:s,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:o,C:{INVITE:"INVITE"}},u="user",E="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",_t=new w.WebSocketInterface(C),R={userAgent:"Chrome",sipServerUrl:m,sipWebSocketServerURL:C},Tt={...R},F={...R,user:u,password:d,register:!0},It={...F,displayName:E},St={...R,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:"",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},Rt={...l,display_name:"",register:!1},W="10.10.10.10",ft=[`X-Vinteo-Remote: ${W}`],At=()=>new P.SipConnector({JsSIP:w});exports.FAILED_CONFERENCE_NUMBER=y;exports.JsSIP=w;exports.NAME_INCORRECT=L;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=T;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=F;exports.dataForConnectionWithAuthorizationWithDisplayName=It;exports.dataForConnectionWithoutAuthorization=St;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=Tt;exports.displayName=E;exports.doMockSipConnector=At;exports.extraHeadersRemoteAddress=ft;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=Nt;exports.uaConfigurationWithAuthorizationWithDisplayName=wt;exports.uaConfigurationWithoutAuthorization=Ct;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=Rt;exports.user=u;
package/dist/doMock.js CHANGED
@@ -5,7 +5,7 @@ import { IncomingRequest as F } from "@krivega/jssip/lib/SIPMessage";
5
5
  import { NameAddrHeader as b, URI as E, C as N } from "@krivega/jssip";
6
6
  import { createAudioMediaStreamTrackMock as V, createVideoMediaStreamTrackMock as k } from "webrtc-mock";
7
7
  import { Events as _ } from "events-constructor";
8
- import { O as W, S as U } from "./@SipConnector-BEZk1hmx.js";
8
+ import { O as W, S as U } from "./@SipConnector-5Rac5oq2.js";
9
9
  class T extends F {
10
10
  headers;
11
11
  constructor(e) {
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("events-constructor");const o=require("./@SipConnector-hpySQIBa.cjs"),j=require("@krivega/cancelable-promise"),de=require("repeated-calls"),ue=require("ts-debounce"),le=require("ua-parser-js"),ge=require("sequent-promises"),he=require("stack-promises"),B=require("debug"),Ce=n=>n instanceof Object&&("originator"in n||"cause"in n),Se=n=>{if(j.isCanceledError(n))return!0;if(!Ce(n))return!1;const{originator:e,cause:t}=n;return typeof t=="string"?t===o.ECallCause.REQUEST_TIMEOUT||t===o.ECallCause.REJECTED||e===o.Originator.LOCAL&&(t===o.ECallCause.CANCELED||t===o.ECallCause.BYE):!1},fe=()=>globalThis.process?.versions?.electron!==void 0,G=()=>{const n=new le.UAParser,{name:e}=n.getBrowser(),t=fe();return{isChrome:e==="Chrome"||t}},F=n=>{const{url:e,cause:t}=n;let r=e;return(t===o.ECallCause.BAD_MEDIA_DESCRIPTION||t===o.ECallCause.NOT_FOUND)&&(r=`${n.message.to.uri.user}@${n.message.to.uri.host}`),r};var K=(n=>(n.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",n.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",n.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",n.NOT_FOUND_ERROR="NOT_FOUND_ERROR",n.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",n.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",n))(K||{});const me=new Error("Unknown error"),pe=(n=me)=>{const{cause:e,socket:t}=n;let r="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{r="WRONG_USER_OR_PASSWORD";break}case o.ECallCause.BAD_MEDIA_DESCRIPTION:{r="BAD_MEDIA_ERROR";break}case o.ECallCause.NOT_FOUND:{r="NOT_FOUND_ERROR";break}default:t!==void 0&&t._ws?.readyState===3?r="WS_CONNECTION_FAILED":F(n)!==void 0&&F(n)!==""&&(r="CONNECT_SERVER_FAILED_BY_LINK")}return r},Re=n=>{let e="";try{e=JSON.stringify(n)}catch(t){o.logger("failed to stringify message",t)}return e},Ee=new Error("Unknown error"),ye=(n=Ee)=>{const{code:e,cause:t,message:r}=n,s=F(n),i={code:"",cause:"",message:""};return typeof r=="object"&&r!==null?i.message=Re(r):r&&(i.message=String(r)),s!==void 0&&s!==""&&(i.link=s),e!==void 0&&e!==""&&(i.code=e),t!==void 0&&t!==""&&(i.cause=t),i},ve=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:K,getLinkError:F,getTypeFromError:pe,getValuesFromError:ye},Symbol.toStringTag,{value:"Module"})),Te=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:r,isRegistered:s,isPresentationCall:i})=>{const c=[],a=t?"0":"1",d=r?"0":"1";return c.push(`X-Vinteo-Mic-State: ${a}`,`X-Vinteo-MainCam-State: ${d}`),(s===!1||s===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Session: ${n}`),i===!0&&c.push("X-Vinteo-Presentation-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Remote: ${e}`),c},Me="[@*!|]",be="_",Be=n=>{let e=n;return e=e.replaceAll(new RegExp(Me,"g"),be),e},Pe=({appName:n,appVersion:e,browserName:t,browserVersion:r})=>{const i=`${Be(n)} ${e}`;return`ChromeNew - ${t===void 0?i:`${t} ${r}, ${i}`}`},Ae=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:r,appName:s})=>n?Pe({appVersion:e,browserName:t,browserVersion:r,appName:s}):"Chrome",Y="purgatory",I=n=>n===Y,_e=n=>e=>[...e].map(r=>async()=>n(r)),Ne=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const s=_e(e)(n);return ge.sequentPromises(s,t)},Oe=(n,e)=>(n.degradationPreference=e.degradationPreference,n),we=(n,e)=>{n.encodings??=[];for(let t=n.encodings.length;t<e;t+=1)n.encodings.push({});return n},z=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,De=z(),ke=(n,e)=>{if(De(n,e))return n},Fe=(n,e)=>{const t=n.maxBitrate,r=ke(e,t);return r!==void 0&&(n.maxBitrate=r),n},Z=1,Ie=z(Z),xe=(n,e)=>{const t=n===void 0?void 0:Math.max(n,Z);if(t!==void 0&&Ie(t,e))return t},Ue=(n,e)=>{const t=n.scaleResolutionDownBy,r=xe(e,t);return r!==void 0&&(n.scaleResolutionDownBy=r),n},Ve=(n,e)=>{const t=e.encodings?.length??0;return we(n,t),n.encodings.forEach((r,s)=>{const i=(e?.encodings??[])[s],c=i?.maxBitrate,a=i?.scaleResolutionDownBy;Fe(r,c),Ue(r,a)}),n},Le=(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},$=async(n,e)=>{const t=n.getParameters(),r=JSON.parse(JSON.stringify(t));Ve(t,e),Oe(t,e);const s=Le(r,t);return s&&await n.setParameters(t),{parameters:t,isChanged:s}},ee=async(n,e,t)=>{const{isChanged:r,parameters:s}=await $(n,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return r&&t&&t(s),{isChanged:r,parameters:s}},He=n=>t=>(o.logger("onStartMainCam"),n.on("api:admin-start-main-cam",t)),qe=n=>t=>(o.logger("onStartMic"),n.on("api:admin-start-mic",t)),$e=n=>t=>(o.logger("onStopMainCam"),n.on("api:admin-stop-main-cam",t)),We=n=>t=>(o.logger("onStopMic"),n.on("api:admin-stop-mic",t)),Qe=({sipConnector:n})=>{const e=(C,f)=>({isSyncForced:m})=>{if(m===!0){C();return}f()},t=He(n),r=$e(n),s=qe(n),i=We(n);let c,a,d,l;const h=({onStartMainCamForced:C,onStartMainCamNotForced:f,onStopMainCamForced:m,onStopMainCamNotForced:p,onStartMicForced:R,onStartMicNotForced:v,onStopMicForced:T,onStopMicNotForced:M})=>{const b=e(C,f);c=t(b);const P=e(m,p);a=r(P);const A=e(R,v);d=s(A);const _=e(T,M);l=i(_)},g=()=>{c?.(),a?.(),d?.(),l?.()};return{start:C=>{h(C)},stop:()=>{g()}}},Je=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:Y,createSyncMediaState:Qe,createUaParser:G,error:ve,getExtraHeaders:Te,getUserAgent:Ae,hasPurgatory:I,prepareMediaStream:o.prepareMediaStream,sendDtmfAccumulated:Ne,setEncodingsToSender:ee,setParametersToSender:$},Symbol.toStringTag,{value:"Module"})),Xe=()=>G().isChrome,je=n=>n.getVideoTracks()[0],Ge=1e6,S=n=>n*Ge,ne=S(.06),te=S(4),Ke=n=>n<=64?ne:n<=128?S(.12):n<=256?S(.25):n<=384?S(.32):n<=426?S(.38):n<=640?S(.5):n<=848?S(.7):n<=1280?S(1):n<=1920?S(2):te,re=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),Ye="av1",ze=n=>re(n,Ye),Ze=.6,W=(n,e)=>ze(e)?n*Ze:n,en=n=>W(ne,n),nn=n=>W(te,n),q=(n,e)=>{const t=Ke(n);return W(t,e)},L=1,se=({videoTrack:n,targetSize:e})=>{const t=n.getSettings(),r=t.width,s=t.height,i=r===void 0?L:r/e.width,c=s===void 0?L:s/e.height;return Math.max(i,c,L)},tn=n=>[...n.keys()].map(e=>n.get(e)),rn=(n,e)=>tn(n).find(t=>t?.type===e),oe=async n=>n.getStats().then(e=>rn(e,"codec")?.mimeType);class sn{async getCodecFromSender(e){return await oe(e)??""}}class on{stackPromises=he.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{o.logger("TaskQueue: error",e)})}}class cn{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new on}async setEncodingsToSender(e,t){return this.taskQueue.add(async()=>ee(e,t,this.onSetParameters))}stop(){this.taskQueue.stop()}}class an{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:t,parametersSetter:r},s){this.senderFinder=e,this.codecProvider=t,this.parametersSetter=r,this.ignoreForCodec=s.ignoreForCodec}async balance(e,t){const r=e.getSenders(),s=this.senderFinder.findVideoSender(r);if(!s?.track)return this.resultNoChanged;const i=await this.codecProvider.getCodecFromSender(s);if(re(i,this.ignoreForCodec))return this.resultNoChanged;const{mainCam:c,resolutionMainCam:a}=t??{};return this.processSender({mainCam:c,resolutionMainCam:a},{sender:s,codec:i,videoTrack:s.track})}async processSender(e,t){const{mainCam:r,resolutionMainCam:s}=e;switch(r){case o.EEventsMainCAM.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(t);case o.EEventsMainCAM.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(t);case o.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return s!==void 0?this.setResolutionSender(s,t):this.setBitrateByTrackResolution(t);case o.EEventsMainCAM.ADMIN_STOP_MAIN_CAM:case o.EEventsMainCAM.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(t);default:return this.setBitrateByTrackResolution(t)}}async downgradeResolutionSender(e){const{sender:t,codec:r}=e,s={scaleResolutionDownBy:200,maxBitrate:en(r)};return this.parametersSetter.setEncodingsToSender(t,s)}async setBitrateByTrackResolution(e){const{sender:t,videoTrack:r,codec:s}=e,c=r.getSettings().width,a=c===void 0?nn(s):q(c,s);return this.parametersSetter.setEncodingsToSender(t,{scaleResolutionDownBy:1,maxBitrate:a})}async setResolutionSender(e,t){const[r,s]=e.split("x"),{sender:i,videoTrack:c,codec:a}=t,d={width:Number(r),height:Number(s)},l=se({videoTrack:c,targetSize:d}),h=q(d.width,a),g={scaleResolutionDownBy:l,maxBitrate:h};return this.parametersSetter.setEncodingsToSender(i,g)}}const dn=n=>n.find(e=>e.track?.kind==="video");class un{findVideoSender(e){return dn(e)}}class ln{sipConnector;currentHandler;constructor(e){this.sipConnector=e}subscribe(e){this.currentHandler=e,this.sipConnector.on("api:main-cam-control",e)}unsubscribe(){this.currentHandler&&(this.sipConnector.off("api:main-cam-control",this.currentHandler),this.currentHandler=void 0)}getConnection(){return this.sipConnector.connection}}class ie{eventHandler;senderBalancer;parametersSetterWithQueue;serverHeaders;constructor(e,{ignoreForCodec:t,onSetParameters:r}={}){this.eventHandler=new ln(e),this.parametersSetterWithQueue=new cn(r),this.senderBalancer=new an({senderFinder:new un,codecProvider:new sn,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:t})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.parametersSetterWithQueue.stop(),this.reset()}reset(){delete this.serverHeaders}async reBalance(){return this.balanceByTrack()}async balanceByTrack(){const e=this.eventHandler.getConnection();if(!e)throw new Error("connection is not exist");return this.senderBalancer.balance(e,this.serverHeaders)}handleMainCamControl=e=>{this.serverHeaders=e,this.balanceByTrack().catch(B)}}const gn=(n,e={})=>new ie(n,e),hn=({videoTrack:n,targetSize:e,codec:t})=>{const r=se({videoTrack:n,targetSize:e}),s=q(e.width,t);return{scaleResolutionDownBy:r,maxBitrate:s}},O=({mediaStream:n,simulcastEncodings:e,sendEncodings:t})=>{if(e&&e.length>0){const r=t??[],s=je(n);if(s===void 0)throw new Error("No video track");return e.forEach((i,c)=>{const a=r[c]??{};a.active=!0,i.rid!==void 0&&(a.rid=i.rid),i.scalabilityMode!==void 0&&(a.scalabilityMode=i.scalabilityMode);const{maxBitrate:d,scaleResolutionDownBy:l}=hn({videoTrack:s,targetSize:{width:i.width,height:i.height}});a.maxBitrate=d,a.scaleResolutionDownBy=l,r[c]=a}),r}return t},Cn=(n,e)=>n.filter(r=>e.some(s=>s.clockRate===r.clockRate&&s.mimeType===r.mimeType&&s.channels===r.channels&&s.sdpFmtpLine===r.sdpFmtpLine)),Sn=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),r=e===null?[]:e.codecs,s=t===null?[]:t.codecs;return Cn(r,s)},fn=(n,e)=>e===void 0||e.length===0?n:n.sort((t,r)=>{const s=e.indexOf(t.mimeType),i=e.indexOf(r.mimeType),c=s===-1?Number.MAX_VALUE:s,a=i===-1?Number.MAX_VALUE:i;return c-a}),mn=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),pn=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>{if(typeof n.setCodecPreferences=="function"&&n.sender.track?.kind==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const r=Sn("video"),s=mn(r,t),i=fn(s,e);n.setCodecPreferences(i)}},w=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>async r=>{try{pn(r,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t}),Object.values(n).filter(i=>i!=null).length>0&&(o.logger("updateTransceiver setParametersToSender",n),await $(r.sender,n))}catch(s){o.logger("updateTransceiver error",s)}},H=n=>{if(!j.isCanceledError(n)&&!de.hasCanceledError(n))throw n;return{isSuccessful:!1}},Rn=({kind:n,readyState:e})=>n==="video"&&e==="live",Q=(n,e,{onEnterPurgatory:t,onEnterConference:r})=>{I(n)?t&&t():r&&r({isSuccessProgressCall:e})},J=(n,e)=>{n(),e&&e()},X=(n,e,t)=>{throw n&&n(),e(),t},En=new Set(["on","once","onceRace","wait","off","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class yn{on;once;onceRace;wait;off;sendDTMF;hangUp;declineToIncomingCall;sendChannels;checkTelephony;waitChannels;ping;connection;isConfigured;isRegistered;sipConnector;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor(e,{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:r}={}){return this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=r,this.sipConnector=e,new Proxy(this,{get:(s,i,c)=>{if(typeof i=="string"&&En.has(i)&&i in this.sipConnector){const d=Reflect.get(this.sipConnector,i,this.sipConnector);return typeof d=="function"?d.bind(this.sipConnector):d}const a=Reflect.get(s,i,c);return typeof a=="function"?a.bind(s):a}})}connectToServer=async e=>{const{userAgent:t,sipWebSocketServerURL:r,sipServerUrl:s,remoteAddress:i,displayName:c,name:a,password:d,isRegisteredUser:l,isDisconnectOnFail:h}=e;return o.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:r,sipServerUrl:s,remoteAddress:i,displayName:c,password:d,user:a,register:l}).then(g=>(o.logger("connectToServer then"),{ua:g,isSuccessful:!0})).catch(async g=>(o.logger("connectToServer catch: error",g),h===!0?this.sipConnector.disconnect().then(()=>H(g)).catch(()=>H(g)):H(g)))};callToServer=async e=>{const{conference:t,mediaStream:r,extraHeaders:s,iceServers:i,contentHint:c,simulcastEncodings:a,degradationPreference:d,sendEncodings:l,offerToReceiveAudio:h,offerToReceiveVideo:g,directionVideo:D,directionAudio:k,setRemoteStreams:C,onBeforeProgressCall:f,onSuccessProgressCall:m,onEnterPurgatory:p,onEnterConference:R,onFailProgressCall:v,onFinishProgressCall:T,onEndedCall:M}=e,b=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:C}),P=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{b().catch(B)}}),A=w({degradationPreference:d},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});o.logger("callToServer",e);const _=async()=>(o.logger("startCall"),this.sipConnector.call({mediaStream:r,extraHeaders:s,iceServers:i,contentHint:c,offerToReceiveAudio:h,offerToReceiveVideo:g,directionVideo:D,directionAudio:k,sendEncodings:O({mediaStream:r,simulcastEncodings:a,sendEncodings:l}),number:t,onAddedTransceiver:A,ontrack:P}));let E=!1,y;const N=(o.logger("subscribeEnterConference: onEnterConference",R),this.sipConnector.on("api:enterRoom",({room:u})=>{o.logger("enterRoom",{_room:u,isSuccessProgressCall:E}),y=u,(p??R)&&Q(y,E,{onEnterPurgatory:p,onEnterConference:R})})),x=u=>(o.logger("onSuccess"),E=!0,b().catch(B),m&&m({isPurgatory:I(y)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{J(N,M)}),u),U=u=>(o.logger("onFail"),X(v,N,u)),V=()=>{o.logger("onFinish"),T&&T()};return o.logger("onBeforeProgressCall"),f&&f(t),_().then(x).catch(u=>U(u)).finally(V)};disconnectFromServer=async()=>this.sipConnector.disconnect().then(()=>(o.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(e=>(o.logger("disconnectFromServer: catch",e),{isSuccessful:!1}));answerToIncomingCall=async e=>{const{mediaStream:t,extraHeaders:r,iceServers:s,contentHint:i,simulcastEncodings:c,degradationPreference:a,sendEncodings:d,offerToReceiveAudio:l,offerToReceiveVideo:h,directionVideo:g,directionAudio:D,setRemoteStreams:k,onBeforeProgressCall:C,onSuccessProgressCall:f,onEnterPurgatory:m,onEnterConference:p,onFailProgressCall:R,onFinishProgressCall:v,onEndedCall:T}=e,M=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:k}),b=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{M().catch(B)}}),P=w({degradationPreference:a},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});o.logger("answerToIncomingCall",e);const A=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:r,iceServers:s,contentHint:i,offerToReceiveAudio:l,offerToReceiveVideo:h,directionVideo:g,directionAudio:D,sendEncodings:O({mediaStream:t,simulcastEncodings:c,sendEncodings:d}),onAddedTransceiver:P,ontrack:b}),_=()=>{const{remoteCallerData:u}=this.sipConnector;return u.incomingNumber};let E=!1,y;const N=(o.logger("subscribeEnterConference: onEnterConference",p),this.sipConnector.on("api:enterRoom",u=>{o.logger("enterRoom",{_room:u,isSuccessProgressCall:E}),y=u,(m??p)&&Q(y,E,{onEnterPurgatory:m,onEnterConference:p})})),x=u=>(o.logger("onSuccess"),E=!0,M().catch(B),f&&f({isPurgatory:I(y)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{J(N,T)}),u),U=u=>(o.logger("onFail"),X(R,N,u)),V=()=>{o.logger("onFinish"),v&&v()};if(o.logger("onBeforeProgressCall"),C){const u=_();C(u)}return A().then(x).catch(u=>U(u)).finally(V)};updatePresentation=async({mediaStream:e,isP2P:t,maxBitrate:r,contentHint:s,simulcastEncodings:i,degradationPreference:c,sendEncodings:a,preferredMimeTypesVideoCodecs:d,excludeMimeTypesVideoCodecs:l})=>{const h=w({degradationPreference:c},{preferredMimeTypesVideoCodecs:d,excludeMimeTypesVideoCodecs:l});return o.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,maxBitrate:r,contentHint:s,sendEncodings:O({mediaStream:e,simulcastEncodings:i,sendEncodings:a}),onAddedTransceiver:h})};startPresentation=async({mediaStream:e,isP2P:t,maxBitrate:r,contentHint:s,simulcastEncodings:i,degradationPreference:c,sendEncodings:a,preferredMimeTypesVideoCodecs:d,excludeMimeTypesVideoCodecs:l,callLimit:h})=>{const g=w({degradationPreference:c},{preferredMimeTypesVideoCodecs:d,excludeMimeTypesVideoCodecs:l});return o.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,maxBitrate:r,contentHint:s,callLimit:h,sendEncodings:O({mediaStream:e,simulcastEncodings:i,sendEncodings:a}),onAddedTransceiver:g})};stopShareSipConnector=async({isP2P:e=!1}={})=>(o.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{o.logger(t)}));sendRefusalToTurnOnMic=async()=>{o.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{o.logger("sendRefusalToTurnOnMic: error",e)})};sendRefusalToTurnOnCam=async()=>{o.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{o.logger("sendRefusalToTurnOnCam: error",e)})};sendMediaState=async({isEnabledCam:e,isEnabledMic:t})=>{o.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:e,mic:t})};replaceMediaStream=async(e,{deleteExisting:t,addMissing:r,forceRenegotiation:s,contentHint:i,simulcastEncodings:c,degradationPreference:a,sendEncodings:d})=>{const l=w({degradationPreference:a},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});return o.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:r,forceRenegotiation:s,contentHint:i,sendEncodings:O({mediaStream:e,simulcastEncodings:c,sendEncodings:d}),onAddedTransceiver:l})};askPermissionToEnableCam=async()=>{o.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam()};resolveHandleReadyRemoteStreamsDebounced=({onReadyRemoteStreams:e})=>ue.debounce(()=>{const t=this.sipConnector.getRemoteStreams();o.logger("remoteStreams",t),t&&e(t)},200);resolveHandleReadyRemoteStreams=({onReadyRemoteStreams:e})=>({track:t})=>{Rn(t)&&e()};getRemoteStreams=()=>(o.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams());onUseLicense=e=>(o.logger("onUseLicense"),this.sipConnector.on("api:useLicense",e));onMustStopPresentation=e=>(o.logger("onMustStopPresentation"),this.sipConnector.on("api:mustStopPresentation",e));onMoveToSpectators=e=>(o.logger("onMoveToSpectators"),this.sipConnector.on("api:participant:move-request-to-spectators",e));onMoveToParticipants=e=>(o.logger("onMoveToParticipants"),this.sipConnector.on("api:participant:move-request-to-participants",e));onStats=e=>(o.logger("onStats"),this.sipConnector.on("stats:collected",e));offStats=e=>{o.logger("offStats"),this.sipConnector.off("stats:collected",e)}}var ce=(n=>(n.VP8="video/VP8",n.VP9="video/VP9",n.H264="video/H264",n.AV1="video/AV1",n.rtx="video/rtx",n.red="video/red",n.flexfec03="video/flexfec-03",n))(ce||{});exports.ECallCause=o.ECallCause;exports.EStatsTypes=o.EStatsTypes;exports.EUseLicense=o.EUseLicense;exports.SipConnector=o.SipConnector;exports.StatsPeerConnection=o.StatsPeerConnection;exports.disableDebug=o.disableDebug;exports.enableDebug=o.enableDebug;exports.hasCanceledStartPresentationError=o.hasCanceledStartPresentationError;exports.debug=B;exports.EMimeTypesVideoCodecs=ce;exports.SipConnectorFacade=yn;exports.VideoSendingBalancer=ie;exports.getCodecFromSender=oe;exports.hasAvailableStats=Xe;exports.hasCanceledCallError=Se;exports.resolveVideoSendingBalancer=gn;exports.tools=Je;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("events-constructor");const o=require("./@SipConnector-Bv3-Y4Rz.cjs"),j=require("@krivega/cancelable-promise"),de=require("repeated-calls"),ue=require("ts-debounce"),le=require("ua-parser-js"),ge=require("sequent-promises"),he=require("stack-promises"),B=require("debug"),Ce=n=>n instanceof Object&&("originator"in n||"cause"in n),Se=n=>{if(j.isCanceledError(n))return!0;if(!Ce(n))return!1;const{originator:e,cause:t}=n;return typeof t=="string"?t===o.ECallCause.REQUEST_TIMEOUT||t===o.ECallCause.REJECTED||e===o.Originator.LOCAL&&(t===o.ECallCause.CANCELED||t===o.ECallCause.BYE):!1},fe=()=>globalThis.process?.versions?.electron!==void 0,G=()=>{const n=new le.UAParser,{name:e}=n.getBrowser(),t=fe();return{isChrome:e==="Chrome"||t}},F=n=>{const{url:e,cause:t}=n;let r=e;return(t===o.ECallCause.BAD_MEDIA_DESCRIPTION||t===o.ECallCause.NOT_FOUND)&&(r=`${n.message.to.uri.user}@${n.message.to.uri.host}`),r};var K=(n=>(n.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",n.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",n.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",n.NOT_FOUND_ERROR="NOT_FOUND_ERROR",n.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",n.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",n))(K||{});const me=new Error("Unknown error"),pe=(n=me)=>{const{cause:e,socket:t}=n;let r="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{r="WRONG_USER_OR_PASSWORD";break}case o.ECallCause.BAD_MEDIA_DESCRIPTION:{r="BAD_MEDIA_ERROR";break}case o.ECallCause.NOT_FOUND:{r="NOT_FOUND_ERROR";break}default:t!==void 0&&t._ws?.readyState===3?r="WS_CONNECTION_FAILED":F(n)!==void 0&&F(n)!==""&&(r="CONNECT_SERVER_FAILED_BY_LINK")}return r},Re=n=>{let e="";try{e=JSON.stringify(n)}catch(t){o.logger("failed to stringify message",t)}return e},Ee=new Error("Unknown error"),ye=(n=Ee)=>{const{code:e,cause:t,message:r}=n,s=F(n),i={code:"",cause:"",message:""};return typeof r=="object"&&r!==null?i.message=Re(r):r&&(i.message=String(r)),s!==void 0&&s!==""&&(i.link=s),e!==void 0&&e!==""&&(i.code=e),t!==void 0&&t!==""&&(i.cause=t),i},ve=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:K,getLinkError:F,getTypeFromError:pe,getValuesFromError:ye},Symbol.toStringTag,{value:"Module"})),Te=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:r,isRegistered:s,isPresentationCall:i})=>{const c=[],a=t?"0":"1",d=r?"0":"1";return c.push(`X-Vinteo-Mic-State: ${a}`,`X-Vinteo-MainCam-State: ${d}`),(s===!1||s===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Session: ${n}`),i===!0&&c.push("X-Vinteo-Presentation-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Remote: ${e}`),c},Me="[@*!|]",be="_",Be=n=>{let e=n;return e=e.replaceAll(new RegExp(Me,"g"),be),e},Pe=({appName:n,appVersion:e,browserName:t,browserVersion:r})=>{const i=`${Be(n)} ${e}`;return`ChromeNew - ${t===void 0?i:`${t} ${r}, ${i}`}`},Ae=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:r,appName:s})=>n?Pe({appVersion:e,browserName:t,browserVersion:r,appName:s}):"Chrome",Y="purgatory",I=n=>n===Y,_e=n=>e=>[...e].map(r=>async()=>n(r)),Ne=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const s=_e(e)(n);return ge.sequentPromises(s,t)},Oe=(n,e)=>(n.degradationPreference=e.degradationPreference,n),we=(n,e)=>{n.encodings??=[];for(let t=n.encodings.length;t<e;t+=1)n.encodings.push({});return n},z=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,De=z(),ke=(n,e)=>{if(De(n,e))return n},Fe=(n,e)=>{const t=n.maxBitrate,r=ke(e,t);return r!==void 0&&(n.maxBitrate=r),n},Z=1,Ie=z(Z),xe=(n,e)=>{const t=n===void 0?void 0:Math.max(n,Z);if(t!==void 0&&Ie(t,e))return t},Ue=(n,e)=>{const t=n.scaleResolutionDownBy,r=xe(e,t);return r!==void 0&&(n.scaleResolutionDownBy=r),n},Ve=(n,e)=>{const t=e.encodings?.length??0;return we(n,t),n.encodings.forEach((r,s)=>{const i=(e?.encodings??[])[s],c=i?.maxBitrate,a=i?.scaleResolutionDownBy;Fe(r,c),Ue(r,a)}),n},Le=(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},$=async(n,e)=>{const t=n.getParameters(),r=JSON.parse(JSON.stringify(t));Ve(t,e),Oe(t,e);const s=Le(r,t);return s&&await n.setParameters(t),{parameters:t,isChanged:s}},ee=async(n,e,t)=>{const{isChanged:r,parameters:s}=await $(n,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return r&&t&&t(s),{isChanged:r,parameters:s}},He=n=>t=>(o.logger("onStartMainCam"),n.on("api:admin-start-main-cam",t)),qe=n=>t=>(o.logger("onStartMic"),n.on("api:admin-start-mic",t)),$e=n=>t=>(o.logger("onStopMainCam"),n.on("api:admin-stop-main-cam",t)),We=n=>t=>(o.logger("onStopMic"),n.on("api:admin-stop-mic",t)),Qe=({sipConnector:n})=>{const e=(C,f)=>({isSyncForced:m})=>{if(m===!0){C();return}f()},t=He(n),r=$e(n),s=qe(n),i=We(n);let c,a,d,l;const h=({onStartMainCamForced:C,onStartMainCamNotForced:f,onStopMainCamForced:m,onStopMainCamNotForced:p,onStartMicForced:R,onStartMicNotForced:v,onStopMicForced:T,onStopMicNotForced:M})=>{const b=e(C,f);c=t(b);const P=e(m,p);a=r(P);const A=e(R,v);d=s(A);const _=e(T,M);l=i(_)},g=()=>{c?.(),a?.(),d?.(),l?.()};return{start:C=>{h(C)},stop:()=>{g()}}},Je=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:Y,createSyncMediaState:Qe,createUaParser:G,error:ve,getExtraHeaders:Te,getUserAgent:Ae,hasPurgatory:I,prepareMediaStream:o.prepareMediaStream,sendDtmfAccumulated:Ne,setEncodingsToSender:ee,setParametersToSender:$},Symbol.toStringTag,{value:"Module"})),Xe=()=>G().isChrome,je=n=>n.getVideoTracks()[0],Ge=1e6,S=n=>n*Ge,ne=S(.06),te=S(4),Ke=n=>n<=64?ne:n<=128?S(.12):n<=256?S(.25):n<=384?S(.32):n<=426?S(.38):n<=640?S(.5):n<=848?S(.7):n<=1280?S(1):n<=1920?S(2):te,re=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),Ye="av1",ze=n=>re(n,Ye),Ze=.6,W=(n,e)=>ze(e)?n*Ze:n,en=n=>W(ne,n),nn=n=>W(te,n),q=(n,e)=>{const t=Ke(n);return W(t,e)},L=1,se=({videoTrack:n,targetSize:e})=>{const t=n.getSettings(),r=t.width,s=t.height,i=r===void 0?L:r/e.width,c=s===void 0?L:s/e.height;return Math.max(i,c,L)},tn=n=>[...n.keys()].map(e=>n.get(e)),rn=(n,e)=>tn(n).find(t=>t?.type===e),oe=async n=>n.getStats().then(e=>rn(e,"codec")?.mimeType);class sn{async getCodecFromSender(e){return await oe(e)??""}}class on{stackPromises=he.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{o.logger("TaskQueue: error",e)})}}class cn{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new on}async setEncodingsToSender(e,t){return this.taskQueue.add(async()=>ee(e,t,this.onSetParameters))}stop(){this.taskQueue.stop()}}class an{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:t,parametersSetter:r},s){this.senderFinder=e,this.codecProvider=t,this.parametersSetter=r,this.ignoreForCodec=s.ignoreForCodec}async balance(e,t){const r=e.getSenders(),s=this.senderFinder.findVideoSender(r);if(!s?.track)return this.resultNoChanged;const i=await this.codecProvider.getCodecFromSender(s);if(re(i,this.ignoreForCodec))return this.resultNoChanged;const{mainCam:c,resolutionMainCam:a}=t??{};return this.processSender({mainCam:c,resolutionMainCam:a},{sender:s,codec:i,videoTrack:s.track})}async processSender(e,t){const{mainCam:r,resolutionMainCam:s}=e;switch(r){case o.EEventsMainCAM.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(t);case o.EEventsMainCAM.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(t);case o.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return s!==void 0?this.setResolutionSender(s,t):this.setBitrateByTrackResolution(t);case o.EEventsMainCAM.ADMIN_STOP_MAIN_CAM:case o.EEventsMainCAM.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(t);default:return this.setBitrateByTrackResolution(t)}}async downgradeResolutionSender(e){const{sender:t,codec:r}=e,s={scaleResolutionDownBy:200,maxBitrate:en(r)};return this.parametersSetter.setEncodingsToSender(t,s)}async setBitrateByTrackResolution(e){const{sender:t,videoTrack:r,codec:s}=e,c=r.getSettings().width,a=c===void 0?nn(s):q(c,s);return this.parametersSetter.setEncodingsToSender(t,{scaleResolutionDownBy:1,maxBitrate:a})}async setResolutionSender(e,t){const[r,s]=e.split("x"),{sender:i,videoTrack:c,codec:a}=t,d={width:Number(r),height:Number(s)},l=se({videoTrack:c,targetSize:d}),h=q(d.width,a),g={scaleResolutionDownBy:l,maxBitrate:h};return this.parametersSetter.setEncodingsToSender(i,g)}}const dn=n=>n.find(e=>e.track?.kind==="video");class un{findVideoSender(e){return dn(e)}}class ln{sipConnector;currentHandler;constructor(e){this.sipConnector=e}subscribe(e){this.currentHandler=e,this.sipConnector.on("api:main-cam-control",e)}unsubscribe(){this.currentHandler&&(this.sipConnector.off("api:main-cam-control",this.currentHandler),this.currentHandler=void 0)}getConnection(){return this.sipConnector.connection}}class ie{eventHandler;senderBalancer;parametersSetterWithQueue;serverHeaders;constructor(e,{ignoreForCodec:t,onSetParameters:r}={}){this.eventHandler=new ln(e),this.parametersSetterWithQueue=new cn(r),this.senderBalancer=new an({senderFinder:new un,codecProvider:new sn,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:t})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.parametersSetterWithQueue.stop(),this.reset()}reset(){delete this.serverHeaders}async reBalance(){return this.balanceByTrack()}async balanceByTrack(){const e=this.eventHandler.getConnection();if(!e)throw new Error("connection is not exist");return this.senderBalancer.balance(e,this.serverHeaders)}handleMainCamControl=e=>{this.serverHeaders=e,this.balanceByTrack().catch(B)}}const gn=(n,e={})=>new ie(n,e),hn=({videoTrack:n,targetSize:e,codec:t})=>{const r=se({videoTrack:n,targetSize:e}),s=q(e.width,t);return{scaleResolutionDownBy:r,maxBitrate:s}},O=({mediaStream:n,simulcastEncodings:e,sendEncodings:t})=>{if(e&&e.length>0){const r=t??[],s=je(n);if(s===void 0)throw new Error("No video track");return e.forEach((i,c)=>{const a=r[c]??{};a.active=!0,i.rid!==void 0&&(a.rid=i.rid),i.scalabilityMode!==void 0&&(a.scalabilityMode=i.scalabilityMode);const{maxBitrate:d,scaleResolutionDownBy:l}=hn({videoTrack:s,targetSize:{width:i.width,height:i.height}});a.maxBitrate=d,a.scaleResolutionDownBy=l,r[c]=a}),r}return t},Cn=(n,e)=>n.filter(r=>e.some(s=>s.clockRate===r.clockRate&&s.mimeType===r.mimeType&&s.channels===r.channels&&s.sdpFmtpLine===r.sdpFmtpLine)),Sn=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),r=e===null?[]:e.codecs,s=t===null?[]:t.codecs;return Cn(r,s)},fn=(n,e)=>e===void 0||e.length===0?n:n.sort((t,r)=>{const s=e.indexOf(t.mimeType),i=e.indexOf(r.mimeType),c=s===-1?Number.MAX_VALUE:s,a=i===-1?Number.MAX_VALUE:i;return c-a}),mn=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),pn=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>{if(typeof n.setCodecPreferences=="function"&&n.sender.track?.kind==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const r=Sn("video"),s=mn(r,t),i=fn(s,e);n.setCodecPreferences(i)}},w=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>async r=>{try{pn(r,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t}),Object.values(n).filter(i=>i!=null).length>0&&(o.logger("updateTransceiver setParametersToSender",n),await $(r.sender,n))}catch(s){o.logger("updateTransceiver error",s)}},H=n=>{if(!j.isCanceledError(n)&&!de.hasCanceledError(n))throw n;return{isSuccessful:!1}},Rn=({kind:n,readyState:e})=>n==="video"&&e==="live",Q=(n,e,{onEnterPurgatory:t,onEnterConference:r})=>{I(n)?t&&t():r&&r({isSuccessProgressCall:e})},J=(n,e)=>{n(),e&&e()},X=(n,e,t)=>{throw n&&n(),e(),t},En=new Set(["on","once","onceRace","wait","off","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class yn{on;once;onceRace;wait;off;sendDTMF;hangUp;declineToIncomingCall;sendChannels;checkTelephony;waitChannels;ping;connection;isConfigured;isRegistered;sipConnector;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor(e,{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:r}={}){return this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=r,this.sipConnector=e,new Proxy(this,{get:(s,i,c)=>{if(typeof i=="string"&&En.has(i)&&i in this.sipConnector){const d=Reflect.get(this.sipConnector,i,this.sipConnector);return typeof d=="function"?d.bind(this.sipConnector):d}const a=Reflect.get(s,i,c);return typeof a=="function"?a.bind(s):a}})}connectToServer=async e=>{const{userAgent:t,sipWebSocketServerURL:r,sipServerUrl:s,remoteAddress:i,displayName:c,name:a,password:d,isRegisteredUser:l,isDisconnectOnFail:h}=e;return o.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:r,sipServerUrl:s,remoteAddress:i,displayName:c,password:d,user:a,register:l}).then(g=>(o.logger("connectToServer then"),{ua:g,isSuccessful:!0})).catch(async g=>(o.logger("connectToServer catch: error",g),h===!0?this.sipConnector.disconnect().then(()=>H(g)).catch(()=>H(g)):H(g)))};callToServer=async e=>{const{conference:t,mediaStream:r,extraHeaders:s,iceServers:i,contentHint:c,simulcastEncodings:a,degradationPreference:d,sendEncodings:l,offerToReceiveAudio:h,offerToReceiveVideo:g,directionVideo:D,directionAudio:k,setRemoteStreams:C,onBeforeProgressCall:f,onSuccessProgressCall:m,onEnterPurgatory:p,onEnterConference:R,onFailProgressCall:v,onFinishProgressCall:T,onEndedCall:M}=e,b=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:C}),P=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{b().catch(B)}}),A=w({degradationPreference:d},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});o.logger("callToServer",e);const _=async()=>(o.logger("startCall"),this.sipConnector.call({mediaStream:r,extraHeaders:s,iceServers:i,contentHint:c,offerToReceiveAudio:h,offerToReceiveVideo:g,directionVideo:D,directionAudio:k,sendEncodings:O({mediaStream:r,simulcastEncodings:a,sendEncodings:l}),number:t,onAddedTransceiver:A,ontrack:P}));let E=!1,y;const N=(o.logger("subscribeEnterConference: onEnterConference",R),this.sipConnector.on("api:enterRoom",({room:u})=>{o.logger("enterRoom",{_room:u,isSuccessProgressCall:E}),y=u,(p??R)&&Q(y,E,{onEnterPurgatory:p,onEnterConference:R})})),x=u=>(o.logger("onSuccess"),E=!0,b().catch(B),m&&m({isPurgatory:I(y)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{J(N,M)}),u),U=u=>(o.logger("onFail"),X(v,N,u)),V=()=>{o.logger("onFinish"),T&&T()};return o.logger("onBeforeProgressCall"),f&&f(t),_().then(x).catch(u=>U(u)).finally(V)};disconnectFromServer=async()=>this.sipConnector.disconnect().then(()=>(o.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(e=>(o.logger("disconnectFromServer: catch",e),{isSuccessful:!1}));answerToIncomingCall=async e=>{const{mediaStream:t,extraHeaders:r,iceServers:s,contentHint:i,simulcastEncodings:c,degradationPreference:a,sendEncodings:d,offerToReceiveAudio:l,offerToReceiveVideo:h,directionVideo:g,directionAudio:D,setRemoteStreams:k,onBeforeProgressCall:C,onSuccessProgressCall:f,onEnterPurgatory:m,onEnterConference:p,onFailProgressCall:R,onFinishProgressCall:v,onEndedCall:T}=e,M=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:k}),b=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{M().catch(B)}}),P=w({degradationPreference:a},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});o.logger("answerToIncomingCall",e);const A=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:r,iceServers:s,contentHint:i,offerToReceiveAudio:l,offerToReceiveVideo:h,directionVideo:g,directionAudio:D,sendEncodings:O({mediaStream:t,simulcastEncodings:c,sendEncodings:d}),onAddedTransceiver:P,ontrack:b}),_=()=>{const{remoteCallerData:u}=this.sipConnector;return u.incomingNumber};let E=!1,y;const N=(o.logger("subscribeEnterConference: onEnterConference",p),this.sipConnector.on("api:enterRoom",u=>{o.logger("enterRoom",{_room:u,isSuccessProgressCall:E}),y=u,(m??p)&&Q(y,E,{onEnterPurgatory:m,onEnterConference:p})})),x=u=>(o.logger("onSuccess"),E=!0,M().catch(B),f&&f({isPurgatory:I(y)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{J(N,T)}),u),U=u=>(o.logger("onFail"),X(R,N,u)),V=()=>{o.logger("onFinish"),v&&v()};if(o.logger("onBeforeProgressCall"),C){const u=_();C(u)}return A().then(x).catch(u=>U(u)).finally(V)};updatePresentation=async({mediaStream:e,isP2P:t,maxBitrate:r,contentHint:s,simulcastEncodings:i,degradationPreference:c,sendEncodings:a,preferredMimeTypesVideoCodecs:d,excludeMimeTypesVideoCodecs:l})=>{const h=w({degradationPreference:c},{preferredMimeTypesVideoCodecs:d,excludeMimeTypesVideoCodecs:l});return o.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,maxBitrate:r,contentHint:s,sendEncodings:O({mediaStream:e,simulcastEncodings:i,sendEncodings:a}),onAddedTransceiver:h})};startPresentation=async({mediaStream:e,isP2P:t,maxBitrate:r,contentHint:s,simulcastEncodings:i,degradationPreference:c,sendEncodings:a,preferredMimeTypesVideoCodecs:d,excludeMimeTypesVideoCodecs:l,callLimit:h})=>{const g=w({degradationPreference:c},{preferredMimeTypesVideoCodecs:d,excludeMimeTypesVideoCodecs:l});return o.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,maxBitrate:r,contentHint:s,callLimit:h,sendEncodings:O({mediaStream:e,simulcastEncodings:i,sendEncodings:a}),onAddedTransceiver:g})};stopShareSipConnector=async({isP2P:e=!1}={})=>(o.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{o.logger(t)}));sendRefusalToTurnOnMic=async()=>{o.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{o.logger("sendRefusalToTurnOnMic: error",e)})};sendRefusalToTurnOnCam=async()=>{o.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{o.logger("sendRefusalToTurnOnCam: error",e)})};sendMediaState=async({isEnabledCam:e,isEnabledMic:t})=>{o.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:e,mic:t})};replaceMediaStream=async(e,{deleteExisting:t,addMissing:r,forceRenegotiation:s,contentHint:i,simulcastEncodings:c,degradationPreference:a,sendEncodings:d})=>{const l=w({degradationPreference:a},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});return o.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:r,forceRenegotiation:s,contentHint:i,sendEncodings:O({mediaStream:e,simulcastEncodings:c,sendEncodings:d}),onAddedTransceiver:l})};askPermissionToEnableCam=async()=>{o.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam()};resolveHandleReadyRemoteStreamsDebounced=({onReadyRemoteStreams:e})=>ue.debounce(()=>{const t=this.sipConnector.getRemoteStreams();o.logger("remoteStreams",t),t&&e(t)},200);resolveHandleReadyRemoteStreams=({onReadyRemoteStreams:e})=>({track:t})=>{Rn(t)&&e()};getRemoteStreams=()=>(o.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams());onUseLicense=e=>(o.logger("onUseLicense"),this.sipConnector.on("api:useLicense",e));onMustStopPresentation=e=>(o.logger("onMustStopPresentation"),this.sipConnector.on("api:mustStopPresentation",e));onMoveToSpectators=e=>(o.logger("onMoveToSpectators"),this.sipConnector.on("api:participant:move-request-to-spectators",e));onMoveToParticipants=e=>(o.logger("onMoveToParticipants"),this.sipConnector.on("api:participant:move-request-to-participants",e));onStats=e=>(o.logger("onStats"),this.sipConnector.on("stats:collected",e));offStats=e=>{o.logger("offStats"),this.sipConnector.off("stats:collected",e)}}var ce=(n=>(n.VP8="video/VP8",n.VP9="video/VP9",n.H264="video/H264",n.AV1="video/AV1",n.rtx="video/rtx",n.red="video/red",n.flexfec03="video/flexfec-03",n))(ce||{});exports.ECallCause=o.ECallCause;exports.EStatsTypes=o.EStatsTypes;exports.EUseLicense=o.EUseLicense;exports.SipConnector=o.SipConnector;exports.StatsPeerConnection=o.StatsPeerConnection;exports.disableDebug=o.disableDebug;exports.enableDebug=o.enableDebug;exports.hasCanceledStartPresentationError=o.hasCanceledStartPresentationError;exports.debug=B;exports.EMimeTypesVideoCodecs=ce;exports.SipConnectorFacade=yn;exports.VideoSendingBalancer=ie;exports.getCodecFromSender=oe;exports.hasAvailableStats=Xe;exports.hasCanceledCallError=Se;exports.resolveVideoSendingBalancer=gn;exports.tools=Je;
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export type { TContentHint } from './PresentationManager';
7
7
  export { SipConnector } from './SipConnector';
8
8
  export { SipConnectorFacade } from './SipConnectorFacade';
9
9
  export { EStatsTypes, hasAvailableStats, StatsPeerConnection } from './StatsPeerConnection';
10
+ export type { TInboundStats, TOutboundStats } from './StatsPeerConnection';
10
11
  export * as tools from './tools';
11
12
  export { EMimeTypesVideoCodecs } from './types';
12
13
  export type { TJsSIP } from './types';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import "events-constructor";
2
- import { E as R, O as ae, l as i, p as de, a as O } from "./@SipConnector-BEZk1hmx.js";
3
- import { c as xn, b as Un, S as Vn, f as Ln, d as Hn, e as $n, h as Wn } from "./@SipConnector-BEZk1hmx.js";
2
+ import { E as R, O as ae, l as i, p as de, a as O } from "./@SipConnector-5Rac5oq2.js";
3
+ import { c as xn, b as Un, S as Vn, f as Ln, d as Hn, e as $n, h as Wn } from "./@SipConnector-5Rac5oq2.js";
4
4
  import { isCanceledError as Y } from "@krivega/cancelable-promise";
5
5
  import { hasCanceledError as ue } from "repeated-calls";
6
6
  import { debounce as le } from "ts-debounce";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sip-connector",
3
- "version": "15.2.0",
3
+ "version": "15.3.1",
4
4
  "description": "Module for connect to Vinteo server",
5
5
  "keywords": [
6
6
  "webrtc",
@@ -57,7 +57,7 @@
57
57
  },
58
58
  "dependencies": {
59
59
  "@krivega/cancelable-promise": "^1.1.4",
60
- "@krivega/jssip": "^5.1.2",
60
+ "@krivega/jssip": "^5.1.3",
61
61
  "@krivega/timeout-requester": "^1.0.0",
62
62
  "debug": "^4.4.1",
63
63
  "events-constructor": "^2.0.0",
@@ -97,7 +97,7 @@
97
97
  },
98
98
  "peerDependencies": {
99
99
  "@krivega/cancelable-promise": "^1.1.4",
100
- "@krivega/jssip": "^5.1.2",
100
+ "@krivega/jssip": "^5.1.3",
101
101
  "@krivega/timeout-requester": "^1.0.0",
102
102
  "debug": "^4.4.1",
103
103
  "events-constructor": "^2.0.0",