sip-connector 6.20.1 → 6.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var Yt=Object.defineProperty;var Gt=(n,e,t)=>e in n?Yt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var a=(n,e,t)=>(Gt(n,typeof e!="symbol"?e+"":e,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const I=require("@krivega/cancelable-promise"),Ye=require("events-constructor"),J=require("debug"),Xt=require("ts-debounce"),zt=require("sequent-promises"),Kt=require("stack-promises"),Jt="Connection Error",et="Request Timeout",Qt="SIP Failure Code",jt="Internal Error",Zt="Busy",tt="Rejected",en="Redirected",tn="Unavailable",se="Not Found",nn="Address Incomplete",sn="Incompatible SDP",rn="Missing SDP",on="Authentication Error",nt="Terminated",an="WebRTC Error",st="Canceled",cn="No Answer",un="Expires",En="No ACK",ln="Dialog Error",_n="User Denied Media Access",re="Bad Media Description",dn="RTP Timeout",Sn=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:nn,AUTHENTICATION_ERROR:on,BAD_MEDIA_DESCRIPTION:re,BUSY:Zt,BYE:nt,CANCELED:st,CONNECTION_ERROR:Jt,DIALOG_ERROR:ln,EXPIRES:un,INCOMPATIBLE_SDP:sn,INTERNAL_ERROR:jt,MISSING_SDP:rn,NOT_FOUND:se,NO_ACK:En,NO_ANSWER:cn,REDIRECTED:en,REJECTED:tt,REQUEST_TIMEOUT:et,RTP_TIMEOUT:dn,SIP_FAILURE_CODE:Qt,UNAVAILABLE:tn,USER_DENIED_MEDIA_ACCESS:_n,WEBRTC_ERROR:an},Symbol.toStringTag,{value:"Module"})),oe="incomingCall",ie="declinedIncomingCall",ae="failedIncomingCall",ce="terminatedIncomingCall",Q="connecting",q="connected",P="disconnected",V="newRTCSession",L="registered",ue="unregistered",B="registrationFailed",rt="newMessage",Ee="sipEvent",le="availableSecondRemoteStream",_e="notAvailableSecondRemoteStream",de="mustStopPresentation",W="shareState",Se="enterRoom",he="useLicense",Te="peerconnection:confirmed",Ce="peerconnection:ontrack",$="channels",ge="channels:notify",Ne="ended:fromserver",Re="main-cam-control",me="admin-stop-main-cam",Ae="admin-start-main-cam",fe="admin-stop-mic",Ie="admin-start-mic",x="admin-force-sync-media-state",Me="participant:added-to-list-moderators",Oe="participant:removed-from-list-moderators",De="participant:move-request-to-conference",Pe="participant:move-request-to-stream",pe="participant:canceling-word-request",ve="webcast:started",be="webcast:stopped",ye="account:changed",we="account:deleted",Ue="conference:participant-token-issued",F="ended",ot="sending",it="reinvite",at="replaces",ct="refer",ut="progress",Et="accepted",Y="confirmed",G="peerconnection",b="failed",lt="muted",_t="unmuted",Le="newDTMF",Be="newInfo",dt="hold",St="unhold",ht="update",Tt="sdp",Ct="icecandidate",gt="getusermediafailed",Nt="peerconnection:createofferfailed",Rt="peerconnection:createanswerfailed",mt="peerconnection:setlocaldescriptionfailed",At="peerconnection:setremotedescriptionfailed",ft="presentation:start",It="presentation:started",Mt="presentation:end",Fe="presentation:ended",X="presentation:failed",hn=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:Et,ACCOUNT_CHANGED:ye,ACCOUNT_DELETED:we,ADMIN_FORCE_SYNC_MEDIA_STATE:x,ADMIN_START_MAIN_CAM:Ae,ADMIN_START_MIC:Ie,ADMIN_STOP_MAIN_CAM:me,ADMIN_STOP_MIC:fe,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:le,CHANNELS:$,CHANNELS_NOTIFY:ge,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Ue,CONFIRMED:Y,CONNECTED:q,CONNECTING:Q,DECLINED_INCOMING_CALL:ie,DISCONNECTED:P,ENDED:F,ENDED_FROM_SERVER:Ne,ENTER_ROOM:Se,FAILED:b,FAILED_INCOMING_CALL:ae,GET_USER_MEDIA_FAILED:gt,HOLD:dt,ICE_CANDIDATE:Ct,INCOMING_CALL:oe,MAIN_CAM_CONTROL:Re,MUST_STOP_PRESENTATION_EVENT:de,MUTED:lt,NEW_DTMF:Le,NEW_INFO:Be,NEW_MESSAGE:rt,NEW_RTC_SESSION:V,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:_e,PARTICIPANT_ADDED_TO_LIST_MODERATORS:Me,PARTICIPANT_CANCELLING_WORD_REQUEST:pe,PARTICIPANT_MOVE_REQUEST_TO_CONFERENCE:De,PARTICIPANT_MOVE_REQUEST_TO_STREAM:Pe,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:Oe,PEER_CONNECTION:G,PEER_CONNECTION_CONFIRMED:Te,PEER_CONNECTION_CREATE_ANSWER_FAILED:Rt,PEER_CONNECTION_CREATE_OFFER_FAILED:Nt,PEER_CONNECTION_ONTRACK:Ce,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:mt,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:At,PRESENTATION_END:Mt,PRESENTATION_ENDED:Fe,PRESENTATION_FAILED:X,PRESENTATION_START:ft,PRESENTATION_STARTED:It,PROGRESS:ut,REFER:ct,REGISTERED:L,REGISTRATION_FAILED:B,REINVITE:it,REPLACES:at,SDP:Tt,SENDING:ot,SHARE_STATE:W,SIP_EVENT:Ee,TERMINATED_INCOMING_CALL:ce,UNHOLD:St,UNMUTED:_t,UNREGISTERED:ue,UPDATE:ht,USE_LICENSE:he,WEBCAST_STARTED:ve,WEBCAST_STOPPED:be},Symbol.toStringTag,{value:"Module"})),Ot=[oe,ie,ce,ae,pe,Pe,De,ge,Ue,ye,we,ve,be,Me,Oe],ke=[Q,q,P,V,L,ue,B,rt,Ee],Dt=[le,_e,de,W,Se,he,Te,Ce,$,Ne,Re,Ae,me,fe,Ie,x],He=[F,Q,ot,it,at,ct,ut,Et,Y,G,b,lt,_t,Le,Be,dt,St,ht,Tt,Ct,gt,Nt,Rt,mt,At,ft,It,Mt,Fe,X],Pt=[...ke,...Ot],pt=[...He,...Dt],Tn=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:pt,SESSION_JSSIP_EVENT_NAMES:He,SESSION_SYNTHETICS_EVENT_NAMES:Dt,UA_EVENT_NAMES:Pt,UA_JSSIP_EVENT_NAMES:ke,UA_SYNTHETICS_EVENT_NAMES:Ot},Symbol.toStringTag,{value:"Module"})),Cn=n=>{const e=[];return n&&e.push(`X-Vinteo-Remote: ${n}`),e},gn="content-type",Nn="x-webrtc-enter-room",j="application/vinteo.webrtc.sharedesktop",Rn="application/vinteo.webrtc.roomname",mn="application/vinteo.webrtc.channels",An="application/vinteo.webrtc.mediastate",fn="application/vinteo.webrtc.refusal",Ge="application/vinteo.webrtc.maincam",In="application/vinteo.webrtc.mic",Mn="application/vinteo.webrtc.uselic",On="X-WEBRTC-USE-LICENSE",Xe="X-WEBRTC-INPUT-CHANNELS",ze="X-WEBRTC-OUTPUT-CHANNELS",Dn="X-WEBRTC-MAINCAM",Pn="X-WEBRTC-MIC",Ke="X-WEBRTC-SYNC",pn="X-WEBRTC-MAINCAM-RESOLUTION",vn="X-WEBRTC-MEDIA-STATE",bn="X-Vinteo-Media-Type",yn="X-Vinteo-MainCam-State",wn="X-Vinteo-Mic-State",Un="application/vinteo.webrtc.notify",Ln="X-VINTEO-NOTIFY",H="x-webrtc-share-state",Bn=`${H}: LETMESTARTPRESENTATION`,Fn=`${H}: STOPPRESENTATION`,vt="YOUCANRECEIVECONTENT",bt="CONTENTEND",kn="YOUMUSTSTOPSENDCONTENT",Hn=`${H}: ${vt}`,qn=`${H}: ${bt}`,Vn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Wn=`${Vn}: LETMESTARTMAINCAM`,qe="sip-connector",E=J(qe),$n=()=>{J.enable(`${qe}`)},xn=()=>{J.enable(`-${qe}`)};var M=(n=>(n.PAUSE_MAIN_CAM="PAUSEMAINCAM",n.RESUME_MAIN_CAM="RESUMEMAINCAM",n.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",n.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",n.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",n))(M||{}),z=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(z||{}),K=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(K||{}),yt=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(yt||{});function Yn(n){return e=>`sip:${e}@${n}`}const Gn=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,Je=n=>n.trim().replaceAll(" ","_"),Xn=Gn(1e5,99999999),Z=(n,{videoMode:e,audioMode:t}={})=>{if(!n||e==="recvonly"&&t==="recvonly")return;const s=t==="recvonly"?[]:n.getAudioTracks(),r=e==="recvonly"?[]:n.getVideoTracks(),o=[...s,...r],i=new MediaStream(o);return i.getTracks=()=>[...i.getAudioTracks(),...i.getVideoTracks()],i},zn=n=>n.some(t=>{const{kind:s}=t;return s==="video"}),Kn="Error decline with 603",Jn=n=>n.message===Kn,Qn=(n,e)=>n.find(t=>t.track&&e.getTracks().includes(t.track)),wt=1,Ut=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,jn=Ut(wt),Zn=(n,e)=>{const t=n===void 0?void 0:Math.max(n,wt);if(t!==void 0&&jn(t,e))return t},es=Ut(),ts=(n,e)=>{if(es(n,e))return n},Lt=async(n,e,t)=>{const s=n.getParameters();(s.encodings===void 0||s.encodings.length===0)&&(s.encodings=[{}]);const[r]=s.encodings,o=r.scaleResolutionDownBy,i=Zn(e.scaleResolutionDownBy,o);let c=!1;i!==void 0&&(s.encodings[0].scaleResolutionDownBy=i,c=!0);const u=r.maxBitrate,l=ts(e.maxBitrate,u);return l!==void 0&&(s.encodings[0].maxBitrate=l,c=!0),c?(t&&t(s),n.setParameters(s).then(()=>({parameters:s,isChanged:c}))):{parameters:s,isChanged:c}},ns=async(n,e,t)=>{const s=Qn(n,e);if(s)return Lt(s,{maxBitrate:t})},ss=486,rs=487,ne="local",Qe="remote",os=(n=new Error)=>{const{originator:e,cause:t}=n;return I.isCanceledError(n)?!0:typeof t=="string"?t===et||t===tt||e===ne&&(t===st||t===nt):!1},D="SipConnector",is="channels",as="WebcastStarted",cs="WebcastStopped",us="accountChanged",Es="accountDeleted",ls="addedToListModerators",_s="removedFromListModerators",ds="WebcastParticipationAccepted",Ss="WebcastParticipationRejected",hs="ParticipantMovedToWebcast",Ts="ConferenceParticipantTokenIssued";class Cs{constructor({JsSIP:e}){a(this,"_isRegisterConfig",!1);a(this,"_connectionConfiguration",{});a(this,"_remoteStreams",{});a(this,"JsSIP");a(this,"_sessionEvents");a(this,"_uaEvents");a(this,"_cancelableConnect");a(this,"_cancelableCreateUa");a(this,"_cancelableDisconnect");a(this,"_cancelableSet");a(this,"_cancelableCall");a(this,"_cancelableAnswer");a(this,"_cancelableSendDTMF");a(this,"getSipServerUrl",e=>e);a(this,"promisePendingStartPresentation");a(this,"promisePendingStopPresentation");a(this,"ua");a(this,"session");a(this,"incomingSession");a(this,"_streamPresentationCurrent");a(this,"socket");a(this,"connect",async e=>(this._cancelRequests(),this._cancelableConnect.request(e)));a(this,"createUa",async e=>this._cancelableCreateUa.request(e));a(this,"set",async e=>this._cancelableSet.request(e));a(this,"call",async e=>this._cancelableCall.request(e));a(this,"disconnect",async()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()));a(this,"answerToIncomingCall",async e=>this._cancelableAnswer.request(e));a(this,"sendDTMF",async e=>this._cancelableSendDTMF.request(e));a(this,"hangUp",async()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()));a(this,"tryRegister",async()=>{if(!this.isRegisterConfig)throw new Error("Config is not registered");this._uaEvents.trigger(Q,void 0);try{await this.unregister()}catch(e){E("tryRegister",e)}return this.register()});a(this,"declineToIncomingCall",async({statusCode:e=rs}={})=>new Promise((t,s)=>{if(!this.isAvailableIncomingCall){s(new Error("no incomingSession"));return}const r=this.incomingSession,o=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(ie,o),t(r.terminate({status_code:e}))}));a(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:ss}));a(this,"removeIncomingSession",()=>{delete this.incomingSession});a(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===Qe){this.incomingSession=t;const s=this.remoteCallerData;t.on(b,r=>{this.removeIncomingSession(),r.originator===ne?this._uaEvents.trigger(ce,s):this._uaEvents.trigger(ae,s)}),this._uaEvents.trigger(oe,s)}});a(this,"_connect",async e=>this.createUa(e).then(async()=>this._start()));a(this,"_createUa",async({displayName:e="",user:t,password:s,register:r=!1,sipServerUrl:o,sipWebSocketServerURL:i,remoteAddress:c,extraHeaders:u=[],sdpSemantics:l="plan-b",sessionTimers:_=!1,registerExpires:d=60*5,connectionRecoveryMinInterval:S=2,connectionRecoveryMaxInterval:h=6,userAgent:T})=>{if(!o)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(r&&!t)throw new Error("user is required for authorized connection");if(r&&!s)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:o,displayName:e,register:r,user:t,password:s},this._init({sipServerUrl:o,sipWebSocketServerURL:i});const g=r&&t?t.trim():`${Xn()}`,N={password:s,register:r,display_name:Je(e),user_agent:T,sdp_semantics:l,sockets:[this.socket],uri:this.getSipServerUrl(g),session_timers:_,register_expires:d,connection_recovery_min_interval:S,connection_recovery_max_interval:h};this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!N.register,this.ua=new this.JsSIP.UA(N),this._uaEvents.eachTriggers((R,m)=>{const v=ke.find(f=>f===m);v&&this.ua&&this.ua.on(v,R)});const O=[...Cn(c),...u];return this.ua.registrator().setExtraHeaders(O),this.ua});a(this,"_start",async()=>new Promise((e,t)=>{const{ua:s}=this;if(!s){t(new Error("this.ua is not initialized"));return}const r=()=>{c(),e(s)},o=u=>{c(),t(u)},i=()=>{this.isRegisterConfig?(this.on(L,r),this.on(B,o)):this.on(q,r),this.on(P,o)},c=()=>{this.off(L,r),this.off(B,o),this.off(q,r),this.off(P,o)};i(),this.on(V,this.handleNewRTCSession),s.start()}));a(this,"_set",async({displayName:e,password:t})=>new Promise((s,r)=>{const{ua:o}=this;if(!o){r(new Error("this.ua is not initialized"));return}let i=!1,c=!1;e!==void 0&&e!==this._connectionConfiguration.displayName&&(i=o.set("display_name",Je(e)),this._connectionConfiguration.displayName=e),t!==void 0&&t!==this._connectionConfiguration.password&&(c=o.set("password",t),this._connectionConfiguration.password=t);const u=i||c;c&&this.isRegisterConfig?this.register().then(()=>{s(u)}).catch(r):u?s(u):r(u)}));a(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());a(this,"_disconnect",async()=>{this.off(V,this.handleNewRTCSession);const e=new Promise(t=>{this.once(P,()=>{delete this.ua,t()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(P,void 0)):this._uaEvents.trigger(P,void 0),e});a(this,"_call",async({number:e,mediaStream:t,extraHeaders:s=[],ontrack:r,iceServers:o,videoMode:i,audioMode:c,degradationPreference:u,offerToReceiveAudio:l=!0,offerToReceiveVideo:_=!0})=>new Promise((d,S)=>{const{ua:h}=this;if(!h){S(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:r}).then(d).catch(S),this.session=h.call(this.getSipServerUrl(e),{extraHeaders:s,mediaStream:Z(t,{videoMode:i,audioMode:c}),eventHandlers:this._sessionEvents.triggers,videoMode:i,audioMode:c,degradationPreference:u,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:l,offerToReceiveVideo:_}})}));a(this,"_answer",async({mediaStream:e,ontrack:t,extraHeaders:s=[],iceServers:r,videoMode:o,audioMode:i,degradationPreference:c})=>new Promise((u,l)=>{if(!this.isAvailableIncomingCall){l(new Error("no incomingSession"));return}this.session=this.incomingSession,this.removeIncomingSession();const{session:_}=this;if(!_){l(new Error("No session established"));return}this._sessionEvents.eachTriggers((S,h)=>{const T=He.find(g=>g===h);T&&_.on(T,S)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=_.remote_identity.uri.user,this._handleCall({ontrack:t}).then(u).catch(l);const d=Z(e,{videoMode:o,audioMode:i});_.answer({extraHeaders:s,videoMode:o,audioMode:i,degradationPreference:c,mediaStream:d,pcConfig:{iceServers:r}})}));a(this,"_handleCall",async({ontrack:e})=>new Promise((t,s)=>{const r=()=>{this.onSession(G,_),this.onSession(Y,d)},o=()=>{this.offSession(G,_),this.offSession(Y,d)},i=()=>{this.onSession(b,u),this.onSession(F,u)},c=()=>{this.offSession(b,u),this.offSession(F,u)},u=S=>{o(),c(),s(S)};let l;const _=({peerconnection:S})=>{l=S,l.ontrack=h=>{this._sessionEvents.trigger(Ce,l),e&&e(h)}},d=()=>{l&&this._sessionEvents.trigger(Te,l),o(),c(),t(l)};r(),i()}));a(this,"_restoreSession",()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}});a(this,"_sendDTMF",async e=>new Promise((t,s)=>{const{session:r}=this;if(!r){s(new Error("No session established"));return}this.onceSession(Le,({originator:o})=>{o===ne&&t()}),r.sendDTMF(e,{duration:120,interToneGap:600})}));a(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.session){const{session:e}=this;this._streamPresentationCurrent&&await this.stopPresentation(),this._restoreSession(),e.isEnded()||e.terminate()}});a(this,"_handleShareState",e=>{switch(e){case vt:{this._sessionEvents.trigger(le,void 0);break}case bt:{this._sessionEvents.trigger(_e,void 0);break}case kn:{this._sessionEvents.trigger(de,void 0);break}}});a(this,"_maybeTriggerChannels",e=>{const t=e.getHeader(Xe),s=e.getHeader(ze);if(t&&s){const r={inputChannels:t,outputChannels:s};this._sessionEvents.trigger($,r)}});a(this,"_handleNotify",e=>{switch(e.cmd){case is:{const t=e;this._triggerChannelsNotify(t);break}case as:{const t=e;this._triggerWebcastStartedNotify(t);break}case cs:{const t=e;this._triggerWebcastStoppedNotify(t);break}case ls:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case _s:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case ds:{const t=e;this._triggerParticipantMoveRequestToConference(t);break}case Ss:{const t=e;this._triggerParticipantCancelingWordRequest(t);break}case hs:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case us:{this._triggerAccountChangedNotify();break}case Es:{this._triggerAccountDeletedNotify();break}case Ts:{const t=e;this._triggerConferenceParticipantTokenIssued(t);break}default:E("unknown cmd",e.cmd)}});a(this,"_triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(Oe,t)});a(this,"_triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(Me,t)});a(this,"_triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(ve,s)});a(this,"_triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(be,s)});a(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(ye,void 0)});a(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(we,void 0)});a(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:s}})=>{const r={conference:e,participant:t,jwt:s};this._uaEvents.trigger(Ue,r)});a(this,"_triggerChannelsNotify",e=>{const t=e.input,s=e.output,r={inputChannels:t,outputChannels:s};this._uaEvents.trigger(ge,r)});a(this,"_triggerParticipantMoveRequestToConference",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(De,t)});a(this,"_triggerParticipantCancelingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(pe,t)});a(this,"_triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Pe,t)});a(this,"_triggerEnterRoom",e=>{const t=e.getHeader(Nn);this._sessionEvents.trigger(Se,t)});a(this,"_triggerShareState",e=>{const t=e.getHeader(H);this._sessionEvents.trigger(W,t)});a(this,"_triggerMainCamControl",e=>{const t=e.getHeader(Dn),s=e.getHeader(Ke),r=s===K.ADMIN_SYNC_FORCED;if(t===M.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger(Ae,{isSyncForced:r});else if(t===M.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger(me,{isSyncForced:r});else if((t===M.RESUME_MAIN_CAM||t===M.PAUSE_MAIN_CAM)&&s)this._sessionEvents.trigger(x,{isSyncForced:r});else{const o=e.getHeader(pn);this._sessionEvents.trigger(Re,{mainCam:t,resolutionMainCam:o})}});a(this,"_triggerMicControl",e=>{const t=e.getHeader(Pn),r=e.getHeader(Ke)===K.ADMIN_SYNC_FORCED;t===z.ADMIN_START_MIC?this._sessionEvents.trigger(Ie,{isSyncForced:r}):t===z.ADMIN_STOP_MIC&&this._sessionEvents.trigger(fe,{isSyncForced:r})});a(this,"_triggerUseLicense",e=>{const t=e.getHeader(On);this._sessionEvents.trigger(he,t)});a(this,"_handleNewInfo",e=>{const{originator:t}=e;if(t!=="remote")return;const{request:s}=e,r=s.getHeader(gn);if(r)switch(r){case Rn:{this._triggerEnterRoom(s),this._maybeTriggerChannels(s);break}case Un:{this._maybeHandleNotify(s);break}case j:{this._triggerShareState(s);break}case Ge:{this._triggerMainCamControl(s);break}case In:{this._triggerMicControl(s);break}case Mn:{this._triggerUseLicense(s);break}}});a(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});a(this,"_maybeHandleNotify",e=>{const t=e.getHeader(Ln);if(t){const s=JSON.parse(t);this._handleNotify(s)}});a(this,"_handleEnded",e=>{const{originator:t}=e;t===Qe&&this._sessionEvents.trigger(Ne,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new Ye(pt),this._uaEvents=new Ye(Pt),this._cancelableConnect=new I.CancelableRequest(this._connect,{moduleName:D,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new I.CancelableRequest(this._createUa,{moduleName:D}),this._cancelableDisconnect=new I.CancelableRequest(this._disconnect,{moduleName:D}),this._cancelableSet=new I.CancelableRequest(this._set,{moduleName:D}),this._cancelableCall=new I.CancelableRequest(this._call,{moduleName:D}),this._cancelableAnswer=new I.CancelableRequest(this._answer,{moduleName:D}),this._cancelableSendDTMF=new I.CancelableRequest(this._sendDTMF,{moduleName:D}),this.onSession(W,this._handleShareState),this.onSession(Be,this._handleNewInfo),this.on(Ee,this._handleSipEvent),this.onSession(b,this._handleEnded),this.onSession(F,this._handleEnded)}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(L,e),this.ua.on(B,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(ue,e),this.ua.unregister()):t(new Error("ua is not registered"))})}async sendOptions(e,t,s){if(!this.ua)throw new Error("is not connected");return new Promise((r,o)=>{try{this.ua.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{r()},failed:o}})}catch(i){o(i)}})}async ping(e,t){var r;if(!((r=this.ua)!=null&&r.configuration.uri))throw new Error("is not connected");const s=this.ua.configuration.uri;return this.sendOptions(s,e,t)}async replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}async askPermissionToEnableCam(e={}){if(!this.session)throw new Error("No session established");const t=[Wn];return this.session.sendInfo(Ge,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(s=>{if(Jn(s))throw s})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async _sendPresentation(e,t,{maxBitrate:s,degradationPreference:r,isNeedReinvite:o=!0,isP2P:i=!1}){const c=Z(t);this._streamPresentationCurrent=c;const u=i?[Hn]:[Bn],l=e.sendInfo(j,void 0,{extraHeaders:u}).then(async()=>e.startPresentation(c,o,r)).then(async()=>{const{connection:_}=this;if(!_||s===void 0)return;const d=_.getSenders();return ns(d,t,s)}).then(()=>t).catch(_=>{throw this._sessionEvents.trigger(X,_),_});return this.promisePendingStartPresentation=l,l.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t=!0,isP2P:s=!1,maxBitrate:r,degradationPreference:o}={}){const i=this.establishedSession;if(!i)throw new Error("No session established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return this._sendPresentation(i,e,{isNeedReinvite:t,isP2P:s,maxBitrate:r,degradationPreference:o})}async stopPresentation({isP2P:e=!1}={}){const t=this._streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve();const r=e?[qn]:[Fn],o=this.establishedSession;return o&&t&&(s=s.then(async()=>o.sendInfo(j,void 0,{extraHeaders:r})).then(async()=>o.stopPresentation(t)).catch(i=>{throw this._sessionEvents.trigger(X,i),i})),!o&&t&&this._sessionEvents.trigger(Fe,t),this.promisePendingStopPresentation=s,s.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t=!1,maxBitrate:s,degradationPreference:r}={}){const o=this.establishedSession;if(!o)throw new Error("No session established");if(!this._streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this._sendPresentation(o,e,{isP2P:t,maxBitrate:s,degradationPreference:r,isNeedReinvite:!1})}_resetPresentation(){delete this._streamPresentationCurrent,this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}async wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){return this._sessionEvents.on(e,t)}onceSession(e,t){return this._sessionEvents.once(e,t)}onceRaceSession(e,t){return this._sessionEvents.onceRace(e,t)}async waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return{...this._connectionConfiguration}}getRemoteStreams(){if(!this.connection)return;const t=this.connection.getReceivers().map(({track:s})=>s);return zn(t)?this._generateStreams(t):this._generateAudioStreams(t)}get connection(){var t;return(t=this.session)==null?void 0:t.connection}get remoteCallerData(){var e,t,s,r,o,i;return{displayName:(t=(e=this.incomingSession)==null?void 0:e.remote_identity)==null?void 0:t.display_name,host:(r=(s=this.incomingSession)==null?void 0:s.remote_identity)==null?void 0:r.uri.host,incomingNumber:(i=(o=this.incomingSession)==null?void 0:o.remote_identity)==null?void 0:i.uri.user,session:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){return this.session&&this.session.isEstablished()?this.session:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!!(this.ua&&this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_init({sipServerUrl:e,sipWebSocketServerURL:t}){this.getSipServerUrl=Yn(e),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const{id:s}=e,r=this._remoteStreams[s]||new MediaStream;return t&&r.addTrack(t),r.addTrack(e),this._remoteStreams[s]=r,r}_generateAudioStream(e){const{id:t}=e,s=this._remoteStreams[t]||new MediaStream;return s.addTrack(e),this._remoteStreams[t]=s,s}_generateStreams(e){const t=[];return e.forEach((s,r)=>{if(s.kind==="audio")return;const o=s,i=e[r-1];let c;i&&i.kind==="audio"&&(c=i);const u=this._generateStream(o,c);t.push(u)}),t}_generateAudioStreams(e){return e.map(s=>this._generateAudioStream(s))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}async waitChannels(){return this.waitSession($)}async waitSyncMediaState(){return this.waitSession(x)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const s=`${Xe}: ${e}`,r=`${ze}: ${t}`,o=[s,r];return this.session.sendInfo(mn,void 0,{extraHeaders:o})}async sendMediaState({cam:e,mic:t},s={}){if(!this.session)throw new Error("No session established");const r=`${vn}: currentstate`,o=`${yn}: ${Number(e)}`,i=`${wn}: ${Number(t)}`,c=[r,o,i];return this.session.sendInfo(An,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async _sendRefusalToTurnOn(e,t={}){if(!this.session)throw new Error("No session established");const c=[`${bn}: ${e==="mic"?0:1}`];return this.session.sendInfo(fn,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}}const Bt="purgatory",k=n=>n===Bt,Ve=n=>()=>(E("getRemoteStreams"),n.getRemoteStreams()),gs=({kind:n,readyState:e})=>n==="video"&&e==="live",Ft=n=>({track:e})=>{gs(e)&&n()},We=({getRemoteStreams:n,setRemoteStreams:e})=>Xt.debounce(()=>{const t=n();E("remoteStreams",t),t&&e(t)},200),Ns=n=>async t=>{const{mediaStream:s,extraHeaders:r,iceServers:o,degradationPreference:i,setRemoteStreams:c,onBeforeProgressCall:u,onSuccessProgressCall:l,onEnterPurgatory:_,onEnterConference:d,onFailProgressCall:S,onFinishProgressCall:h,onEndedCall:T}=t,g=We({setRemoteStreams:c,getRemoteStreams:Ve(n)}),N=Ft(g);E("answerIncomingCall",t);const p=async()=>n.answerToIncomingCall({mediaStream:s,extraHeaders:r,iceServers:o,degradationPreference:i,ontrack:N}),O=()=>{const{remoteCallerData:C}=n;return C.incomingNumber};let R=!1,m;const f=(()=>(E("subscribeEnterConference: onEnterConference",d),_??d?n.onSession("enterRoom",C=>{E("enterRoom",{_room:C,isSuccessProgressCall:R}),m=C,k(m)?_&&_():d&&d({isSuccessProgressCall:R})}):()=>{}))(),y=C=>(E("onSuccess"),R=!0,g(),l&&l({isPurgatory:k(m)}),n.onceRaceSession(["ended","failed"],()=>{f(),T&&T()}),C),w=C=>{throw E("onFail"),S&&S(),f(),C},U=()=>{E("onFinish"),h&&h()};if(E("onBeforeProgressCall"),u){const C=O();u(C)}return p().then(y).catch(w).finally(U)},Rs=n=>async t=>{const{conference:s,mediaStream:r,extraHeaders:o,iceServers:i,degradationPreference:c,setRemoteStreams:u,onBeforeProgressCall:l,onSuccessProgressCall:_,onEnterPurgatory:d,onEnterConference:S,onFailProgressCall:h,onFinishProgressCall:T,onEndedCall:g}=t,N=We({setRemoteStreams:u,getRemoteStreams:Ve(n)}),p=Ft(N);E("callToServer",t);const O=async()=>(E("startCall"),n.call({mediaStream:r,extraHeaders:o,iceServers:i,degradationPreference:c,number:s,ontrack:p}));let R=!1,m;const f=(()=>(E("subscribeEnterConference: onEnterConference",S),d??S?n.onSession("enterRoom",C=>{E("enterRoom",{_room:C,isSuccessProgressCall:R}),m=C,k(m)?d&&d():S&&S({isSuccessProgressCall:R})}):()=>{}))(),y=C=>(E("onSuccess"),R=!0,N(),_&&_({isPurgatory:k(m)}),n.onceRaceSession(["ended","failed"],()=>{f(),g&&g()}),C),w=C=>{throw E("onFail"),h&&h(),f(),C},U=()=>{E("onFinish"),T&&T()};return E("onBeforeProgressCall"),l&&l(s),O().then(y).catch(w).finally(U)},ee=n=>{if(!I.isCanceledError(n))throw n;return!1},ms=n=>async t=>{const{userAgent:s,sipWebSocketServerURL:r,sipServerUrl:o,remoteAddress:i,displayName:c,name:u,password:l,isRegisteredUser:_,sdpSemantics:d,isDisconnectOnFail:S}=t;return E("connectToServer",t),n.connect({userAgent:s,sdpSemantics:d,sipWebSocketServerURL:r,sipServerUrl:o,remoteAddress:i,displayName:c,password:l,user:u,register:_}).then(()=>(E("connectToServer then"),!0)).catch(async h=>(E("connectToServer catch: error",h),S===!0?n.disconnect().then(()=>ee(h)).catch(()=>ee(h)):ee(h)))},As=n=>async()=>(E("disconnectFromServer"),n.disconnect().then(()=>(E("disconnectFromServer: then"),!1)).catch(e=>(E("disconnectFromServer: catch",e),!1))),$e=n=>{const{url:e,cause:t}=n;let s=e;return(t===re||t===se)&&(s=`${n.message.to.uri.user}@${n.message.to.uri.host}`),s};var kt=(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))(kt||{});const fs=(n=new Error)=>{var r;const{cause:e,socket:t}=n;let s="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{s="WRONG_USER_OR_PASSWORD";break}case re:{s="BAD_MEDIA_ERROR";break}case se:{s="NOT_FOUND_ERROR";break}default:t&&((r=t==null?void 0:t._ws)==null?void 0:r.readyState)===3?s="WS_CONNECTION_FAILED":$e(n)&&(s="CONNECT_SERVER_FAILED_BY_LINK")}return s},Is=(n=new Error)=>{const{code:e,cause:t,message:s}=n,r=$e(n),o={};return s&&(o.message=s),r&&(o.link=r),e&&(o.code=e),t&&(o.cause=t),o},Ms=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:kt,getLinkError:$e,getTypeFromError:fs,getValuesFromError:Is},Symbol.toStringTag,{value:"Module"})),Os=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:s,isRegistered:r,isPresentationCall:o})=>{const i=[],c=t?"0":"1",u=s?"0":"1";return i.push(`X-Vinteo-Mic-State: ${c}`,`X-Vinteo-MainCam-State: ${u}`),r||i.push("X-Vinteo-Purgatory-Call: yes"),n&&i.push(`X-Vinteo-Session: ${n}`),o&&i.push("X-Vinteo-Presentation-Call: yes"),e&&i.push(`X-Vinteo-Remote: ${e}`),i},Ds=({appName:n,appVersion:e,browserName:t,browserVersion:s})=>{const r=`${n} ${e}`;return`ChromeNew - ${t?`${t} ${s}, ${r}`:r}`},Ps=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:s,appName:r})=>n?Ds({appVersion:e,browserName:t,browserVersion:s,appName:r}):"Chrome",ps=n=>async()=>{if(n.isCallActive)return E("askPermissionToEnableCam"),n.askPermissionToEnableCam()},vs=n=>t=>(E("onMustStopPresentation"),n.onSession("mustStopPresentation",t)),bs=n=>t=>(E("onUseLicense"),n.onSession("useLicense",t)),ys=n=>async({isEnabledCam:t,isEnabledMic:s})=>{if(n.isCallActive)return E("sendMediaState"),n.sendMediaState({cam:t,mic:s})},ws=n=>async()=>{if(n.isCallActive)return E("sendRefusalToTurnOnCam"),n.sendRefusalToTurnOnCam().catch(t=>{E("sendRefusalToTurnOnCam: error",t)})},Us=n=>async()=>{if(n.isCallActive)return E("sendRefusalToTurnOnMic"),n.sendRefusalToTurnOnMic().catch(t=>{E("sendRefusalToTurnOnMic: error",t)})},Ls=1e6,Bs=({maxBitrate:n=Ls,sipConnector:e})=>async({mediaStream:s,isP2P:r=!1})=>(E("startPresentation"),e.startPresentation(s,{isP2P:r,maxBitrate:n})),Fs=({sipConnector:n})=>async({isP2P:t=!1}={})=>(E("stopShareSipConnector"),n.stopPresentation({isP2P:t}).catch(E)),ks=1e6,Hs=({sipConnector:n,maxBitrate:e=ks})=>async({mediaStream:s,isP2P:r=!1})=>(E("updatePresentation"),n.updatePresentation(s,{isP2P:r,maxBitrate:e})),qs=n=>e=>[...e].map(s=>async()=>n(s)),Vs=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const r=qs(e)(n);return zt(r,t)},Ws=n=>t=>(E("onStartMainCam"),n.onSession("admin-start-main-cam",t)),$s=n=>t=>(E("onStartMic"),n.onSession("admin-start-mic",t)),xs=n=>t=>(E("onStopMainCam"),n.onSession("admin-stop-main-cam",t)),Ys=n=>t=>(E("onStopMic"),n.onSession("admin-stop-mic",t)),Gs=({sipConnector:n})=>{const e=(T,g)=>({isSyncForced:N=!1})=>{if(N){T();return}g()},t=Ws(n),s=xs(n),r=$s(n),o=Ys(n);let i=()=>{},c=()=>{},u=()=>{},l=()=>{};const _=({onStartMainCamForced:T,onStartMainCamNotForced:g,onStopMainCamForced:N,onStopMainCamNotForced:p,onStartMicForced:O,onStartMicNotForced:R,onStopMicForced:m,onStopMicNotForced:v})=>{const f=e(T,g);i=t(f);const y=e(N,p);c=s(y);const w=e(O,R);u=r(w);const U=e(m,v);l=o(U)},d=()=>{i(),c(),u(),l()};return{start:T=>{_(T)},stop:()=>{d()}}},Xs=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:Bt,createSyncMediaState:Gs,error:Ms,getExtraHeaders:Os,getUserAgent:Ps,hasPurgatory:k,resolveAnswerIncomingCall:Ns,resolveAskPermissionToEnableCam:ps,resolveCallToServer:Rs,resolveConnectToServer:ms,resolveDisconnectFromServer:As,resolveGetRemoteStreams:Ve,resolveOnMustStopPresentation:vs,resolveOnUseLicense:bs,resolveSendMediaState:ys,resolveSendRefusalToTurnOnCam:ws,resolveSendRefusalToTurnOnMic:Us,resolveStartPresentation:Bs,resolveStopShareSipConnector:Fs,resolveUpdatePresentation:Hs,resolveUpdateRemoteStreams:We,sendDTMFAccumulated:Vs},Symbol.toStringTag,{value:"Module"})),zs=n=>[...n.keys()].map(e=>n.get(e)),Ks=(n,e)=>zs(n).find(t=>t.type===e),Ht=async n=>n.getStats().then(e=>{const t=Ks(e,"codec");return t==null?void 0:t.mimeType}),Js=n=>n.find(e=>{var t;return((t=e==null?void 0:e.track)==null?void 0:t.kind)==="video"}),qt=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),Qs=1e6,A=n=>n*Qs,Vt=A(.06),js=A(4),Zs=n=>n<=64?Vt:n<=128?A(.12):n<=256?A(.25):n<=384?A(.32):n<=426?A(.38):n<=640?A(.5):n<=848?A(.7):n<=1280?A(1):n<=1920?A(2):js,er="av1",tr=n=>qt(n,er),nr=.6,Wt=(n,e)=>tr(e)?n*nr:n,sr=n=>Wt(Vt,n),$t=(n,e)=>{const t=Zs(n);return Wt(t,e)},xt=Kt(),rr=async()=>xt().catch(n=>{E("videoSendingBalancer: error",n)}),or=async n=>(xt.add(n),rr()),xe=async({sender:n,scaleResolutionDownBy:e,maxBitrate:t,onSetParameters:s})=>or(async()=>Lt(n,{scaleResolutionDownBy:e,maxBitrate:t},s)),ir=async({sender:n,codec:e},t)=>{const r=sr(e);return xe({sender:n,maxBitrate:r,onSetParameters:t,scaleResolutionDownBy:200})},te=async({sender:n,track:e,codec:t},s)=>{const i=e.getSettings().width,c=$t(i,t);return xe({sender:n,maxBitrate:c,onSetParameters:s,scaleResolutionDownBy:1})},ar=async({sender:n,track:e,resolution:t,codec:s},r)=>{const o=e.getSettings(),i=o.width,c=o.height,[u,l]=t.split("x"),_=i/Number(u),d=c/Number(l),h=Math.max(_,d,1),T=$t(Number(u),s);return xe({sender:n,maxBitrate:T,onSetParameters:r,scaleResolutionDownBy:h})},cr=async({mainCam:n,resolutionMainCam:e,sender:t,track:s,codec:r},o)=>{switch(n){case M.PAUSE_MAIN_CAM:return ir({sender:t,codec:r},o);case M.RESUME_MAIN_CAM:return te({sender:t,track:s,codec:r},o);case M.MAX_MAIN_CAM_RESOLUTION:return e!==void 0?ar({sender:t,track:s,codec:r,resolution:e},o):te({sender:t,track:s,codec:r},o);default:return te({sender:t,track:s,codec:r},o)}},je={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},Ze=async({mainCam:n,resolutionMainCam:e,connection:t,onSetParameters:s,ignoreForCodec:r})=>{const o=t.getSenders(),i=Js(o);if(!(i!=null&&i.track))return je;const c=await Ht(i);return qt(c,r)?je:cr({mainCam:n,resolutionMainCam:e,sender:i,codec:c,track:i.track},s)},ur=(n,{ignoreForCodec:e,onSetParameters:t}={})=>{const s=async()=>{const{connection:u}=n;if(!u)throw new Error("connection is not exist");return Ze({connection:u,onSetParameters:t,ignoreForCodec:e})};let r=s;const o=async u=>(r=async()=>{const{mainCam:l,resolutionMainCam:_}=u,{connection:d}=n;if(!d)throw new Error("connection is not exist");return Ze({mainCam:l,resolutionMainCam:_,connection:d,onSetParameters:t,ignoreForCodec:e})},r());return{subscribe:()=>{n.onSession("main-cam-control",o)},unsubscribe:()=>{n.offSession("main-cam-control",o)},balanceByTrack:s,resetMainCamControl(){r=s},async reBalance(){return r()}}};exports.debug=J;exports.EEventsMainCAM=M;exports.EEventsMic=z;exports.EEventsSyncMediaState=K;exports.EUseLicense=yt;exports.causes=Sn;exports.constants=hn;exports.default=Cs;exports.disableDebug=xn;exports.enableDebug=$n;exports.eventNames=Tn;exports.getCodecFromSender=Ht;exports.hasCanceledCallError=os;exports.resolveVideoSendingBalancer=ur;exports.tools=Xs;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const s=require("./SipConnector-3317ff75.cjs"),q=require("ts-debounce"),H=require("@krivega/cancelable-promise"),Y=require("debug");require("events-constructor");const L="purgatory",P=e=>e===L,w=e=>()=>(s.logger("getRemoteStreams"),e.getRemoteStreams()),z=({kind:e,readyState:n})=>e==="video"&&n==="live",x=e=>({track:n})=>{z(n)&&e()},B=({getRemoteStreams:e,setRemoteStreams:n})=>q.debounce(()=>{const t=e();s.logger("remoteStreams",t),t&&n(t)},200),J=e=>async t=>{const{mediaStream:r,extraHeaders:o,iceServers:c,degradationPreference:a,setRemoteStreams:u,onBeforeProgressCall:d,onSuccessProgressCall:E,onEnterPurgatory:f,onEnterConference:m,onFailProgressCall:y,onFinishProgressCall:h,onEndedCall:M}=t,C=B({setRemoteStreams:u,getRemoteStreams:w(e)}),T=x(C);s.logger("answerIncomingCall",t);const O=async()=>e.answerToIncomingCall({mediaStream:r,extraHeaders:o,iceServers:c,degradationPreference:a,ontrack:T}),A=()=>{const{remoteCallerData:S}=e;return S.incomingNumber};let _=!1,i;const l=(()=>(s.logger("subscribeEnterConference: onEnterConference",m),f??m?e.onSession("enterRoom",S=>{s.logger("enterRoom",{_room:S,isSuccessProgressCall:_}),i=S,P(i)?f&&f():m&&m({isSuccessProgressCall:_})}):()=>{}))(),R=S=>(s.logger("onSuccess"),_=!0,C(),E&&E({isPurgatory:P(i)}),e.onceRaceSession(["ended","failed"],()=>{l(),M&&M()}),S),b=S=>{throw s.logger("onFail"),y&&y(),l(),S},N=()=>{s.logger("onFinish"),h&&h()};if(s.logger("onBeforeProgressCall"),d){const S=A();d(S)}return O().then(R).catch(b).finally(N)},Q=e=>async t=>{const{conference:r,mediaStream:o,extraHeaders:c,iceServers:a,degradationPreference:u,setRemoteStreams:d,onBeforeProgressCall:E,onSuccessProgressCall:f,onEnterPurgatory:m,onEnterConference:y,onFailProgressCall:h,onFinishProgressCall:M,onEndedCall:C}=t,T=B({setRemoteStreams:d,getRemoteStreams:w(e)}),O=x(T);s.logger("callToServer",t);const A=async()=>(s.logger("startCall"),e.call({mediaStream:o,extraHeaders:c,iceServers:a,degradationPreference:u,number:r,ontrack:O}));let _=!1,i;const l=(()=>(s.logger("subscribeEnterConference: onEnterConference",y),m??y?e.onSession("enterRoom",S=>{s.logger("enterRoom",{_room:S,isSuccessProgressCall:_}),i=S,P(i)?m&&m():y&&y({isSuccessProgressCall:_})}):()=>{}))(),R=S=>(s.logger("onSuccess"),_=!0,T(),f&&f({isPurgatory:P(i)}),e.onceRaceSession(["ended","failed"],()=>{l(),C&&C()}),S),b=S=>{throw s.logger("onFail"),h&&h(),l(),S},N=()=>{s.logger("onFinish"),M&&M()};return s.logger("onBeforeProgressCall"),E&&E(r),A().then(R).catch(b).finally(N)},p=e=>{if(!H.isCanceledError(e))throw e;return!1},Z=e=>async t=>{const{userAgent:r,sipWebSocketServerURL:o,sipServerUrl:c,remoteAddress:a,displayName:u,name:d,password:E,isRegisteredUser:f,sdpSemantics:m,isDisconnectOnFail:y}=t;return s.logger("connectToServer",t),e.connect({userAgent:r,sdpSemantics:m,sipWebSocketServerURL:o,sipServerUrl:c,remoteAddress:a,displayName:u,password:E,user:d,register:f}).then(()=>(s.logger("connectToServer then"),!0)).catch(async h=>(s.logger("connectToServer catch: error",h),y===!0?e.disconnect().then(()=>p(h)).catch(()=>p(h)):p(h)))},ee=e=>async()=>(s.logger("disconnectFromServer"),e.disconnect().then(()=>(s.logger("disconnectFromServer: then"),!1)).catch(n=>(s.logger("disconnectFromServer: catch",n),!1))),D=e=>{const{url:n,cause:t}=e;let r=n;return(t===s.BAD_MEDIA_DESCRIPTION||t===s.NOT_FOUND)&&(r=`${e.message.to.uri.user}@${e.message.to.uri.host}`),r};var V=(e=>(e.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",e.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",e.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",e.NOT_FOUND_ERROR="NOT_FOUND_ERROR",e.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",e.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",e))(V||{});const ne=(e=new Error)=>{var o;const{cause:n,socket:t}=e;let r="CONNECT_SERVER_FAILED";switch(n){case"Forbidden":{r="WRONG_USER_OR_PASSWORD";break}case s.BAD_MEDIA_DESCRIPTION:{r="BAD_MEDIA_ERROR";break}case s.NOT_FOUND:{r="NOT_FOUND_ERROR";break}default:t&&((o=t==null?void 0:t._ws)==null?void 0:o.readyState)===3?r="WS_CONNECTION_FAILED":D(e)&&(r="CONNECT_SERVER_FAILED_BY_LINK")}return r},te=(e=new Error)=>{const{code:n,cause:t,message:r}=e,o=D(e),c={};return r&&(c.message=r),o&&(c.link=o),n&&(c.code=n),t&&(c.cause=t),c},re=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:V,getLinkError:D,getTypeFromError:ne,getValuesFromError:te},Symbol.toStringTag,{value:"Module"})),se=({sessionId:e,remoteAddress:n,isMutedAudio:t,isMutedVideo:r,isRegistered:o,isPresentationCall:c})=>{const a=[],u=t?"0":"1",d=r?"0":"1";return a.push(`X-Vinteo-Mic-State: ${u}`,`X-Vinteo-MainCam-State: ${d}`),o||a.push("X-Vinteo-Purgatory-Call: yes"),e&&a.push(`X-Vinteo-Session: ${e}`),c&&a.push("X-Vinteo-Presentation-Call: yes"),n&&a.push(`X-Vinteo-Remote: ${n}`),a},oe=({appName:e,appVersion:n,browserName:t,browserVersion:r})=>{const o=`${e} ${n}`;return`ChromeNew - ${t?`${t} ${r}, ${o}`:o}`},ce=({isUnifiedSdpSemantic:e,appVersion:n,browserName:t,browserVersion:r,appName:o})=>e?oe({appVersion:n,browserName:t,browserVersion:r,appName:o}):"Chrome",ae=e=>async()=>{if(e.isCallActive)return s.logger("askPermissionToEnableCam"),e.askPermissionToEnableCam()},ie=e=>t=>(s.logger("onMustStopPresentation"),e.onSession("mustStopPresentation",t)),ue=e=>t=>(s.logger("onUseLicense"),e.onSession("useLicense",t)),le=e=>async({isEnabledCam:t,isEnabledMic:r})=>{if(e.isCallActive)return s.logger("sendMediaState"),e.sendMediaState({cam:t,mic:r})},ge=e=>async()=>{if(e.isCallActive)return s.logger("sendRefusalToTurnOnCam"),e.sendRefusalToTurnOnCam().catch(t=>{s.logger("sendRefusalToTurnOnCam: error",t)})},Se=e=>async()=>{if(e.isCallActive)return s.logger("sendRefusalToTurnOnMic"),e.sendRefusalToTurnOnMic().catch(t=>{s.logger("sendRefusalToTurnOnMic: error",t)})},de=1e6,me=({maxBitrate:e=de,sipConnector:n})=>async({mediaStream:r,isP2P:o=!1})=>(s.logger("startPresentation"),n.startPresentation(r,{isP2P:o,maxBitrate:e})),fe=({sipConnector:e})=>async({isP2P:t=!1}={})=>(s.logger("stopShareSipConnector"),e.stopPresentation({isP2P:t}).catch(s.logger)),Ee=1e6,Ce=({sipConnector:e,maxBitrate:n=Ee})=>async({mediaStream:r,isP2P:o=!1})=>(s.logger("updatePresentation"),e.updatePresentation(r,{isP2P:o,maxBitrate:n})),Re="ERROR_NOT_RUNNING",he=e=>{const n=new Error("Promise was not running");return n.basePromise=e,n.id=Re,n.name="Not running",n},Me=async(e,n)=>e.reduce(async(t,r)=>t.then(async({success:o,errors:c,results:a})=>(!n||n(r)?r():Promise.reject(he(r))).then(u=>({errors:c,success:[...o,u],results:[...a,u],isSuccessful:!0,isError:!1})).catch(u=>({success:o,errors:[...c,u],results:[...a,u],isSuccessful:!1,isError:!0}))),Promise.resolve({success:[],errors:[],results:[],isSuccessful:!1,isError:!1})),ye=e=>n=>[...n].map(r=>async()=>e(r)),Te=async({accumulatedKeys:e,sendKey:n,canRunTask:t})=>{const o=ye(n)(e);return Me(o,t)},_e=e=>t=>(s.logger("onStartMainCam"),e.onSession("admin-start-main-cam",t)),be=e=>t=>(s.logger("onStartMic"),e.onSession("admin-start-mic",t)),ve=e=>t=>(s.logger("onStopMainCam"),e.onSession("admin-stop-main-cam",t)),Ne=e=>t=>(s.logger("onStopMic"),e.onSession("admin-stop-mic",t)),Oe=({sipConnector:e})=>{const n=(M,C)=>({isSyncForced:T=!1})=>{if(T){M();return}C()},t=_e(e),r=ve(e),o=be(e),c=Ne(e);let a=()=>{},u=()=>{},d=()=>{},E=()=>{};const f=({onStartMainCamForced:M,onStartMainCamNotForced:C,onStopMainCamForced:T,onStopMainCamNotForced:O,onStartMicForced:A,onStartMicNotForced:_,onStopMicForced:i,onStopMicNotForced:g})=>{const l=n(M,C);a=t(l);const R=n(T,O);u=r(R);const b=n(A,_);d=o(b);const N=n(i,g);E=c(N)},m=()=>{a(),u(),d(),E()};return{start:M=>{f(M)},stop:()=>{m()}}},Ae=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:L,createSyncMediaState:Oe,error:re,getExtraHeaders:se,getUserAgent:ce,hasPurgatory:P,resolveAnswerIncomingCall:J,resolveAskPermissionToEnableCam:ae,resolveCallToServer:Q,resolveConnectToServer:Z,resolveDisconnectFromServer:ee,resolveGetRemoteStreams:w,resolveOnMustStopPresentation:ie,resolveOnUseLicense:ue,resolveSendMediaState:le,resolveSendRefusalToTurnOnCam:ge,resolveSendRefusalToTurnOnMic:Se,resolveStartPresentation:me,resolveStopShareSipConnector:fe,resolveUpdatePresentation:Ce,resolveUpdateRemoteStreams:B,sendDTMFAccumulated:Te},Symbol.toStringTag,{value:"Module"})),Pe=e=>[...e.keys()].map(n=>e.get(n)),pe=(e,n)=>Pe(e).find(t=>t.type===n),$=async e=>e.getStats().then(n=>{const t=pe(n,"codec");return t==null?void 0:t.mimeType}),Ie=e=>e.find(n=>{var t;return((t=n==null?void 0:n.track)==null?void 0:t.kind)==="video"}),j=(e,n)=>e!==void 0&&n!==void 0&&e.toLowerCase().includes(n.toLowerCase()),we="ERROR_NOT_RUNNING",Be=e=>{const n=new Error("Promise was not running");return n.basePromise=e,n.id=we,n.name="Not running",n},De=async(e,n)=>e.reduce(async(t,r)=>t.then(async({success:o,errors:c,results:a})=>(!n||n(r)?r():Promise.reject(Be(r))).then(u=>({errors:c,success:[...o,u],results:[...a,u],isSuccessful:!0,isError:!1})).catch(u=>({success:o,errors:[...c,u],results:[...a,u],isSuccessful:!1,isError:!0}))),Promise.resolve({success:[],errors:[],results:[],isSuccessful:!1,isError:!1})),ke=new Error("Stack is empty"),Fe=new Error("Promise is not actual"),Ue=new Error("stackPromises only works with functions that returns a Promise"),Le=({noRejectIsNotActual:e=!1,noRunIsNotActual:n=!1}={})=>{const t=[],r=[],o=({task:i,index:g})=>{r.push({task:i,index:g})},c=(i,{task:g,index:l})=>{const R=r.find(({task:b,index:N})=>g===b&&l===N);if(!R)throw new Error("Task not found");if(R.promise)throw new Error("Task is already running");R.promise=i},a=({task:i,index:g})=>{const l=r.find(({task:R,index:b})=>i===R&&g===b);if(l)return l.promise},u=({task:i})=>{const g=r.at(-1);return(g==null?void 0:g.task)===i},d=({task:i,index:g})=>(o({task:i,index:g}),async()=>{let l=a({task:i,index:g});const R=u({task:i});return!l&&n&&!R?Promise.resolve():(l||(l=i({isActual:R}),c(l,{task:i,index:g})),l)}),E=({resolve:i,reject:g})=>({results:l,isSuccessful:R})=>{const b=l.length,N=t.length;if(b===N){const S=l.at(-1);if(R){i(S);return}g(S);return}if(e){const S=l.at(-1);i(S);return}g(Fe)};let f=!1;const m=()=>{f=!0},y=()=>{f=!1},h=()=>f,M=async()=>(m(),De(t,h)),C=async()=>{if(t.length===0)throw ke;return new Promise((i,g)=>{const l=E({resolve:i,reject:g});M().then(l).catch(l)})},T=i=>{if(typeof i!="function")throw Ue;const g=t.length;return t.push(d({task:i,index:g})),C},O=async i=>(T(i),C()),A=()=>{t.length=0,r.length=0},_=()=>{y(),A()};return C.add=T,C.run=O,C.stop=_,C},xe=1e6,v=e=>e*xe,G=v(.06),Ve=v(4),$e=e=>e<=64?G:e<=128?v(.12):e<=256?v(.25):e<=384?v(.32):e<=426?v(.38):e<=640?v(.5):e<=848?v(.7):e<=1280?v(1):e<=1920?v(2):Ve,je="av1",Ge=e=>j(e,je),Xe=.6,X=(e,n)=>Ge(n)?e*Xe:e,Ke=e=>X(G,e),K=(e,n)=>{const t=$e(e);return X(t,n)},W=Le(),We=async()=>W().catch(e=>{s.logger("videoSendingBalancer: error",e)}),qe=async e=>(W.add(e),We()),k=async({sender:e,scaleResolutionDownBy:n,maxBitrate:t,onSetParameters:r})=>qe(async()=>s.setEncodingsToSender(e,{scaleResolutionDownBy:n,maxBitrate:t},r)),He=async({sender:e,codec:n},t)=>{const o=Ke(n);return k({sender:e,maxBitrate:o,onSetParameters:t,scaleResolutionDownBy:200})},I=async({sender:e,track:n,codec:t},r)=>{const a=n.getSettings().width,u=K(a,t);return k({sender:e,maxBitrate:u,onSetParameters:r,scaleResolutionDownBy:1})},Ye=async({sender:e,track:n,resolution:t,codec:r},o)=>{const c=n.getSettings(),a=c.width,u=c.height,[d,E]=t.split("x"),f=a/Number(d),m=u/Number(E),h=Math.max(f,m,1),M=K(Number(d),r);return k({sender:e,maxBitrate:M,onSetParameters:o,scaleResolutionDownBy:h})},ze=async({mainCam:e,resolutionMainCam:n,sender:t,track:r,codec:o},c)=>{switch(e){case s.EEventsMainCAM.PAUSE_MAIN_CAM:return He({sender:t,codec:o},c);case s.EEventsMainCAM.RESUME_MAIN_CAM:return I({sender:t,track:r,codec:o},c);case s.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return n!==void 0?Ye({sender:t,track:r,codec:o,resolution:n},c):I({sender:t,track:r,codec:o},c);default:return I({sender:t,track:r,codec:o},c)}},F={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},U=async({mainCam:e,resolutionMainCam:n,connection:t,onSetParameters:r,ignoreForCodec:o})=>{const c=t.getSenders(),a=Ie(c);if(!(a!=null&&a.track))return F;const u=await $(a);return j(u,o)?F:ze({mainCam:e,resolutionMainCam:n,sender:a,codec:u,track:a.track},r)},Je=(e,{ignoreForCodec:n,onSetParameters:t}={})=>{const r=async()=>{const{connection:d}=e;if(!d)throw new Error("connection is not exist");return U({connection:d,onSetParameters:t,ignoreForCodec:n})};let o=r;const c=async d=>(o=async()=>{const{mainCam:E,resolutionMainCam:f}=d,{connection:m}=e;if(!m)throw new Error("connection is not exist");return U({mainCam:E,resolutionMainCam:f,connection:m,onSetParameters:t,ignoreForCodec:n})},o());return{subscribe:()=>{e.onSession("main-cam-control",c)},unsubscribe:()=>{e.offSession("main-cam-control",c)},balanceByTrack:r,resetMainCamControl(){o=r},async reBalance(){return o()}}};exports.EEventsMainCAM=s.EEventsMainCAM;exports.EEventsMic=s.EEventsMic;exports.EEventsSyncMediaState=s.EEventsSyncMediaState;exports.EUseLicense=s.EUseLicense;exports.causes=s.causes;exports.constants=s.constants;exports.default=s.SipConnector;exports.disableDebug=s.disableDebug;exports.enableDebug=s.enableDebug;exports.eventNames=s.eventNames;exports.hasCanceledCallError=s.hasCanceledCallError;exports.debug=Y;exports.getCodecFromSender=$;exports.resolveVideoSendingBalancer=Je;exports.tools=Ae;