sip-connector 6.22.0 → 6.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ "use strict";var Rt=Object.defineProperty;var It=(r,e,t)=>e in r?Rt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var i=(r,e,t)=>(It(r,typeof e!="symbol"?e+"":e,t),t);const T=require("@krivega/cancelable-promise"),pe=require("events-constructor"),B=require("debug"),mt="Connection Error",He="Request Timeout",ft="SIP Failure Code",Ot="Internal Error",Dt="Busy",V="Rejected",Mt="Redirected",Pt="Unavailable",qe="Not Found",pt="Address Incomplete",vt="Incompatible SDP",bt="Missing SDP",wt="Authentication Error",ke="Terminated",yt="WebRTC Error",Fe="Canceled",Ut="No Answer",Lt="Expires",Ht="No ACK",qt="Dialog Error",kt="User Denied Media Access",We="Bad Media Description",Ft="RTP Timeout",Wt=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:pt,AUTHENTICATION_ERROR:wt,BAD_MEDIA_DESCRIPTION:We,BUSY:Dt,BYE:ke,CANCELED:Fe,CONNECTION_ERROR:mt,DIALOG_ERROR:qt,EXPIRES:Lt,INCOMPATIBLE_SDP:vt,INTERNAL_ERROR:Ot,MISSING_SDP:bt,NOT_FOUND:qe,NO_ACK:Ht,NO_ANSWER:Ut,REDIRECTED:Mt,REJECTED:V,REQUEST_TIMEOUT:He,RTP_TIMEOUT:Ft,SIP_FAILURE_CODE:ft,UNAVAILABLE:Pt,USER_DENIED_MEDIA_ACCESS:kt,WEBRTC_ERROR:yt},Symbol.toStringTag,{value:"Module"})),Y="incomingCall",x="declinedIncomingCall",G="failedIncomingCall",$="terminatedIncomingCall",L="connecting",O="connected",N="disconnected",D="newRTCSession",A="registered",X="unregistered",R="registrationFailed",Be="newMessage",J="sipEvent",z="availableSecondRemoteStream",Q="notAvailableSecondRemoteStream",K="mustStopPresentation",M="shareState",j="enterRoom",Z="useLicense",ee="peerconnection:confirmed",te="peerconnection:ontrack",P="channels",se="channels:notify",ne="ended:fromserver",ie="main-cam-control",re="admin-stop-main-cam",oe="admin-start-main-cam",ae="admin-stop-mic",ce="admin-start-mic",p="admin-force-sync-media-state",Ee="participant:added-to-list-moderators",_e="participant:removed-from-list-moderators",he="participant:move-request-to-stream",de="participation:accepting-word-request",le="participation:cancelling-word-request",ue="webcast:started",Te="webcast:stopped",Se="account:changed",Ne="account:deleted",Ce="conference:participant-token-issued",I="ended",Ve="sending",Ye="reinvite",xe="replaces",Ge="refer",$e="progress",Xe="accepted",v="confirmed",b="peerconnection",C="failed",Je="muted",ze="unmuted",ge="newDTMF",Ae="newInfo",Qe="hold",Ke="unhold",je="update",Ze="sdp",et="icecandidate",tt="getusermediafailed",st="peerconnection:createofferfailed",nt="peerconnection:createanswerfailed",it="peerconnection:setlocaldescriptionfailed",rt="peerconnection:setremotedescriptionfailed",ot="presentation:start",at="presentation:started",ct="presentation:end",Re="presentation:ended",w="presentation:failed",Bt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:Xe,ACCOUNT_CHANGED:Se,ACCOUNT_DELETED:Ne,ADMIN_FORCE_SYNC_MEDIA_STATE:p,ADMIN_START_MAIN_CAM:oe,ADMIN_START_MIC:ce,ADMIN_STOP_MAIN_CAM:re,ADMIN_STOP_MIC:ae,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:z,CHANNELS:P,CHANNELS_NOTIFY:se,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Ce,CONFIRMED:v,CONNECTED:O,CONNECTING:L,DECLINED_INCOMING_CALL:x,DISCONNECTED:N,ENDED:I,ENDED_FROM_SERVER:ne,ENTER_ROOM:j,FAILED:C,FAILED_INCOMING_CALL:G,GET_USER_MEDIA_FAILED:tt,HOLD:Qe,ICE_CANDIDATE:et,INCOMING_CALL:Y,MAIN_CAM_CONTROL:ie,MUST_STOP_PRESENTATION_EVENT:K,MUTED:Je,NEW_DTMF:ge,NEW_INFO:Ae,NEW_MESSAGE:Be,NEW_RTC_SESSION:D,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:Q,PARTICIPANT_ADDED_TO_LIST_MODERATORS:Ee,PARTICIPANT_MOVE_REQUEST_TO_STREAM:he,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:_e,PARTICIPATION_ACCEPTING_WORD_REQUEST:de,PARTICIPATION_CANCELLING_WORD_REQUEST:le,PEER_CONNECTION:b,PEER_CONNECTION_CONFIRMED:ee,PEER_CONNECTION_CREATE_ANSWER_FAILED:nt,PEER_CONNECTION_CREATE_OFFER_FAILED:st,PEER_CONNECTION_ONTRACK:te,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:it,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:rt,PRESENTATION_END:ct,PRESENTATION_ENDED:Re,PRESENTATION_FAILED:w,PRESENTATION_START:ot,PRESENTATION_STARTED:at,PROGRESS:$e,REFER:Ge,REGISTERED:A,REGISTRATION_FAILED:R,REINVITE:Ye,REPLACES:xe,SDP:Ze,SENDING:Ve,SHARE_STATE:M,SIP_EVENT:J,TERMINATED_INCOMING_CALL:$,UNHOLD:Ke,UNMUTED:ze,UNREGISTERED:X,UPDATE:je,USE_LICENSE:Z,WEBCAST_STARTED:ue,WEBCAST_STOPPED:Te},Symbol.toStringTag,{value:"Module"})),Et=[Y,x,$,G,de,le,he,se,Ce,Se,Ne,ue,Te,Ee,_e],Ie=[L,O,N,D,A,X,R,Be,J],_t=[z,Q,K,M,j,Z,ee,te,P,ne,ie,oe,re,ae,ce,p],me=[I,L,Ve,Ye,xe,Ge,$e,Xe,v,b,C,Je,ze,ge,Ae,Qe,Ke,je,Ze,et,tt,st,nt,it,rt,ot,at,ct,Re,w],fe=[...Ie,...Et],Oe=[...me,..._t],Vt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:Oe,SESSION_JSSIP_EVENT_NAMES:me,SESSION_SYNTHETICS_EVENT_NAMES:_t,UA_EVENT_NAMES:fe,UA_JSSIP_EVENT_NAMES:Ie,UA_SYNTHETICS_EVENT_NAMES:Et},Symbol.toStringTag,{value:"Module"})),Yt=r=>{const e=[];return r&&e.push(`X-Vinteo-Remote: ${r}`),e},xt="content-type",Gt="x-webrtc-enter-room",q="application/vinteo.webrtc.sharedesktop",$t="application/vinteo.webrtc.roomname",Xt="application/vinteo.webrtc.channels",Jt="application/vinteo.webrtc.mediastate",zt="application/vinteo.webrtc.refusal",ve="application/vinteo.webrtc.maincam",Qt="application/vinteo.webrtc.mic",Kt="application/vinteo.webrtc.uselic",jt="X-WEBRTC-USE-LICENSE",be="X-WEBRTC-INPUT-CHANNELS",we="X-WEBRTC-OUTPUT-CHANNELS",Zt="X-WEBRTC-MAINCAM",es="X-WEBRTC-MIC",ye="X-WEBRTC-SYNC",ts="X-WEBRTC-MAINCAM-RESOLUTION",ss="X-WEBRTC-MEDIA-STATE",ns="X-Vinteo-Media-Type",is="X-Vinteo-MainCam-State",rs="X-Vinteo-Mic-State",os="application/vinteo.webrtc.notify",as="X-VINTEO-NOTIFY",m="x-webrtc-share-state",cs=`${m}: LETMESTARTPRESENTATION`,Es=`${m}: STOPPRESENTATION`,ht="YOUCANRECEIVECONTENT",dt="CONTENTEND",_s="YOUMUSTSTOPSENDCONTENT",hs=`${m}: ${ht}`,ds=`${m}: ${dt}`,ls="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",us=`${ls}: LETMESTARTMAINCAM`,De="sip-connector",F=B(De),Ts=()=>{B.enable(De)},Ss=()=>{B.enable(`-${De}`)};var g=(r=>(r.PAUSE_MAIN_CAM="PAUSEMAINCAM",r.RESUME_MAIN_CAM="RESUMEMAINCAM",r.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",r.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",r.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",r))(g||{}),y=(r=>(r.ADMIN_STOP_MIC="ADMINSTOPMIC",r.ADMIN_START_MIC="ADMINSTARTMIC",r))(y||{}),U=(r=>(r.ADMIN_SYNC_FORCED="1",r.ADMIN_SYNC_NOT_FORCED="0",r))(U||{}),lt=(r=>(r.AUDIO="AUDIO",r.VIDEO="VIDEO",r.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",r))(lt||{});function Ns(r){return e=>`sip:${e}@${r}`}const Cs=(r,e)=>()=>Math.floor(Math.random()*(e-r))+r,Ue=r=>r.trim().replaceAll(" ","_"),gs=Cs(1e5,99999999),k=(r,{videoMode:e,audioMode:t}={})=>{if(!r||e==="recvonly"&&t==="recvonly")return;const s=t==="recvonly"?[]:r.getAudioTracks(),n=e==="recvonly"?[]:r.getVideoTracks(),o=[...s,...n],a=new MediaStream(o);return a.getTracks=()=>[...a.getAudioTracks(),...a.getVideoTracks()],a},As=r=>r.some(t=>{const{kind:s}=t;return s==="video"}),Rs="Error decline with 603",Is=r=>r.message===Rs,ms=(r,e)=>r.find(t=>t.track&&e.getTracks().includes(t.track)),ut=1,Tt=r=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==r,fs=Tt(ut),Os=(r,e)=>{const t=r===void 0?void 0:Math.max(r,ut);if(t!==void 0&&fs(t,e))return t},Ds=Tt(),Ms=(r,e)=>{if(Ds(r,e))return r},St=async(r,e,t)=>{const s=r.getParameters();(s.encodings===void 0||s.encodings.length===0)&&(s.encodings=[{}]);const[n]=s.encodings,o=n.scaleResolutionDownBy,a=Os(e.scaleResolutionDownBy,o);let c=!1;a!==void 0&&(s.encodings[0].scaleResolutionDownBy=a,c=!0);const E=n.maxBitrate,_=Ms(e.maxBitrate,E);return _!==void 0&&(s.encodings[0].maxBitrate=_,c=!0),c?(t&&t(s),r.setParameters(s).then(()=>({parameters:s,isChanged:c}))):{parameters:s,isChanged:c}},Ps=async(r,e,t)=>{const s=ms(r,e);if(s)return St(s,{maxBitrate:t})},ps=486,vs=487,W="local",Le="remote",bs=(r=new Error)=>{const{originator:e,cause:t}=r;return T.isCanceledError(r)?!0:typeof t=="string"?t===He||t===V||e===W&&(t===Fe||t===ke):!1},S="SipConnector",ws="channels",ys="WebcastStarted",Us="WebcastStopped",Ls="accountChanged",Hs="accountDeleted",qs="addedToListModerators",ks="removedFromListModerators",Fs="ParticipationRequestAccepted",Ws="ParticipationRequestRejected",Bs="ParticipantMovedToWebcast",Vs="ConferenceParticipantTokenIssued";class Ys{constructor({JsSIP:e}){i(this,"_isRegisterConfig",!1);i(this,"_connectionConfiguration",{});i(this,"_remoteStreams",{});i(this,"JsSIP");i(this,"_sessionEvents");i(this,"_uaEvents");i(this,"_cancelableConnect");i(this,"_cancelableCreateUa");i(this,"_cancelableDisconnect");i(this,"_cancelableSet");i(this,"_cancelableCall");i(this,"_cancelableAnswer");i(this,"_cancelableSendDTMF");i(this,"getSipServerUrl",e=>e);i(this,"promisePendingStartPresentation");i(this,"promisePendingStopPresentation");i(this,"ua");i(this,"session");i(this,"incomingSession");i(this,"_streamPresentationCurrent");i(this,"socket");i(this,"connect",async e=>(this._cancelRequests(),this._cancelableConnect.request(e)));i(this,"createUa",async e=>this._cancelableCreateUa.request(e));i(this,"set",async e=>this._cancelableSet.request(e));i(this,"call",async e=>this._cancelableCall.request(e));i(this,"disconnect",async()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()));i(this,"answerToIncomingCall",async e=>this._cancelableAnswer.request(e));i(this,"sendDTMF",async e=>this._cancelableSendDTMF.request(e));i(this,"hangUp",async()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()));i(this,"tryRegister",async()=>{if(!this.isRegisterConfig)throw new Error("Config is not registered");this._uaEvents.trigger(L,void 0);try{await this.unregister()}catch(e){F("tryRegister",e)}return this.register()});i(this,"declineToIncomingCall",async({statusCode:e=vs}={})=>new Promise((t,s)=>{if(!this.isAvailableIncomingCall){s(new Error("no incomingSession"));return}const n=this.incomingSession,o=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(x,o),t(n.terminate({status_code:e}))}));i(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:ps}));i(this,"removeIncomingSession",()=>{delete this.incomingSession});i(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===Le){this.incomingSession=t;const s=this.remoteCallerData;t.on(C,n=>{this.removeIncomingSession(),n.originator===W?this._uaEvents.trigger($,s):this._uaEvents.trigger(G,s)}),this._uaEvents.trigger(Y,s)}});i(this,"_connect",async e=>this.createUa(e).then(async()=>this._start()));i(this,"_createUa",async({displayName:e="",user:t,password:s,register:n=!1,sipServerUrl:o,sipWebSocketServerURL:a,remoteAddress:c,extraHeaders:E=[],sdpSemantics:_="plan-b",sessionTimers:h=!1,registerExpires:d=60*5,connectionRecoveryMinInterval:l=2,connectionRecoveryMaxInterval:u=6,userAgent:f})=>{if(!o)throw new Error("sipServerUrl is required");if(!a)throw new Error("sipWebSocketServerURL is required");if(n&&!t)throw new Error("user is required for authorized connection");if(n&&!s)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:o,displayName:e,register:n,user:t,password:s},this._init({sipServerUrl:o,sipWebSocketServerURL:a});const H=n&&t?t.trim():`${gs()}`,Me={password:s,register:n,display_name:Ue(e),user_agent:f,sdp_semantics:_,sockets:[this.socket],uri:this.getSipServerUrl(H),session_timers:h,register_expires:d,connection_recovery_min_interval:l,connection_recovery_max_interval:u};this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!Me.register,this.ua=new this.JsSIP.UA(Me),this._uaEvents.eachTriggers((Ct,gt)=>{const Pe=Ie.find(At=>At===gt);Pe&&this.ua&&this.ua.on(Pe,Ct)});const Nt=[...Yt(c),...E];return this.ua.registrator().setExtraHeaders(Nt),this.ua});i(this,"_start",async()=>new Promise((e,t)=>{const{ua:s}=this;if(!s){t(new Error("this.ua is not initialized"));return}const n=()=>{c(),e(s)},o=E=>{c(),t(E)},a=()=>{this.isRegisterConfig?(this.on(A,n),this.on(R,o)):this.on(O,n),this.on(N,o)},c=()=>{this.off(A,n),this.off(R,o),this.off(O,n),this.off(N,o)};a(),this.on(D,this.handleNewRTCSession),s.start()}));i(this,"_set",async({displayName:e,password:t})=>new Promise((s,n)=>{const{ua:o}=this;if(!o){n(new Error("this.ua is not initialized"));return}let a=!1,c=!1;e!==void 0&&e!==this._connectionConfiguration.displayName&&(a=o.set("display_name",Ue(e)),this._connectionConfiguration.displayName=e),t!==void 0&&t!==this._connectionConfiguration.password&&(c=o.set("password",t),this._connectionConfiguration.password=t);const E=a||c;c&&this.isRegisterConfig?this.register().then(()=>{s(E)}).catch(n):E?s(E):n(new Error("nothing changed"))}));i(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());i(this,"_disconnect",async()=>{this.off(D,this.handleNewRTCSession);const e=new Promise(t=>{this.once(N,()=>{delete this.ua,t()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(N,void 0)):this._uaEvents.trigger(N,void 0),e});i(this,"_call",async({number:e,mediaStream:t,extraHeaders:s=[],ontrack:n,iceServers:o,videoMode:a,audioMode:c,degradationPreference:E,offerToReceiveAudio:_=!0,offerToReceiveVideo:h=!0})=>new Promise((d,l)=>{const{ua:u}=this;if(!u){l(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:n}).then(d).catch(l),this.session=u.call(this.getSipServerUrl(e),{extraHeaders:s,mediaStream:k(t,{videoMode:a,audioMode:c}),eventHandlers:this._sessionEvents.triggers,videoMode:a,audioMode:c,degradationPreference:E,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:_,offerToReceiveVideo:h}})}));i(this,"_answer",async({mediaStream:e,ontrack:t,extraHeaders:s=[],iceServers:n,videoMode:o,audioMode:a,degradationPreference:c})=>new Promise((E,_)=>{if(!this.isAvailableIncomingCall){_(new Error("no incomingSession"));return}this.session=this.incomingSession,this.removeIncomingSession();const{session:h}=this;if(!h){_(new Error("No session established"));return}this._sessionEvents.eachTriggers((l,u)=>{const f=me.find(H=>H===u);f&&h.on(f,l)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=h.remote_identity.uri.user,this._handleCall({ontrack:t}).then(E).catch(_);const d=k(e,{videoMode:o,audioMode:a});h.answer({extraHeaders:s,videoMode:o,audioMode:a,degradationPreference:c,mediaStream:d,pcConfig:{iceServers:n}})}));i(this,"_handleCall",async({ontrack:e})=>new Promise((t,s)=>{const n=()=>{this.onSession(b,h),this.onSession(v,d)},o=()=>{this.offSession(b,h),this.offSession(v,d)},a=()=>{this.onSession(C,E),this.onSession(I,E)},c=()=>{this.offSession(C,E),this.offSession(I,E)},E=l=>{o(),c(),s(l)};let _;const h=({peerconnection:l})=>{_=l,_.ontrack=u=>{this._sessionEvents.trigger(te,_),e&&e(u)}},d=()=>{_&&this._sessionEvents.trigger(ee,_),o(),c(),t(_)};n(),a()}));i(this,"_restoreSession",()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}});i(this,"_sendDTMF",async e=>new Promise((t,s)=>{const{session:n}=this;if(!n){s(new Error("No session established"));return}this.onceSession(ge,({originator:o})=>{o===W&&t()}),n.sendDTMF(e,{duration:120,interToneGap:600})}));i(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.session){const{session:e}=this;this._streamPresentationCurrent&&await this.stopPresentation(),this._restoreSession(),e.isEnded()||e.terminate()}});i(this,"_handleShareState",e=>{switch(e){case ht:{this._sessionEvents.trigger(z,void 0);break}case dt:{this._sessionEvents.trigger(Q,void 0);break}case _s:{this._sessionEvents.trigger(K,void 0);break}}});i(this,"_maybeTriggerChannels",e=>{const t=e.getHeader(be),s=e.getHeader(we);if(t&&s){const n={inputChannels:t,outputChannels:s};this._sessionEvents.trigger(P,n)}});i(this,"_handleNotify",e=>{switch(e.cmd){case ws:{const t=e;this._triggerChannelsNotify(t);break}case ys:{const t=e;this._triggerWebcastStartedNotify(t);break}case Us:{const t=e;this._triggerWebcastStoppedNotify(t);break}case qs:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case ks:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case Fs:{const t=e;this._triggerParticipationAcceptingWordRequest(t);break}case Ws:{const t=e;this._triggerParticipationCancellingWordRequest(t);break}case Bs:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case Ls:{this._triggerAccountChangedNotify();break}case Hs:{this._triggerAccountDeletedNotify();break}case Vs:{const t=e;this._triggerConferenceParticipantTokenIssued(t);break}default:F("unknown cmd",e.cmd)}});i(this,"_triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(_e,t)});i(this,"_triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(Ee,t)});i(this,"_triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(ue,s)});i(this,"_triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(Te,s)});i(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(Se,void 0)});i(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(Ne,void 0)});i(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:s}})=>{const n={conference:e,participant:t,jwt:s};this._uaEvents.trigger(Ce,n)});i(this,"_triggerChannelsNotify",e=>{const t=e.input,s=e.output,n={inputChannels:t,outputChannels:s};this._uaEvents.trigger(se,n)});i(this,"_triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(de,t)});i(this,"_triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(le,t)});i(this,"_triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(he,t)});i(this,"_triggerEnterRoom",e=>{const t=e.getHeader(Gt);this._sessionEvents.trigger(j,t)});i(this,"_triggerShareState",e=>{const t=e.getHeader(m);this._sessionEvents.trigger(M,t)});i(this,"_triggerMainCamControl",e=>{const t=e.getHeader(Zt),s=e.getHeader(ye),n=s===U.ADMIN_SYNC_FORCED;if(t===g.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger(oe,{isSyncForced:n});else if(t===g.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger(re,{isSyncForced:n});else if((t===g.RESUME_MAIN_CAM||t===g.PAUSE_MAIN_CAM)&&s)this._sessionEvents.trigger(p,{isSyncForced:n});else{const o=e.getHeader(ts);this._sessionEvents.trigger(ie,{mainCam:t,resolutionMainCam:o})}});i(this,"_triggerMicControl",e=>{const t=e.getHeader(es),n=e.getHeader(ye)===U.ADMIN_SYNC_FORCED;t===y.ADMIN_START_MIC?this._sessionEvents.trigger(ce,{isSyncForced:n}):t===y.ADMIN_STOP_MIC&&this._sessionEvents.trigger(ae,{isSyncForced:n})});i(this,"_triggerUseLicense",e=>{const t=e.getHeader(jt);this._sessionEvents.trigger(Z,t)});i(this,"_handleNewInfo",e=>{const{originator:t}=e;if(t!=="remote")return;const{request:s}=e,n=s.getHeader(xt);if(n)switch(n){case $t:{this._triggerEnterRoom(s),this._maybeTriggerChannels(s);break}case os:{this._maybeHandleNotify(s);break}case q:{this._triggerShareState(s);break}case ve:{this._triggerMainCamControl(s);break}case Qt:{this._triggerMicControl(s);break}case Kt:{this._triggerUseLicense(s);break}}});i(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});i(this,"_maybeHandleNotify",e=>{const t=e.getHeader(as);if(t){const s=JSON.parse(t);this._handleNotify(s)}});i(this,"_handleEnded",e=>{const{originator:t}=e;t===Le&&this._sessionEvents.trigger(ne,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new pe(Oe),this._uaEvents=new pe(fe),this._cancelableConnect=new T.CancelableRequest(this._connect,{moduleName:S,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new T.CancelableRequest(this._createUa,{moduleName:S}),this._cancelableDisconnect=new T.CancelableRequest(this._disconnect,{moduleName:S}),this._cancelableSet=new T.CancelableRequest(this._set,{moduleName:S}),this._cancelableCall=new T.CancelableRequest(this._call,{moduleName:S}),this._cancelableAnswer=new T.CancelableRequest(this._answer,{moduleName:S}),this._cancelableSendDTMF=new T.CancelableRequest(this._sendDTMF,{moduleName:S}),this.onSession(M,this._handleShareState),this.onSession(Ae,this._handleNewInfo),this.on(J,this._handleSipEvent),this.onSession(C,this._handleEnded),this.onSession(I,this._handleEnded)}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(A,e),this.ua.on(R,t),this.ua.register()):t(new Error("Config is not registered"))})}async unregister(){return new Promise((e,t)=>{this.isRegistered&&this.ua?(this.ua.on(X,e),this.ua.unregister()):t(new Error("ua is not registered"))})}async sendOptions(e,t,s){if(!this.ua)throw new Error("is not connected");return new Promise((n,o)=>{try{this.ua.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{n()},failed:o}})}catch(a){o(a)}})}async ping(e,t){var n;if(!((n=this.ua)!=null&&n.configuration.uri))throw new Error("is not connected");const s=this.ua.configuration.uri;return this.sendOptions(s,e,t)}async replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}async askPermissionToEnableCam(e={}){if(!this.session)throw new Error("No session established");const t=[us];return this.session.sendInfo(ve,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(s=>{if(Is(s))throw s})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async _sendPresentation(e,t,{maxBitrate:s,degradationPreference:n,isNeedReinvite:o=!0,isP2P:a=!1}){const c=k(t);this._streamPresentationCurrent=c;const E=a?[hs]:[cs],_=e.sendInfo(q,void 0,{extraHeaders:E}).then(async()=>e.startPresentation(c,o,n)).then(async()=>{const{connection:h}=this;if(!h||s===void 0)return;const d=h.getSenders();return Ps(d,t,s)}).then(()=>t).catch(h=>{throw this._sessionEvents.trigger(w,h),h});return this.promisePendingStartPresentation=_,_.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t=!0,isP2P:s=!1,maxBitrate:n,degradationPreference:o}={}){const a=this.establishedSession;if(!a)throw new Error("No session established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return this._sendPresentation(a,e,{isNeedReinvite:t,isP2P:s,maxBitrate:n,degradationPreference:o})}async stopPresentation({isP2P:e=!1}={}){const t=this._streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve();const n=e?[ds]:[Es],o=this.establishedSession;return o&&t&&(s=s.then(async()=>o.sendInfo(q,void 0,{extraHeaders:n})).then(async()=>o.stopPresentation(t)).catch(a=>{throw this._sessionEvents.trigger(w,a),a})),!o&&t&&this._sessionEvents.trigger(Re,t),this.promisePendingStopPresentation=s,s.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t=!1,maxBitrate:s,degradationPreference:n}={}){const o=this.establishedSession;if(!o)throw new Error("No session established");if(!this._streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this._sendPresentation(o,e,{isP2P:t,maxBitrate:s,degradationPreference:n,isNeedReinvite:!1})}_resetPresentation(){delete this._streamPresentationCurrent,this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}async wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){return this._sessionEvents.on(e,t)}onceSession(e,t){return this._sessionEvents.once(e,t)}onceRaceSession(e,t){return this._sessionEvents.onceRace(e,t)}async waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return{...this._connectionConfiguration}}getRemoteStreams(){if(!this.connection)return;const t=this.connection.getReceivers().map(({track:s})=>s);return As(t)?this._generateStreams(t):this._generateAudioStreams(t)}get connection(){var t;return(t=this.session)==null?void 0:t.connection}get remoteCallerData(){var e,t,s,n,o,a;return{displayName:(t=(e=this.incomingSession)==null?void 0:e.remote_identity)==null?void 0:t.display_name,host:(n=(s=this.incomingSession)==null?void 0:s.remote_identity)==null?void 0:n.uri.host,incomingNumber:(a=(o=this.incomingSession)==null?void 0:o.remote_identity)==null?void 0:a.uri.user,session:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){return this.session&&this.session.isEstablished()?this.session:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!!(this.ua&&this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_init({sipServerUrl:e,sipWebSocketServerURL:t}){this.getSipServerUrl=Ns(e),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const{id:s}=e,n=this._remoteStreams[s]||new MediaStream;return t&&n.addTrack(t),n.addTrack(e),this._remoteStreams[s]=n,n}_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,n)=>{if(s.kind==="audio")return;const o=s,a=e[n-1];let c;a&&a.kind==="audio"&&(c=a);const E=this._generateStream(o,c);t.push(E)}),t}_generateAudioStreams(e){return e.map(s=>this._generateAudioStream(s))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}async waitChannels(){return this.waitSession(P)}async waitSyncMediaState(){return this.waitSession(p)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const s=`${be}: ${e}`,n=`${we}: ${t}`,o=[s,n];return this.session.sendInfo(Xt,void 0,{extraHeaders:o})}async sendMediaState({cam:e,mic:t},s={}){if(!this.session)throw new Error("No session established");const n=`${ss}: currentstate`,o=`${is}: ${Number(e)}`,a=`${rs}: ${Number(t)}`,c=[n,o,a];return this.session.sendInfo(Jt,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async _sendRefusalToTurnOn(e,t={}){if(!this.session)throw new Error("No session established");const c=[`${ns}: ${e==="mic"?0:1}`];return this.session.sendInfo(zt,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}}exports.BAD_MEDIA_DESCRIPTION=We;exports.EEventsMainCAM=g;exports.EEventsMic=y;exports.EEventsSyncMediaState=U;exports.EUseLicense=lt;exports.NOT_FOUND=qe;exports.REJECTED=V;exports.SESSION_EVENT_NAMES=Oe;exports.SipConnector=Ys;exports.UA_EVENT_NAMES=fe;exports.causes=Wt;exports.constants=Bt;exports.disableDebug=Ss;exports.enableDebug=Ts;exports.eventNames=Vt;exports.hasCanceledCallError=bs;exports.logger=F;exports.setEncodingsToSender=St;
@@ -189,7 +189,7 @@ const At = "Connection Error", be = "Request Timeout", Rt = "SIP Failure Code",
189
189
  const e = [];
190
190
  return r && e.push(`X-Vinteo-Remote: ${r}`), e;
191
191
  }, Wt = "content-type", Bt = "x-webrtc-enter-room", L = "application/vinteo.webrtc.sharedesktop", Vt = "application/vinteo.webrtc.roomname", Yt = "application/vinteo.webrtc.channels", xt = "application/vinteo.webrtc.mediastate", Gt = "application/vinteo.webrtc.refusal", De = "application/vinteo.webrtc.maincam", $t = "application/vinteo.webrtc.mic", Xt = "application/vinteo.webrtc.uselic", Jt = "X-WEBRTC-USE-LICENSE", Me = "X-WEBRTC-INPUT-CHANNELS", Pe = "X-WEBRTC-OUTPUT-CHANNELS", zt = "X-WEBRTC-MAINCAM", Qt = "X-WEBRTC-MIC", pe = "X-WEBRTC-SYNC", Kt = "X-WEBRTC-MAINCAM-RESOLUTION", jt = "X-WEBRTC-MEDIA-STATE", Zt = "X-Vinteo-Media-Type", es = "X-Vinteo-MainCam-State", ts = "X-Vinteo-Mic-State", ss = "application/vinteo.webrtc.notify", ns = "X-VINTEO-NOTIFY", m = "x-webrtc-share-state", is = `${m}: LETMESTARTPRESENTATION`, rs = `${m}: STOPPRESENTATION`, Et = "YOUCANRECEIVECONTENT", _t = "CONTENTEND", os = "YOUMUSTSTOPSENDCONTENT", as = `${m}: ${Et}`, cs = `${m}: ${_t}`, Es = "X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE", _s = `${Es}: LETMESTARTMAINCAM`, Ie = "sip-connector", ve = W(Ie), $s = () => {
192
- W.enable(`${Ie}`);
192
+ W.enable(Ie);
193
193
  }, Xs = () => {
194
194
  W.enable(`-${Ie}`);
195
195
  };
@@ -383,7 +383,7 @@ class zs {
383
383
  const E = a || c;
384
384
  c && this.isRegisterConfig ? this.register().then(() => {
385
385
  s(E);
386
- }).catch(n) : E ? s(E) : n(E);
386
+ }).catch(n) : E ? s(E) : n(new Error("nothing changed"));
387
387
  }));
388
388
  i(this, "_disconnectWithoutCancelRequests", async () => this._cancelableDisconnect.request());
389
389
  i(this, "_disconnect", async () => {
package/dist/doMock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var W=Object.defineProperty;var b=(i,e,t)=>e in i?W(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var n=(i,e,t)=>(b(i,typeof e!="symbol"?e+"":e,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const u=require("./SipConnector-XqVe938n.cjs"),D=require("@krivega/jssip/lib/NameAddrHeader"),k=require("@krivega/jssip/lib/URI"),L=require("node:events"),P=require("@krivega/jssip/lib/SIPMessage"),f=require("events-constructor");require("@krivega/cancelable-promise");require("debug");class R extends P.IncomingRequest{constructor(t){super();n(this,"headers");this.headers=new Headers(t)}getHeader(t){return this.headers.get(t)||""}}var x=Object.defineProperty,F=(i,e,t)=>e in i?x(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,s=(i,e,t)=>(F(i,typeof e!="symbol"?e+"":e,t),t);const m="ended",U="mute",V="isolationchange",z="overconstrained",q="unmute",H=[m,U,q,V,z];class S{constructor(e,{id:t="identifier",constraints:r={}}={}){s(this,"events"),s(this,"id"),s(this,"kind"),s(this,"constraints"),s(this,"enabled"),s(this,"contentHint",""),s(this,"readyState","live"),s(this,"isolated",!1),s(this,"label",""),s(this,"muted",!1),s(this,"onended",null),s(this,"onisolationchange",null),s(this,"onmute",null),s(this,"onunmute",null),s(this,"getConstraints",()=>this.constraints),s(this,"stop",()=>{const o={...new Event(m)};this.events.trigger(m,o),this.readyState=m,this.onended&&this.onended(o)}),s(this,"addEventListener",(o,a)=>{this.events.on(o,a)}),s(this,"removeEventListener",(o,a)=>{this.events.off(o,a)}),this.id=`${t}-${e}-track`,this.kind=e,this.enabled=!0,this.constraints={...r},this.events=new f(H)}clone(){return{...this}}getCapabilities(){return{width:{min:352,max:4096},height:{min:288,max:2160}}}getSettings(){let e=0,t=0;return typeof this.constraints.width=="object"&&this.constraints.width.ideal!==void 0?e=this.constraints.width.ideal:typeof this.constraints.width=="object"&&this.constraints.width.exact!==void 0?e=this.constraints.width.exact:typeof this.constraints.width=="number"&&this.constraints.width&&(e=this.constraints.width),typeof this.constraints.height=="object"&&this.constraints.height.ideal!==void 0?t=this.constraints.height.ideal:typeof this.constraints.height=="object"&&this.constraints.height.exact!==void 0?t=this.constraints.height.exact:typeof this.constraints.height=="number"&&this.constraints.height&&(t=this.constraints.height),{width:e,height:t}}async applyConstraints(e){this.constraints={...e}}dispatchEvent(e){const t=e.type;return this.events.trigger(t,e),!0}}const j=i=>new S("audio",i),$=i=>new S("video",i);class B{constructor({originator:e="local",eventHandlers:t}){n(this,"originator");n(this,"_connection");n(this,"_events");n(this,"_remote_identity");n(this,"_mutedOptions",{audio:!1,video:!1});this.originator=e,this._events=new f(u.SESSION_EVENT_NAMES),this.initEvents(t)}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}set data(e){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}get connection(){return this._connection}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 remote_identity(){return this._remote_identity}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.")}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){throw new Error("Method not implemented.")}removeAllListeners(e){throw new Error("Method not implemented.")}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=[]){Object.entries(e).forEach(([t,r])=>this.on(t,r))}on(e,t){return 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 e}async updatePresentation(e){return e}async stopPresentation(e){return e}isEstablished(){return!0}}class K{constructor(e,t){n(this,"_senders",[]);n(this,"_receivers",[]);n(this,"canTrickleIceCandidates");n(this,"connectionState");n(this,"currentLocalDescription");n(this,"currentRemoteDescription");n(this,"iceConnectionState");n(this,"iceGatheringState");n(this,"idpErrorInfo");n(this,"idpLoginUrl");n(this,"localDescription");n(this,"onconnectionstatechange");n(this,"ondatachannel");n(this,"onicecandidate");n(this,"onicecandidateerror",null);n(this,"oniceconnectionstatechange");n(this,"onicegatheringstatechange");n(this,"onnegotiationneeded");n(this,"onsignalingstatechange");n(this,"ontrack");n(this,"peerIdentity");n(this,"pendingLocalDescription");n(this,"pendingRemoteDescription");n(this,"remoteDescription");n(this,"sctp",null);n(this,"signalingState");n(this,"getReceivers",()=>this._receivers);n(this,"getSenders",()=>this._senders);n(this,"addTrack",e=>{const t={track:e};return this._senders.push(t),t});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){throw new Error("Method not implemented.")}removeEventListener(e,t,r){throw new Error("Method not implemented.")}dispatchEvent(e){throw new Error("Method not implemented.")}}function Y(i){const e=i.match(/[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const p=400,T="777",J=i=>i.getVideoTracks().length>0;class y extends B{constructor({url:t="",mediaStream:r,eventHandlers:o,originator:a}){super({originator:a,eventHandlers:o});n(this,"url");n(this,"status_code");n(this,"_isEnded",!1);n(this,"answer",jest.fn(({mediaStream:t})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(t),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},p)}));this.url=t,this.initPeerconnection(r)}initPeerconnection(t){return t?(this.createPeerconnection(t),!0):!1}createPeerconnection(t){const r=j();r.id="mainaudio1";const o=[r];if(J(t)){const C=$();C.id="mainvideo1",o.push(C)}this._connection=new K(void 0,o),this._addStream(t),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},p)}connect(t){const r=Y(t);setTimeout(()=>{this.url.includes(T)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:u.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",r)},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},p)}terminate({status_code:t}={}){return this.status_code=t,this.trigger("ended",{status_code:t}),this._isEnded=!1,this}terminateRemote({status_code:t}={}){return this.status_code=t,this.trigger("ended",{status_code:t,originator:"remote"}),this}_addStream(t,r="getTracks"){t[r]().forEach(o=>this.connection.addTrack(o))}_forEachSenders(t){const r=this.connection.getSenders();for(const o of r)t(o);return r}_toggleMuteAudio(t){this._forEachSenders(({track:r})=>{r&&r.kind==="audio"&&(r.enabled=!t)})}_toggleMuteVideo(t){this._forEachSenders(({track:r})=>{r&&r.kind==="video"&&(r.enabled=!t)})}mute(t){t.audio&&(this._mutedOptions.audio=!0,this._toggleMuteAudio(this._mutedOptions.audio)),t.video&&(this._mutedOptions.video=!0,this._toggleMuteVideo(this._mutedOptions.video)),this._onmute(t)}unmute(t){t.audio&&(this._mutedOptions.audio=!1),t.video&&(this._mutedOptions.video=!1),this.trigger("unmuted",t)}isMuted(){return this._mutedOptions}async replaceMediaStream(t){return t}_onmute({audio:t,video:r}){this.trigger("muted",{audio:t,video:r})}async sendInfo(){}isEnded(){return this._isEnded}newInfo(t){this.trigger("newInfo",t)}}class G{constructor(){n(this,"extraHeaders")}setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",w="PASSWORD_CORRECT_2",A="NAME_INCORRECT",c=400;class X{constructor(e){n(this,"_events");n(this,"_startedTimeout");n(this,"_stopedTimeout");n(this,"session");n(this,"_isRegistered");n(this,"_isConnected");n(this,"configuration");n(this,"_registrator");n(this,"call",jest.fn((e,t)=>{const{mediaStream:r,eventHandlers:o}=t;return this.session=new y({url:e,mediaStream:r,eventHandlers:o,originator:"local"}),this.session.connect(e),this.session}));this._events=new f(u.UA_EVENT_NAMES),this.configuration=e,this._registrator=new G}start(){this.register()}stop(){this._startedTimeout&&clearTimeout(this._startedTimeout),this._stopedTimeout&&clearTimeout(this._stopedTimeout),this.unregister(),this.isStarted()?this._stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:new Error("stoped")})},c):this.trigger("disconnected",{error:new Error("stoped")})}on(e,t){return this._events.on(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&&r.includes(A)?(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Request Timeout"})},c)):!this._isRegistered&&t&&(e===d||e===w)?(this._isRegistered=!0,this._startedTimeout=setTimeout(()=>{this.trigger("registered")},c)):t&&e!==d&&e!==w&&(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Wrong credentials"})},c)),this.trigger("connected"),this._isConnected=!0}unregister(){this._isRegistered=!1,this._isConnected=!1,this.trigger("unregistered")}isRegistered(){return!!this._isRegistered}isStarted(){return this.configuration&&(this.configuration.register&&!!this._isRegistered||!this.configuration.register&&!!this._isConnected)}registrator(){return this._registrator}newSipEvent(e){this.trigger("sipEvent",e)}}class Q{constructor(e){n(this,"url");this.url=e}}class Z extends L.EventEmitter{constructor(t,r){super();n(this,"contentType");n(this,"body");this.contentType=t,this.body=r}}const E="remote",ee=(i,e)=>{const t=new R(e),r={originator:E,request:t,info:new Z("","")};i.newInfo(r)},te=(i,e)=>{const r={request:new R(e)};i.newSipEvent(r)},ne=(i,{incomingNumber:e="1234",displayName:t,host:r})=>{const o=new y({originator:E}),a=new k("sip",e,r);o._remote_identity=new D(a,t),i.trigger("newRTCSession",{originator:E,session:o})},re=(i,e)=>{e?i.trigger("failed",e):i.trigger("failed",i)},I={triggerNewInfo:ee,triggerNewSipEvent:te,triggerIncomingSession:ne,triggerFailIncomingSession:re,WebSocketInterface:Q,UA:X,C:{INVITE:"INVITE"}},l="user",h="displayName",g="SIP_SERVER_URL",M="SIP_WEB_SOCKET_SERVER_URL",ie=new I.WebSocketInterface(M),v={userAgent:"Chrome",sipServerUrl:g,sipWebSocketServerURL:M},oe={...v},O={...v,user:l,password:d,register:!0},se={...O,displayName:h},ae={...v,displayName:h,register:!1},_={session_timers:!1,sockets:[ie],user_agent:"Chrome",sdp_semantics:"plan-b",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},de={..._,password:d,uri:`sip:${l}@${g}`,display_name:"",register:!0},he={..._,password:d,uri:`sip:${l}@${g}`,display_name:h,register:!0},ce={..._,display_name:h,register:!1},me={..._,display_name:"",register:!1},N="10.10.10.10",ue=[`X-Vinteo-Remote: ${N}`],le=()=>new u.SipConnector({JsSIP:I});exports.FAILED_CONFERENCE_NUMBER=T;exports.NAME_INCORRECT=A;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=w;exports.SIP_SERVER_URL=g;exports.SIP_WEB_SOCKET_SERVER_URL=M;exports.dataForConnectionWithAuthorization=O;exports.dataForConnectionWithAuthorizationWithDisplayName=se;exports.dataForConnectionWithoutAuthorization=ae;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=oe;exports.default=le;exports.displayName=h;exports.extraHeadersRemoteAddress=ue;exports.remoteAddress=N;exports.uaConfigurationWithAuthorization=de;exports.uaConfigurationWithAuthorizationWithDisplayName=he;exports.uaConfigurationWithoutAuthorization=ce;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=me;exports.user=l;
1
+ "use strict";var N=Object.defineProperty;var O=(o,t,e)=>t in o?N(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var r=(o,t,e)=>(O(o,typeof t!="symbol"?t+"":t,e),e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const h=require("./SipConnector-4TW1xlov.cjs"),W=require("@krivega/jssip/lib/NameAddrHeader"),k=require("@krivega/jssip/lib/URI"),D=require("node:events"),L=require("@krivega/jssip/lib/SIPMessage"),M=require("webrtc-mock"),R=require("events-constructor");require("@krivega/cancelable-promise");require("debug");class C extends L.IncomingRequest{constructor(e){super();r(this,"headers");this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)||""}}class P{constructor({originator:t="local",eventHandlers:e}){r(this,"originator");r(this,"_connection");r(this,"_events");r(this,"_remote_identity");r(this,"_mutedOptions",{audio:!1,video:!1});this.originator=t,this._events=new R(h.SESSION_EVENT_NAMES),this.initEvents(e)}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}set data(t){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}get connection(){return this._connection}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 remote_identity(){return this._remote_identity}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.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(t){throw new Error("Method not implemented.")}terminate(t){throw new Error("Method not implemented.")}async sendInfo(t,e,n){throw new Error("Method not implemented.")}hold(t,e){throw new Error("Method not implemented.")}unhold(t,e){throw new Error("Method not implemented.")}async renegotiate(t,e){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(t){throw new Error("Method not implemented.")}unmute(t){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(t,e){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(t,e){throw new Error("Method not implemented.")}addListener(t,e){throw new Error("Method not implemented.")}once(t,e){throw new Error("Method not implemented.")}removeListener(t,e){throw new Error("Method not implemented.")}off(t,e){throw new Error("Method not implemented.")}removeAllListeners(t){throw new Error("Method not implemented.")}setMaxListeners(t){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(t){throw new Error("Method not implemented.")}rawListeners(t){throw new Error("Method not implemented.")}emit(t,...e){throw new Error("Method not implemented.")}listenerCount(t){throw new Error("Method not implemented.")}prependListener(t,e){throw new Error("Method not implemented.")}prependOnceListener(t,e){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(t=[]){Object.entries(t).forEach(([e,n])=>this.on(e,n))}on(t,e){return this._events.on(t,e),this}trigger(t,e){this._events.trigger(t,e)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(t){return t}async updatePresentation(t){return t}async stopPresentation(t){return t}isEstablished(){return!0}}class b{constructor(t,e){r(this,"_senders",[]);r(this,"_receivers",[]);r(this,"canTrickleIceCandidates");r(this,"connectionState");r(this,"currentLocalDescription");r(this,"currentRemoteDescription");r(this,"iceConnectionState");r(this,"iceGatheringState");r(this,"idpErrorInfo");r(this,"idpLoginUrl");r(this,"localDescription");r(this,"onconnectionstatechange");r(this,"ondatachannel");r(this,"onicecandidate");r(this,"onicecandidateerror",null);r(this,"oniceconnectionstatechange");r(this,"onicegatheringstatechange");r(this,"onnegotiationneeded");r(this,"onsignalingstatechange");r(this,"ontrack");r(this,"peerIdentity");r(this,"pendingLocalDescription");r(this,"pendingRemoteDescription");r(this,"remoteDescription");r(this,"sctp",null);r(this,"signalingState");r(this,"getReceivers",()=>this._receivers);r(this,"getSenders",()=>this._senders);r(this,"addTrack",t=>{const e={track:t};return this._senders.push(e),e});this._receivers=e.map(n=>({track:n}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(t){throw new Error("Method not implemented.")}addTransceiver(t,e){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(t,e){throw new Error("Method not implemented.")}createDataChannel(t,e){throw new Error("Method not implemented.")}async createOffer(t,e,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(t){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(t){throw new Error("Method not implemented.")}setConfiguration(t){throw new Error("Method not implemented.")}async setLocalDescription(t){throw new Error("Method not implemented.")}async setRemoteDescription(t){throw new Error("Method not implemented.")}addEventListener(t,e,n){throw new Error("Method not implemented.")}removeEventListener(t,e,n){throw new Error("Method not implemented.")}dispatchEvent(t){throw new Error("Method not implemented.")}}function F(o){const t=o.match(/[\d.]+/g);if(!t)throw new Error("wrong sip url");return t[0]}const g=400,S="777",V=o=>o.getVideoTracks().length>0;class T extends P{constructor({url:e="",mediaStream:n,eventHandlers:i,originator:d}){super({originator:d,eventHandlers:i});r(this,"url");r(this,"status_code");r(this,"_isEnded",!1);r(this,"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)},g)}));this.url=e,this.initPeerconnection(n)}initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const n=M.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(V(e)){const f=M.createVideoMediaStreamTrackMock();f.id="mainvideo1",i.push(f)}this._connection=new b(void 0,i),this._addStream(e),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},g)}connect(e){const n=F(e);setTimeout(()=>{this.url.includes(S)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:h.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",n)},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},g)}terminate({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e}),this._isEnded=!1,this}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}_addStream(e,n="getTracks"){e[n]().forEach(i=>this.connection.addTrack(i))}_forEachSenders(e){const n=this.connection.getSenders();for(const i of n)e(i);return n}_toggleMuteAudio(e){this._forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!e)})}_toggleMuteVideo(e){this._forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.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}async replaceMediaStream(e){return e}_onmute({audio:e,video:n}){this.trigger("muted",{audio:e,video:n})}async sendInfo(){}isEnded(){return this._isEnded}newInfo(e){this.trigger("newInfo",e)}}class U{constructor(){r(this,"extraHeaders")}setExtraHeaders(t){this.extraHeaders=t}setExtraContactParams(){}}const s="PASSWORD_CORRECT",_="PASSWORD_CORRECT_2",v="NAME_INCORRECT",c=400;class z{constructor(t){r(this,"_events");r(this,"_startedTimeout");r(this,"_stopedTimeout");r(this,"session");r(this,"_isRegistered");r(this,"_isConnected");r(this,"configuration");r(this,"_registrator");r(this,"call",jest.fn((t,e)=>{const{mediaStream:n,eventHandlers:i}=e;return this.session=new T({url:t,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(t),this.session}));this._events=new R(h.UA_EVENT_NAMES),this.configuration=t,this._registrator=new U}start(){this.register()}stop(){this._startedTimeout&&clearTimeout(this._startedTimeout),this._stopedTimeout&&clearTimeout(this._stopedTimeout),this.unregister(),this.isStarted()?this._stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:new Error("stoped")})},c):this.trigger("disconnected",{error:new Error("stoped")})}on(t,e){return this._events.on(t,e),this}trigger(t,e){this._events.trigger(t,e)}terminateSessions(){this.session.terminate()}set(t,e){return this.configuration[t]=e,!0}register(){this._startedTimeout&&clearTimeout(this._startedTimeout);const{password:t,register:e,uri:n}=this.configuration;e&&n.includes(v)?(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Request Timeout"})},c)):!this._isRegistered&&e&&(t===s||t===_)?(this._isRegistered=!0,this._startedTimeout=setTimeout(()=>{this.trigger("registered")},c)):e&&t!==s&&t!==_&&(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Wrong credentials"})},c)),this.trigger("connected"),this._isConnected=!0}unregister(){this._isRegistered=!1,this._isConnected=!1,this.trigger("unregistered")}isRegistered(){return!!this._isRegistered}isStarted(){return this.configuration&&(this.configuration.register&&!!this._isRegistered||!this.configuration.register&&!!this._isConnected)}registrator(){return this._registrator}newSipEvent(t){this.trigger("sipEvent",t)}}class q{constructor(t){r(this,"url");this.url=t}}class x extends D.EventEmitter{constructor(e,n){super();r(this,"contentType");r(this,"body");this.contentType=e,this.body=n}}const p="remote",H=(o,t)=>{const e=new C(t),n={originator:p,request:e,info:new x("","")};o.newInfo(n)},B=(o,t)=>{const n={request:new C(t)};o.newSipEvent(n)},$=(o,{incomingNumber:t="1234",displayName:e,host:n})=>{const i=new T({originator:p}),d=new k("sip",t,n);i._remote_identity=new W(d,e),o.trigger("newRTCSession",{originator:p,session:i})},j=(o,t)=>{t?o.trigger("failed",t):o.trigger("failed",o)},y={triggerNewInfo:H,triggerNewSipEvent:B,triggerIncomingSession:$,triggerFailIncomingSession:j,WebSocketInterface:q,UA:z,C:{INVITE:"INVITE"}},m="user",a="displayName",u="SIP_SERVER_URL",w="SIP_WEB_SOCKET_SERVER_URL",K=new y.WebSocketInterface(w),E={userAgent:"Chrome",sipServerUrl:u,sipWebSocketServerURL:w},J={...E},A={...E,user:m,password:s,register:!0},Y={...A,displayName:a},G={...E,displayName:a,register:!1},l={session_timers:!1,sockets:[K],user_agent:"Chrome",sdp_semantics:"plan-b",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},X={...l,password:s,uri:`sip:${m}@${u}`,display_name:"",register:!0},Q={...l,password:s,uri:`sip:${m}@${u}`,display_name:a,register:!0},Z={...l,display_name:a,register:!1},ee={...l,display_name:"",register:!1},I="10.10.10.10",te=[`X-Vinteo-Remote: ${I}`],re=()=>new h.SipConnector({JsSIP:y});exports.FAILED_CONFERENCE_NUMBER=S;exports.NAME_INCORRECT=v;exports.PASSWORD_CORRECT=s;exports.PASSWORD_CORRECT_2=_;exports.SIP_SERVER_URL=u;exports.SIP_WEB_SOCKET_SERVER_URL=w;exports.dataForConnectionWithAuthorization=A;exports.dataForConnectionWithAuthorizationWithDisplayName=Y;exports.dataForConnectionWithoutAuthorization=G;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=J;exports.default=re;exports.displayName=a;exports.extraHeadersRemoteAddress=te;exports.remoteAddress=I;exports.uaConfigurationWithAuthorization=X;exports.uaConfigurationWithAuthorizationWithDisplayName=Q;exports.uaConfigurationWithoutAuthorization=Z;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ee;exports.user=m;