sip-connector 14.1.2-5 → 14.1.2-7

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.
@@ -293,7 +293,7 @@ const sn = (s, e) => () => Math.floor(Math.random() * (e - s)) + s, ye = (s) =>
293
293
  return;
294
294
  const i = t === "recvonly" ? [] : s.getAudioTracks(), o = e === "recvonly" ? [] : s.getVideoTracks(), a = [...i, ...o], c = new MediaStream(a);
295
295
  return c.getTracks = () => [...c.getAudioTracks(), ...c.getVideoTracks()], n && n !== "none" && Hn(c, n), c;
296
- }, Wn = "Error decline with 603", kn = 1006, Bn = (s) => typeof s == "object" && s !== null && "code" in s && s.code === kn, xn = (s) => s.message === Wn, Fn = (s, e) => s.find((t) => t.track && e.getTracks().includes(t.track)), Vn = async (s, e, t) => {
296
+ }, Wn = "Error decline with 603", kn = 1006, Bn = (s) => typeof s == "object" && s !== null && "code" in s && s.code === kn, xn = (s) => s.message === Wn, Fn = (s, e) => s.find((t) => t.track !== null && e.getTracks().includes(t.track)), Vn = async (s, e, t) => {
297
297
  const n = Fn(s, e);
298
298
  if (n)
299
299
  return tn(n, { maxBitrate: t });
@@ -0,0 +1 @@
1
+ "use strict";var Ot=Object.defineProperty;var mt=(s,e,t)=>e in s?Ot(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var r=(s,e,t)=>mt(s,typeof e!="symbol"?e+"":e,t);const Mt=require("@krivega/cancelable-promise"),we=require("events-constructor"),G=require("repeated-calls"),J=require("debug"),Dt="Connection Error",ke="Request Timeout",pt="SIP Failure Code",vt="Internal Error",yt="Busy",X="Rejected",wt="Redirected",bt="Unavailable",Be="Not Found",Ut="Address Incomplete",Lt="Incompatible SDP",Ht="Missing SDP",Wt="Authentication Error",Fe="Terminated",kt="WebRTC Error",Q="Canceled",Bt="No Answer",Ft="Expires",xt="No ACK",Vt="Dialog Error",Yt="User Denied Media Access",xe="Bad Media Description",qt="RTP Timeout",$t=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:Ut,AUTHENTICATION_ERROR:Wt,BAD_MEDIA_DESCRIPTION:xe,BUSY:yt,BYE:Fe,CANCELED:Q,CONNECTION_ERROR:Dt,DIALOG_ERROR:Vt,EXPIRES:Ft,INCOMPATIBLE_SDP:Lt,INTERNAL_ERROR:vt,MISSING_SDP:Ht,NOT_FOUND:Be,NO_ACK:xt,NO_ANSWER:Bt,REDIRECTED:wt,REJECTED:X,REQUEST_TIMEOUT:ke,RTP_TIMEOUT:qt,SIP_FAILURE_CODE:pt,UNAVAILABLE:bt,USER_DENIED_MEDIA_ACCESS:Yt,WEBRTC_ERROR:kt},Symbol.toStringTag,{value:"Module"})),z="incomingCall",j="declinedIncomingCall",K="failedIncomingCall",Z="terminatedIncomingCall",F="connecting",P="connected",C="disconnected",y="newRTCSession",O="registered",ee="unregistered",m="registrationFailed",Ve="newMessage",te="sipEvent",ne="availableSecondRemoteStream",se="notAvailableSecondRemoteStream",ie="mustStopPresentation",w="shareState",oe="enterRoom",re="useLicense",ae="peerconnection:confirmed",ce="peerconnection:ontrack",b="channels",Ee="channels:notify",de="ended:fromserver",he="main-cam-control",Se="admin-stop-main-cam",Te="admin-start-main-cam",le="admin-stop-mic",ue="admin-start-mic",U="admin-force-sync-media-state",ge="participant:added-to-list-moderators",Ce="participant:removed-from-list-moderators",_e="participant:move-request-to-stream",x="participant:move-request-to-spectators",V="participant:move-request-to-participants",Ne="participation:accepting-word-request",Ae="participation:cancelling-word-request",Re="webcast:started",fe="webcast:stopped",Ie="account:changed",Pe="account:deleted",Oe="conference:participant-token-issued",M="ended",Ye="sending",qe="reinvite",$e="replaces",Ge="refer",Je="progress",Xe="accepted",L="confirmed",H="peerconnection",A="failed",Qe="muted",ze="unmuted",me="newDTMF",Me="newInfo",je="hold",Ke="unhold",Ze="update",et="sdp",tt="icecandidate",nt="getusermediafailed",st="peerconnection:createofferfailed",it="peerconnection:createanswerfailed",ot="peerconnection:setlocaldescriptionfailed",rt="peerconnection:setremotedescriptionfailed",at="presentation:start",ct="presentation:started",Et="presentation:end",De="presentation:ended",W="presentation:failed",dt="SPECTATOR",ht="PARTICIPANT",St=1e6;var _=(s=>(s.LOCAL="local",s.REMOTE="remote",s.SYSTEM="system",s))(_||{});const Gt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:Xe,ACCOUNT_CHANGED:Ie,ACCOUNT_DELETED:Pe,ADMIN_FORCE_SYNC_MEDIA_STATE:U,ADMIN_START_MAIN_CAM:Te,ADMIN_START_MIC:ue,ADMIN_STOP_MAIN_CAM:Se,ADMIN_STOP_MIC:le,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:ne,CHANNELS:b,CHANNELS_NOTIFY:Ee,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Oe,CONFIRMED:L,CONNECTED:P,CONNECTING:F,DECLINED_INCOMING_CALL:j,DISCONNECTED:C,ENDED:M,ENDED_FROM_SERVER:de,ENTER_ROOM:oe,FAILED:A,FAILED_INCOMING_CALL:K,GET_USER_MEDIA_FAILED:nt,HOLD:je,ICE_CANDIDATE:tt,INCOMING_CALL:z,MAIN_CAM_CONTROL:he,MUST_STOP_PRESENTATION_EVENT:ie,MUTED:Qe,NEW_DTMF:me,NEW_INFO:Me,NEW_MESSAGE:Ve,NEW_RTC_SESSION:y,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:se,ONE_MEGABIT_IN_BITS:St,Originator:_,PARTICIPANT:ht,PARTICIPANT_ADDED_TO_LIST_MODERATORS:ge,PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS:V,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:x,PARTICIPANT_MOVE_REQUEST_TO_STREAM:_e,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:Ce,PARTICIPATION_ACCEPTING_WORD_REQUEST:Ne,PARTICIPATION_CANCELLING_WORD_REQUEST:Ae,PEER_CONNECTION:H,PEER_CONNECTION_CONFIRMED:ae,PEER_CONNECTION_CREATE_ANSWER_FAILED:it,PEER_CONNECTION_CREATE_OFFER_FAILED:st,PEER_CONNECTION_ONTRACK:ce,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:ot,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:rt,PRESENTATION_END:Et,PRESENTATION_ENDED:De,PRESENTATION_FAILED:W,PRESENTATION_START:at,PRESENTATION_STARTED:ct,PROGRESS:Je,REFER:Ge,REGISTERED:O,REGISTRATION_FAILED:m,REINVITE:qe,REPLACES:$e,SDP:et,SENDING:Ye,SHARE_STATE:w,SIP_EVENT:te,SPECTATOR:dt,TERMINATED_INCOMING_CALL:Z,UNHOLD:Ke,UNMUTED:ze,UNREGISTERED:ee,UPDATE:Ze,USE_LICENSE:re,WEBCAST_STARTED:Re,WEBCAST_STOPPED:fe},Symbol.toStringTag,{value:"Module"})),Tt=[z,j,Z,K,Ne,Ae,_e,Ee,Oe,Ie,Pe,Re,fe,ge,Ce],Y=[F,P,C,y,O,ee,m,Ve,te],lt=[ne,se,ie,w,oe,re,ae,ce,b,de,he,Te,Se,le,ue,U,x,V],pe=[M,F,Ye,qe,$e,Ge,Je,Xe,L,H,A,Qe,ze,me,Me,je,Ke,Ze,et,tt,nt,st,it,ot,rt,at,ct,Et,De,W],ut=[...Y,...Tt],ve=[...pe,...lt],Jt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:ve,SESSION_JSSIP_EVENT_NAMES:pe,SESSION_SYNTHETICS_EVENT_NAMES:lt,UA_EVENT_NAMES:ut,UA_JSSIP_EVENT_NAMES:Y,UA_SYNTHETICS_EVENT_NAMES:Tt},Symbol.toStringTag,{value:"Module"})),ye="sip-connector",v=J(ye),Xt=()=>{J.enable(ye)},Qt=()=>{J.enable(`-${ye}`)},zt=(s,e)=>(s.degradationPreference=e.degradationPreference,s),jt=(s,e)=>{s.encodings??(s.encodings=[]);for(let t=s.encodings.length;t<e;t+=1)s.encodings.push({});return s},gt=s=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==s,Kt=gt(),Zt=(s,e)=>{if(Kt(s,e))return s},en=(s,e)=>{const t=s.maxBitrate,n=Zt(e,t);return n!==void 0&&(s.maxBitrate=n),s},Ct=1,tn=gt(Ct),nn=(s,e)=>{const t=s===void 0?void 0:Math.max(s,Ct);if(t!==void 0&&tn(t,e))return t},sn=(s,e)=>{const t=s.scaleResolutionDownBy,n=nn(e,t);return n!==void 0&&(s.scaleResolutionDownBy=n),s},on=(s,e)=>{var n;const t=((n=e.encodings)==null?void 0:n.length)??0;return jt(s,t),s.encodings.forEach((i,o)=>{const a=((e==null?void 0:e.encodings)??[])[o],c=a==null?void 0:a.maxBitrate,E=a==null?void 0:a.scaleResolutionDownBy;en(i,c),sn(i,E)}),s},rn=(s,e)=>{var t,n,i,o,a,c,E,d,T,l,S,u;if(((t=s.codecs)==null?void 0:t.length)!==((n=e.codecs)==null?void 0:n.length))return!0;for(let h=0;h<(((i=s.codecs)==null?void 0:i.length)??0);h++)if(JSON.stringify(s.codecs[h])!==JSON.stringify(e.codecs[h]))return!0;if(((o=s.headerExtensions)==null?void 0:o.length)!==((a=e.headerExtensions)==null?void 0:a.length))return!0;for(let h=0;h<(((c=s.headerExtensions)==null?void 0:c.length)??0);h++)if(JSON.stringify(s.headerExtensions[h])!==JSON.stringify(e.headerExtensions[h]))return!0;if(((E=s.encodings)==null?void 0:E.length)!==((d=e.encodings)==null?void 0:d.length))return!0;for(let h=0;h<(s.encodings.length??0);h++)if(JSON.stringify(s.encodings[h])!==JSON.stringify(e.encodings[h]))return!0;return((T=s.rtcp)==null?void 0:T.cname)!==((l=e.rtcp)==null?void 0:l.cname)||((S=s.rtcp)==null?void 0:S.reducedSize)!==((u=e.rtcp)==null?void 0:u.reducedSize)||s.degradationPreference!==e.degradationPreference},_t=async(s,e)=>{const t=s.getParameters(),n=JSON.parse(JSON.stringify(t));on(t,e),zt(t,e);const i=rn(n,t);return i&&await s.setParameters(t),{parameters:t,isChanged:i}};var R=(s=>(s.PAUSE_MAIN_CAM="PAUSEMAINCAM",s.RESUME_MAIN_CAM="RESUMEMAINCAM",s.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",s.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",s.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",s))(R||{}),k=(s=>(s.ADMIN_STOP_MIC="ADMINSTOPMIC",s.ADMIN_START_MIC="ADMINSTARTMIC",s))(k||{}),B=(s=>(s.ADMIN_SYNC_FORCED="1",s.ADMIN_SYNC_NOT_FORCED="0",s))(B||{}),Nt=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",s))(Nt||{}),At=(s=>(s.VP8="video/VP8",s.VP9="video/VP9",s.H264="video/H264",s.AV1="video/AV1",s.rtx="video/rtx",s.red="video/red",s.flexfec03="video/flexfec-03",s))(At||{});const Rt=async(s,e,t)=>{const{isChanged:n,parameters:i}=await _t(s,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return n&&t&&t(i),{isChanged:n,parameters:i}};function an(s){return e=>`sip:${e}@${s}`}const cn=(s,e)=>()=>Math.floor(Math.random()*(e-s))+s,be=s=>s.trim().replaceAll(" ","_"),En=cn(1e5,99999999),dn=s=>s.some(t=>{const{kind:n}=t;return n==="video"}),hn=s=>{const e=[];return s!==void 0&&s!==""&&e.push(`X-Vinteo-Remote: ${s}`),e},Sn="content-type",Tn="x-webrtc-enter-room",D="application/vinteo.webrtc.sharedesktop",ln="application/vinteo.webrtc.roomname",un="application/vinteo.webrtc.channels",gn="application/vinteo.webrtc.mediastate",Cn="application/vinteo.webrtc.refusal",Ue="application/vinteo.webrtc.maincam",_n="application/vinteo.webrtc.mic",Nn="application/vinteo.webrtc.uselic",An="X-WEBRTC-USE-LICENSE",Rn="X-WEBRTC-PARTICIPANT-NAME",Le="X-WEBRTC-INPUT-CHANNELS",He="X-WEBRTC-OUTPUT-CHANNELS",fn="X-WEBRTC-MAINCAM",In="X-WEBRTC-MIC",We="X-WEBRTC-SYNC",Pn="X-WEBRTC-MAINCAM-RESOLUTION",On="X-WEBRTC-MEDIA-STATE",mn="X-Vinteo-Media-Type",Mn="X-Vinteo-MainCam-State",Dn="X-Vinteo-Mic-State",pn="application/vinteo.webrtc.partstate",vn="X-WEBRTC-PARTSTATE",yn="application/vinteo.webrtc.notify",wn="X-VINTEO-NOTIFY",f="x-webrtc-share-state",bn=`${f}: LETMESTARTPRESENTATION`,Un=`${f}: STOPPRESENTATION`,ft="YOUCANRECEIVECONTENT",It="CONTENTEND",Pt="YOUMUSTSTOPSENDCONTENT",Ln=`${f}: ${Pt}`,Hn=`${f}: ${ft}`,Wn=`${f}: ${It}`,kn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Bn=`${kn}: LETMESTARTMAINCAM`,Fn=(s,e)=>{s.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},p=(s,{directionVideo:e,directionAudio:t,contentHint:n}={})=>{if(!s||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:s.getAudioTracks(),o=e==="recvonly"?[]:s.getVideoTracks(),a=[...i,...o],c=new MediaStream(a);return c.getTracks=()=>[...c.getAudioTracks(),...c.getVideoTracks()],n&&n!=="none"&&Fn(c,n),c},xn="Error decline with 603",Vn=1006,Yn=s=>typeof s=="object"&&s!==null&&"code"in s&&s.code===Vn,qn=s=>s.message===xn,$n=(s,e)=>s.find(t=>t.track!==null&&e.getTracks().includes(t.track)),Gn=async(s,e,t)=>{const n=$n(s,e);if(n)return Rt(n,{maxBitrate:t})},Jn=486,Xn=487,Qn=3,zn=1,jn=s=>s instanceof Object&&("originator"in s||"cause"in s),Kn=s=>{if(Mt.isCanceledError(s))return!0;if(!jn(s))return!1;const{originator:e,cause:t}=s;return typeof t=="string"?t===ke||t===X||e===_.LOCAL&&(t===Q||t===Fe):!1},Zn=s=>G.hasCanceledError(s),es="channels",ts="WebcastStarted",ns="WebcastStopped",ss="accountChanged",is="accountDeleted",os="addedToListModerators",rs="removedFromListModerators",as="ParticipationRequestAccepted",cs="ParticipationRequestRejected",Es="ParticipantMovedToWebcast",ds="ConferenceParticipantTokenIssued";class hs{constructor({JsSIP:e}){r(this,"promisePendingStartPresentation");r(this,"promisePendingStopPresentation");r(this,"ua");r(this,"rtcSession");r(this,"incomingRTCSession");r(this,"streamPresentationCurrent");r(this,"socket");r(this,"isRegisterConfigInner",!1);r(this,"connectionConfiguration",{});r(this,"remoteStreams",{});r(this,"JsSIP");r(this,"sessionEvents");r(this,"uaEvents");r(this,"cancelableConnectWithRepeatedCalls");r(this,"cancelableSendPresentationWithRepeatedCalls");r(this,"isPendingConnect",!1);r(this,"isPendingInitUa",!1);r(this,"isPendingCall",!1);r(this,"isPendingAnswer",!1);r(this,"connect",async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t)));r(this,"hangUp",async()=>(this.cancelRequests(),this.hangUpWithoutCancelRequests()));r(this,"tryRegister",async()=>{if(!this.isRegisterConfig)throw new Error("Config is not registered");this.uaEvents.trigger(F,void 0);try{await this.unregister()}catch(e){v("tryRegister",e)}return this.register()});r(this,"declineToIncomingCall",async({statusCode:e=Xn}={})=>new Promise((t,n)=>{try{const i=this.getIncomingRTCSession(),o=this.remoteCallerData;this.removeIncomingSession(),this.uaEvents.trigger(j,o),i.terminate({status_code:e}),t()}catch(i){n(i)}}));r(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:Jn}));r(this,"set",async({displayName:e,password:t})=>new Promise((n,i)=>{const{ua:o}=this;if(!o){i(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",be(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(()=>{n(E)}).catch(d=>{i(d)}):E?n(E):i(new Error("nothing changed"))}));r(this,"disconnect",async()=>{this.off(y,this.handleNewRTCSession);const e=new Promise(n=>{this.once(C,()=>{n()})}),{ua:t}=this;return t?(await this.hangUpWithoutCancelRequests(),t.stop()):this.uaEvents.trigger(C,void 0),e.finally(()=>{delete this.ua})});r(this,"call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:i,iceServers:o,directionVideo:a,directionAudio:c,contentHint:E,offerToReceiveAudio:d=!0,offerToReceiveVideo:T=!0,sendEncodings:l,onAddedTransceiver:S})=>(this.isPendingCall=!0,new Promise((u,h)=>{const{ua:g}=this;if(!g){h(new Error("this.ua is not initialized"));return}this.connectionConfiguration.number=e,this.connectionConfiguration.answer=!1,this.handleCall({ontrack:i}).then(u).catch(N=>{h(N)}),this.rtcSession=g.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:p(t,{directionVideo:a,directionAudio:c,contentHint:E}),eventHandlers:this.sessionEvents.triggers,directionVideo:a,directionAudio:c,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:d,offerToReceiveVideo:T},sendEncodings:l,onAddedTransceiver:S})}).finally(()=>{this.isPendingCall=!1})));r(this,"answerToIncomingCall",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:i,directionVideo:o,directionAudio:a,offerToReceiveAudio:c,offerToReceiveVideo:E,contentHint:d,sendEncodings:T,onAddedTransceiver:l})=>(this.isPendingAnswer=!0,new Promise((S,u)=>{try{const h=this.getIncomingRTCSession();this.rtcSession=h,this.removeIncomingSession(),this.sessionEvents.eachTriggers((N,q)=>{const I=pe.find($=>$===q);I&&h.on(I,N)}),this.connectionConfiguration.answer=!0,this.connectionConfiguration.number=h.remote_identity.uri.user,this.handleCall({ontrack:t}).then(S).catch(N=>{u(N)});const g=p(e,{directionVideo:o,directionAudio:a,contentHint:d});h.answer({extraHeaders:n,directionVideo:o,directionAudio:a,mediaStream:g,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:E},sendEncodings:T,onAddedTransceiver:l})}catch(h){u(h)}}).finally(()=>{this.isPendingAnswer=!1})));r(this,"sendDTMF",async e=>new Promise((t,n)=>{const{rtcSession:i}=this;if(!i){n(new Error("No rtcSession established"));return}this.onceSession(me,({originator:o})=>{o===_.LOCAL&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600})}));r(this,"removeIncomingSession",()=>{delete this.incomingRTCSession});r(this,"getSipServerUrl",e=>e);r(this,"connectWithDuplicatedCalls",async(e,{callLimit:t=Qn}={})=>{const n=async()=>this.connectInner(e),i=o=>{var d;const c=((d=this.ua)==null?void 0:d.isConnected())===!0&&this.hasEqualConnectionConfiguration(e),E=o!=null&&!Yn(o);return c||E};return this.isPendingConnect=!0,this.cancelableConnectWithRepeatedCalls=G.repeatedCallsAsync({targetFunction:n,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(o=>{if(o instanceof this.JsSIP.UA)return o;throw o}).finally(()=>{this.isPendingConnect=!1})});r(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===_.REMOTE){this.incomingRTCSession=t;const n=this.remoteCallerData;t.on(A,i=>{this.removeIncomingSession(),i.originator===_.LOCAL?this.uaEvents.trigger(Z,n):this.uaEvents.trigger(K,n)}),this.uaEvents.trigger(z,n)}});r(this,"connectInner",async e=>this.initUa(e).then(async()=>this.start()));r(this,"initUa",async({user:e,password:t,sipServerUrl:n,sipWebSocketServerURL:i,remoteAddress:o,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:d,userAgent:T,displayName:l="",register:S=!1,extraHeaders:u=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(S&&(e===void 0||e===""))throw new Error("user is required for authorized connection");if(S&&(t===void 0||t===""))throw new Error("password is required for authorized connection");this.isPendingInitUa=!0;try{this.connectionConfiguration={sipServerUrl:n,displayName:l,register:S,user:e,password:t};const{configuration:h,helpers:g}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:i,password:t,displayName:l,register:S,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:d,userAgent:T});return this.getSipServerUrl=g.getSipServerUrl,this.socket=g.socket,this.ua&&await this.disconnect(),this.isRegisterConfigInner=!!S,this.ua=this.createUa({...h,remoteAddress:o,extraHeaders:u}),this.uaEvents.eachTriggers((N,q)=>{const I=Y.find($=>$===q);I&&this.ua&&this.ua.on(I,N)}),this.ua}finally{this.isPendingInitUa=!1}});r(this,"createUa",({remoteAddress:e,extraHeaders:t=[],...n})=>{const i=new this.JsSIP.UA(n),a=[...e!==void 0&&e!==""?hn(e):[],...t];return a.length>0&&i.registrator().setExtraHeaders(a),i});r(this,"start",async()=>new Promise((e,t)=>{const{ua:n}=this;if(!n){t(new Error("this.ua is not initialized"));return}const i=()=>{c(),e(n)},o=E=>{c(),t(E)},a=()=>{this.isRegisterConfig?(this.on(O,i),this.on(m,o)):this.on(P,i),this.on(C,o)},c=()=>{this.off(O,i),this.off(m,o),this.off(P,i),this.off(C,o)};a(),this.on(y,this.handleNewRTCSession),n.start()}));r(this,"handleCall",async({ontrack:e})=>new Promise((t,n)=>{const i=()=>{this.onSession(H,T),this.onSession(L,l)},o=()=>{this.offSession(H,T),this.offSession(L,l)},a=()=>{this.onSession(A,E),this.onSession(M,E)},c=()=>{this.offSession(A,E),this.offSession(M,E)},E=S=>{o(),c(),n(S)};let d;const T=({peerconnection:S})=>{d=S,d.ontrack=u=>{this.sessionEvents.trigger(ce,d),e&&e(u)}},l=()=>{d!==void 0&&this.sessionEvents.trigger(ae,d),o(),c(),t(d)};i(),a()}));r(this,"restoreSession",()=>{this.cancelRequestsAndResetPresentation(),delete this.connectionConfiguration.number,delete this.rtcSession,this.remoteStreams={}});r(this,"hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.rtcSession){const{rtcSession:e}=this;if(this.streamPresentationCurrent)try{await this.stopPresentation()}catch(t){v("error stop presentation: ",t)}if(this.restoreSession(),!e.isEnded())return e.terminateAsync({cause:Q})}});r(this,"handleShareState",e=>{switch(e){case ft:{this.sessionEvents.trigger(ne,void 0);break}case It:{this.sessionEvents.trigger(se,void 0);break}case Pt:{this.sessionEvents.trigger(ie,void 0);break}}});r(this,"maybeTriggerChannels",e=>{const t=e.getHeader(Le),n=e.getHeader(He);if(t&&n){const i={inputChannels:t,outputChannels:n};this.sessionEvents.trigger(b,i)}});r(this,"handleNotify",e=>{switch(e.cmd){case es:{const t=e;this.triggerChannelsNotify(t);break}case ts:{const t=e;this.triggerWebcastStartedNotify(t);break}case ns:{const t=e;this.triggerWebcastStoppedNotify(t);break}case os:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case rs:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case as:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case cs:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case Es:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case ss:{this.triggerAccountChangedNotify();break}case is:{this.triggerAccountDeletedNotify();break}case ds:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:v("unknown cmd",e.cmd)}});r(this,"triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this.uaEvents.trigger(Ce,t)});r(this,"triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this.uaEvents.trigger(ge,t)});r(this,"triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this.uaEvents.trigger(Re,n)});r(this,"triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this.uaEvents.trigger(fe,n)});r(this,"triggerAccountChangedNotify",()=>{this.uaEvents.trigger(Ie,void 0)});r(this,"triggerAccountDeletedNotify",()=>{this.uaEvents.trigger(Pe,void 0)});r(this,"triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const i={conference:e,participant:t,jwt:n};this.uaEvents.trigger(Oe,i)});r(this,"triggerChannelsNotify",e=>{const t=e.input,n=e.output,i={inputChannels:t,outputChannels:n};this.uaEvents.trigger(Ee,i)});r(this,"triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(Ne,t)});r(this,"triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(Ae,t)});r(this,"triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(_e,t)});r(this,"triggerEnterRoom",e=>{const t=e.getHeader(Tn),n=e.getHeader(Rn);this.sessionEvents.trigger(oe,{room:t,participantName:n})});r(this,"triggerShareState",e=>{const t=e.getHeader(f);this.sessionEvents.trigger(w,t)});r(this,"maybeTriggerParticipantMoveRequest",e=>{const t=e.getHeader(vn);t===dt&&this.sessionEvents.trigger(x,void 0),t===ht&&this.sessionEvents.trigger(V,void 0)});r(this,"triggerMainCamControl",e=>{const t=e.getHeader(fn),n=e.getHeader(We),i=n===B.ADMIN_SYNC_FORCED;if(t===R.ADMIN_START_MAIN_CAM){this.sessionEvents.trigger(Te,{isSyncForced:i});return}if(t===R.ADMIN_STOP_MAIN_CAM){this.sessionEvents.trigger(Se,{isSyncForced:i});return}(t===R.RESUME_MAIN_CAM||t===R.PAUSE_MAIN_CAM)&&n!==void 0&&this.sessionEvents.trigger(U,{isSyncForced:i});const o=e.getHeader(Pn);this.sessionEvents.trigger(he,{mainCam:t,resolutionMainCam:o})});r(this,"triggerMicControl",e=>{const t=e.getHeader(In),i=e.getHeader(We)===B.ADMIN_SYNC_FORCED;t===k.ADMIN_START_MIC?this.sessionEvents.trigger(ue,{isSyncForced:i}):t===k.ADMIN_STOP_MIC&&this.sessionEvents.trigger(le,{isSyncForced:i})});r(this,"triggerUseLicense",e=>{const t=e.getHeader(An);this.sessionEvents.trigger(re,t)});r(this,"handleNewInfo",e=>{const{originator:t}=e;if(t!==_.REMOTE)return;const{request:n}=e,i=n.getHeader(Sn);if(i)switch(i){case ln:{this.triggerEnterRoom(n),this.maybeTriggerChannels(n);break}case yn:{this.maybeHandleNotify(n);break}case D:{this.triggerShareState(n);break}case Ue:{this.triggerMainCamControl(n);break}case _n:{this.triggerMicControl(n);break}case Nn:{this.triggerUseLicense(n);break}case pn:{this.maybeTriggerParticipantMoveRequest(n);break}}});r(this,"handleSipEvent",({request:e})=>{this.maybeHandleNotify(e)});r(this,"maybeHandleNotify",e=>{const t=e.getHeader(wn);if(t){const n=JSON.parse(t);this.handleNotify(n)}});r(this,"handleEnded",e=>{const{originator:t}=e;t===_.REMOTE&&this.sessionEvents.trigger(de,e),this.restoreSession()});this.JsSIP=e,this.sessionEvents=new we(ve),this.uaEvents=new we(ut),this.onSession(w,this.handleShareState),this.onSession(Me,this.handleNewInfo),this.on(te,this.handleSipEvent),this.onSession(A,this.handleEnded),this.onSession(M,this.handleEnded)}get connection(){var t;return(t=this.rtcSession)==null?void 0:t.connection}get remoteCallerData(){var e,t,n;return{displayName:(e=this.incomingRTCSession)==null?void 0:e.remote_identity.display_name,host:(t=this.incomingRTCSession)==null?void 0:t.remote_identity.uri.host,incomingNumber:(n=this.incomingRTCSession)==null?void 0:n.remote_identity.uri.user,rtcSession:this.incomingRTCSession}}get requested(){return this.isPendingInitUa||this.isPendingConnect||this.isPendingCall||this.isPendingAnswer}get establishedRTCSession(){var e;return((e=this.rtcSession)==null?void 0:e.isEstablished())===!0?this.rtcSession:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this.isRegisterConfigInner}get isCallActive(){return!!(this.ua&&this.rtcSession)}get isAvailableIncomingCall(){return!!this.incomingRTCSession}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(O,e),this.ua.on(m,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(ee,e),this.ua.unregister()):t(new Error("ua is not registered"))})}async sendOptions(e,t,n){if(!this.ua)throw new Error("is not connected");return new Promise((i,o)=>{try{this.ua.sendOptions(e,t,{extraHeaders:n,eventHandlers:{succeeded:()=>{i()},failed:o}})}catch(a){o(a)}})}async ping(e,t){var i;if(!((i=this.ua)!=null&&i.configuration.uri))throw new Error("is not connected");const n=this.ua.configuration.uri;return this.sendOptions(n,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerUrl:n,sipWebSocketServerURL:i,remoteAddress:o,extraHeaders:a}){return new Promise((c,E)=>{const{configuration:d}=this.createUaConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:n}),T=this.createUa({...d,remoteAddress:o,extraHeaders:a}),l=()=>{const u=new Error("Telephony is not available");E(u)};T.once(C,l);const S=()=>{T.removeAllListeners(),T.once(C,c),T.stop()};T.once(P,S),T.start()})}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:n}=t??{},i=p(e,{contentHint:n});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}async askPermissionToEnableCam(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");const t=[Bn];return this.rtcSession.sendInfo(Ue,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if(qn(n))throw n})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:o,sendEncodings:a,onAddedTransceiver:c}={},E){const d=this.establishedRTCSession;if(!d)throw new Error("No rtcSession established");if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return n===!0&&await this.sendMustStopPresentation(),this.sendPresentationWithDuplicatedCalls({rtcSession:d,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:o,sendEncodings:a,onAddedTransceiver:c},options:E})}async stopPresentation({isP2P:e=!1}={}){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve(void 0);const i=e?[Wn]:[Un],o=this.establishedRTCSession;return o&&t&&(n=n.then(async()=>o.sendInfo(D,void 0,{extraHeaders:i})).then(async()=>o.stopPresentation(t)).catch(a=>{throw this.sessionEvents.trigger(W,a),a})),!o&&t&&this.sessionEvents.trigger(De,t),this.promisePendingStopPresentation=n,n.finally(()=>{this.resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,contentHint:i,sendEncodings:o,onAddedTransceiver:a}={}){const c=this.establishedRTCSession;if(!c)throw new Error("No rtcSession established");if(!this.streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this.sendPresentation(c,e,{isP2P:t,maxBitrate:n,contentHint:i,isNeedReinvite:!1,sendEncodings:o,onAddedTransceiver:a})}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:n})=>n);return dn(t)?this.generateStreams(t):this.generateAudioStreams(t)}getIncomingRTCSession(){const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e}cancelSendPresentationWithRepeatedCalls(){var e;(e=this.cancelableSendPresentationWithRepeatedCalls)==null||e.cancel()}async waitChannels(){return this.waitSession(b)}async waitSyncMediaState(){return this.waitSession(U)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.rtcSession)throw new Error("No rtcSession established");const n=`${Le}: ${e}`,i=`${He}: ${t}`,o=[n,i];return this.rtcSession.sendInfo(un,void 0,{extraHeaders:o})}async sendMediaState({cam:e,mic:t},n={}){if(!this.rtcSession)throw new Error("No rtcSession established");const i=`${On}: currentstate`,o=`${Mn}: ${Number(e)}`,a=`${Dn}: ${Number(t)}`,c=[i,o,a];return this.rtcSession.sendInfo(gn,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async sendRefusalToTurnOn(e,t={}){if(!this.rtcSession)throw new Error("No rtcSession established");const c=[`${mn}: ${e==="mic"?0:1}`];return this.rtcSession.sendInfo(Cn,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendMustStopPresentation(){const e=this.establishedRTCSession;if(!e)throw new Error("No rtcSession established");await e.sendInfo(D,void 0,{extraHeaders:[Ln]})}async sendPresentationWithDuplicatedCalls({rtcSession:e,stream:t,presentationOptions:n,options:i={callLimit:zn}}){const o=async()=>this.sendPresentation(e,t,n),a=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=G.repeatedCallsAsync({targetFunction:o,isComplete:a,isRejectAsValid:!0,...i}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}hasEqualConnectionConfiguration(e){var i;const{configuration:t}=this.createUaConfiguration(e),n=(i=this.ua)==null?void 0:i.configuration;return(n==null?void 0:n.password)===t.password&&(n==null?void 0:n.register)===t.register&&n.uri.toString()===t.uri&&n.display_name===t.display_name&&n.user_agent===t.user_agent&&n.sockets===t.sockets&&n.session_timers===t.session_timers&&n.register_expires===t.register_expires&&n.connection_recovery_min_interval===t.connection_recovery_min_interval&&n.connection_recovery_max_interval===t.connection_recovery_max_interval}createUaConfiguration({user:e,password:t,sipWebSocketServerURL:n,displayName:i="",sipServerUrl:o,register:a=!1,sessionTimers:c=!1,registerExpires:E=60*5,connectionRecoveryMinInterval:d=2,connectionRecoveryMaxInterval:T=6,userAgent:l}){if(a&&(t===void 0||t===""))throw new Error("password is required for authorized connection");const S=a&&e!==void 0&&e.trim()!==""?e.trim():`${En()}`,u=an(o),h=u(S),g=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:h,display_name:be(i),user_agent:l,sdp_semantics:"unified-plan",sockets:[g],session_timers:c,register_expires:E,connection_recovery_min_interval:d,connection_recovery_max_interval:T},helpers:{socket:g,getSipServerUrl:u}}}async sendPresentation(e,t,{maxBitrate:n=St,isNeedReinvite:i=!0,isP2P:o=!1,contentHint:a="detail",sendEncodings:c,onAddedTransceiver:E}){const d=p(t,{contentHint:a});if(d===void 0)throw new Error("No streamPresentationCurrent");this.streamPresentationCurrent=d;const T=o?[Hn]:[bn],l=e.sendInfo(D,void 0,{extraHeaders:T}).then(async()=>e.startPresentation(d,i,{sendEncodings:c,onAddedTransceiver:E})).then(async()=>{const{connection:S}=this;if(!S)return;const u=S.getSenders();await Gn(u,t,n)}).then(()=>t).catch(S=>{throw this.removeStreamPresentationCurrent(),this.sessionEvents.trigger(W,S),S});return this.promisePendingStartPresentation=l,l.finally(()=>{this.promisePendingStartPresentation=void 0})}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}cancelRequestsAndResetPresentation(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}generateStream(e,t){const{id:n}=e,i=this.remoteStreams[n]??new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this.remoteStreams[n]=i,i}generateAudioStream(e){const{id:t}=e,n=this.remoteStreams[t]??new MediaStream;return n.addTrack(e),this.remoteStreams[t]=n,n}generateStreams(e){const t=[];return e.forEach((n,i)=>{if(n.kind==="audio")return;const o=n,a=e[i-1];let c;(a==null?void 0:a.kind)==="audio"&&(c=a);const E=this.generateStream(o,c);t.push(E)}),t}generateAudioStreams(e){return e.map(n=>this.generateAudioStream(n))}cancelRequests(){this.cancelConnectWithRepeatedCalls()}cancelConnectWithRepeatedCalls(){var e;(e=this.cancelableConnectWithRepeatedCalls)==null||e.cancel()}}exports.BAD_MEDIA_DESCRIPTION=xe;exports.EEventsMainCAM=R;exports.EEventsMic=k;exports.EEventsSyncMediaState=B;exports.EMimeTypesVideoCodecs=At;exports.EUseLicense=Nt;exports.NOT_FOUND=Be;exports.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS=V;exports.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS=x;exports.REJECTED=X;exports.SESSION_EVENT_NAMES=ve;exports.SipConnector=hs;exports.UA_JSSIP_EVENT_NAMES=Y;exports.causes=$t;exports.constants=Gt;exports.disableDebug=Qt;exports.enableDebug=Xt;exports.eventNames=Jt;exports.hasCanceledCallError=Kn;exports.hasCanceledStartPresentationError=Zn;exports.logger=v;exports.setEncodingsToSender=Rt;exports.setParametersToSender=_t;
package/dist/doMock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var F=Object.defineProperty;var L=(o,e,t)=>e in o?F(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var r=(o,e,t)=>L(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./SipConnector-J07EhbbA.cjs"),V=require("@krivega/jssip/lib/NameAddrHeader"),U=require("@krivega/jssip/lib/URI"),z=require("node:events"),x=require("@krivega/jssip/lib/SIPMessage"),y=require("webrtc-mock"),A=require("events-constructor"),u=require("@krivega/jssip");class v extends x.IncomingRequest{constructor(t){super();r(this,"headers");this.headers=new Headers(t)}getHeader(t){return this.headers.get(t)??""}}class q{constructor({originator:e="local",eventHandlers:t}){r(this,"originator");r(this,"connection");r(this,"events");r(this,"remote_identity");r(this,"mutedOptions",{audio:!1,video:!1});this.originator=e,this.events=new A(p.SESSION_EVENT_NAMES),this.initEvents(t)}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,n){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,n])=>this.on(t,n))}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 H{constructor({track:e}={}){r(this,"dtmf",null);r(this,"track",null);r(this,"transport",null);r(this,"transform",null);r(this,"parameters",{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}});r(this,"parametersGets");this.track=e??null}async getStats(){throw new Error("Method not implemented.")}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class Y{constructor(e,t){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",e=>{const t=new H({track:e});return this.senders.push(t),t});this.receivers=t.map(n=>({track:n}))}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,n){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,n){throw new Error("Method not implemented.")}removeEventListener(e,t,n){throw new Error("Method not implemented.")}dispatchEvent(e){throw new Error("Method not implemented.")}}function j(o){const e=o.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const S=400,O="777",B=o=>o.getVideoTracks().length>0,a=class a extends q{constructor({url:t="",mediaStream:n,eventHandlers:i,originator:d}){super({originator:d,eventHandlers:i});r(this,"url");r(this,"status_code");r(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)},S)}));r(this,"isEndedInner",!1);this.url=t,this.initPeerconnection(n)}static setStartPresentationError(t,{count:n=Number.POSITIVE_INFINITY}={}){this.startPresentationError=t,this.countStartPresentationError=n}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}async startPresentation(t){if(a.countStartsPresentation+=1,a.startPresentationError&&a.countStartsPresentation<a.countStartPresentationError)throw a.startPresentationError;return super.startPresentation(t)}initPeerconnection(t){return t?(this.createPeerconnection(t),!0):!1}createPeerconnection(t){const n=y.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(B(t)){const c=y.createVideoMediaStreamTrackMock();c.id="mainvideo1",i.push(c)}this.connection=new Y(void 0,i),this.addStream(t),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},S)}connect(t){const n=j(t);setTimeout(()=>{this.url.includes(O)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:p.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},S)}terminate({status_code:t,cause:n}={}){return this.status_code=t,this.trigger("ended",{status_code:t,cause:n,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:t,cause:n}={}){this.terminate({status_code:t,cause:n})}terminateRemote({status_code:t}={}){return this.status_code=t,this.trigger("ended",{status_code:t,originator:"remote"}),this}addStream(t,n="getTracks"){t[n]().forEach(i=>this.connection.addTrack(i))}forEachSenders(t){const n=this.connection.getSenders();for(const i of n)t(i);return n}toggleMuteAudio(t){this.forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!t)})}toggleMuteVideo(t){this.forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.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){}onmute({audio:t,video:n}){this.trigger("muted",{audio:t,video:n})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(t){this.trigger("newInfo",t)}};r(a,"startPresentationError"),r(a,"countStartPresentationError",Number.POSITIVE_INFINITY),r(a,"countStartsPresentation",0);let g=a;class G{constructor(){r(this,"extraHeaders",[])}setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const h="PASSWORD_CORRECT",I="PASSWORD_CORRECT_2",k="NAME_INCORRECT",l=400,f={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},N={status_code:200,reason_phrase:"OK"},P={status_code:401,reason_phrase:"Unauthorized"},s=class s{constructor(e){r(this,"events");r(this,"registratorInner");r(this,"call",jest.fn((e,t)=>{const{mediaStream:n,eventHandlers:i}=t;return this.session=new g({url:e,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(e),this.session}));r(this,"startedTimeout");r(this,"stopedTimeout");r(this,"session");r(this,"isRegisteredInner");r(this,"isConnectedInner");r(this,"configuration");this.events=new A(p.UA_JSSIP_EVENT_NAMES);const[t,n]=e.uri.split(":"),[i,d]=n.split("@"),c={...e,uri:new u.URI(t,i,d)};this.configuration=c,this.registratorInner=new G}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startError=e,this.countStartError=t}static resetStartError(){this.startError=void 0,this.countStartError=Number.POSITIVE_INFINITY,this.countStarts=0}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}start(){if(s.countStarts+=1,s.startError&&s.countStarts<s.countStartError){this.trigger("disconnected",s.startError);return}this.register()}stop(){this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:f})},l):this.trigger("disconnected",{error:!0,socket:f})}on(e,t){return this.events.on(e,t),this}once(e,t){return this.events.once(e,t),this}off(e,t){return this.events.off(e,t),this}removeAllListeners(){return this.events.removeEventHandlers(),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){var e;(e=this.session)==null||e.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:n}=this.configuration;t===!0&&n.user.includes(k)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:u.C.causes.REJECTED})},l)):!this.isRegistered()&&t===!0&&(e===h||e===I)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:N})},l)):t===!0&&e!==h&&e!==I&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:u.C.causes.REJECTED})},l)),s.isAvailableTelephony?(this.trigger("connected",{socket:f}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:N})}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}};r(s,"isAvailableTelephony",!0),r(s,"startError"),r(s,"countStartError",Number.POSITIVE_INFINITY),r(s,"countStarts",0);let M=s;class J{constructor(e){r(this,"url");this.url=e}}class K extends z.EventEmitter{constructor(t,n){super();r(this,"contentType");r(this,"body");this.contentType=t,this.body=n}}const T="remote",$=(o,e)=>{const t=new v(e),n={originator:T,request:t,info:new K("","")};o.newInfo(n)},X=(o,e)=>{const n={event:"sipEvent",request:new v(e)};o.newSipEvent(n)},Q=(o,{incomingNumber:e="1234",displayName:t,host:n})=>{const i=new g({originator:T,eventHandlers:{}}),d=new U("sip",e,n);i.remote_identity=new V(d,t);const c=new v([]);o.trigger("newRTCSession",{originator:T,session:i,request:c})},Z=(o,e)=>{e?o.trigger("failed",e):o.trigger("failed",o)},W={triggerNewInfo:$,triggerNewSipEvent:X,triggerIncomingSession:Q,triggerFailIncomingSession:Z,WebSocketInterface:J,UA:M,C:{INVITE:"INVITE"}},E="user",m="displayName",w="SIP_SERVER_URL",R="SIP_WEB_SOCKET_SERVER_URL",ee=new W.WebSocketInterface(R),C={userAgent:"Chrome",sipServerUrl:w,sipWebSocketServerURL:R},te={...C},b={...C,user:E,password:h,register:!0},re={...b,displayName:m},ne={...C,displayName:m,register:!1},_={session_timers:!1,sockets:[ee],user_agent:"Chrome",sdp_semantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},oe={..._,password:h,uri:new u.URI("sip",E,w),display_name:"",register:!0},ie={..._,password:h,uri:new u.URI("sip",E,w),display_name:m,register:!0},se={..._,display_name:m,register:!1},ae={..._,display_name:"",register:!1},D="10.10.10.10",de=[`X-Vinteo-Remote: ${D}`],ce=()=>new p.SipConnector({JsSIP:W});exports.FAILED_CONFERENCE_NUMBER=O;exports.NAME_INCORRECT=k;exports.PASSWORD_CORRECT=h;exports.PASSWORD_CORRECT_2=I;exports.SIP_SERVER_URL=w;exports.SIP_WEB_SOCKET_SERVER_URL=R;exports.dataForConnectionWithAuthorization=b;exports.dataForConnectionWithAuthorizationWithDisplayName=re;exports.dataForConnectionWithoutAuthorization=ne;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=te;exports.displayName=m;exports.doMockSipConnector=ce;exports.extraHeadersRemoteAddress=de;exports.remoteAddress=D;exports.uaConfigurationWithAuthorization=oe;exports.uaConfigurationWithAuthorizationWithDisplayName=ie;exports.uaConfigurationWithoutAuthorization=se;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ae;exports.user=E;
1
+ "use strict";var F=Object.defineProperty;var L=(o,e,t)=>e in o?F(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var r=(o,e,t)=>L(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./SipConnector-ChW25Tx9.cjs"),V=require("@krivega/jssip/lib/NameAddrHeader"),U=require("@krivega/jssip/lib/URI"),z=require("node:events"),x=require("@krivega/jssip/lib/SIPMessage"),y=require("webrtc-mock"),A=require("events-constructor"),u=require("@krivega/jssip");class v extends x.IncomingRequest{constructor(t){super();r(this,"headers");this.headers=new Headers(t)}getHeader(t){return this.headers.get(t)??""}}class q{constructor({originator:e="local",eventHandlers:t}){r(this,"originator");r(this,"connection");r(this,"events");r(this,"remote_identity");r(this,"mutedOptions",{audio:!1,video:!1});this.originator=e,this.events=new A(p.SESSION_EVENT_NAMES),this.initEvents(t)}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,n){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,n])=>this.on(t,n))}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 H{constructor({track:e}={}){r(this,"dtmf",null);r(this,"track",null);r(this,"transport",null);r(this,"transform",null);r(this,"parameters",{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}});r(this,"parametersGets");this.track=e??null}async getStats(){throw new Error("Method not implemented.")}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class Y{constructor(e,t){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",e=>{const t=new H({track:e});return this.senders.push(t),t});this.receivers=t.map(n=>({track:n}))}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,n){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,n){throw new Error("Method not implemented.")}removeEventListener(e,t,n){throw new Error("Method not implemented.")}dispatchEvent(e){throw new Error("Method not implemented.")}}function j(o){const e=o.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const S=400,O="777",B=o=>o.getVideoTracks().length>0,a=class a extends q{constructor({url:t="",mediaStream:n,eventHandlers:i,originator:d}){super({originator:d,eventHandlers:i});r(this,"url");r(this,"status_code");r(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)},S)}));r(this,"isEndedInner",!1);this.url=t,this.initPeerconnection(n)}static setStartPresentationError(t,{count:n=Number.POSITIVE_INFINITY}={}){this.startPresentationError=t,this.countStartPresentationError=n}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}async startPresentation(t){if(a.countStartsPresentation+=1,a.startPresentationError&&a.countStartsPresentation<a.countStartPresentationError)throw a.startPresentationError;return super.startPresentation(t)}initPeerconnection(t){return t?(this.createPeerconnection(t),!0):!1}createPeerconnection(t){const n=y.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(B(t)){const c=y.createVideoMediaStreamTrackMock();c.id="mainvideo1",i.push(c)}this.connection=new Y(void 0,i),this.addStream(t),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},S)}connect(t){const n=j(t);setTimeout(()=>{this.url.includes(O)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:p.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},S)}terminate({status_code:t,cause:n}={}){return this.status_code=t,this.trigger("ended",{status_code:t,cause:n,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:t,cause:n}={}){this.terminate({status_code:t,cause:n})}terminateRemote({status_code:t}={}){return this.status_code=t,this.trigger("ended",{status_code:t,originator:"remote"}),this}addStream(t,n="getTracks"){t[n]().forEach(i=>this.connection.addTrack(i))}forEachSenders(t){const n=this.connection.getSenders();for(const i of n)t(i);return n}toggleMuteAudio(t){this.forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!t)})}toggleMuteVideo(t){this.forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.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){}onmute({audio:t,video:n}){this.trigger("muted",{audio:t,video:n})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(t){this.trigger("newInfo",t)}};r(a,"startPresentationError"),r(a,"countStartPresentationError",Number.POSITIVE_INFINITY),r(a,"countStartsPresentation",0);let g=a;class G{constructor(){r(this,"extraHeaders",[])}setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const h="PASSWORD_CORRECT",I="PASSWORD_CORRECT_2",k="NAME_INCORRECT",l=400,f={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},N={status_code:200,reason_phrase:"OK"},P={status_code:401,reason_phrase:"Unauthorized"},s=class s{constructor(e){r(this,"events");r(this,"registratorInner");r(this,"call",jest.fn((e,t)=>{const{mediaStream:n,eventHandlers:i}=t;return this.session=new g({url:e,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(e),this.session}));r(this,"startedTimeout");r(this,"stopedTimeout");r(this,"session");r(this,"isRegisteredInner");r(this,"isConnectedInner");r(this,"configuration");this.events=new A(p.UA_JSSIP_EVENT_NAMES);const[t,n]=e.uri.split(":"),[i,d]=n.split("@"),c={...e,uri:new u.URI(t,i,d)};this.configuration=c,this.registratorInner=new G}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startError=e,this.countStartError=t}static resetStartError(){this.startError=void 0,this.countStartError=Number.POSITIVE_INFINITY,this.countStarts=0}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}start(){if(s.countStarts+=1,s.startError&&s.countStarts<s.countStartError){this.trigger("disconnected",s.startError);return}this.register()}stop(){this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:f})},l):this.trigger("disconnected",{error:!0,socket:f})}on(e,t){return this.events.on(e,t),this}once(e,t){return this.events.once(e,t),this}off(e,t){return this.events.off(e,t),this}removeAllListeners(){return this.events.removeEventHandlers(),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){var e;(e=this.session)==null||e.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:n}=this.configuration;t===!0&&n.user.includes(k)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:u.C.causes.REJECTED})},l)):!this.isRegistered()&&t===!0&&(e===h||e===I)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:N})},l)):t===!0&&e!==h&&e!==I&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:u.C.causes.REJECTED})},l)),s.isAvailableTelephony?(this.trigger("connected",{socket:f}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:N})}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}};r(s,"isAvailableTelephony",!0),r(s,"startError"),r(s,"countStartError",Number.POSITIVE_INFINITY),r(s,"countStarts",0);let M=s;class J{constructor(e){r(this,"url");this.url=e}}class K extends z.EventEmitter{constructor(t,n){super();r(this,"contentType");r(this,"body");this.contentType=t,this.body=n}}const T="remote",$=(o,e)=>{const t=new v(e),n={originator:T,request:t,info:new K("","")};o.newInfo(n)},X=(o,e)=>{const n={event:"sipEvent",request:new v(e)};o.newSipEvent(n)},Q=(o,{incomingNumber:e="1234",displayName:t,host:n})=>{const i=new g({originator:T,eventHandlers:{}}),d=new U("sip",e,n);i.remote_identity=new V(d,t);const c=new v([]);o.trigger("newRTCSession",{originator:T,session:i,request:c})},Z=(o,e)=>{e?o.trigger("failed",e):o.trigger("failed",o)},W={triggerNewInfo:$,triggerNewSipEvent:X,triggerIncomingSession:Q,triggerFailIncomingSession:Z,WebSocketInterface:J,UA:M,C:{INVITE:"INVITE"}},E="user",m="displayName",w="SIP_SERVER_URL",R="SIP_WEB_SOCKET_SERVER_URL",ee=new W.WebSocketInterface(R),C={userAgent:"Chrome",sipServerUrl:w,sipWebSocketServerURL:R},te={...C},b={...C,user:E,password:h,register:!0},re={...b,displayName:m},ne={...C,displayName:m,register:!1},_={session_timers:!1,sockets:[ee],user_agent:"Chrome",sdp_semantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},oe={..._,password:h,uri:new u.URI("sip",E,w),display_name:"",register:!0},ie={..._,password:h,uri:new u.URI("sip",E,w),display_name:m,register:!0},se={..._,display_name:m,register:!1},ae={..._,display_name:"",register:!1},D="10.10.10.10",de=[`X-Vinteo-Remote: ${D}`],ce=()=>new p.SipConnector({JsSIP:W});exports.FAILED_CONFERENCE_NUMBER=O;exports.NAME_INCORRECT=k;exports.PASSWORD_CORRECT=h;exports.PASSWORD_CORRECT_2=I;exports.SIP_SERVER_URL=w;exports.SIP_WEB_SOCKET_SERVER_URL=R;exports.dataForConnectionWithAuthorization=b;exports.dataForConnectionWithAuthorizationWithDisplayName=re;exports.dataForConnectionWithoutAuthorization=ne;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=te;exports.displayName=m;exports.doMockSipConnector=ce;exports.extraHeadersRemoteAddress=de;exports.remoteAddress=D;exports.uaConfigurationWithAuthorization=oe;exports.uaConfigurationWithAuthorizationWithDisplayName=ie;exports.uaConfigurationWithoutAuthorization=se;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ae;exports.user=E;
package/dist/doMock.js CHANGED
@@ -1,7 +1,7 @@
1
1
  var k = Object.defineProperty;
2
2
  var A = (o, e, t) => e in o ? k(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
3
  var r = (o, e, t) => A(o, typeof e != "symbol" ? e + "" : e, t);
4
- import { o as b, R as D, U as L, S as W } from "./SipConnector-D9frFCEK.js";
4
+ import { o as b, R as D, U as L, S as W } from "./SipConnector-BHvTGgmw.js";
5
5
  import V from "@krivega/jssip/lib/NameAddrHeader";
6
6
  import F from "@krivega/jssip/lib/URI";
7
7
  import { EventEmitter as x } from "node:events";
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var te=Object.defineProperty;var oe=(n,e,t)=>e in n?te(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var a=(n,e,t)=>oe(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./SipConnector-J07EhbbA.cjs"),se=require("sequent-promises"),re=require("stack-promises"),_=require("debug"),ie=require("@krivega/cancelable-promise"),ce=require("repeated-calls"),ae=require("ts-debounce"),U=n=>{const{url:e,cause:t}=n;let o=e;return(t===s.BAD_MEDIA_DESCRIPTION||t===s.NOT_FOUND)&&(o=`${n.message.to.uri.user}@${n.message.to.uri.host}`),o};var W=(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))(W||{});const le=new Error("Unknown error"),ue=(n=le)=>{var r;const{cause:e,socket:t}=n;let o="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{o="WRONG_USER_OR_PASSWORD";break}case s.BAD_MEDIA_DESCRIPTION:{o="BAD_MEDIA_ERROR";break}case s.NOT_FOUND:{o="NOT_FOUND_ERROR";break}default:t!==void 0&&((r=t._ws)==null?void 0:r.readyState)===3?o="WS_CONNECTION_FAILED":U(n)!==void 0&&U(n)!==""&&(o="CONNECT_SERVER_FAILED_BY_LINK")}return o},de=n=>{let e="";try{e=JSON.stringify(n)}catch(t){s.logger("failed to stringify message",t)}return e},ge=new Error("Unknown error"),Ce=(n=ge)=>{const{code:e,cause:t,message:o}=n,r=U(n),i={code:"",cause:"",message:""};return typeof o=="object"&&o!==null?i.message=de(o):o&&(i.message=String(o)),r!==void 0&&r!==""&&(i.link=r),e!==void 0&&e!==""&&(i.code=e),t!==void 0&&t!==""&&(i.cause=t),i},Se=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:W,getLinkError:U,getTypeFromError:ue,getValuesFromError:Ce},Symbol.toStringTag,{value:"Module"})),fe=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:o,isRegistered:r,isPresentationCall:i})=>{const c=[],l=t?"0":"1",u=o?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${u}`),(r===!1||r===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="[@*!|]",he="_",Re=n=>{let e=n;return e=e.replaceAll(new RegExp(me,"g"),he),e},pe=({appName:n,appVersion:e,browserName:t,browserVersion:o})=>{const i=`${Re(n)} ${e}`;return`ChromeNew - ${t?`${t} ${o}, ${i}`:i}`},Ee=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:o,appName:r})=>n?pe({appVersion:e,browserName:t,browserVersion:o,appName:r}):"Chrome",G="purgatory",I=n=>n===G,ye=n=>e=>[...e].map(o=>async()=>n(o)),Te=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const r=ye(e)(n);return se.sequentPromises(r,t)},Me=n=>t=>(s.logger("onStartMainCam"),n.onSession("admin-start-main-cam",t)),be=n=>t=>(s.logger("onStartMic"),n.onSession("admin-start-mic",t)),ve=n=>t=>(s.logger("onStopMainCam"),n.onSession("admin-stop-main-cam",t)),Ae=n=>t=>(s.logger("onStopMic"),n.onSession("admin-stop-mic",t)),_e=({sipConnector:n})=>{const e=(f,p)=>({isSyncForced:m=!1})=>{if(m){f();return}p()},t=Me(n),o=ve(n),r=be(n),i=Ae(n);let c=()=>{},l=()=>{},u=()=>{},g=()=>{};const S=({onStartMainCamForced:f,onStartMainCamNotForced:p,onStopMainCamForced:m,onStopMainCamNotForced:h,onStartMicForced:E,onStartMicNotForced:y,onStopMicForced:T,onStopMicNotForced:M})=>{const A=e(f,p);c=t(A);const O=e(m,h);l=o(O);const N=e(E,y);u=r(N);const w=e(T,M);g=i(w)},C=()=>{c(),l(),u(),g()};return{start:f=>{S(f)},stop:()=>{C()}}},Oe=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:G,createSyncMediaState:_e,error:Se,getExtraHeaders:fe,getUserAgent:Ee,hasPurgatory:I,sendDtmfAccumulated:Te},Symbol.toStringTag,{value:"Module"})),Ne=n=>[...n.keys()].map(e=>n.get(e)),we=(n,e)=>Ne(n).find(t=>t.type===e),K=async n=>n.getStats().then(e=>{const t=we(e,"codec");return t==null?void 0:t.mimeType}),Pe=n=>n.find(e=>{var t;return((t=e==null?void 0:e.track)==null?void 0:t.kind)==="video"}),Y=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),De=1e6,R=n=>n*De,z=R(.06),Be=R(4),Ie=n=>n<=64?z:n<=128?R(.12):n<=256?R(.25):n<=384?R(.32):n<=426?R(.38):n<=640?R(.5):n<=848?R(.7):n<=1280?R(1):n<=1920?R(2):Be,Fe="av1",ke=n=>Y(n,Fe),Ve=.6,Q=(n,e)=>ke(e)?n*Ve:n,Ue=n=>Q(z,n),J=(n,e)=>{const t=Ie(n);return Q(t,e)},xe=1,Z=({videoTrack:n,targetSize:e,codec:t})=>{const o=n.getSettings(),r=o.width,i=o.height,c=r/e.width,l=i/e.height,u=Math.max(c,l,xe),g=J(e.width,t);return{scaleResolutionDownBy:u,maxBitrate:g}},ee=re.createStackPromises(),Le=async()=>ee().catch(n=>{s.logger("videoSendingBalancer: error",n)}),$e=async n=>(ee.add(n),Le()),q=async({sender:n,scaleResolutionDownBy:e,maxBitrate:t,onSetParameters:o})=>$e(async()=>s.setEncodingsToSender(n,{scaleResolutionDownBy:e,maxBitrate:t},o)),He=async({sender:n,codec:e},t)=>{const r=Ue(e);return q({sender:n,maxBitrate:r,onSetParameters:t,scaleResolutionDownBy:200})},V=async({sender:n,videoTrack:e,codec:t},o)=>{const c=e.getSettings().width,l=J(c,t);return q({sender:n,maxBitrate:l,onSetParameters:o,scaleResolutionDownBy:1})},qe=async({sender:n,videoTrack:e,resolution:t,codec:o},r)=>{const[i,c]=t.split("x"),{maxBitrate:l,scaleResolutionDownBy:u}=Z({videoTrack:e,codec:o,targetSize:{width:Number(i),height:Number(c)}});return q({sender:n,maxBitrate:l,onSetParameters:r,scaleResolutionDownBy:u})},Xe=async({mainCam:n,resolutionMainCam:e,sender:t,videoTrack:o,codec:r},i)=>{switch(n){case s.EEventsMainCAM.PAUSE_MAIN_CAM:return He({sender:t,codec:r},i);case s.EEventsMainCAM.RESUME_MAIN_CAM:return V({sender:t,videoTrack:o,codec:r},i);case s.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return e!==void 0?qe({sender:t,videoTrack:o,codec:r,resolution:e},i):V({sender:t,videoTrack:o,codec:r},i);case s.EEventsMainCAM.ADMIN_STOP_MAIN_CAM:case s.EEventsMainCAM.ADMIN_START_MAIN_CAM:case void 0:return V({sender:t,videoTrack:o,codec:r},i);default:return V({sender:t,videoTrack:o,codec:r},i)}},X={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},j=async({mainCam:n,resolutionMainCam:e,connection:t,onSetParameters:o,ignoreForCodec:r})=>{const i=t.getSenders(),c=Pe(i);if(!(c!=null&&c.track))return X;const l=await K(c);return Y(l,r)?X:Xe({mainCam:n,resolutionMainCam:e,sender:c,codec:l,videoTrack:c.track},o)},je=(n,{ignoreForCodec:e,onSetParameters:t}={})=>{const o=async()=>{const{connection:u}=n;if(!u)throw new Error("connection is not exist");return j({connection:u,onSetParameters:t,ignoreForCodec:e})};let r=o;const i=u=>{r=async()=>{const{mainCam:g,resolutionMainCam:S}=u,{connection:C}=n;if(!C)throw new Error("connection is not exist");return j({mainCam:g,resolutionMainCam:S,connection:C,onSetParameters:t,ignoreForCodec:e})},r().catch(_)};return{subscribe:()=>{n.onSession("main-cam-control",i)},unsubscribe:()=>{n.offSession("main-cam-control",i)},balanceByTrack:o,resetMainCamControl(){r=o},async reBalance(){return r()}}},We=n=>n.getVideoTracks()[0],D=({mediaStream:n,simulcastEncodings:e,sendEncodings:t})=>{if(e&&e.length>0){const o=t??[],r=We(n);if(r===void 0)throw new Error("No video track");return e.forEach((i,c)=>{const l=o[c]??{};l.active=!0,i.rid!==void 0&&(l.rid=i.rid),i.scalabilityMode!==void 0&&(l.scalabilityMode=i.scalabilityMode);const{maxBitrate:u,scaleResolutionDownBy:g}=Z({videoTrack:r,targetSize:{width:i.width,height:i.height}});l.maxBitrate=u,l.scaleResolutionDownBy=g,o[c]=l}),o}return t},Ge=(n,e)=>n.filter(o=>e.some(r=>r.clockRate===o.clockRate&&r.mimeType===o.mimeType&&r.channels===o.channels&&r.sdpFmtpLine===o.sdpFmtpLine)),Ke=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),o=e===null?[]:e.codecs,r=t===null?[]:t.codecs;return Ge(o,r)},Ye=(n,e)=>e===void 0||e.length===0?n:n.sort((t,o)=>{const r=e.indexOf(t.mimeType),i=e.indexOf(o.mimeType),c=r===-1?Number.MAX_VALUE:r,l=i===-1?Number.MAX_VALUE:i;return c-l}),ze=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),B=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>async o=>{var r;try{if(typeof o.setCodecPreferences=="function"&&((r=o.sender.track)==null?void 0:r.kind)==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const i=Ke("video"),c=ze(i,t),l=Ye(c,e);o.setCodecPreferences(l)}Object.keys(n).length>0&&await s.setParametersToSender(o.sender,n)}catch(i){s.logger("updateTransceiver error",i)}},H=n=>{if(!ie.isCanceledError(n)&&!ce.hasCanceledError(n))throw n;return{isSuccessful:!1}},Qe=({kind:n,readyState:e})=>n==="video"&&e==="live",Je=new Set(["on","once","onceRace","wait","off","onSession","onceSession","onceRaceSession","waitSession","offSession","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class Ze{constructor(e,{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:o}={}){a(this,"on");a(this,"once");a(this,"onceRace");a(this,"wait");a(this,"off");a(this,"onSession");a(this,"onceSession");a(this,"onceRaceSession");a(this,"waitSession");a(this,"offSession");a(this,"sendDTMF");a(this,"hangUp");a(this,"declineToIncomingCall");a(this,"sendChannels");a(this,"checkTelephony");a(this,"waitChannels");a(this,"ping");a(this,"connection");a(this,"isConfigured");a(this,"isRegistered");a(this,"sipConnector");a(this,"preferredMimeTypesVideoCodecs");a(this,"excludeMimeTypesVideoCodecs");a(this,"connectToServer",async e=>{const{userAgent:t,sipWebSocketServerURL:o,sipServerUrl:r,remoteAddress:i,displayName:c,name:l,password:u,isRegisteredUser:g,isDisconnectOnFail:S}=e;return s.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:o,sipServerUrl:r,remoteAddress:i,displayName:c,password:u,user:l,register:g}).then(C=>(s.logger("connectToServer then"),{ua:C,isSuccessful:!0})).catch(async C=>(s.logger("connectToServer catch: error",C),S===!0?this.sipConnector.disconnect().then(()=>H(C)).catch(()=>H(C)):H(C)))});a(this,"callToServer",async e=>{const{conference:t,mediaStream:o,extraHeaders:r,iceServers:i,contentHint:c,simulcastEncodings:l,degradationPreference:u,sendEncodings:g,offerToReceiveAudio:S,offerToReceiveVideo:C,directionVideo:F,directionAudio:k,setRemoteStreams:f,onBeforeProgressCall:p,onSuccessProgressCall:m,onEnterPurgatory:h,onEnterConference:E,onFailProgressCall:y,onFinishProgressCall:T,onEndedCall:M}=e,A=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:f}),O=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{A().catch(_)}}),N=B({degradationPreference:u},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});s.logger("callToServer",e);const w=async()=>(s.logger("startCall"),this.sipConnector.call({mediaStream:o,extraHeaders:r,iceServers:i,contentHint:c,offerToReceiveAudio:S,offerToReceiveVideo:C,directionVideo:F,directionAudio:k,sendEncodings:D({mediaStream:o,simulcastEncodings:l,sendEncodings:g}),number:t,onAddedTransceiver:N,ontrack:O}));let b=!1,v;const P=(s.logger("subscribeEnterConference: onEnterConference",E),h??E?this.sipConnector.onSession("enterRoom",({room:d})=>{s.logger("enterRoom",{_room:d,isSuccessProgressCall:b}),v=d,I(v)?h&&h():E&&E({isSuccessProgressCall:b})}):()=>{}),x=d=>(s.logger("onSuccess"),b=!0,A().catch(_),m&&m({isPurgatory:I(v)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),M&&M()}),d),L=d=>{throw s.logger("onFail"),y&&y(),P(),d},$=()=>{s.logger("onFinish"),T&&T()};return s.logger("onBeforeProgressCall"),p&&p(t),w().then(x).catch(d=>L(d)).finally($)});a(this,"disconnectFromServer",async()=>this.sipConnector.disconnect().then(()=>(s.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(e=>(s.logger("disconnectFromServer: catch",e),{isSuccessful:!1})));a(this,"answerIncomingCall",async e=>{const{mediaStream:t,extraHeaders:o,iceServers:r,contentHint:i,simulcastEncodings:c,degradationPreference:l,sendEncodings:u,offerToReceiveAudio:g,offerToReceiveVideo:S,directionVideo:C,directionAudio:F,setRemoteStreams:k,onBeforeProgressCall:f,onSuccessProgressCall:p,onEnterPurgatory:m,onEnterConference:h,onFailProgressCall:E,onFinishProgressCall:y,onEndedCall:T}=e,M=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:k}),A=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{M().catch(_)}}),O=B({degradationPreference:l},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});s.logger("answerIncomingCall",e);const N=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:o,iceServers:r,contentHint:i,offerToReceiveAudio:g,offerToReceiveVideo:S,directionVideo:C,directionAudio:F,sendEncodings:D({mediaStream:t,simulcastEncodings:c,sendEncodings:u}),onAddedTransceiver:O,ontrack:A}),w=()=>{const{remoteCallerData:d}=this.sipConnector;return d.incomingNumber};let b=!1,v;const P=(s.logger("subscribeEnterConference: onEnterConference",h),m??h?this.sipConnector.onSession("enterRoom",d=>{s.logger("enterRoom",{_room:d,isSuccessProgressCall:b}),v=d,I(v)?m&&m():h&&h({isSuccessProgressCall:b})}):()=>{}),x=d=>(s.logger("onSuccess"),b=!0,M().catch(_),p&&p({isPurgatory:I(v)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),T&&T()}),d),L=d=>{throw s.logger("onFail"),E&&E(),P(),d},$=()=>{s.logger("onFinish"),y&&y()};if(s.logger("onBeforeProgressCall"),f){const d=w();f(d)}return N().then(x).catch(d=>L(d)).finally($)});a(this,"updatePresentation",async({mediaStream:e,isP2P:t,maxBitrate:o,contentHint:r,simulcastEncodings:i,degradationPreference:c,sendEncodings:l,preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g})=>{const S=B({degradationPreference:c},{preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g});return s.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,maxBitrate:o,contentHint:r,sendEncodings:D({mediaStream:e,simulcastEncodings:i,sendEncodings:l}),onAddedTransceiver:S})});a(this,"startPresentation",async({mediaStream:e,isP2P:t,maxBitrate:o,contentHint:r,simulcastEncodings:i,degradationPreference:c,sendEncodings:l,preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g},S)=>{const C=B({degradationPreference:c},{preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g});return s.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,maxBitrate:o,contentHint:r,sendEncodings:D({mediaStream:e,simulcastEncodings:i,sendEncodings:l}),onAddedTransceiver:C},S)});a(this,"stopShareSipConnector",async({isP2P:e=!1}={})=>(s.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{s.logger(t)})));a(this,"sendRefusalToTurnOnMic",async()=>{this.sipConnector.isCallActive&&(s.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{s.logger("sendRefusalToTurnOnMic: error",e)}))});a(this,"sendRefusalToTurnOnCam",async()=>{this.sipConnector.isCallActive&&(s.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{s.logger("sendRefusalToTurnOnCam: error",e)}))});a(this,"sendMediaState",async({isEnabledCam:e,isEnabledMic:t})=>{this.sipConnector.isCallActive&&(s.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:e,mic:t}))});a(this,"replaceMediaStream",async(e,{deleteExisting:t,addMissing:o,forceRenegotiation:r,contentHint:i,simulcastEncodings:c,degradationPreference:l,sendEncodings:u}={})=>{const g=B({degradationPreference:l},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});return s.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:o,forceRenegotiation:r,contentHint:i,sendEncodings:D({mediaStream:e,simulcastEncodings:c,sendEncodings:u}),onAddedTransceiver:g})});a(this,"askPermissionToEnableCam",async()=>{this.sipConnector.isCallActive&&(s.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam())});a(this,"resolveHandleReadyRemoteStreamsDebounced",({onReadyRemoteStreams:e})=>ae.debounce(()=>{const t=this.sipConnector.getRemoteStreams();s.logger("remoteStreams",t),t&&e(t)},200));a(this,"resolveHandleReadyRemoteStreams",({onReadyRemoteStreams:e})=>({track:t})=>{Qe(t)&&e()});a(this,"getRemoteStreams",()=>(s.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams()));a(this,"onUseLicense",e=>(s.logger("onUseLicense"),this.sipConnector.onSession("useLicense",e)));a(this,"onMustStopPresentation",e=>(s.logger("onMustStopPresentation"),this.sipConnector.onSession("mustStopPresentation",e)));a(this,"onMoveToSpectators",e=>(s.logger("onMoveToSpectators"),this.sipConnector.onSession(s.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,e)));a(this,"onMoveToParticipants",e=>(s.logger("onMoveToParticipants"),this.sipConnector.onSession(s.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,e)));return this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=o,this.sipConnector=e,new Proxy(this,{get:(r,i,c)=>{if(typeof i=="string"&&Je.has(i)&&i in this.sipConnector){const u=Reflect.get(this.sipConnector,i,this.sipConnector);return typeof u=="function"?u.bind(this.sipConnector):u}const l=Reflect.get(r,i,c);return typeof l=="function"?l.bind(r):l}})}}exports.EEventsMainCAM=s.EEventsMainCAM;exports.EEventsMic=s.EEventsMic;exports.EEventsSyncMediaState=s.EEventsSyncMediaState;exports.EMimeTypesVideoCodecs=s.EMimeTypesVideoCodecs;exports.EUseLicense=s.EUseLicense;exports.SipConnector=s.SipConnector;exports.causes=s.causes;exports.constants=s.constants;exports.disableDebug=s.disableDebug;exports.enableDebug=s.enableDebug;exports.eventNames=s.eventNames;exports.hasCanceledCallError=s.hasCanceledCallError;exports.hasCanceledStartPresentationError=s.hasCanceledStartPresentationError;exports.setParametersToSender=s.setParametersToSender;exports.debug=_;exports.SipConnectorFacade=Ze;exports.getCodecFromSender=K;exports.resolveVideoSendingBalancer=je;exports.tools=Oe;
1
+ "use strict";var se=Object.defineProperty;var oe=(n,e,t)=>e in n?se(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var a=(n,e,t)=>oe(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./SipConnector-ChW25Tx9.cjs"),re=require("sequent-promises"),ie=require("stack-promises"),_=require("debug"),ce=require("@krivega/cancelable-promise"),ae=require("repeated-calls"),le=require("ts-debounce"),U=n=>{const{url:e,cause:t}=n;let s=e;return(t===o.BAD_MEDIA_DESCRIPTION||t===o.NOT_FOUND)&&(s=`${n.message.to.uri.user}@${n.message.to.uri.host}`),s};var G=(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))(G||{});const ue=new Error("Unknown error"),de=(n=ue)=>{var r;const{cause:e,socket:t}=n;let s="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{s="WRONG_USER_OR_PASSWORD";break}case o.BAD_MEDIA_DESCRIPTION:{s="BAD_MEDIA_ERROR";break}case o.NOT_FOUND:{s="NOT_FOUND_ERROR";break}default:t!==void 0&&((r=t._ws)==null?void 0:r.readyState)===3?s="WS_CONNECTION_FAILED":U(n)!==void 0&&U(n)!==""&&(s="CONNECT_SERVER_FAILED_BY_LINK")}return s},ge=n=>{let e="";try{e=JSON.stringify(n)}catch(t){o.logger("failed to stringify message",t)}return e},Ce=new Error("Unknown error"),Se=(n=Ce)=>{const{code:e,cause:t,message:s}=n,r=U(n),i={code:"",cause:"",message:""};return typeof s=="object"&&s!==null?i.message=ge(s):s&&(i.message=String(s)),r!==void 0&&r!==""&&(i.link=r),e!==void 0&&e!==""&&(i.code=e),t!==void 0&&t!==""&&(i.cause=t),i},fe=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:G,getLinkError:U,getTypeFromError:de,getValuesFromError:Se},Symbol.toStringTag,{value:"Module"})),me=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:s,isRegistered:r,isPresentationCall:i})=>{const c=[],l=t?"0":"1",u=s?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${u}`),(r===!1||r===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},he="[@*!|]",Re="_",pe=n=>{let e=n;return e=e.replaceAll(new RegExp(he,"g"),Re),e},Ee=({appName:n,appVersion:e,browserName:t,browserVersion:s})=>{const i=`${pe(n)} ${e}`;return`ChromeNew - ${t===void 0?i:`${t} ${s}, ${i}`}`},ye=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:s,appName:r})=>n?Ee({appVersion:e,browserName:t,browserVersion:s,appName:r}):"Chrome",K="purgatory",I=n=>n===K,Te=n=>e=>[...e].map(s=>async()=>n(s)),Me=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const r=Te(e)(n);return re.sequentPromises(r,t)},be=n=>t=>(o.logger("onStartMainCam"),n.onSession("admin-start-main-cam",t)),ve=n=>t=>(o.logger("onStartMic"),n.onSession("admin-start-mic",t)),Ae=n=>t=>(o.logger("onStopMainCam"),n.onSession("admin-stop-main-cam",t)),_e=n=>t=>(o.logger("onStopMic"),n.onSession("admin-stop-mic",t)),Oe=({sipConnector:n})=>{const e=(f,p)=>({isSyncForced:m=!1})=>{if(m){f();return}p()},t=be(n),s=Ae(n),r=ve(n),i=_e(n);let c=()=>{},l=()=>{},u=()=>{},g=()=>{};const S=({onStartMainCamForced:f,onStartMainCamNotForced:p,onStopMainCamForced:m,onStopMainCamNotForced:h,onStartMicForced:E,onStartMicNotForced:y,onStopMicForced:T,onStopMicNotForced:M})=>{const A=e(f,p);c=t(A);const O=e(m,h);l=s(O);const N=e(E,y);u=r(N);const w=e(T,M);g=i(w)},C=()=>{c(),l(),u(),g()};return{start:f=>{S(f)},stop:()=>{C()}}},Ne=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:K,createSyncMediaState:Oe,error:fe,getExtraHeaders:me,getUserAgent:ye,hasPurgatory:I,sendDtmfAccumulated:Me},Symbol.toStringTag,{value:"Module"})),we=n=>[...n.keys()].map(e=>n.get(e)),Pe=(n,e)=>we(n).find(t=>(t==null?void 0:t.type)===e),Y=async n=>n.getStats().then(e=>{const t=Pe(e,"codec");return t==null?void 0:t.mimeType}),De=n=>n.find(e=>{var t;return((t=e.track)==null?void 0:t.kind)==="video"}),z=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),Be=1e6,R=n=>n*Be,Q=R(.06),Ie=R(4),Fe=n=>n<=64?Q:n<=128?R(.12):n<=256?R(.25):n<=384?R(.32):n<=426?R(.38):n<=640?R(.5):n<=848?R(.7):n<=1280?R(1):n<=1920?R(2):Ie,ke="av1",Ve=n=>z(n,ke),Ue=.6,J=(n,e)=>Ve(e)?n*Ue:n,xe=n=>J(Q,n),Z=(n,e)=>{const t=Fe(n);return J(t,e)},H=1,ee=({videoTrack:n,targetSize:e,codec:t})=>{const s=n.getSettings(),r=s.width,i=s.height,c=r===void 0?H:r/e.width,l=i===void 0?H:i/e.height,u=Math.max(c,l,H),g=Z(e.width,t);return{scaleResolutionDownBy:u,maxBitrate:g}},ne=ie.createStackPromises(),Le=async()=>ne().catch(n=>{o.logger("videoSendingBalancer: error",n)}),$e=async n=>(ne.add(n),Le()),X=async({sender:n,scaleResolutionDownBy:e,maxBitrate:t,onSetParameters:s})=>$e(async()=>o.setEncodingsToSender(n,{scaleResolutionDownBy:e,maxBitrate:t},s)),He=async({sender:n,codec:e},t)=>{const r=xe(e);return X({sender:n,maxBitrate:r,onSetParameters:t,scaleResolutionDownBy:200})},V=async({sender:n,videoTrack:e,codec:t},s)=>{const c=e.getSettings().width,l=Z(c,t);return X({sender:n,maxBitrate:l,onSetParameters:s,scaleResolutionDownBy:1})},qe=async({sender:n,videoTrack:e,resolution:t,codec:s},r)=>{const[i,c]=t.split("x"),{maxBitrate:l,scaleResolutionDownBy:u}=ee({videoTrack:e,codec:s,targetSize:{width:Number(i),height:Number(c)}});return X({sender:n,maxBitrate:l,onSetParameters:r,scaleResolutionDownBy:u})},Xe=async({mainCam:n,resolutionMainCam:e,sender:t,videoTrack:s,codec:r},i)=>{switch(n){case o.EEventsMainCAM.PAUSE_MAIN_CAM:return He({sender:t,codec:r},i);case o.EEventsMainCAM.RESUME_MAIN_CAM:return V({sender:t,videoTrack:s,codec:r},i);case o.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return e!==void 0?qe({sender:t,videoTrack:s,codec:r,resolution:e},i):V({sender:t,videoTrack:s,codec:r},i);case o.EEventsMainCAM.ADMIN_STOP_MAIN_CAM:case o.EEventsMainCAM.ADMIN_START_MAIN_CAM:case void 0:return V({sender:t,videoTrack:s,codec:r},i);default:return V({sender:t,videoTrack:s,codec:r},i)}},j={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},W=async({mainCam:n,resolutionMainCam:e,connection:t,onSetParameters:s,ignoreForCodec:r})=>{const i=t.getSenders(),c=De(i);if(!(c!=null&&c.track))return j;const l=await Y(c);return z(l,r)?j:Xe({mainCam:n,resolutionMainCam:e,sender:c,codec:l,videoTrack:c.track},s)},je=(n,{ignoreForCodec:e,onSetParameters:t}={})=>{const s=async()=>{const{connection:u}=n;if(!u)throw new Error("connection is not exist");return W({connection:u,onSetParameters:t,ignoreForCodec:e})};let r=s;const i=u=>{r=async()=>{const{mainCam:g,resolutionMainCam:S}=u,{connection:C}=n;if(!C)throw new Error("connection is not exist");return W({mainCam:g,resolutionMainCam:S,connection:C,onSetParameters:t,ignoreForCodec:e})},r().catch(_)};return{subscribe:()=>{n.onSession("main-cam-control",i)},unsubscribe:()=>{n.offSession("main-cam-control",i)},balanceByTrack:s,resetMainCamControl(){r=s},async reBalance(){return r()}}},We=n=>n.getVideoTracks()[0],D=({mediaStream:n,simulcastEncodings:e,sendEncodings:t})=>{if(e&&e.length>0){const s=t??[],r=We(n);if(r===void 0)throw new Error("No video track");return e.forEach((i,c)=>{const l=s[c]??{};l.active=!0,i.rid!==void 0&&(l.rid=i.rid),i.scalabilityMode!==void 0&&(l.scalabilityMode=i.scalabilityMode);const{maxBitrate:u,scaleResolutionDownBy:g}=ee({videoTrack:r,targetSize:{width:i.width,height:i.height}});l.maxBitrate=u,l.scaleResolutionDownBy=g,s[c]=l}),s}return t},Ge=(n,e)=>n.filter(s=>e.some(r=>r.clockRate===s.clockRate&&r.mimeType===s.mimeType&&r.channels===s.channels&&r.sdpFmtpLine===s.sdpFmtpLine)),Ke=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,r=t===null?[]:t.codecs;return Ge(s,r)},Ye=(n,e)=>e===void 0||e.length===0?n:n.sort((t,s)=>{const r=e.indexOf(t.mimeType),i=e.indexOf(s.mimeType),c=r===-1?Number.MAX_VALUE:r,l=i===-1?Number.MAX_VALUE:i;return c-l}),ze=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),B=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>async s=>{var r;try{if(typeof s.setCodecPreferences=="function"&&((r=s.sender.track)==null?void 0:r.kind)==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const i=Ke("video"),c=ze(i,t),l=Ye(c,e);s.setCodecPreferences(l)}Object.keys(n).length>0&&await o.setParametersToSender(s.sender,n)}catch(i){o.logger("updateTransceiver error",i)}},q=n=>{if(!ce.isCanceledError(n)&&!ae.hasCanceledError(n))throw n;return{isSuccessful:!1}},Qe=({kind:n,readyState:e})=>n==="video"&&e==="live",Je=new Set(["on","once","onceRace","wait","off","onSession","onceSession","onceRaceSession","waitSession","offSession","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class Ze{constructor(e,{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s}={}){a(this,"on");a(this,"once");a(this,"onceRace");a(this,"wait");a(this,"off");a(this,"onSession");a(this,"onceSession");a(this,"onceRaceSession");a(this,"waitSession");a(this,"offSession");a(this,"sendDTMF");a(this,"hangUp");a(this,"declineToIncomingCall");a(this,"sendChannels");a(this,"checkTelephony");a(this,"waitChannels");a(this,"ping");a(this,"connection");a(this,"isConfigured");a(this,"isRegistered");a(this,"sipConnector");a(this,"preferredMimeTypesVideoCodecs");a(this,"excludeMimeTypesVideoCodecs");a(this,"connectToServer",async e=>{const{userAgent:t,sipWebSocketServerURL:s,sipServerUrl:r,remoteAddress:i,displayName:c,name:l,password:u,isRegisteredUser:g,isDisconnectOnFail:S}=e;return o.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:s,sipServerUrl:r,remoteAddress:i,displayName:c,password:u,user:l,register:g}).then(C=>(o.logger("connectToServer then"),{ua:C,isSuccessful:!0})).catch(async C=>(o.logger("connectToServer catch: error",C),S===!0?this.sipConnector.disconnect().then(()=>q(C)).catch(()=>q(C)):q(C)))});a(this,"callToServer",async e=>{const{conference:t,mediaStream:s,extraHeaders:r,iceServers:i,contentHint:c,simulcastEncodings:l,degradationPreference:u,sendEncodings:g,offerToReceiveAudio:S,offerToReceiveVideo:C,directionVideo:F,directionAudio:k,setRemoteStreams:f,onBeforeProgressCall:p,onSuccessProgressCall:m,onEnterPurgatory:h,onEnterConference:E,onFailProgressCall:y,onFinishProgressCall:T,onEndedCall:M}=e,A=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:f}),O=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{A().catch(_)}}),N=B({degradationPreference:u},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});o.logger("callToServer",e);const w=async()=>(o.logger("startCall"),this.sipConnector.call({mediaStream:s,extraHeaders:r,iceServers:i,contentHint:c,offerToReceiveAudio:S,offerToReceiveVideo:C,directionVideo:F,directionAudio:k,sendEncodings:D({mediaStream:s,simulcastEncodings:l,sendEncodings:g}),number:t,onAddedTransceiver:N,ontrack:O}));let b=!1,v;const P=(o.logger("subscribeEnterConference: onEnterConference",E),h??E?this.sipConnector.onSession("enterRoom",({room:d})=>{o.logger("enterRoom",{_room:d,isSuccessProgressCall:b}),v=d,I(v)?h&&h():E&&E({isSuccessProgressCall:b})}):()=>{}),x=d=>(o.logger("onSuccess"),b=!0,A().catch(_),m&&m({isPurgatory:I(v)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),M&&M()}),d),L=d=>{throw o.logger("onFail"),y&&y(),P(),d},$=()=>{o.logger("onFinish"),T&&T()};return o.logger("onBeforeProgressCall"),p&&p(t),w().then(x).catch(d=>L(d)).finally($)});a(this,"disconnectFromServer",async()=>this.sipConnector.disconnect().then(()=>(o.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(e=>(o.logger("disconnectFromServer: catch",e),{isSuccessful:!1})));a(this,"answerIncomingCall",async e=>{const{mediaStream:t,extraHeaders:s,iceServers:r,contentHint:i,simulcastEncodings:c,degradationPreference:l,sendEncodings:u,offerToReceiveAudio:g,offerToReceiveVideo:S,directionVideo:C,directionAudio:F,setRemoteStreams:k,onBeforeProgressCall:f,onSuccessProgressCall:p,onEnterPurgatory:m,onEnterConference:h,onFailProgressCall:E,onFinishProgressCall:y,onEndedCall:T}=e,M=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:k}),A=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{M().catch(_)}}),O=B({degradationPreference:l},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});o.logger("answerIncomingCall",e);const N=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:s,iceServers:r,contentHint:i,offerToReceiveAudio:g,offerToReceiveVideo:S,directionVideo:C,directionAudio:F,sendEncodings:D({mediaStream:t,simulcastEncodings:c,sendEncodings:u}),onAddedTransceiver:O,ontrack:A}),w=()=>{const{remoteCallerData:d}=this.sipConnector;return d.incomingNumber};let b=!1,v;const P=(o.logger("subscribeEnterConference: onEnterConference",h),m??h?this.sipConnector.onSession("enterRoom",d=>{o.logger("enterRoom",{_room:d,isSuccessProgressCall:b}),v=d,I(v)?m&&m():h&&h({isSuccessProgressCall:b})}):()=>{}),x=d=>(o.logger("onSuccess"),b=!0,M().catch(_),p&&p({isPurgatory:I(v)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),T&&T()}),d),L=d=>{throw o.logger("onFail"),E&&E(),P(),d},$=()=>{o.logger("onFinish"),y&&y()};if(o.logger("onBeforeProgressCall"),f){const d=w();f(d)}return N().then(x).catch(d=>L(d)).finally($)});a(this,"updatePresentation",async({mediaStream:e,isP2P:t,maxBitrate:s,contentHint:r,simulcastEncodings:i,degradationPreference:c,sendEncodings:l,preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g})=>{const S=B({degradationPreference:c},{preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g});return o.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,maxBitrate:s,contentHint:r,sendEncodings:D({mediaStream:e,simulcastEncodings:i,sendEncodings:l}),onAddedTransceiver:S})});a(this,"startPresentation",async({mediaStream:e,isP2P:t,maxBitrate:s,contentHint:r,simulcastEncodings:i,degradationPreference:c,sendEncodings:l,preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g},S)=>{const C=B({degradationPreference:c},{preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g});return o.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,maxBitrate:s,contentHint:r,sendEncodings:D({mediaStream:e,simulcastEncodings:i,sendEncodings:l}),onAddedTransceiver:C},S)});a(this,"stopShareSipConnector",async({isP2P:e=!1}={})=>(o.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{o.logger(t)})));a(this,"sendRefusalToTurnOnMic",async()=>{this.sipConnector.isCallActive&&(o.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{o.logger("sendRefusalToTurnOnMic: error",e)}))});a(this,"sendRefusalToTurnOnCam",async()=>{this.sipConnector.isCallActive&&(o.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{o.logger("sendRefusalToTurnOnCam: error",e)}))});a(this,"sendMediaState",async({isEnabledCam:e,isEnabledMic:t})=>{this.sipConnector.isCallActive&&(o.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:e,mic:t}))});a(this,"replaceMediaStream",async(e,{deleteExisting:t,addMissing:s,forceRenegotiation:r,contentHint:i,simulcastEncodings:c,degradationPreference:l,sendEncodings:u}={})=>{const g=B({degradationPreference:l},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});return o.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:s,forceRenegotiation:r,contentHint:i,sendEncodings:D({mediaStream:e,simulcastEncodings:c,sendEncodings:u}),onAddedTransceiver:g})});a(this,"askPermissionToEnableCam",async()=>{this.sipConnector.isCallActive&&(o.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam())});a(this,"resolveHandleReadyRemoteStreamsDebounced",({onReadyRemoteStreams:e})=>le.debounce(()=>{const t=this.sipConnector.getRemoteStreams();o.logger("remoteStreams",t),t&&e(t)},200));a(this,"resolveHandleReadyRemoteStreams",({onReadyRemoteStreams:e})=>({track:t})=>{Qe(t)&&e()});a(this,"getRemoteStreams",()=>(o.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams()));a(this,"onUseLicense",e=>(o.logger("onUseLicense"),this.sipConnector.onSession("useLicense",e)));a(this,"onMustStopPresentation",e=>(o.logger("onMustStopPresentation"),this.sipConnector.onSession("mustStopPresentation",e)));a(this,"onMoveToSpectators",e=>(o.logger("onMoveToSpectators"),this.sipConnector.onSession(o.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,e)));a(this,"onMoveToParticipants",e=>(o.logger("onMoveToParticipants"),this.sipConnector.onSession(o.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,e)));return this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=s,this.sipConnector=e,new Proxy(this,{get:(r,i,c)=>{if(typeof i=="string"&&Je.has(i)&&i in this.sipConnector){const u=Reflect.get(this.sipConnector,i,this.sipConnector);return typeof u=="function"?u.bind(this.sipConnector):u}const l=Reflect.get(r,i,c);return typeof l=="function"?l.bind(r):l}})}}exports.EEventsMainCAM=o.EEventsMainCAM;exports.EEventsMic=o.EEventsMic;exports.EEventsSyncMediaState=o.EEventsSyncMediaState;exports.EMimeTypesVideoCodecs=o.EMimeTypesVideoCodecs;exports.EUseLicense=o.EUseLicense;exports.SipConnector=o.SipConnector;exports.causes=o.causes;exports.constants=o.constants;exports.disableDebug=o.disableDebug;exports.enableDebug=o.enableDebug;exports.eventNames=o.eventNames;exports.hasCanceledCallError=o.hasCanceledCallError;exports.hasCanceledStartPresentationError=o.hasCanceledStartPresentationError;exports.setParametersToSender=o.setParametersToSender;exports.debug=_;exports.SipConnectorFacade=Ze;exports.getCodecFromSender=Y;exports.resolveVideoSendingBalancer=je;exports.tools=Ne;
package/dist/index.js CHANGED
@@ -1,22 +1,22 @@
1
- var oe = Object.defineProperty;
2
- var re = (n, e, t) => e in n ? oe(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
- var a = (n, e, t) => re(n, typeof e != "symbol" ? e + "" : e, t);
4
- import { B as K, N as Y, l as c, E as B, s as ie, a as ce, P as ae, b as ue } from "./SipConnector-D9frFCEK.js";
5
- import { j as Rn, k as gn, n as yn, m as Tn, S as En, c as Mn, d as bn, f as _n, g as An, e as vn, h as On, i as Nn } from "./SipConnector-D9frFCEK.js";
6
- import { sequentPromises as de } from "sequent-promises";
7
- import { createStackPromises as le } from "stack-promises";
1
+ var re = Object.defineProperty;
2
+ var ie = (n, e, t) => e in n ? re(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
+ var a = (n, e, t) => ie(n, typeof e != "symbol" ? e + "" : e, t);
4
+ import { B as Y, N as q, l as c, E as B, s as ce, a as ae, P as ue, b as de } from "./SipConnector-BHvTGgmw.js";
5
+ import { j as Rn, k as gn, n as yn, m as Tn, S as En, c as Mn, d as bn, f as _n, g as An, e as vn, h as On, i as Nn } from "./SipConnector-BHvTGgmw.js";
6
+ import { sequentPromises as le } from "sequent-promises";
7
+ import { createStackPromises as Ce } from "stack-promises";
8
8
  import D from "debug";
9
9
  import { default as Bn } from "debug";
10
- import { isCanceledError as Ce } from "@krivega/cancelable-promise";
11
- import { hasCanceledError as Se } from "repeated-calls";
12
- import { debounce as fe } from "ts-debounce";
10
+ import { isCanceledError as Se } from "@krivega/cancelable-promise";
11
+ import { hasCanceledError as fe } from "repeated-calls";
12
+ import { debounce as me } from "ts-debounce";
13
13
  const x = (n) => {
14
14
  const { url: e, cause: t } = n;
15
15
  let s = e;
16
- return (t === K || t === Y) && (s = `${n.message.to.uri.user}@${n.message.to.uri.host}`), s;
16
+ return (t === Y || t === q) && (s = `${n.message.to.uri.user}@${n.message.to.uri.host}`), s;
17
17
  };
18
- var q = /* @__PURE__ */ ((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))(q || {});
19
- const me = new Error("Unknown error"), he = (n = me) => {
18
+ var z = /* @__PURE__ */ ((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))(z || {});
19
+ const he = new Error("Unknown error"), pe = (n = he) => {
20
20
  var o;
21
21
  const { cause: e, socket: t } = n;
22
22
  let s = "CONNECT_SERVER_FAILED";
@@ -25,11 +25,11 @@ const me = new Error("Unknown error"), he = (n = me) => {
25
25
  s = "WRONG_USER_OR_PASSWORD";
26
26
  break;
27
27
  }
28
- case K: {
28
+ case Y: {
29
29
  s = "BAD_MEDIA_ERROR";
30
30
  break;
31
31
  }
32
- case Y: {
32
+ case q: {
33
33
  s = "NOT_FOUND_ERROR";
34
34
  break;
35
35
  }
@@ -37,7 +37,7 @@ const me = new Error("Unknown error"), he = (n = me) => {
37
37
  t !== void 0 && ((o = t._ws) == null ? void 0 : o.readyState) === 3 ? s = "WS_CONNECTION_FAILED" : x(n) !== void 0 && x(n) !== "" && (s = "CONNECT_SERVER_FAILED_BY_LINK");
38
38
  }
39
39
  return s;
40
- }, pe = (n) => {
40
+ }, Re = (n) => {
41
41
  let e = "";
42
42
  try {
43
43
  e = JSON.stringify(n);
@@ -45,16 +45,16 @@ const me = new Error("Unknown error"), he = (n = me) => {
45
45
  c("failed to stringify message", t);
46
46
  }
47
47
  return e;
48
- }, Re = new Error("Unknown error"), ge = (n = Re) => {
48
+ }, ge = new Error("Unknown error"), ye = (n = ge) => {
49
49
  const { code: e, cause: t, message: s } = n, o = x(n), r = { code: "", cause: "", message: "" };
50
- return typeof s == "object" && s !== null ? r.message = pe(s) : s && (r.message = String(s)), o !== void 0 && o !== "" && (r.link = o), e !== void 0 && e !== "" && (r.code = e), t !== void 0 && t !== "" && (r.cause = t), r;
51
- }, ye = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
50
+ return typeof s == "object" && s !== null ? r.message = Re(s) : s && (r.message = String(s)), o !== void 0 && o !== "" && (r.link = o), e !== void 0 && e !== "" && (r.code = e), t !== void 0 && t !== "" && (r.cause = t), r;
51
+ }, Te = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
52
52
  __proto__: null,
53
- EErrorTypes: q,
53
+ EErrorTypes: z,
54
54
  getLinkError: x,
55
- getTypeFromError: he,
56
- getValuesFromError: ge
57
- }, Symbol.toStringTag, { value: "Module" })), Te = ({
55
+ getTypeFromError: pe,
56
+ getValuesFromError: ye
57
+ }, Symbol.toStringTag, { value: "Module" })), Ee = ({
58
58
  sessionId: n,
59
59
  remoteAddress: e,
60
60
  isMutedAudio: t,
@@ -64,38 +64,38 @@ const me = new Error("Unknown error"), he = (n = me) => {
64
64
  }) => {
65
65
  const i = [], u = t ? "0" : "1", d = s ? "0" : "1";
66
66
  return i.push(`X-Vinteo-Mic-State: ${u}`, `X-Vinteo-MainCam-State: ${d}`), (o === !1 || o === void 0) && i.push("X-Vinteo-Purgatory-Call: yes"), n !== void 0 && n !== "" && i.push(`X-Vinteo-Session: ${n}`), r === !0 && i.push("X-Vinteo-Presentation-Call: yes"), e !== void 0 && e !== "" && i.push(`X-Vinteo-Remote: ${e}`), i;
67
- }, Ee = "[@*!|]", Me = "_", be = (n) => {
67
+ }, Me = "[@*!|]", be = "_", _e = (n) => {
68
68
  let e = n;
69
- return e = e.replaceAll(new RegExp(Ee, "g"), Me), e;
70
- }, _e = ({
69
+ return e = e.replaceAll(new RegExp(Me, "g"), be), e;
70
+ }, Ae = ({
71
71
  appName: n,
72
72
  appVersion: e,
73
73
  browserName: t,
74
74
  browserVersion: s
75
75
  }) => {
76
- const r = `${be(n)} ${e}`;
77
- return `ChromeNew - ${t ? `${t} ${s}, ${r}` : r}`;
78
- }, Ae = ({
76
+ const r = `${_e(n)} ${e}`;
77
+ return `ChromeNew - ${t === void 0 ? r : `${t} ${s}, ${r}`}`;
78
+ }, ve = ({
79
79
  isUnifiedSdpSemantic: n,
80
80
  appVersion: e,
81
81
  browserName: t,
82
82
  browserVersion: s,
83
83
  appName: o
84
- }) => n ? _e({ appVersion: e, browserName: t, browserVersion: s, appName: o }) : "Chrome", z = "purgatory", k = (n) => n === z, ve = (n) => (e) => [...e].map((s) => async () => n(s)), Oe = async ({
84
+ }) => n ? Ae({ appVersion: e, browserName: t, browserVersion: s, appName: o }) : "Chrome", Q = "purgatory", k = (n) => n === Q, Oe = (n) => (e) => [...e].map((s) => async () => n(s)), Ne = async ({
85
85
  accumulatedKeys: n,
86
86
  sendKey: e,
87
87
  canRunTask: t
88
88
  }) => {
89
- const o = ve(e)(n);
90
- return de(o, t);
91
- }, Ne = (n) => (t) => (c("onStartMainCam"), n.onSession("admin-start-main-cam", t)), we = (n) => (t) => (c("onStartMic"), n.onSession("admin-start-mic", t)), Be = (n) => (t) => (c("onStopMainCam"), n.onSession("admin-stop-main-cam", t)), Pe = (n) => (t) => (c("onStopMic"), n.onSession("admin-stop-mic", t)), Ie = ({ sipConnector: n }) => {
89
+ const o = Oe(e)(n);
90
+ return le(o, t);
91
+ }, we = (n) => (t) => (c("onStartMainCam"), n.onSession("admin-start-main-cam", t)), Be = (n) => (t) => (c("onStartMic"), n.onSession("admin-start-mic", t)), Pe = (n) => (t) => (c("onStopMainCam"), n.onSession("admin-stop-main-cam", t)), Ie = (n) => (t) => (c("onStopMic"), n.onSession("admin-stop-mic", t)), De = ({ sipConnector: n }) => {
92
92
  const e = (m, g) => ({ isSyncForced: h = !1 }) => {
93
93
  if (h) {
94
94
  m();
95
95
  return;
96
96
  }
97
97
  g();
98
- }, t = Ne(n), s = Be(n), o = we(n), r = Pe(n);
98
+ }, t = we(n), s = Pe(n), o = Be(n), r = Ie(n);
99
99
  let i = () => {
100
100
  }, u = () => {
101
101
  }, d = () => {
@@ -138,39 +138,39 @@ const me = new Error("Unknown error"), he = (n = me) => {
138
138
  };
139
139
  }, Sn = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
140
140
  __proto__: null,
141
- PURGATORY_CONFERENCE_NUMBER: z,
142
- createSyncMediaState: Ie,
143
- error: ye,
144
- getExtraHeaders: Te,
145
- getUserAgent: Ae,
141
+ PURGATORY_CONFERENCE_NUMBER: Q,
142
+ createSyncMediaState: De,
143
+ error: Te,
144
+ getExtraHeaders: Ee,
145
+ getUserAgent: ve,
146
146
  hasPurgatory: k,
147
- sendDtmfAccumulated: Oe
148
- }, Symbol.toStringTag, { value: "Module" })), De = (n) => [...n.keys()].map((e) => n.get(e)), ke = (n, e) => De(n).find((t) => t.type === e), Fe = async (n) => n.getStats().then((e) => {
149
- const t = ke(e, "codec");
147
+ sendDtmfAccumulated: Ne
148
+ }, Symbol.toStringTag, { value: "Module" })), ke = (n) => [...n.keys()].map((e) => n.get(e)), Fe = (n, e) => ke(n).find((t) => (t == null ? void 0 : t.type) === e), Ve = async (n) => n.getStats().then((e) => {
149
+ const t = Fe(e, "codec");
150
150
  return t == null ? void 0 : t.mimeType;
151
- }), Ve = (n) => n.find((e) => {
151
+ }), Ue = (n) => n.find((e) => {
152
152
  var t;
153
- return ((t = e == null ? void 0 : e.track) == null ? void 0 : t.kind) === "video";
154
- }), Q = (n, e) => n !== void 0 && e !== void 0 && n.toLowerCase().includes(e.toLowerCase()), Ue = 1e6, R = (n) => n * Ue, J = R(0.06), xe = R(4), Le = (n) => n <= 64 ? J : n <= 128 ? R(0.12) : n <= 256 ? R(0.25) : n <= 384 ? R(0.32) : n <= 426 ? R(0.38) : n <= 640 ? R(0.5) : n <= 848 ? R(0.7) : n <= 1280 ? R(1) : n <= 1920 ? R(2) : xe, $e = "av1", He = (n) => Q(n, $e), Xe = 0.6, Z = (n, e) => He(e) ? n * Xe : n, je = (n) => Z(J, n), ee = (n, e) => {
155
- const t = Le(n);
156
- return Z(t, e);
157
- }, We = 1, ne = ({
153
+ return ((t = e.track) == null ? void 0 : t.kind) === "video";
154
+ }), J = (n, e) => n !== void 0 && e !== void 0 && n.toLowerCase().includes(e.toLowerCase()), xe = 1e6, R = (n) => n * xe, Z = R(0.06), Le = R(4), $e = (n) => n <= 64 ? Z : n <= 128 ? R(0.12) : n <= 256 ? R(0.25) : n <= 384 ? R(0.32) : n <= 426 ? R(0.38) : n <= 640 ? R(0.5) : n <= 848 ? R(0.7) : n <= 1280 ? R(1) : n <= 1920 ? R(2) : Le, He = "av1", Xe = (n) => J(n, He), je = 0.6, ee = (n, e) => Xe(e) ? n * je : n, We = (n) => ee(Z, n), ne = (n, e) => {
155
+ const t = $e(n);
156
+ return ee(t, e);
157
+ }, X = 1, te = ({
158
158
  videoTrack: n,
159
159
  targetSize: e,
160
160
  codec: t
161
161
  }) => {
162
- const s = n.getSettings(), o = s.width, r = s.height, i = o / e.width, u = r / e.height, d = Math.max(i, u, We), C = ee(e.width, t);
162
+ const s = n.getSettings(), o = s.width, r = s.height, i = o === void 0 ? X : o / e.width, u = r === void 0 ? X : r / e.height, d = Math.max(i, u, X), C = ne(e.width, t);
163
163
  return { scaleResolutionDownBy: d, maxBitrate: C };
164
- }, te = le(), Ge = async () => te().catch((n) => {
164
+ }, se = Ce(), Ge = async () => se().catch((n) => {
165
165
  c("videoSendingBalancer: error", n);
166
- }), Ke = async (n) => (te.add(n), Ge()), j = async ({
166
+ }), Ke = async (n) => (se.add(n), Ge()), W = async ({
167
167
  sender: n,
168
168
  scaleResolutionDownBy: e,
169
169
  maxBitrate: t,
170
170
  onSetParameters: s
171
- }) => Ke(async () => ie(n, { scaleResolutionDownBy: e, maxBitrate: t }, s)), Ye = async ({ sender: n, codec: e }, t) => {
172
- const o = je(e);
173
- return j({
171
+ }) => Ke(async () => ce(n, { scaleResolutionDownBy: e, maxBitrate: t }, s)), Ye = async ({ sender: n, codec: e }, t) => {
172
+ const o = We(e);
173
+ return W({
174
174
  sender: n,
175
175
  maxBitrate: o,
176
176
  onSetParameters: t,
@@ -181,8 +181,8 @@ const me = new Error("Unknown error"), he = (n = me) => {
181
181
  videoTrack: e,
182
182
  codec: t
183
183
  }, s) => {
184
- const i = e.getSettings().width, u = ee(i, t);
185
- return j({
184
+ const i = e.getSettings().width, u = ne(i, t);
185
+ return W({
186
186
  sender: n,
187
187
  maxBitrate: u,
188
188
  onSetParameters: s,
@@ -194,7 +194,7 @@ const me = new Error("Unknown error"), he = (n = me) => {
194
194
  resolution: t,
195
195
  codec: s
196
196
  }, o) => {
197
- const [r, i] = t.split("x"), { maxBitrate: u, scaleResolutionDownBy: d } = ne({
197
+ const [r, i] = t.split("x"), { maxBitrate: u, scaleResolutionDownBy: d } = te({
198
198
  videoTrack: e,
199
199
  codec: s,
200
200
  targetSize: {
@@ -202,7 +202,7 @@ const me = new Error("Unknown error"), he = (n = me) => {
202
202
  height: Number(i)
203
203
  }
204
204
  });
205
- return j({
205
+ return W({
206
206
  sender: n,
207
207
  maxBitrate: u,
208
208
  onSetParameters: o,
@@ -232,7 +232,7 @@ const me = new Error("Unknown error"), he = (n = me) => {
232
232
  default:
233
233
  return U({ sender: t, videoTrack: s, codec: o }, r);
234
234
  }
235
- }, W = {
235
+ }, G = {
236
236
  isChanged: !1,
237
237
  parameters: {
238
238
  encodings: [{}],
@@ -241,18 +241,18 @@ const me = new Error("Unknown error"), he = (n = me) => {
241
241
  headerExtensions: [],
242
242
  rtcp: {}
243
243
  }
244
- }, G = async ({
244
+ }, K = async ({
245
245
  mainCam: n,
246
246
  resolutionMainCam: e,
247
247
  connection: t,
248
248
  onSetParameters: s,
249
249
  ignoreForCodec: o
250
250
  }) => {
251
- const r = t.getSenders(), i = Ve(r);
251
+ const r = t.getSenders(), i = Ue(r);
252
252
  if (!(i != null && i.track))
253
- return W;
254
- const u = await Fe(i);
255
- return Q(u, o) ? W : ze(
253
+ return G;
254
+ const u = await Ve(i);
255
+ return J(u, o) ? G : ze(
256
256
  {
257
257
  mainCam: n,
258
258
  resolutionMainCam: e,
@@ -270,7 +270,7 @@ const me = new Error("Unknown error"), he = (n = me) => {
270
270
  const { connection: d } = n;
271
271
  if (!d)
272
272
  throw new Error("connection is not exist");
273
- return G({
273
+ return K({
274
274
  connection: d,
275
275
  onSetParameters: t,
276
276
  ignoreForCodec: e
@@ -282,7 +282,7 @@ const me = new Error("Unknown error"), he = (n = me) => {
282
282
  const { mainCam: C, resolutionMainCam: f } = d, { connection: S } = n;
283
283
  if (!S)
284
284
  throw new Error("connection is not exist");
285
- return G({
285
+ return K({
286
286
  mainCam: C,
287
287
  resolutionMainCam: f,
288
288
  connection: S,
@@ -318,7 +318,7 @@ const me = new Error("Unknown error"), he = (n = me) => {
318
318
  return e.forEach((r, i) => {
319
319
  const u = s[i] ?? {};
320
320
  u.active = !0, r.rid !== void 0 && (u.rid = r.rid), r.scalabilityMode !== void 0 && (u.scalabilityMode = r.scalabilityMode);
321
- const { maxBitrate: d, scaleResolutionDownBy: C } = ne({
321
+ const { maxBitrate: d, scaleResolutionDownBy: C } = te({
322
322
  videoTrack: o,
323
323
  targetSize: {
324
324
  width: r.width,
@@ -345,12 +345,12 @@ const me = new Error("Unknown error"), he = (n = me) => {
345
345
  const r = Ze("video"), i = nn(r, t), u = en(i, e);
346
346
  s.setCodecPreferences(u);
347
347
  }
348
- Object.keys(n).length > 0 && await ce(s.sender, n);
348
+ Object.keys(n).length > 0 && await ae(s.sender, n);
349
349
  } catch (r) {
350
350
  c("updateTransceiver error", r);
351
351
  }
352
- }, X = (n) => {
353
- if (!Ce(n) && !Se(n))
352
+ }, j = (n) => {
353
+ if (!Se(n) && !fe(n))
354
354
  throw n;
355
355
  return { isSuccessful: !1 };
356
356
  }, tn = ({ kind: n, readyState: e }) => n === "video" && e === "live", sn = /* @__PURE__ */ new Set([
@@ -444,7 +444,7 @@ class mn {
444
444
  password: d,
445
445
  user: u,
446
446
  register: C
447
- }).then((S) => (c("connectToServer then"), { ua: S, isSuccessful: !0 })).catch(async (S) => (c("connectToServer catch: error", S), f === !0 ? this.sipConnector.disconnect().then(() => X(S)).catch(() => X(S)) : X(S)));
447
+ }).then((S) => (c("connectToServer then"), { ua: S, isSuccessful: !0 })).catch(async (S) => (c("connectToServer catch: error", S), f === !0 ? this.sipConnector.disconnect().then(() => j(S)).catch(() => j(S)) : j(S)));
448
448
  });
449
449
  a(this, "callToServer", async (e) => {
450
450
  const {
@@ -715,7 +715,7 @@ class mn {
715
715
  });
716
716
  a(this, "resolveHandleReadyRemoteStreamsDebounced", ({
717
717
  onReadyRemoteStreams: e
718
- }) => fe(() => {
718
+ }) => me(() => {
719
719
  const t = this.sipConnector.getRemoteStreams();
720
720
  c("remoteStreams", t), t && e(t);
721
721
  }, 200));
@@ -728,8 +728,8 @@ class mn {
728
728
  a(this, "getRemoteStreams", () => (c("getRemoteStreams"), this.sipConnector.getRemoteStreams()));
729
729
  a(this, "onUseLicense", (e) => (c("onUseLicense"), this.sipConnector.onSession("useLicense", e)));
730
730
  a(this, "onMustStopPresentation", (e) => (c("onMustStopPresentation"), this.sipConnector.onSession("mustStopPresentation", e)));
731
- a(this, "onMoveToSpectators", (e) => (c("onMoveToSpectators"), this.sipConnector.onSession(ae, e)));
732
- a(this, "onMoveToParticipants", (e) => (c("onMoveToParticipants"), this.sipConnector.onSession(ue, e)));
731
+ a(this, "onMoveToSpectators", (e) => (c("onMoveToSpectators"), this.sipConnector.onSession(ue, e)));
732
+ a(this, "onMoveToParticipants", (e) => (c("onMoveToParticipants"), this.sipConnector.onSession(de, e)));
733
733
  return this.preferredMimeTypesVideoCodecs = t, this.excludeMimeTypesVideoCodecs = s, this.sipConnector = e, new Proxy(this, {
734
734
  get: (o, r, i) => {
735
735
  if (typeof r == "string" && sn.has(r) && r in this.sipConnector) {
@@ -756,10 +756,10 @@ export {
756
756
  _n as disableDebug,
757
757
  An as enableDebug,
758
758
  vn as eventNames,
759
- Fe as getCodecFromSender,
759
+ Ve as getCodecFromSender,
760
760
  On as hasCanceledCallError,
761
761
  Nn as hasCanceledStartPresentationError,
762
762
  fn as resolveVideoSendingBalancer,
763
- ce as setParametersToSender,
763
+ ae as setParametersToSender,
764
764
  Sn as tools
765
765
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sip-connector",
3
- "version": "14.1.2-5",
3
+ "version": "14.1.2-7",
4
4
  "description": "Module for connect to Vinteo server",
5
5
  "keywords": [
6
6
  "webrtc",
@@ -55,8 +55,9 @@
55
55
  "preview": "vite preview",
56
56
  "release": "standard-version && npm run release:publish",
57
57
  "release:major": "standard-version --release-as major && npm run release:publish",
58
- "release:pre": "standard-version --prerelease && npm run release:publish",
58
+ "release:pre": "standard-version --prerelease && npm run release:publish:prerelease",
59
59
  "release:publish": "git push --follow-tags origin master && npm publish --access=public",
60
+ "release:publish:prerelease": "git push --follow-tags origin test-fix && npm publish --tag prerelease",
60
61
  "test": "jest",
61
62
  "test:ci": "cross-env CI=true jest",
62
63
  "test:coverage": "yarn test:ci --coverage --reporters=default --reporters=jest-junit",
@@ -1 +0,0 @@
1
- "use strict";var Ot=Object.defineProperty;var mt=(s,e,t)=>e in s?Ot(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var r=(s,e,t)=>mt(s,typeof e!="symbol"?e+"":e,t);const Mt=require("@krivega/cancelable-promise"),we=require("events-constructor"),G=require("repeated-calls"),J=require("debug"),Dt="Connection Error",ke="Request Timeout",pt="SIP Failure Code",vt="Internal Error",yt="Busy",X="Rejected",wt="Redirected",bt="Unavailable",Be="Not Found",Ut="Address Incomplete",Lt="Incompatible SDP",Ht="Missing SDP",Wt="Authentication Error",Fe="Terminated",kt="WebRTC Error",Q="Canceled",Bt="No Answer",Ft="Expires",xt="No ACK",Vt="Dialog Error",Yt="User Denied Media Access",xe="Bad Media Description",qt="RTP Timeout",$t=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:Ut,AUTHENTICATION_ERROR:Wt,BAD_MEDIA_DESCRIPTION:xe,BUSY:yt,BYE:Fe,CANCELED:Q,CONNECTION_ERROR:Dt,DIALOG_ERROR:Vt,EXPIRES:Ft,INCOMPATIBLE_SDP:Lt,INTERNAL_ERROR:vt,MISSING_SDP:Ht,NOT_FOUND:Be,NO_ACK:xt,NO_ANSWER:Bt,REDIRECTED:wt,REJECTED:X,REQUEST_TIMEOUT:ke,RTP_TIMEOUT:qt,SIP_FAILURE_CODE:pt,UNAVAILABLE:bt,USER_DENIED_MEDIA_ACCESS:Yt,WEBRTC_ERROR:kt},Symbol.toStringTag,{value:"Module"})),z="incomingCall",j="declinedIncomingCall",K="failedIncomingCall",Z="terminatedIncomingCall",F="connecting",P="connected",C="disconnected",y="newRTCSession",O="registered",ee="unregistered",m="registrationFailed",Ve="newMessage",te="sipEvent",ne="availableSecondRemoteStream",se="notAvailableSecondRemoteStream",ie="mustStopPresentation",w="shareState",oe="enterRoom",re="useLicense",ae="peerconnection:confirmed",ce="peerconnection:ontrack",b="channels",Ee="channels:notify",de="ended:fromserver",he="main-cam-control",Se="admin-stop-main-cam",Te="admin-start-main-cam",le="admin-stop-mic",ue="admin-start-mic",U="admin-force-sync-media-state",ge="participant:added-to-list-moderators",Ce="participant:removed-from-list-moderators",_e="participant:move-request-to-stream",x="participant:move-request-to-spectators",V="participant:move-request-to-participants",Ne="participation:accepting-word-request",Ae="participation:cancelling-word-request",Re="webcast:started",fe="webcast:stopped",Ie="account:changed",Pe="account:deleted",Oe="conference:participant-token-issued",M="ended",Ye="sending",qe="reinvite",$e="replaces",Ge="refer",Je="progress",Xe="accepted",L="confirmed",H="peerconnection",A="failed",Qe="muted",ze="unmuted",me="newDTMF",Me="newInfo",je="hold",Ke="unhold",Ze="update",et="sdp",tt="icecandidate",nt="getusermediafailed",st="peerconnection:createofferfailed",it="peerconnection:createanswerfailed",ot="peerconnection:setlocaldescriptionfailed",rt="peerconnection:setremotedescriptionfailed",at="presentation:start",ct="presentation:started",Et="presentation:end",De="presentation:ended",W="presentation:failed",dt="SPECTATOR",ht="PARTICIPANT",St=1e6;var _=(s=>(s.LOCAL="local",s.REMOTE="remote",s.SYSTEM="system",s))(_||{});const Gt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:Xe,ACCOUNT_CHANGED:Ie,ACCOUNT_DELETED:Pe,ADMIN_FORCE_SYNC_MEDIA_STATE:U,ADMIN_START_MAIN_CAM:Te,ADMIN_START_MIC:ue,ADMIN_STOP_MAIN_CAM:Se,ADMIN_STOP_MIC:le,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:ne,CHANNELS:b,CHANNELS_NOTIFY:Ee,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Oe,CONFIRMED:L,CONNECTED:P,CONNECTING:F,DECLINED_INCOMING_CALL:j,DISCONNECTED:C,ENDED:M,ENDED_FROM_SERVER:de,ENTER_ROOM:oe,FAILED:A,FAILED_INCOMING_CALL:K,GET_USER_MEDIA_FAILED:nt,HOLD:je,ICE_CANDIDATE:tt,INCOMING_CALL:z,MAIN_CAM_CONTROL:he,MUST_STOP_PRESENTATION_EVENT:ie,MUTED:Qe,NEW_DTMF:me,NEW_INFO:Me,NEW_MESSAGE:Ve,NEW_RTC_SESSION:y,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:se,ONE_MEGABIT_IN_BITS:St,Originator:_,PARTICIPANT:ht,PARTICIPANT_ADDED_TO_LIST_MODERATORS:ge,PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS:V,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:x,PARTICIPANT_MOVE_REQUEST_TO_STREAM:_e,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:Ce,PARTICIPATION_ACCEPTING_WORD_REQUEST:Ne,PARTICIPATION_CANCELLING_WORD_REQUEST:Ae,PEER_CONNECTION:H,PEER_CONNECTION_CONFIRMED:ae,PEER_CONNECTION_CREATE_ANSWER_FAILED:it,PEER_CONNECTION_CREATE_OFFER_FAILED:st,PEER_CONNECTION_ONTRACK:ce,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:ot,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:rt,PRESENTATION_END:Et,PRESENTATION_ENDED:De,PRESENTATION_FAILED:W,PRESENTATION_START:at,PRESENTATION_STARTED:ct,PROGRESS:Je,REFER:Ge,REGISTERED:O,REGISTRATION_FAILED:m,REINVITE:qe,REPLACES:$e,SDP:et,SENDING:Ye,SHARE_STATE:w,SIP_EVENT:te,SPECTATOR:dt,TERMINATED_INCOMING_CALL:Z,UNHOLD:Ke,UNMUTED:ze,UNREGISTERED:ee,UPDATE:Ze,USE_LICENSE:re,WEBCAST_STARTED:Re,WEBCAST_STOPPED:fe},Symbol.toStringTag,{value:"Module"})),Tt=[z,j,Z,K,Ne,Ae,_e,Ee,Oe,Ie,Pe,Re,fe,ge,Ce],Y=[F,P,C,y,O,ee,m,Ve,te],lt=[ne,se,ie,w,oe,re,ae,ce,b,de,he,Te,Se,le,ue,U,x,V],pe=[M,F,Ye,qe,$e,Ge,Je,Xe,L,H,A,Qe,ze,me,Me,je,Ke,Ze,et,tt,nt,st,it,ot,rt,at,ct,Et,De,W],ut=[...Y,...Tt],ve=[...pe,...lt],Jt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:ve,SESSION_JSSIP_EVENT_NAMES:pe,SESSION_SYNTHETICS_EVENT_NAMES:lt,UA_EVENT_NAMES:ut,UA_JSSIP_EVENT_NAMES:Y,UA_SYNTHETICS_EVENT_NAMES:Tt},Symbol.toStringTag,{value:"Module"})),ye="sip-connector",v=J(ye),Xt=()=>{J.enable(ye)},Qt=()=>{J.enable(`-${ye}`)},zt=(s,e)=>(s.degradationPreference=e.degradationPreference,s),jt=(s,e)=>{s.encodings??(s.encodings=[]);for(let t=s.encodings.length;t<e;t+=1)s.encodings.push({});return s},gt=s=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==s,Kt=gt(),Zt=(s,e)=>{if(Kt(s,e))return s},en=(s,e)=>{const t=s.maxBitrate,n=Zt(e,t);return n!==void 0&&(s.maxBitrate=n),s},Ct=1,tn=gt(Ct),nn=(s,e)=>{const t=s===void 0?void 0:Math.max(s,Ct);if(t!==void 0&&tn(t,e))return t},sn=(s,e)=>{const t=s.scaleResolutionDownBy,n=nn(e,t);return n!==void 0&&(s.scaleResolutionDownBy=n),s},on=(s,e)=>{var n;const t=((n=e.encodings)==null?void 0:n.length)??0;return jt(s,t),s.encodings.forEach((i,o)=>{const a=((e==null?void 0:e.encodings)??[])[o],c=a==null?void 0:a.maxBitrate,E=a==null?void 0:a.scaleResolutionDownBy;en(i,c),sn(i,E)}),s},rn=(s,e)=>{var t,n,i,o,a,c,E,d,T,l,S,u;if(((t=s.codecs)==null?void 0:t.length)!==((n=e.codecs)==null?void 0:n.length))return!0;for(let h=0;h<(((i=s.codecs)==null?void 0:i.length)??0);h++)if(JSON.stringify(s.codecs[h])!==JSON.stringify(e.codecs[h]))return!0;if(((o=s.headerExtensions)==null?void 0:o.length)!==((a=e.headerExtensions)==null?void 0:a.length))return!0;for(let h=0;h<(((c=s.headerExtensions)==null?void 0:c.length)??0);h++)if(JSON.stringify(s.headerExtensions[h])!==JSON.stringify(e.headerExtensions[h]))return!0;if(((E=s.encodings)==null?void 0:E.length)!==((d=e.encodings)==null?void 0:d.length))return!0;for(let h=0;h<(s.encodings.length??0);h++)if(JSON.stringify(s.encodings[h])!==JSON.stringify(e.encodings[h]))return!0;return((T=s.rtcp)==null?void 0:T.cname)!==((l=e.rtcp)==null?void 0:l.cname)||((S=s.rtcp)==null?void 0:S.reducedSize)!==((u=e.rtcp)==null?void 0:u.reducedSize)||s.degradationPreference!==e.degradationPreference},_t=async(s,e)=>{const t=s.getParameters(),n=JSON.parse(JSON.stringify(t));on(t,e),zt(t,e);const i=rn(n,t);return i&&await s.setParameters(t),{parameters:t,isChanged:i}};var R=(s=>(s.PAUSE_MAIN_CAM="PAUSEMAINCAM",s.RESUME_MAIN_CAM="RESUMEMAINCAM",s.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",s.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",s.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",s))(R||{}),k=(s=>(s.ADMIN_STOP_MIC="ADMINSTOPMIC",s.ADMIN_START_MIC="ADMINSTARTMIC",s))(k||{}),B=(s=>(s.ADMIN_SYNC_FORCED="1",s.ADMIN_SYNC_NOT_FORCED="0",s))(B||{}),Nt=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",s))(Nt||{}),At=(s=>(s.VP8="video/VP8",s.VP9="video/VP9",s.H264="video/H264",s.AV1="video/AV1",s.rtx="video/rtx",s.red="video/red",s.flexfec03="video/flexfec-03",s))(At||{});const Rt=async(s,e,t)=>{const{isChanged:n,parameters:i}=await _t(s,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return n&&t&&t(i),{isChanged:n,parameters:i}};function an(s){return e=>`sip:${e}@${s}`}const cn=(s,e)=>()=>Math.floor(Math.random()*(e-s))+s,be=s=>s.trim().replaceAll(" ","_"),En=cn(1e5,99999999),dn=s=>s.some(t=>{const{kind:n}=t;return n==="video"}),hn=s=>{const e=[];return s!==void 0&&s!==""&&e.push(`X-Vinteo-Remote: ${s}`),e},Sn="content-type",Tn="x-webrtc-enter-room",D="application/vinteo.webrtc.sharedesktop",ln="application/vinteo.webrtc.roomname",un="application/vinteo.webrtc.channels",gn="application/vinteo.webrtc.mediastate",Cn="application/vinteo.webrtc.refusal",Ue="application/vinteo.webrtc.maincam",_n="application/vinteo.webrtc.mic",Nn="application/vinteo.webrtc.uselic",An="X-WEBRTC-USE-LICENSE",Rn="X-WEBRTC-PARTICIPANT-NAME",Le="X-WEBRTC-INPUT-CHANNELS",He="X-WEBRTC-OUTPUT-CHANNELS",fn="X-WEBRTC-MAINCAM",In="X-WEBRTC-MIC",We="X-WEBRTC-SYNC",Pn="X-WEBRTC-MAINCAM-RESOLUTION",On="X-WEBRTC-MEDIA-STATE",mn="X-Vinteo-Media-Type",Mn="X-Vinteo-MainCam-State",Dn="X-Vinteo-Mic-State",pn="application/vinteo.webrtc.partstate",vn="X-WEBRTC-PARTSTATE",yn="application/vinteo.webrtc.notify",wn="X-VINTEO-NOTIFY",f="x-webrtc-share-state",bn=`${f}: LETMESTARTPRESENTATION`,Un=`${f}: STOPPRESENTATION`,ft="YOUCANRECEIVECONTENT",It="CONTENTEND",Pt="YOUMUSTSTOPSENDCONTENT",Ln=`${f}: ${Pt}`,Hn=`${f}: ${ft}`,Wn=`${f}: ${It}`,kn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Bn=`${kn}: LETMESTARTMAINCAM`,Fn=(s,e)=>{s.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},p=(s,{directionVideo:e,directionAudio:t,contentHint:n}={})=>{if(!s||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:s.getAudioTracks(),o=e==="recvonly"?[]:s.getVideoTracks(),a=[...i,...o],c=new MediaStream(a);return c.getTracks=()=>[...c.getAudioTracks(),...c.getVideoTracks()],n&&n!=="none"&&Fn(c,n),c},xn="Error decline with 603",Vn=1006,Yn=s=>typeof s=="object"&&s!==null&&"code"in s&&s.code===Vn,qn=s=>s.message===xn,$n=(s,e)=>s.find(t=>t.track&&e.getTracks().includes(t.track)),Gn=async(s,e,t)=>{const n=$n(s,e);if(n)return Rt(n,{maxBitrate:t})},Jn=486,Xn=487,Qn=3,zn=1,jn=s=>s instanceof Object&&("originator"in s||"cause"in s),Kn=s=>{if(Mt.isCanceledError(s))return!0;if(!jn(s))return!1;const{originator:e,cause:t}=s;return typeof t=="string"?t===ke||t===X||e===_.LOCAL&&(t===Q||t===Fe):!1},Zn=s=>G.hasCanceledError(s),es="channels",ts="WebcastStarted",ns="WebcastStopped",ss="accountChanged",is="accountDeleted",os="addedToListModerators",rs="removedFromListModerators",as="ParticipationRequestAccepted",cs="ParticipationRequestRejected",Es="ParticipantMovedToWebcast",ds="ConferenceParticipantTokenIssued";class hs{constructor({JsSIP:e}){r(this,"promisePendingStartPresentation");r(this,"promisePendingStopPresentation");r(this,"ua");r(this,"rtcSession");r(this,"incomingRTCSession");r(this,"streamPresentationCurrent");r(this,"socket");r(this,"isRegisterConfigInner",!1);r(this,"connectionConfiguration",{});r(this,"remoteStreams",{});r(this,"JsSIP");r(this,"sessionEvents");r(this,"uaEvents");r(this,"cancelableConnectWithRepeatedCalls");r(this,"cancelableSendPresentationWithRepeatedCalls");r(this,"isPendingConnect",!1);r(this,"isPendingInitUa",!1);r(this,"isPendingCall",!1);r(this,"isPendingAnswer",!1);r(this,"connect",async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t)));r(this,"hangUp",async()=>(this.cancelRequests(),this.hangUpWithoutCancelRequests()));r(this,"tryRegister",async()=>{if(!this.isRegisterConfig)throw new Error("Config is not registered");this.uaEvents.trigger(F,void 0);try{await this.unregister()}catch(e){v("tryRegister",e)}return this.register()});r(this,"declineToIncomingCall",async({statusCode:e=Xn}={})=>new Promise((t,n)=>{try{const i=this.getIncomingRTCSession(),o=this.remoteCallerData;this.removeIncomingSession(),this.uaEvents.trigger(j,o),i.terminate({status_code:e}),t()}catch(i){n(i)}}));r(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:Jn}));r(this,"set",async({displayName:e,password:t})=>new Promise((n,i)=>{const{ua:o}=this;if(!o){i(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",be(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(()=>{n(E)}).catch(d=>{i(d)}):E?n(E):i(new Error("nothing changed"))}));r(this,"disconnect",async()=>{this.off(y,this.handleNewRTCSession);const e=new Promise(n=>{this.once(C,()=>{n()})}),{ua:t}=this;return t?(await this.hangUpWithoutCancelRequests(),t.stop()):this.uaEvents.trigger(C,void 0),e.finally(()=>{delete this.ua})});r(this,"call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:i,iceServers:o,directionVideo:a,directionAudio:c,contentHint:E,offerToReceiveAudio:d=!0,offerToReceiveVideo:T=!0,sendEncodings:l,onAddedTransceiver:S})=>(this.isPendingCall=!0,new Promise((u,h)=>{const{ua:g}=this;if(!g){h(new Error("this.ua is not initialized"));return}this.connectionConfiguration.number=e,this.connectionConfiguration.answer=!1,this.handleCall({ontrack:i}).then(u).catch(N=>{h(N)}),this.rtcSession=g.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:p(t,{directionVideo:a,directionAudio:c,contentHint:E}),eventHandlers:this.sessionEvents.triggers,directionVideo:a,directionAudio:c,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:d,offerToReceiveVideo:T},sendEncodings:l,onAddedTransceiver:S})}).finally(()=>{this.isPendingCall=!1})));r(this,"answerToIncomingCall",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:i,directionVideo:o,directionAudio:a,offerToReceiveAudio:c,offerToReceiveVideo:E,contentHint:d,sendEncodings:T,onAddedTransceiver:l})=>(this.isPendingAnswer=!0,new Promise((S,u)=>{try{const h=this.getIncomingRTCSession();this.rtcSession=h,this.removeIncomingSession(),this.sessionEvents.eachTriggers((N,q)=>{const I=pe.find($=>$===q);I&&h.on(I,N)}),this.connectionConfiguration.answer=!0,this.connectionConfiguration.number=h.remote_identity.uri.user,this.handleCall({ontrack:t}).then(S).catch(N=>{u(N)});const g=p(e,{directionVideo:o,directionAudio:a,contentHint:d});h.answer({extraHeaders:n,directionVideo:o,directionAudio:a,mediaStream:g,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:E},sendEncodings:T,onAddedTransceiver:l})}catch(h){u(h)}}).finally(()=>{this.isPendingAnswer=!1})));r(this,"sendDTMF",async e=>new Promise((t,n)=>{const{rtcSession:i}=this;if(!i){n(new Error("No rtcSession established"));return}this.onceSession(me,({originator:o})=>{o===_.LOCAL&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600})}));r(this,"removeIncomingSession",()=>{delete this.incomingRTCSession});r(this,"getSipServerUrl",e=>e);r(this,"connectWithDuplicatedCalls",async(e,{callLimit:t=Qn}={})=>{const n=async()=>this.connectInner(e),i=o=>{var d;const c=((d=this.ua)==null?void 0:d.isConnected())===!0&&this.hasEqualConnectionConfiguration(e),E=o!=null&&!Yn(o);return c||E};return this.isPendingConnect=!0,this.cancelableConnectWithRepeatedCalls=G.repeatedCallsAsync({targetFunction:n,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(o=>{if(o instanceof this.JsSIP.UA)return o;throw o}).finally(()=>{this.isPendingConnect=!1})});r(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===_.REMOTE){this.incomingRTCSession=t;const n=this.remoteCallerData;t.on(A,i=>{this.removeIncomingSession(),i.originator===_.LOCAL?this.uaEvents.trigger(Z,n):this.uaEvents.trigger(K,n)}),this.uaEvents.trigger(z,n)}});r(this,"connectInner",async e=>this.initUa(e).then(async()=>this.start()));r(this,"initUa",async({user:e,password:t,sipServerUrl:n,sipWebSocketServerURL:i,remoteAddress:o,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:d,userAgent:T,displayName:l="",register:S=!1,extraHeaders:u=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(S&&(e===void 0||e===""))throw new Error("user is required for authorized connection");if(S&&(t===void 0||t===""))throw new Error("password is required for authorized connection");this.isPendingInitUa=!0;try{this.connectionConfiguration={sipServerUrl:n,displayName:l,register:S,user:e,password:t};const{configuration:h,helpers:g}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:i,password:t,displayName:l,register:S,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:d,userAgent:T});return this.getSipServerUrl=g.getSipServerUrl,this.socket=g.socket,this.ua&&await this.disconnect(),this.isRegisterConfigInner=!!S,this.ua=this.createUa({...h,remoteAddress:o,extraHeaders:u}),this.uaEvents.eachTriggers((N,q)=>{const I=Y.find($=>$===q);I&&this.ua&&this.ua.on(I,N)}),this.ua}finally{this.isPendingInitUa=!1}});r(this,"createUa",({remoteAddress:e,extraHeaders:t=[],...n})=>{const i=new this.JsSIP.UA(n),a=[...e!==void 0&&e!==""?hn(e):[],...t];return a.length>0&&i.registrator().setExtraHeaders(a),i});r(this,"start",async()=>new Promise((e,t)=>{const{ua:n}=this;if(!n){t(new Error("this.ua is not initialized"));return}const i=()=>{c(),e(n)},o=E=>{c(),t(E)},a=()=>{this.isRegisterConfig?(this.on(O,i),this.on(m,o)):this.on(P,i),this.on(C,o)},c=()=>{this.off(O,i),this.off(m,o),this.off(P,i),this.off(C,o)};a(),this.on(y,this.handleNewRTCSession),n.start()}));r(this,"handleCall",async({ontrack:e})=>new Promise((t,n)=>{const i=()=>{this.onSession(H,T),this.onSession(L,l)},o=()=>{this.offSession(H,T),this.offSession(L,l)},a=()=>{this.onSession(A,E),this.onSession(M,E)},c=()=>{this.offSession(A,E),this.offSession(M,E)},E=S=>{o(),c(),n(S)};let d;const T=({peerconnection:S})=>{d=S,d.ontrack=u=>{this.sessionEvents.trigger(ce,d),e&&e(u)}},l=()=>{d!==void 0&&this.sessionEvents.trigger(ae,d),o(),c(),t(d)};i(),a()}));r(this,"restoreSession",()=>{this.cancelRequestsAndResetPresentation(),delete this.connectionConfiguration.number,delete this.rtcSession,this.remoteStreams={}});r(this,"hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.rtcSession){const{rtcSession:e}=this;if(this.streamPresentationCurrent)try{await this.stopPresentation()}catch(t){v("error stop presentation: ",t)}if(this.restoreSession(),!e.isEnded())return e.terminateAsync({cause:Q})}});r(this,"handleShareState",e=>{switch(e){case ft:{this.sessionEvents.trigger(ne,void 0);break}case It:{this.sessionEvents.trigger(se,void 0);break}case Pt:{this.sessionEvents.trigger(ie,void 0);break}}});r(this,"maybeTriggerChannels",e=>{const t=e.getHeader(Le),n=e.getHeader(He);if(t&&n){const i={inputChannels:t,outputChannels:n};this.sessionEvents.trigger(b,i)}});r(this,"handleNotify",e=>{switch(e.cmd){case es:{const t=e;this.triggerChannelsNotify(t);break}case ts:{const t=e;this.triggerWebcastStartedNotify(t);break}case ns:{const t=e;this.triggerWebcastStoppedNotify(t);break}case os:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case rs:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case as:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case cs:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case Es:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case ss:{this.triggerAccountChangedNotify();break}case is:{this.triggerAccountDeletedNotify();break}case ds:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:v("unknown cmd",e.cmd)}});r(this,"triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this.uaEvents.trigger(Ce,t)});r(this,"triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this.uaEvents.trigger(ge,t)});r(this,"triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this.uaEvents.trigger(Re,n)});r(this,"triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this.uaEvents.trigger(fe,n)});r(this,"triggerAccountChangedNotify",()=>{this.uaEvents.trigger(Ie,void 0)});r(this,"triggerAccountDeletedNotify",()=>{this.uaEvents.trigger(Pe,void 0)});r(this,"triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const i={conference:e,participant:t,jwt:n};this.uaEvents.trigger(Oe,i)});r(this,"triggerChannelsNotify",e=>{const t=e.input,n=e.output,i={inputChannels:t,outputChannels:n};this.uaEvents.trigger(Ee,i)});r(this,"triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(Ne,t)});r(this,"triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(Ae,t)});r(this,"triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(_e,t)});r(this,"triggerEnterRoom",e=>{const t=e.getHeader(Tn),n=e.getHeader(Rn);this.sessionEvents.trigger(oe,{room:t,participantName:n})});r(this,"triggerShareState",e=>{const t=e.getHeader(f);this.sessionEvents.trigger(w,t)});r(this,"maybeTriggerParticipantMoveRequest",e=>{const t=e.getHeader(vn);t===dt&&this.sessionEvents.trigger(x,void 0),t===ht&&this.sessionEvents.trigger(V,void 0)});r(this,"triggerMainCamControl",e=>{const t=e.getHeader(fn),n=e.getHeader(We),i=n===B.ADMIN_SYNC_FORCED;if(t===R.ADMIN_START_MAIN_CAM){this.sessionEvents.trigger(Te,{isSyncForced:i});return}if(t===R.ADMIN_STOP_MAIN_CAM){this.sessionEvents.trigger(Se,{isSyncForced:i});return}(t===R.RESUME_MAIN_CAM||t===R.PAUSE_MAIN_CAM)&&n!==void 0&&this.sessionEvents.trigger(U,{isSyncForced:i});const o=e.getHeader(Pn);this.sessionEvents.trigger(he,{mainCam:t,resolutionMainCam:o})});r(this,"triggerMicControl",e=>{const t=e.getHeader(In),i=e.getHeader(We)===B.ADMIN_SYNC_FORCED;t===k.ADMIN_START_MIC?this.sessionEvents.trigger(ue,{isSyncForced:i}):t===k.ADMIN_STOP_MIC&&this.sessionEvents.trigger(le,{isSyncForced:i})});r(this,"triggerUseLicense",e=>{const t=e.getHeader(An);this.sessionEvents.trigger(re,t)});r(this,"handleNewInfo",e=>{const{originator:t}=e;if(t!==_.REMOTE)return;const{request:n}=e,i=n.getHeader(Sn);if(i)switch(i){case ln:{this.triggerEnterRoom(n),this.maybeTriggerChannels(n);break}case yn:{this.maybeHandleNotify(n);break}case D:{this.triggerShareState(n);break}case Ue:{this.triggerMainCamControl(n);break}case _n:{this.triggerMicControl(n);break}case Nn:{this.triggerUseLicense(n);break}case pn:{this.maybeTriggerParticipantMoveRequest(n);break}}});r(this,"handleSipEvent",({request:e})=>{this.maybeHandleNotify(e)});r(this,"maybeHandleNotify",e=>{const t=e.getHeader(wn);if(t){const n=JSON.parse(t);this.handleNotify(n)}});r(this,"handleEnded",e=>{const{originator:t}=e;t===_.REMOTE&&this.sessionEvents.trigger(de,e),this.restoreSession()});this.JsSIP=e,this.sessionEvents=new we(ve),this.uaEvents=new we(ut),this.onSession(w,this.handleShareState),this.onSession(Me,this.handleNewInfo),this.on(te,this.handleSipEvent),this.onSession(A,this.handleEnded),this.onSession(M,this.handleEnded)}get connection(){var t;return(t=this.rtcSession)==null?void 0:t.connection}get remoteCallerData(){var e,t,n;return{displayName:(e=this.incomingRTCSession)==null?void 0:e.remote_identity.display_name,host:(t=this.incomingRTCSession)==null?void 0:t.remote_identity.uri.host,incomingNumber:(n=this.incomingRTCSession)==null?void 0:n.remote_identity.uri.user,rtcSession:this.incomingRTCSession}}get requested(){return this.isPendingInitUa||this.isPendingConnect||this.isPendingCall||this.isPendingAnswer}get establishedRTCSession(){var e;return((e=this.rtcSession)==null?void 0:e.isEstablished())===!0?this.rtcSession:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this.isRegisterConfigInner}get isCallActive(){return!!(this.ua&&this.rtcSession)}get isAvailableIncomingCall(){return!!this.incomingRTCSession}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(O,e),this.ua.on(m,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(ee,e),this.ua.unregister()):t(new Error("ua is not registered"))})}async sendOptions(e,t,n){if(!this.ua)throw new Error("is not connected");return new Promise((i,o)=>{try{this.ua.sendOptions(e,t,{extraHeaders:n,eventHandlers:{succeeded:()=>{i()},failed:o}})}catch(a){o(a)}})}async ping(e,t){var i;if(!((i=this.ua)!=null&&i.configuration.uri))throw new Error("is not connected");const n=this.ua.configuration.uri;return this.sendOptions(n,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerUrl:n,sipWebSocketServerURL:i,remoteAddress:o,extraHeaders:a}){return new Promise((c,E)=>{const{configuration:d}=this.createUaConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:n}),T=this.createUa({...d,remoteAddress:o,extraHeaders:a}),l=()=>{const u=new Error("Telephony is not available");E(u)};T.once(C,l);const S=()=>{T.removeAllListeners(),T.once(C,c),T.stop()};T.once(P,S),T.start()})}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:n}=t??{},i=p(e,{contentHint:n});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}async askPermissionToEnableCam(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");const t=[Bn];return this.rtcSession.sendInfo(Ue,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if(qn(n))throw n})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:o,sendEncodings:a,onAddedTransceiver:c}={},E){const d=this.establishedRTCSession;if(!d)throw new Error("No rtcSession established");if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return n===!0&&await this.sendMustStopPresentation(),this.sendPresentationWithDuplicatedCalls({rtcSession:d,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:o,sendEncodings:a,onAddedTransceiver:c},options:E})}async stopPresentation({isP2P:e=!1}={}){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve(void 0);const i=e?[Wn]:[Un],o=this.establishedRTCSession;return o&&t&&(n=n.then(async()=>o.sendInfo(D,void 0,{extraHeaders:i})).then(async()=>o.stopPresentation(t)).catch(a=>{throw this.sessionEvents.trigger(W,a),a})),!o&&t&&this.sessionEvents.trigger(De,t),this.promisePendingStopPresentation=n,n.finally(()=>{this.resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,contentHint:i,sendEncodings:o,onAddedTransceiver:a}={}){const c=this.establishedRTCSession;if(!c)throw new Error("No rtcSession established");if(!this.streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this.sendPresentation(c,e,{isP2P:t,maxBitrate:n,contentHint:i,isNeedReinvite:!1,sendEncodings:o,onAddedTransceiver:a})}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:n})=>n);return dn(t)?this.generateStreams(t):this.generateAudioStreams(t)}getIncomingRTCSession(){const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e}cancelSendPresentationWithRepeatedCalls(){var e;(e=this.cancelableSendPresentationWithRepeatedCalls)==null||e.cancel()}async waitChannels(){return this.waitSession(b)}async waitSyncMediaState(){return this.waitSession(U)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.rtcSession)throw new Error("No rtcSession established");const n=`${Le}: ${e}`,i=`${He}: ${t}`,o=[n,i];return this.rtcSession.sendInfo(un,void 0,{extraHeaders:o})}async sendMediaState({cam:e,mic:t},n={}){if(!this.rtcSession)throw new Error("No rtcSession established");const i=`${On}: currentstate`,o=`${Mn}: ${Number(e)}`,a=`${Dn}: ${Number(t)}`,c=[i,o,a];return this.rtcSession.sendInfo(gn,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async sendRefusalToTurnOn(e,t={}){if(!this.rtcSession)throw new Error("No rtcSession established");const c=[`${mn}: ${e==="mic"?0:1}`];return this.rtcSession.sendInfo(Cn,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendMustStopPresentation(){const e=this.establishedRTCSession;if(!e)throw new Error("No rtcSession established");await e.sendInfo(D,void 0,{extraHeaders:[Ln]})}async sendPresentationWithDuplicatedCalls({rtcSession:e,stream:t,presentationOptions:n,options:i={callLimit:zn}}){const o=async()=>this.sendPresentation(e,t,n),a=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=G.repeatedCallsAsync({targetFunction:o,isComplete:a,isRejectAsValid:!0,...i}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}hasEqualConnectionConfiguration(e){var i;const{configuration:t}=this.createUaConfiguration(e),n=(i=this.ua)==null?void 0:i.configuration;return(n==null?void 0:n.password)===t.password&&(n==null?void 0:n.register)===t.register&&n.uri.toString()===t.uri&&n.display_name===t.display_name&&n.user_agent===t.user_agent&&n.sockets===t.sockets&&n.session_timers===t.session_timers&&n.register_expires===t.register_expires&&n.connection_recovery_min_interval===t.connection_recovery_min_interval&&n.connection_recovery_max_interval===t.connection_recovery_max_interval}createUaConfiguration({user:e,password:t,sipWebSocketServerURL:n,displayName:i="",sipServerUrl:o,register:a=!1,sessionTimers:c=!1,registerExpires:E=60*5,connectionRecoveryMinInterval:d=2,connectionRecoveryMaxInterval:T=6,userAgent:l}){if(a&&(t===void 0||t===""))throw new Error("password is required for authorized connection");const S=a&&e!==void 0&&e.trim()!==""?e.trim():`${En()}`,u=an(o),h=u(S),g=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:h,display_name:be(i),user_agent:l,sdp_semantics:"unified-plan",sockets:[g],session_timers:c,register_expires:E,connection_recovery_min_interval:d,connection_recovery_max_interval:T},helpers:{socket:g,getSipServerUrl:u}}}async sendPresentation(e,t,{maxBitrate:n=St,isNeedReinvite:i=!0,isP2P:o=!1,contentHint:a="detail",sendEncodings:c,onAddedTransceiver:E}){const d=p(t,{contentHint:a});if(d===void 0)throw new Error("No streamPresentationCurrent");this.streamPresentationCurrent=d;const T=o?[Hn]:[bn],l=e.sendInfo(D,void 0,{extraHeaders:T}).then(async()=>e.startPresentation(d,i,{sendEncodings:c,onAddedTransceiver:E})).then(async()=>{const{connection:S}=this;if(!S)return;const u=S.getSenders();await Gn(u,t,n)}).then(()=>t).catch(S=>{throw this.removeStreamPresentationCurrent(),this.sessionEvents.trigger(W,S),S});return this.promisePendingStartPresentation=l,l.finally(()=>{this.promisePendingStartPresentation=void 0})}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}cancelRequestsAndResetPresentation(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}generateStream(e,t){const{id:n}=e,i=this.remoteStreams[n]??new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this.remoteStreams[n]=i,i}generateAudioStream(e){const{id:t}=e,n=this.remoteStreams[t]??new MediaStream;return n.addTrack(e),this.remoteStreams[t]=n,n}generateStreams(e){const t=[];return e.forEach((n,i)=>{if(n.kind==="audio")return;const o=n,a=e[i-1];let c;(a==null?void 0:a.kind)==="audio"&&(c=a);const E=this.generateStream(o,c);t.push(E)}),t}generateAudioStreams(e){return e.map(n=>this.generateAudioStream(n))}cancelRequests(){this.cancelConnectWithRepeatedCalls()}cancelConnectWithRepeatedCalls(){var e;(e=this.cancelableConnectWithRepeatedCalls)==null||e.cancel()}}exports.BAD_MEDIA_DESCRIPTION=xe;exports.EEventsMainCAM=R;exports.EEventsMic=k;exports.EEventsSyncMediaState=B;exports.EMimeTypesVideoCodecs=At;exports.EUseLicense=Nt;exports.NOT_FOUND=Be;exports.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS=V;exports.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS=x;exports.REJECTED=X;exports.SESSION_EVENT_NAMES=ve;exports.SipConnector=hs;exports.UA_JSSIP_EVENT_NAMES=Y;exports.causes=$t;exports.constants=Gt;exports.disableDebug=Qt;exports.enableDebug=Xt;exports.eventNames=Jt;exports.hasCanceledCallError=Kn;exports.hasCanceledStartPresentationError=Zn;exports.logger=v;exports.setEncodingsToSender=Rt;exports.setParametersToSender=_t;