sip-connector 9.2.0 → 9.2.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.
@@ -5,11 +5,11 @@ import { CancelableRequest as N, isCanceledError as It } from "@krivega/cancelab
5
5
  import Oe from "events-constructor";
6
6
  import { repeatedCallsAsync as De } from "repeated-calls";
7
7
  import V from "debug";
8
- const mt = "Connection Error", Le = "Request Timeout", pt = "SIP Failure Code", ft = "Internal Error", Pt = "Busy", He = "Rejected", Ot = "Redirected", Dt = "Unavailable", Mt = "Not Found", vt = "Address Incomplete", yt = "Incompatible SDP", bt = "Missing SDP", wt = "Authentication Error", We = "Terminated", Ut = "WebRTC Error", ke = "Canceled", Lt = "No Answer", Ht = "Expires", Wt = "No ACK", kt = "Dialog Error", qt = "User Denied Media Access", Ft = "Bad Media Description", Bt = "RTP Timeout", ts = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
8
+ const mt = "Connection Error", Le = "Request Timeout", pt = "SIP Failure Code", ft = "Internal Error", Pt = "Busy", He = "Rejected", Ot = "Redirected", Dt = "Unavailable", Mt = "Not Found", vt = "Address Incomplete", yt = "Incompatible SDP", bt = "Missing SDP", wt = "Authentication Error", We = "Terminated", Ut = "WebRTC Error", ke = "Canceled", Lt = "No Answer", Ht = "Expires", Wt = "No ACK", kt = "Dialog Error", qt = "User Denied Media Access", Bt = "Bad Media Description", Ft = "RTP Timeout", ts = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
9
9
  __proto__: null,
10
10
  ADDRESS_INCOMPLETE: vt,
11
11
  AUTHENTICATION_ERROR: wt,
12
- BAD_MEDIA_DESCRIPTION: Ft,
12
+ BAD_MEDIA_DESCRIPTION: Bt,
13
13
  BUSY: Pt,
14
14
  BYE: We,
15
15
  CANCELED: ke,
@@ -25,12 +25,12 @@ const mt = "Connection Error", Le = "Request Timeout", pt = "SIP Failure Code",
25
25
  REDIRECTED: Ot,
26
26
  REJECTED: He,
27
27
  REQUEST_TIMEOUT: Le,
28
- RTP_TIMEOUT: Bt,
28
+ RTP_TIMEOUT: Ft,
29
29
  SIP_FAILURE_CODE: pt,
30
30
  UNAVAILABLE: Dt,
31
31
  USER_DENIED_MEDIA_ACCESS: qt,
32
32
  WEBRTC_ERROR: Ut
33
- }, Symbol.toStringTag, { value: "Module" })), Y = "incomingCall", x = "declinedIncomingCall", G = "failedIncomingCall", $ = "terminatedIncomingCall", H = "connecting", m = "connected", u = "disconnected", M = "newRTCSession", p = "registered", X = "unregistered", f = "registrationFailed", qe = "newMessage", J = "sipEvent", z = "availableSecondRemoteStream", Q = "notAvailableSecondRemoteStream", j = "mustStopPresentation", v = "shareState", K = "enterRoom", Z = "useLicense", ee = "peerconnection:confirmed", te = "peerconnection:ontrack", y = "channels", ne = "channels:notify", se = "ended:fromserver", ie = "main-cam-control", re = "admin-stop-main-cam", oe = "admin-start-main-cam", ae = "admin-stop-mic", ce = "admin-start-mic", b = "admin-force-sync-media-state", _e = "participant:added-to-list-moderators", Ee = "participant:removed-from-list-moderators", he = "participant:move-request-to-stream", le = "participant:move-request-to-spectators", de = "participation:accepting-word-request", Te = "participation:cancelling-word-request", Se = "webcast:started", ue = "webcast:stopped", Ce = "account:changed", Ne = "account:deleted", ge = "conference:participant-token-issued", P = "ended", Fe = "sending", Be = "reinvite", Ve = "replaces", Ye = "refer", xe = "progress", Ge = "accepted", w = "confirmed", U = "peerconnection", A = "failed", $e = "muted", Xe = "unmuted", Ae = "newDTMF", Re = "newInfo", Je = "hold", ze = "unhold", Qe = "update", je = "sdp", Ke = "icecandidate", Ze = "getusermediafailed", et = "peerconnection:createofferfailed", tt = "peerconnection:createanswerfailed", nt = "peerconnection:setlocaldescriptionfailed", st = "peerconnection:setremotedescriptionfailed", it = "presentation:start", rt = "presentation:started", ot = "presentation:end", Ie = "presentation:ended", L = "presentation:failed", at = "SPECTATOR", ct = 1e6, ns = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
33
+ }, Symbol.toStringTag, { value: "Module" })), Y = "incomingCall", x = "declinedIncomingCall", G = "failedIncomingCall", $ = "terminatedIncomingCall", H = "connecting", m = "connected", u = "disconnected", M = "newRTCSession", p = "registered", X = "unregistered", f = "registrationFailed", qe = "newMessage", J = "sipEvent", z = "availableSecondRemoteStream", Q = "notAvailableSecondRemoteStream", j = "mustStopPresentation", v = "shareState", K = "enterRoom", Z = "useLicense", ee = "peerconnection:confirmed", te = "peerconnection:ontrack", y = "channels", ne = "channels:notify", se = "ended:fromserver", ie = "main-cam-control", re = "admin-stop-main-cam", oe = "admin-start-main-cam", ae = "admin-stop-mic", ce = "admin-start-mic", b = "admin-force-sync-media-state", _e = "participant:added-to-list-moderators", Ee = "participant:removed-from-list-moderators", he = "participant:move-request-to-stream", le = "participant:move-request-to-spectators", de = "participation:accepting-word-request", Te = "participation:cancelling-word-request", Se = "webcast:started", ue = "webcast:stopped", Ce = "account:changed", Ne = "account:deleted", ge = "conference:participant-token-issued", P = "ended", Be = "sending", Fe = "reinvite", Ve = "replaces", Ye = "refer", xe = "progress", Ge = "accepted", w = "confirmed", U = "peerconnection", A = "failed", $e = "muted", Xe = "unmuted", Ae = "newDTMF", Re = "newInfo", Je = "hold", ze = "unhold", Qe = "update", je = "sdp", Ke = "icecandidate", Ze = "getusermediafailed", et = "peerconnection:createofferfailed", tt = "peerconnection:createanswerfailed", nt = "peerconnection:setlocaldescriptionfailed", st = "peerconnection:setremotedescriptionfailed", it = "presentation:start", rt = "presentation:started", ot = "presentation:end", Ie = "presentation:ended", L = "presentation:failed", at = "SPECTATOR", ct = 1e6, ns = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
34
34
  __proto__: null,
35
35
  ACCEPTED: Ge,
36
36
  ACCOUNT_CHANGED: Ce,
@@ -89,10 +89,10 @@ const mt = "Connection Error", Le = "Request Timeout", pt = "SIP Failure Code",
89
89
  REFER: Ye,
90
90
  REGISTERED: p,
91
91
  REGISTRATION_FAILED: f,
92
- REINVITE: Be,
92
+ REINVITE: Fe,
93
93
  REPLACES: Ve,
94
94
  SDP: je,
95
- SENDING: Fe,
95
+ SENDING: Be,
96
96
  SHARE_STATE: v,
97
97
  SIP_EVENT: J,
98
98
  SPECTATOR: at,
@@ -151,8 +151,8 @@ const mt = "Connection Error", Le = "Request Timeout", pt = "SIP Failure Code",
151
151
  ], pe = [
152
152
  P,
153
153
  H,
154
- Fe,
155
154
  Be,
155
+ Fe,
156
156
  Ve,
157
157
  Ye,
158
158
  xe,
@@ -211,7 +211,7 @@ const mt = "Connection Error", Le = "Request Timeout", pt = "SIP Failure Code",
211
211
  const s = t === "recvonly" ? [] : r.getAudioTracks(), o = e === "recvonly" ? [] : r.getVideoTracks(), a = [...s, ...o], c = new MediaStream(a);
212
212
  return c.getTracks = () => [...c.getAudioTracks(), ...c.getVideoTracks()], n && n !== "none" && Nn(c, n), c;
213
213
  };
214
- var I = /* @__PURE__ */ ((r) => (r.PAUSE_MAIN_CAM = "PAUSEMAINCAM", r.RESUME_MAIN_CAM = "RESUMEMAINCAM", r.MAX_MAIN_CAM_RESOLUTION = "MAXMAINCAMRESOLUTION", r.ADMIN_STOP_MAIN_CAM = "ADMINSTOPMAINCAM", r.ADMIN_START_MAIN_CAM = "ADMINSTARTMAINCAM", r))(I || {}), q = /* @__PURE__ */ ((r) => (r.ADMIN_STOP_MIC = "ADMINSTOPMIC", r.ADMIN_START_MIC = "ADMINSTARTMIC", r))(q || {}), F = /* @__PURE__ */ ((r) => (r.ADMIN_SYNC_FORCED = "1", r.ADMIN_SYNC_NOT_FORCED = "0", r))(F || {}), gn = /* @__PURE__ */ ((r) => (r.AUDIO = "AUDIO", r.VIDEO = "VIDEO", r.AUDIOPLUSPRESENTATION = "AUDIOPLUSPRESENTATION", r))(gn || {});
214
+ var I = /* @__PURE__ */ ((r) => (r.PAUSE_MAIN_CAM = "PAUSEMAINCAM", r.RESUME_MAIN_CAM = "RESUMEMAINCAM", r.MAX_MAIN_CAM_RESOLUTION = "MAXMAINCAMRESOLUTION", r.ADMIN_STOP_MAIN_CAM = "ADMINSTOPMAINCAM", r.ADMIN_START_MAIN_CAM = "ADMINSTARTMAINCAM", r))(I || {}), q = /* @__PURE__ */ ((r) => (r.ADMIN_STOP_MIC = "ADMINSTOPMIC", r.ADMIN_START_MIC = "ADMINSTARTMIC", r))(q || {}), B = /* @__PURE__ */ ((r) => (r.ADMIN_SYNC_FORCED = "1", r.ADMIN_SYNC_NOT_FORCED = "0", r))(B || {}), gn = /* @__PURE__ */ ((r) => (r.AUDIO = "AUDIO", r.VIDEO = "VIDEO", r.AUDIOPLUSPRESENTATION = "AUDIOPLUSPRESENTATION", r))(gn || {});
215
215
  function An(r) {
216
216
  return (e) => `sip:${e}@${r}`;
217
217
  }
@@ -245,10 +245,10 @@ const Rn = (r, e) => () => Math.floor(Math.random() * (e - r)) + r, we = (r) =>
245
245
  const n = Dn(r, e);
246
246
  if (n)
247
247
  return wn(n, { maxBitrate: t });
248
- }, Ln = 486, Hn = 487, B = "local", Ue = "remote", Wn = 3, kn = 1, os = (r = new Error()) => {
248
+ }, Ln = 486, Hn = 487, F = "local", Ue = "remote", Wn = 3, kn = 1, os = (r = new Error()) => {
249
249
  const { originator: e, cause: t } = r;
250
- return It(r) ? !0 : typeof t == "string" ? t === Le || t === He || e === B && (t === ke || t === We) : !1;
251
- }, g = "SipConnector", qn = "channels", Fn = "WebcastStarted", Bn = "WebcastStopped", Vn = "accountChanged", Yn = "accountDeleted", xn = "addedToListModerators", Gn = "removedFromListModerators", $n = "ParticipationRequestAccepted", Xn = "ParticipationRequestRejected", Jn = "ParticipantMovedToWebcast", zn = "ConferenceParticipantTokenIssued";
250
+ return It(r) ? !0 : typeof t == "string" ? t === Le || t === He || e === F && (t === ke || t === We) : !1;
251
+ }, g = "SipConnector", qn = "channels", Bn = "WebcastStarted", Fn = "WebcastStopped", Vn = "accountChanged", Yn = "accountDeleted", xn = "addedToListModerators", Gn = "removedFromListModerators", $n = "ParticipationRequestAccepted", Xn = "ParticipationRequestRejected", Jn = "ParticipantMovedToWebcast", zn = "ConferenceParticipantTokenIssued";
252
252
  class as {
253
253
  constructor({ JsSIP: e }) {
254
254
  i(this, "_isRegisterConfig", !1);
@@ -306,24 +306,24 @@ class as {
306
306
  delete this.incomingSession;
307
307
  });
308
308
  i(this, "_connectWithDuplicatedCalls", async (e, { callLimit: t = Wn } = {}) => {
309
- let n = !0;
310
- const s = async () => (n = !1, this._cancelableConnect.request(e)), o = (a) => {
311
- var h;
312
- const c = !!((h = this.ua) != null && h.isConnected()), _ = !n && c && this.hasEqualConnectionConfiguration(e), E = !!a && !Pn(a);
313
- return _ || E;
309
+ const n = async () => this._cancelableConnect.request(e), s = (o) => {
310
+ var E;
311
+ const c = !!((E = this.ua) != null && E.isConnected()) && this.hasEqualConnectionConfiguration(e), _ = !!o && !Pn(o);
312
+ return c || _;
314
313
  };
315
314
  return this._cancelableConnectWithRepeatedCalls = De({
316
- targetFunction: s,
317
- isComplete: o,
315
+ targetFunction: n,
316
+ isComplete: s,
318
317
  callLimit: t,
319
318
  isRejectAsValid: !0,
319
+ isCheckBeforeCall: !1,
320
320
  onAfterCancel: () => {
321
321
  this._cancelableConnect.cancelRequest();
322
322
  }
323
- }), this._cancelableConnectWithRepeatedCalls.then((a) => {
324
- if (a instanceof this.JsSIP.UA)
325
- return a;
326
- throw a;
323
+ }), this._cancelableConnectWithRepeatedCalls.then((o) => {
324
+ if (o instanceof this.JsSIP.UA)
325
+ return o;
326
+ throw o;
327
327
  });
328
328
  });
329
329
  i(this, "handleNewRTCSession", ({ originator: e, session: t }) => {
@@ -331,7 +331,7 @@ class as {
331
331
  this.incomingSession = t;
332
332
  const n = this.remoteCallerData;
333
333
  t.on(A, (s) => {
334
- this.removeIncomingSession(), s.originator === B ? this._uaEvents.trigger($, n) : this._uaEvents.trigger(G, n);
334
+ this.removeIncomingSession(), s.originator === F ? this._uaEvents.trigger($, n) : this._uaEvents.trigger(G, n);
335
335
  }), this._uaEvents.trigger(Y, n);
336
336
  }
337
337
  });
@@ -548,7 +548,7 @@ class as {
548
548
  return;
549
549
  }
550
550
  this.onceSession(Ae, ({ originator: o }) => {
551
- o === B && t();
551
+ o === F && t();
552
552
  }), s.sendDTMF(e, {
553
553
  duration: 120,
554
554
  interToneGap: 600
@@ -600,12 +600,12 @@ class as {
600
600
  this._triggerChannelsNotify(t);
601
601
  break;
602
602
  }
603
- case Fn: {
603
+ case Bn: {
604
604
  const t = e;
605
605
  this._triggerWebcastStartedNotify(t);
606
606
  break;
607
607
  }
608
- case Bn: {
608
+ case Fn: {
609
609
  const t = e;
610
610
  this._triggerWebcastStoppedNotify(t);
611
611
  break;
@@ -745,7 +745,7 @@ class as {
745
745
  e.getHeader(cn) === at && this._sessionEvents.trigger(le, void 0);
746
746
  });
747
747
  i(this, "_triggerMainCamControl", (e) => {
748
- const t = e.getHeader(Zt), n = e.getHeader(be), s = n === F.ADMIN_SYNC_FORCED;
748
+ const t = e.getHeader(Zt), n = e.getHeader(be), s = n === B.ADMIN_SYNC_FORCED;
749
749
  if (t === I.ADMIN_START_MAIN_CAM) {
750
750
  this._sessionEvents.trigger(oe, { isSyncForced: s });
751
751
  return;
@@ -762,7 +762,7 @@ class as {
762
762
  });
763
763
  });
764
764
  i(this, "_triggerMicControl", (e) => {
765
- const t = e.getHeader(en), s = e.getHeader(be) === F.ADMIN_SYNC_FORCED;
765
+ const t = e.getHeader(en), s = e.getHeader(be) === B.ADMIN_SYNC_FORCED;
766
766
  t === q.ADMIN_START_MIC ? this._sessionEvents.trigger(ce, { isSyncForced: s }) : t === q.ADMIN_STOP_MIC && this._sessionEvents.trigger(ae, { isSyncForced: s });
767
767
  });
768
768
  i(this, "_triggerUseLicense", (e) => {
@@ -1248,7 +1248,7 @@ class as {
1248
1248
  }
1249
1249
  }
1250
1250
  export {
1251
- Ft as B,
1251
+ Bt as B,
1252
1252
  I as E,
1253
1253
  Mt as N,
1254
1254
  He as R,
@@ -1260,7 +1260,7 @@ export {
1260
1260
  rs as d,
1261
1261
  ss as e,
1262
1262
  q as f,
1263
- F as g,
1263
+ B as g,
1264
1264
  os as h,
1265
1265
  gn as i,
1266
1266
  lt as j,
@@ -0,0 +1 @@
1
+ "use strict";var pt=Object.defineProperty;var Pt=(r,e,t)=>e in r?pt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var i=(r,e,t)=>Pt(r,typeof e!="symbol"?e+"":e,t);const N=require("@krivega/cancelable-promise"),ve=require("events-constructor"),be=require("repeated-calls"),V=require("debug"),ft="Connection Error",qe="Request Timeout",Ot="SIP Failure Code",Dt="Internal Error",Mt="Busy",Y="Rejected",vt="Redirected",bt="Unavailable",ke="Not Found",yt="Address Incomplete",wt="Incompatible SDP",Ut="Missing SDP",Lt="Authentication Error",Fe="Terminated",Ht="WebRTC Error",Be="Canceled",Wt="No Answer",qt="Expires",kt="No ACK",Ft="Dialog Error",Bt="User Denied Media Access",Ve="Bad Media Description",Vt="RTP Timeout",Yt=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:yt,AUTHENTICATION_ERROR:Lt,BAD_MEDIA_DESCRIPTION:Ve,BUSY:Mt,BYE:Fe,CANCELED:Be,CONNECTION_ERROR:ft,DIALOG_ERROR:Ft,EXPIRES:qt,INCOMPATIBLE_SDP:wt,INTERNAL_ERROR:Dt,MISSING_SDP:Ut,NOT_FOUND:ke,NO_ACK:kt,NO_ANSWER:Wt,REDIRECTED:vt,REJECTED:Y,REQUEST_TIMEOUT:qe,RTP_TIMEOUT:Vt,SIP_FAILURE_CODE:Ot,UNAVAILABLE:bt,USER_DENIED_MEDIA_ACCESS:Bt,WEBRTC_ERROR:Ht},Symbol.toStringTag,{value:"Module"})),x="incomingCall",G="declinedIncomingCall",$="failedIncomingCall",X="terminatedIncomingCall",k="connecting",m="connected",S="disconnected",v="newRTCSession",p="registered",J="unregistered",P="registrationFailed",Ye="newMessage",z="sipEvent",Q="availableSecondRemoteStream",j="notAvailableSecondRemoteStream",K="mustStopPresentation",b="shareState",Z="enterRoom",ee="useLicense",te="peerconnection:confirmed",ne="peerconnection:ontrack",y="channels",se="channels:notify",ie="ended:fromserver",re="main-cam-control",oe="admin-stop-main-cam",ae="admin-start-main-cam",ce="admin-stop-mic",_e="admin-start-mic",w="admin-force-sync-media-state",Ee="participant:added-to-list-moderators",le="participant:removed-from-list-moderators",he="participant:move-request-to-stream",de="participant:move-request-to-spectators",Te="participation:accepting-word-request",ue="participation:cancelling-word-request",Se="webcast:started",Ce="webcast:stopped",Ne="account:changed",ge="account:deleted",Ae="conference:participant-token-issued",f="ended",xe="sending",Ge="reinvite",$e="replaces",Xe="refer",Je="progress",ze="accepted",U="confirmed",L="peerconnection",A="failed",Qe="muted",je="unmuted",Re="newDTMF",Ie="newInfo",Ke="hold",Ze="unhold",et="update",tt="sdp",nt="icecandidate",st="getusermediafailed",it="peerconnection:createofferfailed",rt="peerconnection:createanswerfailed",ot="peerconnection:setlocaldescriptionfailed",at="peerconnection:setremotedescriptionfailed",ct="presentation:start",_t="presentation:started",Et="presentation:end",me="presentation:ended",H="presentation:failed",lt="SPECTATOR",ht=1e6,xt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:ze,ACCOUNT_CHANGED:Ne,ACCOUNT_DELETED:ge,ADMIN_FORCE_SYNC_MEDIA_STATE:w,ADMIN_START_MAIN_CAM:ae,ADMIN_START_MIC:_e,ADMIN_STOP_MAIN_CAM:oe,ADMIN_STOP_MIC:ce,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:Q,CHANNELS:y,CHANNELS_NOTIFY:se,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Ae,CONFIRMED:U,CONNECTED:m,CONNECTING:k,DECLINED_INCOMING_CALL:G,DISCONNECTED:S,ENDED:f,ENDED_FROM_SERVER:ie,ENTER_ROOM:Z,FAILED:A,FAILED_INCOMING_CALL:$,GET_USER_MEDIA_FAILED:st,HOLD:Ke,ICE_CANDIDATE:nt,INCOMING_CALL:x,MAIN_CAM_CONTROL:re,MUST_STOP_PRESENTATION_EVENT:K,MUTED:Qe,NEW_DTMF:Re,NEW_INFO:Ie,NEW_MESSAGE:Ye,NEW_RTC_SESSION:v,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:j,ONE_MEGABIT_IN_BITS:ht,PARTICIPANT_ADDED_TO_LIST_MODERATORS:Ee,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:de,PARTICIPANT_MOVE_REQUEST_TO_STREAM:he,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:le,PARTICIPATION_ACCEPTING_WORD_REQUEST:Te,PARTICIPATION_CANCELLING_WORD_REQUEST:ue,PEER_CONNECTION:L,PEER_CONNECTION_CONFIRMED:te,PEER_CONNECTION_CREATE_ANSWER_FAILED:rt,PEER_CONNECTION_CREATE_OFFER_FAILED:it,PEER_CONNECTION_ONTRACK:ne,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:ot,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:at,PRESENTATION_END:Et,PRESENTATION_ENDED:me,PRESENTATION_FAILED:H,PRESENTATION_START:ct,PRESENTATION_STARTED:_t,PROGRESS:Je,REFER:Xe,REGISTERED:p,REGISTRATION_FAILED:P,REINVITE:Ge,REPLACES:$e,SDP:tt,SENDING:xe,SHARE_STATE:b,SIP_EVENT:z,SPECTATOR:lt,TERMINATED_INCOMING_CALL:X,UNHOLD:Ze,UNMUTED:je,UNREGISTERED:J,UPDATE:et,USE_LICENSE:ee,WEBCAST_STARTED:Se,WEBCAST_STOPPED:Ce},Symbol.toStringTag,{value:"Module"})),dt=[x,G,X,$,Te,ue,he,se,Ae,Ne,ge,Se,Ce,Ee,le],pe=[k,m,S,v,p,J,P,Ye,z],Tt=[Q,j,K,b,Z,ee,te,ne,y,ie,re,ae,oe,ce,_e,w,de],Pe=[f,k,xe,Ge,$e,Xe,Je,ze,U,L,A,Qe,je,Re,Ie,Ke,Ze,et,tt,nt,st,it,rt,ot,at,ct,_t,Et,me,H],fe=[...pe,...dt],Oe=[...Pe,...Tt],Gt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:Oe,SESSION_JSSIP_EVENT_NAMES:Pe,SESSION_SYNTHETICS_EVENT_NAMES:Tt,UA_EVENT_NAMES:fe,UA_JSSIP_EVENT_NAMES:pe,UA_SYNTHETICS_EVENT_NAMES:dt},Symbol.toStringTag,{value:"Module"})),$t=r=>{const e=[];return r&&e.push(`X-Vinteo-Remote: ${r}`),e},Xt="content-type",Jt="x-webrtc-enter-room",O="application/vinteo.webrtc.sharedesktop",zt="application/vinteo.webrtc.roomname",Qt="application/vinteo.webrtc.channels",jt="application/vinteo.webrtc.mediastate",Kt="application/vinteo.webrtc.refusal",ye="application/vinteo.webrtc.maincam",Zt="application/vinteo.webrtc.mic",en="application/vinteo.webrtc.uselic",tn="X-WEBRTC-USE-LICENSE",nn="X-WEBRTC-PARTICIPANT-NAME",we="X-WEBRTC-INPUT-CHANNELS",Ue="X-WEBRTC-OUTPUT-CHANNELS",sn="X-WEBRTC-MAINCAM",rn="X-WEBRTC-MIC",Le="X-WEBRTC-SYNC",on="X-WEBRTC-MAINCAM-RESOLUTION",an="X-WEBRTC-MEDIA-STATE",cn="X-Vinteo-Media-Type",_n="X-Vinteo-MainCam-State",En="X-Vinteo-Mic-State",ln="application/vinteo.webrtc.partstate",hn="X-WEBRTC-PARTSTATE",dn="application/vinteo.webrtc.notify",Tn="X-VINTEO-NOTIFY",I="x-webrtc-share-state",un=`${I}: LETMESTARTPRESENTATION`,Sn=`${I}: STOPPRESENTATION`,ut="YOUCANRECEIVECONTENT",St="CONTENTEND",Ct="YOUMUSTSTOPSENDCONTENT",Cn=`${I}: ${Ct}`,Nn=`${I}: ${ut}`,gn=`${I}: ${St}`,An="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Rn=`${An}: LETMESTARTMAINCAM`,De="sip-connector",M=V(De),In=()=>{V.enable(De)},mn=()=>{V.enable(`-${De}`)},pn=(r,e)=>{r.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},D=(r,{videoMode:e,audioMode:t,contentHint:n}={})=>{if(!r||e==="recvonly"&&t==="recvonly")return;const s=t==="recvonly"?[]:r.getAudioTracks(),o=e==="recvonly"?[]:r.getVideoTracks(),a=[...s,...o],c=new MediaStream(a);return c.getTracks=()=>[...c.getAudioTracks(),...c.getVideoTracks()],n&&n!=="none"&&pn(c,n),c};var R=(r=>(r.PAUSE_MAIN_CAM="PAUSEMAINCAM",r.RESUME_MAIN_CAM="RESUMEMAINCAM",r.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",r.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",r.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",r))(R||{}),W=(r=>(r.ADMIN_STOP_MIC="ADMINSTOPMIC",r.ADMIN_START_MIC="ADMINSTARTMIC",r))(W||{}),q=(r=>(r.ADMIN_SYNC_FORCED="1",r.ADMIN_SYNC_NOT_FORCED="0",r))(q||{}),Nt=(r=>(r.AUDIO="AUDIO",r.VIDEO="VIDEO",r.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",r))(Nt||{});function Pn(r){return e=>`sip:${e}@${r}`}const fn=(r,e)=>()=>Math.floor(Math.random()*(e-r))+r,He=r=>r.trim().replaceAll(" ","_"),On=fn(1e5,99999999),Dn=r=>r.some(t=>{const{kind:n}=t;return n==="video"}),Mn="Error decline with 603",vn=1006,bn=r=>typeof r=="object"&&r!==null&&"code"in r&&r.code===vn,yn=r=>r.message===Mn,wn=(r,e)=>r.find(t=>t.track&&e.getTracks().includes(t.track)),gt=1,At=r=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==r,Un=At(gt),Ln=(r,e)=>{const t=r===void 0?void 0:Math.max(r,gt);if(t!==void 0&&Un(t,e))return t},Hn=At(),Wn=(r,e)=>{if(Hn(r,e))return r},Rt=async(r,e,t)=>{const n=r.getParameters();(n.encodings===void 0||n.encodings.length===0)&&(n.encodings=[{}]);const[s]=n.encodings,o=s.scaleResolutionDownBy,a=Ln(e.scaleResolutionDownBy,o);let c=!1;a!==void 0&&(n.encodings[0].scaleResolutionDownBy=a,c=!0);const _=s.maxBitrate,E=Wn(e.maxBitrate,_);return E!==void 0&&(n.encodings[0].maxBitrate=E,c=!0),c?(t&&t(n),r.setParameters(n).then(()=>({parameters:n,isChanged:c}))):{parameters:n,isChanged:c}},qn=async(r,e,t)=>{const n=wn(r,e);if(n)return Rt(n,{maxBitrate:t})},kn=486,Fn=487,B="local",We="remote",Bn=3,Vn=1,Yn=(r=new Error)=>{const{originator:e,cause:t}=r;return N.isCanceledError(r)?!0:typeof t=="string"?t===qe||t===Y||e===B&&(t===Be||t===Fe):!1},g="SipConnector",xn="channels",Gn="WebcastStarted",$n="WebcastStopped",Xn="accountChanged",Jn="accountDeleted",zn="addedToListModerators",Qn="removedFromListModerators",jn="ParticipationRequestAccepted",Kn="ParticipationRequestRejected",Zn="ParticipantMovedToWebcast",es="ConferenceParticipantTokenIssued";class ts{constructor({JsSIP:e}){i(this,"_isRegisterConfig",!1);i(this,"_connectionConfiguration",{});i(this,"_remoteStreams",{});i(this,"JsSIP");i(this,"_sessionEvents");i(this,"_uaEvents");i(this,"_cancelableConnect");i(this,"_cancelableConnectWithRepeatedCalls");i(this,"_cancelableSendPresentationWithRepeatedCalls");i(this,"_cancelableInitUa");i(this,"_cancelableDisconnect");i(this,"_cancelableSet");i(this,"_cancelableCall");i(this,"_cancelableAnswer");i(this,"_cancelableSendDTMF");i(this,"getSipServerUrl",e=>e);i(this,"promisePendingStartPresentation");i(this,"promisePendingStopPresentation");i(this,"ua");i(this,"session");i(this,"incomingSession");i(this,"_streamPresentationCurrent");i(this,"socket");i(this,"connect",async(e,t)=>(this._cancelRequests(),this._connectWithDuplicatedCalls(e,t)));i(this,"initUa",async e=>this._cancelableInitUa.request(e));i(this,"set",async e=>this._cancelableSet.request(e));i(this,"call",async e=>this._cancelableCall.request(e));i(this,"disconnect",async()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()));i(this,"answerToIncomingCall",async e=>this._cancelableAnswer.request(e));i(this,"sendDTMF",async e=>this._cancelableSendDTMF.request(e));i(this,"hangUp",async()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()));i(this,"tryRegister",async()=>{if(!this.isRegisterConfig)throw new Error("Config is not registered");this._uaEvents.trigger(k,void 0);try{await this.unregister()}catch(e){M("tryRegister",e)}return this.register()});i(this,"declineToIncomingCall",async({statusCode:e=Fn}={})=>new Promise((t,n)=>{if(!this.isAvailableIncomingCall){n(new Error("no incomingSession"));return}const s=this.incomingSession,o=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(G,o),t(s.terminate({status_code:e}))}));i(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:kn}));i(this,"removeIncomingSession",()=>{delete this.incomingSession});i(this,"_connectWithDuplicatedCalls",async(e,{callLimit:t=Bn}={})=>{const n=async()=>this._cancelableConnect.request(e),s=o=>{var E;const c=!!((E=this.ua)!=null&&E.isConnected())&&this.hasEqualConnectionConfiguration(e),_=!!o&&!bn(o);return c||_};return this._cancelableConnectWithRepeatedCalls=be.repeatedCallsAsync({targetFunction:n,isComplete:s,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1,onAfterCancel:()=>{this._cancelableConnect.cancelRequest()}}),this._cancelableConnectWithRepeatedCalls.then(o=>{if(o instanceof this.JsSIP.UA)return o;throw o})});i(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===We){this.incomingSession=t;const n=this.remoteCallerData;t.on(A,s=>{this.removeIncomingSession(),s.originator===B?this._uaEvents.trigger(X,n):this._uaEvents.trigger($,n)}),this._uaEvents.trigger(x,n)}});i(this,"_connect",async e=>this.initUa(e).then(async()=>this._start()));i(this,"_initUa",async({user:e,password:t,sipServerUrl:n,sipWebSocketServerURL:s,remoteAddress:o,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:_,connectionRecoveryMaxInterval:E,userAgent:l,displayName:h="",register:d=!1,extraHeaders:T=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!s)throw new Error("sipWebSocketServerURL is required");if(d&&!e)throw new Error("user is required for authorized connection");if(d&&!t)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:n,displayName:h,register:d,user:e,password:t};const{configuration:C,helpers:u}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:s,password:t,displayName:h,register:d,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:_,connectionRecoveryMaxInterval:E,userAgent:l});return this.getSipServerUrl=u.getSipServerUrl,this.socket=u.socket,this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!d,this.ua=this._createUa({...C,remoteAddress:o,extraHeaders:T}),this._uaEvents.eachTriggers((F,It)=>{const Me=pe.find(mt=>mt===It);Me&&this.ua&&this.ua.on(Me,F)}),this.ua});i(this,"_createUa",({remoteAddress:e,extraHeaders:t=[],...n})=>{const s=new this.JsSIP.UA(n),a=[...e?$t(e):[],...t];return a.length>0&&s.registrator().setExtraHeaders(a),s});i(this,"_start",async()=>new Promise((e,t)=>{const{ua:n}=this;if(!n){t(new Error("this.ua is not initialized"));return}const s=()=>{c(),e(n)},o=_=>{c(),t(_)},a=()=>{this.isRegisterConfig?(this.on(p,s),this.on(P,o)):this.on(m,s),this.on(S,o)},c=()=>{this.off(p,s),this.off(P,o),this.off(m,s),this.off(S,o)};a(),this.on(v,this.handleNewRTCSession),n.start()}));i(this,"_set",async({displayName:e,password:t})=>new Promise((n,s)=>{const{ua:o}=this;if(!o){s(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",He(e)),this._connectionConfiguration.displayName=e),t!==void 0&&t!==this._connectionConfiguration.password&&(c=o.set("password",t),this._connectionConfiguration.password=t);const _=a||c;c&&this.isRegisterConfig?this.register().then(()=>{n(_)}).catch(E=>{s(E)}):_?n(_):s(new Error("nothing changed"))}));i(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());i(this,"_disconnect",async()=>{this.off(v,this.handleNewRTCSession);const e=new Promise(t=>{this.once(S,()=>{delete this.ua,t()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(S,void 0)):this._uaEvents.trigger(S,void 0),e});i(this,"_call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:s,iceServers:o,videoMode:a,audioMode:c,degradationPreference:_,contentHint:E,offerToReceiveAudio:l=!0,offerToReceiveVideo:h=!0})=>new Promise((d,T)=>{const{ua:C}=this;if(!C){T(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:s}).then(d).catch(u=>{T(u)}),this.session=C.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:D(t,{videoMode:a,audioMode:c,contentHint:E}),eventHandlers:this._sessionEvents.triggers,videoMode:a,audioMode:c,degradationPreference:_,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:l,offerToReceiveVideo:h}})}));i(this,"_answer",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:s,videoMode:o,audioMode:a,degradationPreference:c,contentHint:_})=>new Promise((E,l)=>{if(!this.isAvailableIncomingCall){l(new Error("no incomingSession"));return}this.session=this.incomingSession,this.removeIncomingSession();const{session:h}=this;if(!h){l(new Error("No session established"));return}this._sessionEvents.eachTriggers((T,C)=>{const u=Pe.find(F=>F===C);u&&h.on(u,T)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=h.remote_identity.uri.user,this._handleCall({ontrack:t}).then(E).catch(T=>{l(T)});const d=D(e,{videoMode:o,audioMode:a,contentHint:_});h.answer({extraHeaders:n,videoMode:o,audioMode:a,degradationPreference:c,mediaStream:d,pcConfig:{iceServers:s}})}));i(this,"_handleCall",async({ontrack:e})=>new Promise((t,n)=>{const s=()=>{this.onSession(L,l),this.onSession(U,h)},o=()=>{this.offSession(L,l),this.offSession(U,h)},a=()=>{this.onSession(A,_),this.onSession(f,_)},c=()=>{this.offSession(A,_),this.offSession(f,_)},_=d=>{o(),c(),n(d)};let E;const l=({peerconnection:d})=>{E=d,E.ontrack=T=>{this._sessionEvents.trigger(ne,E),e&&e(T)}},h=()=>{E&&this._sessionEvents.trigger(te,E),o(),c(),t(E)};s(),a()}));i(this,"_restoreSession",()=>{this._cancelRequestsAndResetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}});i(this,"_sendDTMF",async e=>new Promise((t,n)=>{const{session:s}=this;if(!s){n(new Error("No session established"));return}this.onceSession(Re,({originator:o})=>{o===B&&t()}),s.sendDTMF(e,{duration:120,interToneGap:600})}));i(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.session){const{session:e}=this;if(this._streamPresentationCurrent)try{await this.stopPresentation()}catch(t){M("error stop presentation: ",t)}if(this._restoreSession(),!e.isEnded())return e.terminateAsync()}});i(this,"_handleShareState",e=>{switch(e){case ut:{this._sessionEvents.trigger(Q,void 0);break}case St:{this._sessionEvents.trigger(j,void 0);break}case Ct:{this._sessionEvents.trigger(K,void 0);break}}});i(this,"_maybeTriggerChannels",e=>{const t=e.getHeader(we),n=e.getHeader(Ue);if(t&&n){const s={inputChannels:t,outputChannels:n};this._sessionEvents.trigger(y,s)}});i(this,"_handleNotify",e=>{switch(e.cmd){case xn:{const t=e;this._triggerChannelsNotify(t);break}case Gn:{const t=e;this._triggerWebcastStartedNotify(t);break}case $n:{const t=e;this._triggerWebcastStoppedNotify(t);break}case zn:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case Qn:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case jn:{const t=e;this._triggerParticipationAcceptingWordRequest(t);break}case Kn:{const t=e;this._triggerParticipationCancellingWordRequest(t);break}case Zn:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case Xn:{this._triggerAccountChangedNotify();break}case Jn:{this._triggerAccountDeletedNotify();break}case es:{const t=e;this._triggerConferenceParticipantTokenIssued(t);break}default:M("unknown cmd",e.cmd)}});i(this,"_triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(le,t)});i(this,"_triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(Ee,t)});i(this,"_triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Se,n)});i(this,"_triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Ce,n)});i(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(Ne,void 0)});i(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(ge,void 0)});i(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const s={conference:e,participant:t,jwt:n};this._uaEvents.trigger(Ae,s)});i(this,"_triggerChannelsNotify",e=>{const t=e.input,n=e.output,s={inputChannels:t,outputChannels:n};this._uaEvents.trigger(se,s)});i(this,"_triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Te,t)});i(this,"_triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ue,t)});i(this,"_triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(he,t)});i(this,"_triggerEnterRoom",e=>{const t=e.getHeader(Jt),n=e.getHeader(nn);this._sessionEvents.trigger(Z,{room:t,participantName:n})});i(this,"_triggerShareState",e=>{const t=e.getHeader(I);this._sessionEvents.trigger(b,t)});i(this,"_maybeTriggerParticipantMoveRequestToSpectators",e=>{e.getHeader(hn)===lt&&this._sessionEvents.trigger(de,void 0)});i(this,"_triggerMainCamControl",e=>{const t=e.getHeader(sn),n=e.getHeader(Le),s=n===q.ADMIN_SYNC_FORCED;if(t===R.ADMIN_START_MAIN_CAM){this._sessionEvents.trigger(ae,{isSyncForced:s});return}if(t===R.ADMIN_STOP_MAIN_CAM){this._sessionEvents.trigger(oe,{isSyncForced:s});return}(t===R.RESUME_MAIN_CAM||t===R.PAUSE_MAIN_CAM)&&n&&this._sessionEvents.trigger(w,{isSyncForced:s});const o=e.getHeader(on);this._sessionEvents.trigger(re,{mainCam:t,resolutionMainCam:o})});i(this,"_triggerMicControl",e=>{const t=e.getHeader(rn),s=e.getHeader(Le)===q.ADMIN_SYNC_FORCED;t===W.ADMIN_START_MIC?this._sessionEvents.trigger(_e,{isSyncForced:s}):t===W.ADMIN_STOP_MIC&&this._sessionEvents.trigger(ce,{isSyncForced:s})});i(this,"_triggerUseLicense",e=>{const t=e.getHeader(tn);this._sessionEvents.trigger(ee,t)});i(this,"_handleNewInfo",e=>{const{originator:t}=e;if(t!=="remote")return;const{request:n}=e,s=n.getHeader(Xt);if(s)switch(s){case zt:{this._triggerEnterRoom(n),this._maybeTriggerChannels(n);break}case dn:{this._maybeHandleNotify(n);break}case O:{this._triggerShareState(n);break}case ye:{this._triggerMainCamControl(n);break}case Zt:{this._triggerMicControl(n);break}case en:{this._triggerUseLicense(n);break}case ln:{this._maybeTriggerParticipantMoveRequestToSpectators(n);break}}});i(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});i(this,"_maybeHandleNotify",e=>{const t=e.getHeader(Tn);if(t){const n=JSON.parse(t);this._handleNotify(n)}});i(this,"_handleEnded",e=>{const{originator:t}=e;t===We&&this._sessionEvents.trigger(ie,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new ve(Oe),this._uaEvents=new ve(fe),this._cancelableConnect=new N.CancelableRequest(this._connect,{moduleName:g,afterCancelRequest:()=>{this._cancelableInitUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableInitUa=new N.CancelableRequest(this._initUa,{moduleName:g}),this._cancelableDisconnect=new N.CancelableRequest(this._disconnect,{moduleName:g}),this._cancelableSet=new N.CancelableRequest(this._set,{moduleName:g}),this._cancelableCall=new N.CancelableRequest(this._call,{moduleName:g}),this._cancelableAnswer=new N.CancelableRequest(this._answer,{moduleName:g}),this._cancelableSendDTMF=new N.CancelableRequest(this._sendDTMF,{moduleName:g}),this.onSession(b,this._handleShareState),this.onSession(Ie,this._handleNewInfo),this.on(z,this._handleSipEvent),this.onSession(A,this._handleEnded),this.onSession(f,this._handleEnded)}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(p,e),this.ua.on(P,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(J,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((s,o)=>{try{this.ua.sendOptions(e,t,{extraHeaders:n,eventHandlers:{succeeded:()=>{s()},failed:o}})}catch(a){o(a)}})}async ping(e,t){var s;if(!((s=this.ua)!=null&&s.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:s,remoteAddress:o,extraHeaders:a}){return new Promise((c,_)=>{const{configuration:E}=this.createUaConfiguration({sipWebSocketServerURL:s,displayName:t,userAgent:e,sipServerUrl:n}),l=this._createUa({...E,remoteAddress:o,extraHeaders:a}),h=()=>{const T=new Error("Telephony is not available");_(T)};l.once(S,h);const d=()=>{l.removeAllListeners(),l.once(S,c),l.stop()};l.once(m,d),l.start()})}async replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");const{contentHint:n}=t||{},s=D(e,{contentHint:n});return this.session.replaceMediaStream(s,t)}async askPermissionToEnableCam(e={}){if(!this.session)throw new Error("No session established");const t=[Rn];return this.session.sendInfo(ye,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if(yn(n))throw n})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async _sendPresentationWithDuplicatedCalls({session:e,stream:t,presentationOptions:n,options:s={callLimit:Vn}}){const o=async()=>this._sendPresentation(e,t,n),a=()=>!!this._streamPresentationCurrent;return this._cancelableSendPresentationWithRepeatedCalls=be.repeatedCallsAsync({targetFunction:o,isComplete:a,isRejectAsValid:!0,...s}),this._cancelableSendPresentationWithRepeatedCalls.then(c=>c)}hasEqualConnectionConfiguration(e){var s;const{configuration:t}=this.createUaConfiguration(e),n=(s=this.ua)==null?void 0:s.configuration;return(n==null?void 0:n.password)===t.password&&(n==null?void 0:n.register)===t.register&&(n==null?void 0:n.uri.toString())===t.uri&&(n==null?void 0:n.display_name)===t.display_name&&(n==null?void 0:n.user_agent)===t.user_agent&&(n==null?void 0:n.sockets)===t.sockets&&(n==null?void 0:n.session_timers)===t.session_timers&&(n==null?void 0:n.register_expires)===t.register_expires&&(n==null?void 0:n.connection_recovery_min_interval)===t.connection_recovery_min_interval&&(n==null?void 0:n.connection_recovery_max_interval)===t.connection_recovery_max_interval}createUaConfiguration({user:e,password:t,sipWebSocketServerURL:n,displayName:s="",sipServerUrl:o,register:a=!1,sessionTimers:c=!1,registerExpires:_=60*5,connectionRecoveryMinInterval:E=2,connectionRecoveryMaxInterval:l=6,userAgent:h}){if(a&&!t)throw new Error("password is required for authorized connection");const d=a&&e?e.trim():`${On()}`,T=Pn(o),C=T(d),u=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:C,display_name:He(s),user_agent:h,sdp_semantics:"unified-plan",sockets:[u],session_timers:c,register_expires:_,connection_recovery_min_interval:E,connection_recovery_max_interval:l},helpers:{socket:u,getSipServerUrl:T}}}async _sendPresentation(e,t,{maxBitrate:n=ht,degradationPreference:s="maintain-resolution",isNeedReinvite:o=!0,isP2P:a=!1,contentHint:c="detail"}){const _=D(t,{contentHint:c});this._streamPresentationCurrent=_;const E=a?[Nn]:[un],l=e.sendInfo(O,void 0,{extraHeaders:E}).then(async()=>e.startPresentation(_,o,s)).then(async()=>{const{connection:h}=this;if(!h||n===void 0)return;const d=h.getSenders();await qn(d,t,n)}).then(()=>t).catch(h=>{throw this._removeStreamPresentationCurrent(),this._sessionEvents.trigger(H,h),h});return this.promisePendingStartPresentation=l,l.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:s,degradationPreference:o,contentHint:a}={},c){const _=this.establishedSession;if(!_)throw new Error("No session established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return n&&await this.sendMustStopPresentation(_),this._sendPresentationWithDuplicatedCalls({session:_,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:s,degradationPreference:o,contentHint:a},options:c})}async sendMustStopPresentation(e){await e.sendInfo(O,void 0,{extraHeaders:[Cn]})}async stopPresentation({isP2P:e=!1}={}){this._cancelSendPresentationWithRepeatedCalls();const t=this._streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve();const s=e?[gn]:[Sn],o=this.establishedSession;return o&&t&&(n=n.then(async()=>o.sendInfo(O,void 0,{extraHeaders:s})).then(async()=>o.stopPresentation(t)).catch(a=>{throw this._sessionEvents.trigger(H,a),a})),!o&&t&&this._sessionEvents.trigger(me,t),this.promisePendingStopPresentation=n,n.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,degradationPreference:s,contentHint:o}={}){const a=this.establishedSession;if(!a)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(a,e,{isP2P:t,maxBitrate:n,degradationPreference:s,contentHint:o,isNeedReinvite:!1})}_removeStreamPresentationCurrent(){delete this._streamPresentationCurrent}_resetPresentation(){this._removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}_cancelRequestsAndResetPresentation(){this._cancelSendPresentationWithRepeatedCalls(),this._resetPresentation()}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)}get connection(){var t;return(t=this.session)==null?void 0:t.connection}get remoteCallerData(){var e,t,n,s,o,a;return{displayName:(t=(e=this.incomingSession)==null?void 0:e.remote_identity)==null?void 0:t.display_name,host:(s=(n=this.incomingSession)==null?void 0:n.remote_identity)==null?void 0:s.uri.host,incomingNumber:(a=(o=this.incomingSession)==null?void 0:o.remote_identity)==null?void 0:a.uri.user,session:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableInitUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){var e;return(e=this.session)!=null&&e.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}_generateStream(e,t){const{id:n}=e,s=this._remoteStreams[n]||new MediaStream;return t&&s.addTrack(t),s.addTrack(e),this._remoteStreams[n]=s,s}_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,s)=>{if(n.kind==="audio")return;const o=n,a=e[s-1];let c;a&&a.kind==="audio"&&(c=a);const _=this._generateStream(o,c);t.push(_)}),t}_generateAudioStreams(e){return e.map(n=>this._generateAudioStream(n))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectWithRepeatedCalls()}_cancelConnectWithRepeatedCalls(){var e;(e=this._cancelableConnectWithRepeatedCalls)==null||e.cancel()}_cancelSendPresentationWithRepeatedCalls(){var e;(e=this._cancelableSendPresentationWithRepeatedCalls)==null||e.cancel()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}async waitChannels(){return this.waitSession(y)}async waitSyncMediaState(){return this.waitSession(w)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const n=`${we}: ${e}`,s=`${Ue}: ${t}`,o=[n,s];return this.session.sendInfo(Qt,void 0,{extraHeaders:o})}async sendMediaState({cam:e,mic:t},n={}){if(!this.session)throw new Error("No session established");const s=`${an}: currentstate`,o=`${_n}: ${Number(e)}`,a=`${En}: ${Number(t)}`,c=[s,o,a];return this.session.sendInfo(jt,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async _sendRefusalToTurnOn(e,t={}){if(!this.session)throw new Error("No session established");const c=[`${cn}: ${e==="mic"?0:1}`];return this.session.sendInfo(Kt,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}}exports.BAD_MEDIA_DESCRIPTION=Ve;exports.EEventsMainCAM=R;exports.EEventsMic=W;exports.EEventsSyncMediaState=q;exports.EUseLicense=Nt;exports.NOT_FOUND=ke;exports.REJECTED=Y;exports.SESSION_EVENT_NAMES=Oe;exports.SipConnector=ts;exports.UA_EVENT_NAMES=fe;exports.causes=Yt;exports.constants=xt;exports.disableDebug=mn;exports.enableDebug=In;exports.eventNames=Gt;exports.hasCanceledCallError=Yn;exports.logger=M;exports.setEncodingsToSender=Rt;
@@ -1,5 +1,6 @@
1
1
  import { RTCPeerConnectionDeprecated } from '@krivega/jssip';
2
2
  import { MediaStreamTrackMock } from 'webrtc-mock';
3
+ import { default as RTCRtpSenderMock } from './RTCRtpSenderMock';
3
4
  declare class RTCPeerConnectionMock implements RTCPeerConnectionDeprecated {
4
5
  _senders: RTCRtpSender[];
5
6
  _receivers: any[];
@@ -53,6 +54,6 @@ declare class RTCPeerConnectionMock implements RTCPeerConnectionDeprecated {
53
54
  dispatchEvent(_event: Event): boolean;
54
55
  getReceivers: () => any[];
55
56
  getSenders: () => RTCRtpSender[];
56
- addTrack: (track: MediaStreamTrack) => RTCRtpSender;
57
+ addTrack: (track: MediaStreamTrack) => RTCRtpSenderMock;
57
58
  }
58
59
  export default RTCPeerConnectionMock;
@@ -4,8 +4,11 @@ declare class RTCRtpSenderMock implements RTCRtpSender {
4
4
  transport: RTCDtlsTransport | null;
5
5
  transform: RTCRtpTransform | null;
6
6
  private _parameters;
7
+ constructor({ track }?: {
8
+ track?: MediaStreamTrack;
9
+ });
7
10
  getStats(): Promise<RTCStatsReport>;
8
- replaceTrack(): Promise<void>;
11
+ replaceTrack(track: MediaStreamTrack | null): Promise<void>;
9
12
  setParameters(parameters: RTCRtpSendParameters): Promise<void>;
10
13
  getParameters(): RTCRtpSendParameters;
11
14
  setStreams(): void;
package/dist/doMock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var b=Object.defineProperty;var k=(o,t,e)=>t in o?b(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var r=(o,t,e)=>k(o,typeof t!="symbol"?t+"":t,e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const g=require("./SipConnector-lgvJyyG7.cjs"),D=require("@krivega/jssip/lib/NameAddrHeader"),L=require("@krivega/jssip/lib/URI"),F=require("node:events"),V=require("@krivega/jssip/lib/SIPMessage"),C=require("webrtc-mock"),I=require("events-constructor"),T=require("@krivega/jssip");class y extends V.IncomingRequest{constructor(e){super();r(this,"headers");this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)||""}}class z{constructor({originator:t="local",eventHandlers:e}){r(this,"originator");r(this,"_connection");r(this,"_events");r(this,"_remote_identity");r(this,"_mutedOptions",{audio:!1,video:!1});this.originator=t,this._events=new I(g.SESSION_EVENT_NAMES),this.initEvents(e)}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}set data(t){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}get connection(){return this._connection}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get remote_identity(){return this._remote_identity}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(t){throw new Error("Method not implemented.")}terminate(t){throw new Error("Method not implemented.")}async sendInfo(t,e,n){throw new Error("Method not implemented.")}hold(t,e){throw new Error("Method not implemented.")}unhold(t,e){throw new Error("Method not implemented.")}async renegotiate(t,e){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(t){throw new Error("Method not implemented.")}unmute(t){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(t,e){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(t,e){throw new Error("Method not implemented.")}addListener(t,e){throw new Error("Method not implemented.")}once(t,e){throw new Error("Method not implemented.")}removeListener(t,e){throw new Error("Method not implemented.")}off(t,e){throw new Error("Method not implemented.")}removeAllListeners(t){throw new Error("Method not implemented.")}setMaxListeners(t){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(t){throw new Error("Method not implemented.")}rawListeners(t){throw new Error("Method not implemented.")}emit(t,...e){throw new Error("Method not implemented.")}listenerCount(t){throw new Error("Method not implemented.")}prependListener(t,e){throw new Error("Method not implemented.")}prependOnceListener(t,e){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(t=[]){Object.entries(t).forEach(([e,n])=>this.on(e,n))}on(t,e){return this._events.on(t,e),this}trigger(t,e){this._events.trigger(t,e)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(t){return t}async updatePresentation(t){return t}async stopPresentation(t){return t}isEstablished(){return!0}}class U{constructor(t,e){r(this,"_senders",[]);r(this,"_receivers",[]);r(this,"canTrickleIceCandidates");r(this,"connectionState");r(this,"currentLocalDescription");r(this,"currentRemoteDescription");r(this,"iceConnectionState");r(this,"iceGatheringState");r(this,"idpErrorInfo");r(this,"idpLoginUrl");r(this,"localDescription");r(this,"onconnectionstatechange");r(this,"ondatachannel");r(this,"onicecandidate");r(this,"onicecandidateerror",null);r(this,"oniceconnectionstatechange");r(this,"onicegatheringstatechange");r(this,"onnegotiationneeded");r(this,"onsignalingstatechange");r(this,"ontrack");r(this,"peerIdentity");r(this,"pendingLocalDescription");r(this,"pendingRemoteDescription");r(this,"remoteDescription");r(this,"sctp",null);r(this,"signalingState");r(this,"getReceivers",()=>this._receivers);r(this,"getSenders",()=>this._senders);r(this,"addTrack",t=>{const e={track:t};return this._senders.push(e),e});this._receivers=e.map(n=>({track:n}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(t){throw new Error("Method not implemented.")}addTransceiver(t,e){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(t,e){throw new Error("Method not implemented.")}createDataChannel(t,e){throw new Error("Method not implemented.")}async createOffer(t,e,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(t){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(t){throw new Error("Method not implemented.")}setConfiguration(t){throw new Error("Method not implemented.")}async setLocalDescription(t){throw new Error("Method not implemented.")}async setRemoteDescription(t){throw new Error("Method not implemented.")}addEventListener(t,e,n){throw new Error("Method not implemented.")}removeEventListener(t,e,n){throw new Error("Method not implemented.")}dispatchEvent(t){throw new Error("Method not implemented.")}}function q(o){const t=o.match(/(purgatory)|[\d.]+/g);if(!t)throw new Error("wrong sip url");return t[0]}const w=400,N="777",x=o=>o.getVideoTracks().length>0,a=class a extends z{constructor({url:e="",mediaStream:n,eventHandlers:i,originator:d}){super({originator:d,eventHandlers:i});r(this,"url");r(this,"status_code");r(this,"_isEnded",!1);r(this,"answer",jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},w)}));this.url=e,this.initPeerconnection(n)}static setStartPresentationError(e,{count:n=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=n}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}async startPresentation(e){if(a.countStartsPresentation+=1,a.startPresentationError&&a.countStartsPresentation<a.countStartPresentationError)throw a.startPresentationError;return super.startPresentation(e)}initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const n=C.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(x(e)){const u=C.createVideoMediaStreamTrackMock();u.id="mainvideo1",i.push(u)}this._connection=new U(void 0,i),this._addStream(e),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},w)}connect(e){const n=q(e);setTimeout(()=>{this.url.includes(N)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:g.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},w)}terminate({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e}),this._isEnded=!1,this}async terminateAsync({status_code:e}={}){this.terminate({status_code:e})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}_addStream(e,n="getTracks"){e[n]().forEach(i=>this.connection.addTrack(i))}_forEachSenders(e){const n=this.connection.getSenders();for(const i of n)e(i);return n}_toggleMuteAudio(e){this._forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!e)})}_toggleMuteVideo(e){this._forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.enabled=!e)})}mute(e){e.audio&&(this._mutedOptions.audio=!0,this._toggleMuteAudio(this._mutedOptions.audio)),e.video&&(this._mutedOptions.video=!0,this._toggleMuteVideo(this._mutedOptions.video)),this._onmute(e)}unmute(e){e.audio&&(this._mutedOptions.audio=!1),e.video&&(this._mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this._mutedOptions}async replaceMediaStream(e){return e}_onmute({audio:e,video:n}){this.trigger("muted",{audio:e,video:n})}async sendInfo(){}isEnded(){return this._isEnded}newInfo(e){this.trigger("newInfo",e)}};r(a,"startPresentationError"),r(a,"countStartPresentationError",Number.POSITIVE_INFINITY),r(a,"countStartsPresentation",0);let l=a;class H{constructor(){r(this,"extraHeaders")}setExtraHeaders(t){this.extraHeaders=t}setExtraContactParams(){}}const c="PASSWORD_CORRECT",f="PASSWORD_CORRECT_2",P="NAME_INCORRECT",m=400,s=class s{constructor(t){r(this,"_events");r(this,"_startedTimeout");r(this,"_stopedTimeout");r(this,"session");r(this,"_isRegistered");r(this,"_isConnected");r(this,"configuration");r(this,"_registrator");r(this,"call",jest.fn((t,e)=>{const{mediaStream:n,eventHandlers:i}=e;return this.session=new l({url:t,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(t),this.session}));this._events=new I(g.UA_EVENT_NAMES);const[e,n]=t.uri.split(":"),[i,d]=n.split("@"),u={...t,uri:new T.URI(e,i,d)};this.configuration=u,this._registrator=new H}static setStartError(t,{count:e=Number.POSITIVE_INFINITY}={}){this.startError=t,this.countStartError=e}static resetStartError(){this.startError=void 0,this.countStartError=Number.POSITIVE_INFINITY,this.countStarts=0}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}isConnected(){return!!this._isConnected}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:new Error("stoped")})},m):this.trigger("disconnected",{error:new Error("stoped")})}on(t,e){return this._events.on(t,e),this}once(t,e){return this._events.once(t,e),this}off(t,e){return this._events.off(t,e),this}removeAllListeners(){return this._events.removeEventHandlers(),this}trigger(t,e){this._events.trigger(t,e)}terminateSessions(){this.session.terminate()}set(t,e){return this.configuration[t]=e,!0}register(){this._startedTimeout&&clearTimeout(this._startedTimeout);const{password:t,register:e,uri:n}=this.configuration;e&&n.user.includes(P)?(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Request Timeout"})},m)):!this._isRegistered&&e&&(t===c||t===f)?(this._isRegistered=!0,this._startedTimeout=setTimeout(()=>{this.trigger("registered")},m)):e&&t!==c&&t!==f&&(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Wrong credentials"})},m)),s.isAvailableTelephony?(this.trigger("connected"),this._isConnected=!0):this.stop()}unregister(){this._isRegistered=!1,this._isConnected=!1,this.trigger("unregistered")}isRegistered(){return!!this._isRegistered}isStarted(){return this.configuration&&(this.configuration.register&&!!this._isRegistered||!this.configuration.register&&!!this._isConnected)}registrator(){return this._registrator}newSipEvent(t){this.trigger("sipEvent",t)}};r(s,"isAvailableTelephony",!0),r(s,"startError"),r(s,"countStartError",Number.POSITIVE_INFINITY),r(s,"countStarts",0);let M=s;class Y{constructor(t){r(this,"url");this.url=t}}class j extends F.EventEmitter{constructor(e,n){super();r(this,"contentType");r(this,"body");this.contentType=e,this.body=n}}const S="remote",B=(o,t)=>{const e=new y(t),n={originator:S,request:e,info:new j("","")};o.newInfo(n)},K=(o,t)=>{const n={request:new y(t)};o.newSipEvent(n)},$=(o,{incomingNumber:t="1234",displayName:e,host:n})=>{const i=new l({originator:S}),d=new L("sip",t,n);i._remote_identity=new D(d,e),o.trigger("newRTCSession",{originator:S,session:i})},J=(o,t)=>{t?o.trigger("failed",t):o.trigger("failed",o)},A={triggerNewInfo:B,triggerNewSipEvent:K,triggerIncomingSession:$,triggerFailIncomingSession:J,WebSocketInterface:Y,UA:M,C:{INVITE:"INVITE"}},_="user",h="displayName",E="SIP_SERVER_URL",R="SIP_WEB_SOCKET_SERVER_URL",G=new A.WebSocketInterface(R),v={userAgent:"Chrome",sipServerUrl:E,sipWebSocketServerURL:R},X={...v},O={...v,user:_,password:c,register:!0},Q={...O,displayName:h},Z={...v,displayName:h,register:!1},p={session_timers:!1,sockets:[G],user_agent:"Chrome",sdp_semantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},ee={...p,password:c,uri:new T.URI("sip",_,E),display_name:"",register:!0},te={...p,password:c,uri:new T.URI("sip",_,E),display_name:h,register:!0},re={...p,display_name:h,register:!1},ne={...p,display_name:"",register:!1},W="10.10.10.10",oe=[`X-Vinteo-Remote: ${W}`],ie=()=>new g.SipConnector({JsSIP:A});exports.FAILED_CONFERENCE_NUMBER=N;exports.NAME_INCORRECT=P;exports.PASSWORD_CORRECT=c;exports.PASSWORD_CORRECT_2=f;exports.SIP_SERVER_URL=E;exports.SIP_WEB_SOCKET_SERVER_URL=R;exports.dataForConnectionWithAuthorization=O;exports.dataForConnectionWithAuthorizationWithDisplayName=Q;exports.dataForConnectionWithoutAuthorization=Z;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=X;exports.default=ie;exports.displayName=h;exports.extraHeadersRemoteAddress=oe;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=ee;exports.uaConfigurationWithAuthorizationWithDisplayName=te;exports.uaConfigurationWithoutAuthorization=re;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ne;exports.user=_;
1
+ "use strict";var k=Object.defineProperty;var b=(o,t,e)=>t in o?k(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var r=(o,t,e)=>b(o,typeof t!="symbol"?t+"":t,e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const g=require("./SipConnector-BhCqlPz2.cjs"),D=require("@krivega/jssip/lib/NameAddrHeader"),L=require("@krivega/jssip/lib/URI"),F=require("node:events"),V=require("@krivega/jssip/lib/SIPMessage"),C=require("webrtc-mock"),I=require("events-constructor"),T=require("@krivega/jssip");class y extends V.IncomingRequest{constructor(e){super();r(this,"headers");this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)||""}}class z{constructor({originator:t="local",eventHandlers:e}){r(this,"originator");r(this,"_connection");r(this,"_events");r(this,"_remote_identity");r(this,"_mutedOptions",{audio:!1,video:!1});this.originator=t,this._events=new I(g.SESSION_EVENT_NAMES),this.initEvents(e)}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}set data(t){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}get connection(){return this._connection}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get remote_identity(){return this._remote_identity}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(t){throw new Error("Method not implemented.")}terminate(t){throw new Error("Method not implemented.")}async sendInfo(t,e,n){throw new Error("Method not implemented.")}hold(t,e){throw new Error("Method not implemented.")}unhold(t,e){throw new Error("Method not implemented.")}async renegotiate(t,e){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(t){throw new Error("Method not implemented.")}unmute(t){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(t,e){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(t,e){throw new Error("Method not implemented.")}addListener(t,e){throw new Error("Method not implemented.")}once(t,e){throw new Error("Method not implemented.")}removeListener(t,e){throw new Error("Method not implemented.")}off(t,e){throw new Error("Method not implemented.")}removeAllListeners(t){throw new Error("Method not implemented.")}setMaxListeners(t){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(t){throw new Error("Method not implemented.")}rawListeners(t){throw new Error("Method not implemented.")}emit(t,...e){throw new Error("Method not implemented.")}listenerCount(t){throw new Error("Method not implemented.")}prependListener(t,e){throw new Error("Method not implemented.")}prependOnceListener(t,e){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(t=[]){Object.entries(t).forEach(([e,n])=>this.on(e,n))}on(t,e){return this._events.on(t,e),this}trigger(t,e){this._events.trigger(t,e)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(t){return t}async updatePresentation(t){return t}async stopPresentation(t){return t}isEstablished(){return!0}}class U{constructor({track:t}={}){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:{}});this.track=t??null}async getStats(){throw new Error("Method not implemented.")}async replaceTrack(t){this.track=t??null}async setParameters(t){const{transactionId:e}=this._parameters;this._parameters={...this._parameters,...t,transactionId:`${Number(e)+1}`}}getParameters(){return{...this._parameters}}setStreams(){throw new Error("Method not implemented.")}}class q{constructor(t,e){r(this,"_senders",[]);r(this,"_receivers",[]);r(this,"canTrickleIceCandidates");r(this,"connectionState");r(this,"currentLocalDescription");r(this,"currentRemoteDescription");r(this,"iceConnectionState");r(this,"iceGatheringState");r(this,"idpErrorInfo");r(this,"idpLoginUrl");r(this,"localDescription");r(this,"onconnectionstatechange");r(this,"ondatachannel");r(this,"onicecandidate");r(this,"onicecandidateerror",null);r(this,"oniceconnectionstatechange");r(this,"onicegatheringstatechange");r(this,"onnegotiationneeded");r(this,"onsignalingstatechange");r(this,"ontrack");r(this,"peerIdentity");r(this,"pendingLocalDescription");r(this,"pendingRemoteDescription");r(this,"remoteDescription");r(this,"sctp",null);r(this,"signalingState");r(this,"getReceivers",()=>this._receivers);r(this,"getSenders",()=>this._senders);r(this,"addTrack",t=>{const e=new U({track:t});return this._senders.push(e),e});this._receivers=e.map(n=>({track:n}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(t){throw new Error("Method not implemented.")}addTransceiver(t,e){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(t,e){throw new Error("Method not implemented.")}createDataChannel(t,e){throw new Error("Method not implemented.")}async createOffer(t,e,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(t){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(t){throw new Error("Method not implemented.")}setConfiguration(t){throw new Error("Method not implemented.")}async setLocalDescription(t){throw new Error("Method not implemented.")}async setRemoteDescription(t){throw new Error("Method not implemented.")}addEventListener(t,e,n){throw new Error("Method not implemented.")}removeEventListener(t,e,n){throw new Error("Method not implemented.")}dispatchEvent(t){throw new Error("Method not implemented.")}}function x(o){const t=o.match(/(purgatory)|[\d.]+/g);if(!t)throw new Error("wrong sip url");return t[0]}const w=400,N="777",H=o=>o.getVideoTracks().length>0,a=class a extends z{constructor({url:e="",mediaStream:n,eventHandlers:i,originator:d}){super({originator:d,eventHandlers:i});r(this,"url");r(this,"status_code");r(this,"_isEnded",!1);r(this,"answer",jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},w)}));this.url=e,this.initPeerconnection(n)}static setStartPresentationError(e,{count:n=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=n}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}async startPresentation(e){if(a.countStartsPresentation+=1,a.startPresentationError&&a.countStartsPresentation<a.countStartPresentationError)throw a.startPresentationError;return super.startPresentation(e)}initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const n=C.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(H(e)){const u=C.createVideoMediaStreamTrackMock();u.id="mainvideo1",i.push(u)}this._connection=new q(void 0,i),this._addStream(e),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},w)}connect(e){const n=x(e);setTimeout(()=>{this.url.includes(N)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:g.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},w)}terminate({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e}),this._isEnded=!1,this}async terminateAsync({status_code:e}={}){this.terminate({status_code:e})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}_addStream(e,n="getTracks"){e[n]().forEach(i=>this.connection.addTrack(i))}_forEachSenders(e){const n=this.connection.getSenders();for(const i of n)e(i);return n}_toggleMuteAudio(e){this._forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!e)})}_toggleMuteVideo(e){this._forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.enabled=!e)})}mute(e){e.audio&&(this._mutedOptions.audio=!0,this._toggleMuteAudio(this._mutedOptions.audio)),e.video&&(this._mutedOptions.video=!0,this._toggleMuteVideo(this._mutedOptions.video)),this._onmute(e)}unmute(e){e.audio&&(this._mutedOptions.audio=!1),e.video&&(this._mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this._mutedOptions}async replaceMediaStream(e){return e}_onmute({audio:e,video:n}){this.trigger("muted",{audio:e,video:n})}async sendInfo(){}isEnded(){return this._isEnded}newInfo(e){this.trigger("newInfo",e)}};r(a,"startPresentationError"),r(a,"countStartPresentationError",Number.POSITIVE_INFINITY),r(a,"countStartsPresentation",0);let l=a;class Y{constructor(){r(this,"extraHeaders",[])}setExtraHeaders(t){this.extraHeaders=t}setExtraContactParams(){}}const c="PASSWORD_CORRECT",f="PASSWORD_CORRECT_2",P="NAME_INCORRECT",m=400,s=class s{constructor(t){r(this,"_events");r(this,"_startedTimeout");r(this,"_stopedTimeout");r(this,"session");r(this,"_isRegistered");r(this,"_isConnected");r(this,"configuration");r(this,"_registrator");r(this,"call",jest.fn((t,e)=>{const{mediaStream:n,eventHandlers:i}=e;return this.session=new l({url:t,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(t),this.session}));this._events=new I(g.UA_EVENT_NAMES);const[e,n]=t.uri.split(":"),[i,d]=n.split("@"),u={...t,uri:new T.URI(e,i,d)};this.configuration=u,this._registrator=new Y}static setStartError(t,{count:e=Number.POSITIVE_INFINITY}={}){this.startError=t,this.countStartError=e}static resetStartError(){this.startError=void 0,this.countStartError=Number.POSITIVE_INFINITY,this.countStarts=0}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}isConnected(){return!!this._isConnected}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:new Error("stoped")})},m):this.trigger("disconnected",{error:new Error("stoped")})}on(t,e){return this._events.on(t,e),this}once(t,e){return this._events.once(t,e),this}off(t,e){return this._events.off(t,e),this}removeAllListeners(){return this._events.removeEventHandlers(),this}trigger(t,e){this._events.trigger(t,e)}terminateSessions(){this.session.terminate()}set(t,e){return this.configuration[t]=e,!0}register(){this._startedTimeout&&clearTimeout(this._startedTimeout);const{password:t,register:e,uri:n}=this.configuration;e&&n.user.includes(P)?(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Request Timeout"})},m)):!this._isRegistered&&e&&(t===c||t===f)?(this._isRegistered=!0,this._startedTimeout=setTimeout(()=>{this.trigger("registered")},m)):e&&t!==c&&t!==f&&(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Wrong credentials"})},m)),s.isAvailableTelephony?(this.trigger("connected"),this._isConnected=!0):this.stop()}unregister(){this._isRegistered=!1,this._isConnected=!1,this.trigger("unregistered")}isRegistered(){return!!this._isRegistered}isStarted(){return this.configuration&&(this.configuration.register&&!!this._isRegistered||!this.configuration.register&&!!this._isConnected)}registrator(){return this._registrator}newSipEvent(t){this.trigger("sipEvent",t)}};r(s,"isAvailableTelephony",!0),r(s,"startError"),r(s,"countStartError",Number.POSITIVE_INFINITY),r(s,"countStarts",0);let M=s;class j{constructor(t){r(this,"url");this.url=t}}class B extends F.EventEmitter{constructor(e,n){super();r(this,"contentType");r(this,"body");this.contentType=e,this.body=n}}const S="remote",K=(o,t)=>{const e=new y(t),n={originator:S,request:e,info:new B("","")};o.newInfo(n)},$=(o,t)=>{const n={request:new y(t)};o.newSipEvent(n)},J=(o,{incomingNumber:t="1234",displayName:e,host:n})=>{const i=new l({originator:S}),d=new L("sip",t,n);i._remote_identity=new D(d,e),o.trigger("newRTCSession",{originator:S,session:i})},G=(o,t)=>{t?o.trigger("failed",t):o.trigger("failed",o)},A={triggerNewInfo:K,triggerNewSipEvent:$,triggerIncomingSession:J,triggerFailIncomingSession:G,WebSocketInterface:j,UA:M,C:{INVITE:"INVITE"}},_="user",h="displayName",p="SIP_SERVER_URL",R="SIP_WEB_SOCKET_SERVER_URL",X=new A.WebSocketInterface(R),v={userAgent:"Chrome",sipServerUrl:p,sipWebSocketServerURL:R},Q={...v},O={...v,user:_,password:c,register:!0},Z={...O,displayName:h},ee={...v,displayName:h,register:!1},E={session_timers:!1,sockets:[X],user_agent:"Chrome",sdp_semantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},te={...E,password:c,uri:new T.URI("sip",_,p),display_name:"",register:!0},re={...E,password:c,uri:new T.URI("sip",_,p),display_name:h,register:!0},ne={...E,display_name:h,register:!1},oe={...E,display_name:"",register:!1},W="10.10.10.10",ie=[`X-Vinteo-Remote: ${W}`],se=()=>new g.SipConnector({JsSIP:A});exports.FAILED_CONFERENCE_NUMBER=N;exports.NAME_INCORRECT=P;exports.PASSWORD_CORRECT=c;exports.PASSWORD_CORRECT_2=f;exports.SIP_SERVER_URL=p;exports.SIP_WEB_SOCKET_SERVER_URL=R;exports.dataForConnectionWithAuthorization=O;exports.dataForConnectionWithAuthorizationWithDisplayName=Z;exports.dataForConnectionWithoutAuthorization=ee;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=Q;exports.default=se;exports.displayName=h;exports.extraHeadersRemoteAddress=ie;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=te;exports.uaConfigurationWithAuthorizationWithDisplayName=re;exports.uaConfigurationWithoutAuthorization=ne;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=oe;exports.user=_;
package/dist/doMock.js CHANGED
@@ -1,8 +1,8 @@
1
1
  var y = Object.defineProperty;
2
2
  var N = (o, t, e) => t in o ? y(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e;
3
3
  var r = (o, t, e) => N(o, typeof t != "symbol" ? t + "" : t, e);
4
- import { j as P, R as O, U as A, S as b } from "./SipConnector-xflR79mb.js";
5
- import k from "@krivega/jssip/lib/NameAddrHeader";
4
+ import { j as P, R as O, U as k, S as A } from "./SipConnector-7Qar6pDS.js";
5
+ import b from "@krivega/jssip/lib/NameAddrHeader";
6
6
  import D from "@krivega/jssip/lib/URI";
7
7
  import { EventEmitter as L } from "node:events";
8
8
  import { IncomingRequest as W } from "@krivega/jssip/lib/SIPMessage";
@@ -202,6 +202,42 @@ class x {
202
202
  }
203
203
  }
204
204
  class U {
205
+ constructor({ track: t } = {}) {
206
+ r(this, "dtmf", null);
207
+ r(this, "track", null);
208
+ r(this, "transport", null);
209
+ r(this, "transform", null);
210
+ r(this, "_parameters", {
211
+ encodings: [{}],
212
+ transactionId: "0",
213
+ codecs: [],
214
+ headerExtensions: [],
215
+ rtcp: {}
216
+ });
217
+ this.track = t ?? null;
218
+ }
219
+ async getStats() {
220
+ throw new Error("Method not implemented.");
221
+ }
222
+ async replaceTrack(t) {
223
+ this.track = t ?? null;
224
+ }
225
+ async setParameters(t) {
226
+ const { transactionId: e } = this._parameters;
227
+ this._parameters = {
228
+ ...this._parameters,
229
+ ...t,
230
+ transactionId: `${Number(e) + 1}`
231
+ };
232
+ }
233
+ getParameters() {
234
+ return { ...this._parameters };
235
+ }
236
+ setStreams() {
237
+ throw new Error("Method not implemented.");
238
+ }
239
+ }
240
+ class H {
205
241
  constructor(t, e) {
206
242
  r(this, "_senders", []);
207
243
  r(this, "_receivers", []);
@@ -232,7 +268,7 @@ class U {
232
268
  r(this, "getReceivers", () => this._receivers);
233
269
  r(this, "getSenders", () => this._senders);
234
270
  r(this, "addTrack", (t) => {
235
- const e = { track: t };
271
+ const e = new U({ track: t });
236
272
  return this._senders.push(e), e;
237
273
  });
238
274
  this._receivers = e.map((n) => ({ track: n }));
@@ -295,13 +331,13 @@ class U {
295
331
  throw new Error("Method not implemented.");
296
332
  }
297
333
  }
298
- function H(o) {
334
+ function z(o) {
299
335
  const t = o.match(/(purgatory)|[\d.]+/g);
300
336
  if (!t)
301
337
  throw new Error("wrong sip url");
302
338
  return t[0];
303
339
  }
304
- const p = 400, z = "777", Y = (o) => o.getVideoTracks().length > 0, a = class a extends x {
340
+ const p = 400, Y = "777", q = (o) => o.getVideoTracks().length > 0, a = class a extends x {
305
341
  constructor({
306
342
  url: e = "",
307
343
  mediaStream: n,
@@ -352,18 +388,18 @@ const p = 400, z = "777", Y = (o) => o.getVideoTracks().length > 0, a = class a
352
388
  const n = V();
353
389
  n.id = "mainaudio1";
354
390
  const i = [n];
355
- if (Y(e)) {
391
+ if (q(e)) {
356
392
  const h = F();
357
393
  h.id = "mainvideo1", i.push(h);
358
394
  }
359
- this._connection = new U(void 0, i), this._addStream(e), setTimeout(() => {
395
+ this._connection = new H(void 0, i), this._addStream(e), setTimeout(() => {
360
396
  this.trigger("peerconnection", { peerconnection: this.connection });
361
397
  }, p);
362
398
  }
363
399
  connect(e) {
364
- const n = H(e);
400
+ const n = z(e);
365
401
  setTimeout(() => {
366
- this.url.includes(z) ? this.trigger("failed", {
402
+ this.url.includes(Y) ? this.trigger("failed", {
367
403
  originator: "remote",
368
404
  message: "IncomingResponse",
369
405
  cause: O
@@ -437,9 +473,9 @@ const p = 400, z = "777", Y = (o) => o.getVideoTracks().length > 0, a = class a
437
473
  };
438
474
  r(a, "startPresentationError"), r(a, "countStartPresentationError", Number.POSITIVE_INFINITY), r(a, "countStartsPresentation", 0);
439
475
  let u = a;
440
- class q {
476
+ class j {
441
477
  constructor() {
442
- r(this, "extraHeaders");
478
+ r(this, "extraHeaders", []);
443
479
  }
444
480
  setExtraHeaders(t) {
445
481
  this.extraHeaders = t;
@@ -447,7 +483,7 @@ class q {
447
483
  setExtraContactParams() {
448
484
  }
449
485
  }
450
- const c = "PASSWORD_CORRECT", T = "PASSWORD_CORRECT_2", j = "NAME_INCORRECT", m = 400, s = class s {
486
+ const c = "PASSWORD_CORRECT", T = "PASSWORD_CORRECT_2", B = "NAME_INCORRECT", m = 400, s = class s {
451
487
  constructor(t) {
452
488
  r(this, "_events");
453
489
  r(this, "_startedTimeout");
@@ -462,12 +498,12 @@ const c = "PASSWORD_CORRECT", T = "PASSWORD_CORRECT_2", j = "NAME_INCORRECT", m
462
498
  const { mediaStream: n, eventHandlers: i } = e;
463
499
  return this.session = new u({ url: t, mediaStream: n, eventHandlers: i, originator: "local" }), this.session.connect(t), this.session;
464
500
  }));
465
- this._events = new v(A);
501
+ this._events = new v(k);
466
502
  const [e, n] = t.uri.split(":"), [i, d] = n.split("@"), h = {
467
503
  ...t,
468
504
  uri: new E(e, i, d)
469
505
  };
470
- this.configuration = h, this._registrator = new q();
506
+ this.configuration = h, this._registrator = new j();
471
507
  }
472
508
  static setStartError(t, { count: e = Number.POSITIVE_INFINITY } = {}) {
473
509
  this.startError = t, this.countStartError = e;
@@ -551,7 +587,7 @@ const c = "PASSWORD_CORRECT", T = "PASSWORD_CORRECT_2", j = "NAME_INCORRECT", m
551
587
  register() {
552
588
  this._startedTimeout && clearTimeout(this._startedTimeout);
553
589
  const { password: t, register: e, uri: n } = this.configuration;
554
- e && n.user.includes(j) ? (this._isRegistered = !1, this._isConnected = !1, this._startedTimeout = setTimeout(() => {
590
+ e && n.user.includes(B) ? (this._isRegistered = !1, this._isConnected = !1, this._startedTimeout = setTimeout(() => {
555
591
  this.trigger("registrationFailed", { response: null, cause: "Request Timeout" });
556
592
  }, m)) : !this._isRegistered && e && (t === c || t === T) ? (this._isRegistered = !0, this._startedTimeout = setTimeout(() => {
557
593
  this.trigger("registered");
@@ -592,7 +628,7 @@ const c = "PASSWORD_CORRECT", T = "PASSWORD_CORRECT_2", j = "NAME_INCORRECT", m
592
628
  };
593
629
  r(s, "isAvailableTelephony", !0), r(s, "startError"), r(s, "countStartError", Number.POSITIVE_INFINITY), r(s, "countStarts", 0);
594
630
  let _ = s;
595
- class B {
631
+ class $ {
596
632
  constructor(t) {
597
633
  r(this, "url");
598
634
  this.url = t;
@@ -606,102 +642,102 @@ class K extends L {
606
642
  this.contentType = e, this.body = n;
607
643
  }
608
644
  }
609
- const w = "remote", $ = (o, t) => {
645
+ const w = "remote", J = (o, t) => {
610
646
  const e = new I(t), n = {
611
647
  originator: w,
612
648
  request: e,
613
649
  info: new K("", "")
614
650
  };
615
651
  o.newInfo(n);
616
- }, J = (o, t) => {
652
+ }, G = (o, t) => {
617
653
  const n = { request: new I(t) };
618
654
  o.newSipEvent(n);
619
- }, G = (o, {
655
+ }, X = (o, {
620
656
  incomingNumber: t = "1234",
621
657
  displayName: e,
622
658
  host: n
623
659
  }) => {
624
660
  const i = new u({ originator: w }), d = new D("sip", t, n);
625
- i._remote_identity = new k(d, e), o.trigger("newRTCSession", { originator: w, session: i });
626
- }, X = (o, t) => {
661
+ i._remote_identity = new b(d, e), o.trigger("newRTCSession", { originator: w, session: i });
662
+ }, Q = (o, t) => {
627
663
  t ? o.trigger("failed", t) : o.trigger("failed", o);
628
664
  }, R = {
629
- triggerNewInfo: $,
630
- triggerNewSipEvent: J,
631
- triggerIncomingSession: G,
632
- triggerFailIncomingSession: X,
633
- WebSocketInterface: B,
665
+ triggerNewInfo: J,
666
+ triggerNewSipEvent: G,
667
+ triggerIncomingSession: X,
668
+ triggerFailIncomingSession: Q,
669
+ WebSocketInterface: $,
634
670
  UA: _,
635
671
  C: {
636
672
  INVITE: "INVITE"
637
673
  }
638
- }, f = "user", l = "displayName", M = "SIP_SERVER_URL", C = "SIP_WEB_SOCKET_SERVER_URL", Q = new R.WebSocketInterface(C), S = {
674
+ }, f = "user", l = "displayName", M = "SIP_SERVER_URL", C = "SIP_WEB_SOCKET_SERVER_URL", Z = new R.WebSocketInterface(C), S = {
639
675
  userAgent: "Chrome",
640
676
  sipServerUrl: M,
641
677
  sipWebSocketServerURL: C
642
- }, he = {
678
+ }, me = {
643
679
  ...S
644
- }, Z = {
680
+ }, ee = {
645
681
  ...S,
646
682
  user: f,
647
683
  password: c,
648
684
  register: !0
649
- }, me = {
650
- ...Z,
651
- displayName: l
652
685
  }, ue = {
686
+ ...ee,
687
+ displayName: l
688
+ }, le = {
653
689
  ...S,
654
690
  displayName: l,
655
691
  register: !1
656
692
  }, g = {
657
693
  session_timers: !1,
658
- sockets: [Q],
694
+ sockets: [Z],
659
695
  user_agent: "Chrome",
660
696
  sdp_semantics: "unified-plan",
661
697
  register_expires: 300,
662
698
  connection_recovery_max_interval: 6,
663
699
  connection_recovery_min_interval: 2
664
- }, le = {
700
+ }, ge = {
665
701
  ...g,
666
702
  password: c,
667
703
  uri: new E("sip", f, M),
668
704
  display_name: "",
669
705
  register: !0
670
- }, ge = {
706
+ }, pe = {
671
707
  ...g,
672
708
  password: c,
673
709
  uri: new E("sip", f, M),
674
710
  display_name: l,
675
711
  register: !0
676
- }, pe = {
712
+ }, _e = {
677
713
  ...g,
678
714
  display_name: l,
679
715
  register: !1
680
- }, _e = {
716
+ }, we = {
681
717
  ...g,
682
718
  display_name: "",
683
719
  register: !1
684
- }, ee = "10.10.10.10", we = [`X-Vinteo-Remote: ${ee}`], Ee = () => new b({
720
+ }, te = "10.10.10.10", Ee = [`X-Vinteo-Remote: ${te}`], fe = () => new A({
685
721
  JsSIP: R
686
722
  });
687
723
  export {
688
- z as FAILED_CONFERENCE_NUMBER,
689
- j as NAME_INCORRECT,
724
+ Y as FAILED_CONFERENCE_NUMBER,
725
+ B as NAME_INCORRECT,
690
726
  c as PASSWORD_CORRECT,
691
727
  T as PASSWORD_CORRECT_2,
692
728
  M as SIP_SERVER_URL,
693
729
  C as SIP_WEB_SOCKET_SERVER_URL,
694
- Z as dataForConnectionWithAuthorization,
695
- me as dataForConnectionWithAuthorizationWithDisplayName,
696
- ue as dataForConnectionWithoutAuthorization,
697
- he as dataForConnectionWithoutAuthorizationWithoutDisplayName,
698
- Ee as default,
730
+ ee as dataForConnectionWithAuthorization,
731
+ ue as dataForConnectionWithAuthorizationWithDisplayName,
732
+ le as dataForConnectionWithoutAuthorization,
733
+ me as dataForConnectionWithoutAuthorizationWithoutDisplayName,
734
+ fe as default,
699
735
  l as displayName,
700
- we as extraHeadersRemoteAddress,
701
- ee as remoteAddress,
702
- le as uaConfigurationWithAuthorization,
703
- ge as uaConfigurationWithAuthorizationWithDisplayName,
704
- pe as uaConfigurationWithoutAuthorization,
705
- _e as uaConfigurationWithoutAuthorizationWithoutDisplayName,
736
+ Ee as extraHeadersRemoteAddress,
737
+ te as remoteAddress,
738
+ ge as uaConfigurationWithAuthorization,
739
+ pe as uaConfigurationWithAuthorizationWithDisplayName,
740
+ _e as uaConfigurationWithoutAuthorization,
741
+ we as uaConfigurationWithoutAuthorizationWithoutDisplayName,
706
742
  f as user
707
743
  };
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const r=require("./SipConnector-lgvJyyG7.cjs"),K=require("ts-debounce"),Y=require("@krivega/cancelable-promise"),z=require("repeated-calls"),J=require("sequent-promises"),Q=require("stack-promises"),Z=require("debug"),V="purgatory",A=e=>e===V,I=e=>()=>(r.logger("getRemoteStreams"),e.getRemoteStreams()),ee=({kind:e,readyState:t})=>e==="video"&&t==="live",x=e=>({track:t})=>{ee(t)&&e()},w=({getRemoteStreams:e,setRemoteStreams:t})=>K.debounce(()=>{const n=e();r.logger("remoteStreams",n),n&&t(n)},200),ne=e=>async n=>{const{mediaStream:s,extraHeaders:o,iceServers:c,degradationPreference:a,contentHint:i,setRemoteStreams:l,onBeforeProgressCall:d,onSuccessProgressCall:m,onEnterPurgatory:S,onEnterConference:g,onFailProgressCall:C,onFinishProgressCall:f,onEndedCall:R}=n,M=w({setRemoteStreams:l,getRemoteStreams:I(e)}),_=x(M);r.logger("answerIncomingCall",n);const h=async()=>e.answerToIncomingCall({mediaStream:s,extraHeaders:o,iceServers:c,contentHint:i,degradationPreference:a,ontrack:_}),v=()=>{const{remoteCallerData:u}=e;return u.incomingNumber};let T=!1,y;const b=(r.logger("subscribeEnterConference: onEnterConference",g),S??g?e.onSession("enterRoom",u=>{r.logger("enterRoom",{_room:u,isSuccessProgressCall:T}),y=u,A(y)?S&&S():g&&g({isSuccessProgressCall:T})}):()=>{}),O=u=>(r.logger("onSuccess"),T=!0,M(),m&&m({isPurgatory:A(y)}),e.onceRaceSession(["ended","failed"],()=>{b(),R&&R()}),u),p=u=>{throw r.logger("onFail"),C&&C(),b(),u},P=()=>{r.logger("onFinish"),f&&f()};if(r.logger("onBeforeProgressCall"),d){const u=v();d(u)}return h().then(O).catch(u=>p(u)).finally(P)},te=e=>async n=>{const{conference:s,mediaStream:o,extraHeaders:c,iceServers:a,degradationPreference:i,contentHint:l,setRemoteStreams:d,onBeforeProgressCall:m,onSuccessProgressCall:S,onEnterPurgatory:g,onEnterConference:C,onFailProgressCall:f,onFinishProgressCall:R,onEndedCall:M}=n,_=w({setRemoteStreams:d,getRemoteStreams:I(e)}),h=x(_);r.logger("callToServer",n);const v=async()=>(r.logger("startCall"),e.call({mediaStream:o,extraHeaders:c,iceServers:a,degradationPreference:i,contentHint:l,number:s,ontrack:h}));let T=!1,y;const b=(r.logger("subscribeEnterConference: onEnterConference",C),g??C?e.onSession("enterRoom",({room:u})=>{r.logger("enterRoom",{_room:u,isSuccessProgressCall:T}),y=u,A(y)?g&&g():C&&C({isSuccessProgressCall:T})}):()=>{}),O=u=>(r.logger("onSuccess"),T=!0,_(),S&&S({isPurgatory:A(y)}),e.onceRaceSession(["ended","failed"],()=>{b(),M&&M()}),u),p=u=>{throw r.logger("onFail"),f&&f(),b(),u},P=()=>{r.logger("onFinish"),R&&R()};return r.logger("onBeforeProgressCall"),m&&m(s),v().then(O).catch(u=>p(u)).finally(P)},B=e=>{if(!Y.isCanceledError(e)&&!z.hasCanceledError(e))throw e;return{isSuccessful:!1}},re=e=>async n=>{const{userAgent:s,sipWebSocketServerURL:o,sipServerUrl:c,remoteAddress:a,displayName:i,name:l,password:d,isRegisteredUser:m,isDisconnectOnFail:S}=n;return r.logger("connectToServer",n),e.connect({userAgent:s,sipWebSocketServerURL:o,sipServerUrl:c,remoteAddress:a,displayName:i,password:d,user:l,register:m}).then(g=>(r.logger("connectToServer then"),{ua:g,isSuccessful:!0})).catch(async g=>(r.logger("connectToServer catch: error",g),S===!0?e.disconnect().then(()=>B(g)).catch(()=>B(g)):B(g)))},se=e=>async()=>(r.logger("disconnectFromServer"),e.disconnect().then(()=>(r.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(t=>(r.logger("disconnectFromServer: catch",t),{isSuccessful:!1}))),F=e=>{const{url:t,cause:n}=e;let s=t;return(n===r.BAD_MEDIA_DESCRIPTION||n===r.NOT_FOUND)&&(s=`${e.message.to.uri.user}@${e.message.to.uri.host}`),s};var $=(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))($||{});const oe=(e=new Error)=>{var o;const{cause:t,socket:n}=e;let s="CONNECT_SERVER_FAILED";switch(t){case"Forbidden":{s="WRONG_USER_OR_PASSWORD";break}case r.BAD_MEDIA_DESCRIPTION:{s="BAD_MEDIA_ERROR";break}case r.NOT_FOUND:{s="NOT_FOUND_ERROR";break}default:n&&((o=n==null?void 0:n._ws)==null?void 0:o.readyState)===3?s="WS_CONNECTION_FAILED":F(e)&&(s="CONNECT_SERVER_FAILED_BY_LINK")}return s},ce=e=>{let t="";try{t=JSON.stringify(e)}catch(n){r.logger("failed to stringify message",n)}return t},ae=(e=new Error)=>{const{code:t,cause:n,message:s}=e,o=F(e),c={code:"",cause:"",message:""};return typeof s=="object"&&s!==null?c.message=ce(s):s&&(c.message=String(s)),o&&(c.link=o),t&&(c.code=t),n&&(c.cause=n),c},ie=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:$,getLinkError:F,getTypeFromError:oe,getValuesFromError:ae},Symbol.toStringTag,{value:"Module"})),ue=({sessionId:e,remoteAddress:t,isMutedAudio:n,isMutedVideo:s,isRegistered:o,isPresentationCall:c})=>{const a=[],i=n?"0":"1",l=s?"0":"1";return a.push(`X-Vinteo-Mic-State: ${i}`,`X-Vinteo-MainCam-State: ${l}`),o||a.push("X-Vinteo-Purgatory-Call: yes"),e&&a.push(`X-Vinteo-Session: ${e}`),c&&a.push("X-Vinteo-Presentation-Call: yes"),t&&a.push(`X-Vinteo-Remote: ${t}`),a},le="[@*!|]",ge="_",Se=e=>{let t=e;return t=t.replaceAll(new RegExp(le,"g"),ge),t},de=({appName:e,appVersion:t,browserName:n,browserVersion:s})=>{const c=`${Se(e)} ${t}`;return`ChromeNew - ${n?`${n} ${s}, ${c}`:c}`},me=({isUnifiedSdpSemantic:e,appVersion:t,browserName:n,browserVersion:s,appName:o})=>e?de({appVersion:t,browserName:n,browserVersion:s,appName:o}):"Chrome",fe=e=>async()=>{if(e.isCallActive)return r.logger("askPermissionToEnableCam"),e.askPermissionToEnableCam()},Ce=e=>n=>(r.logger("onMustStopPresentation"),e.onSession("mustStopPresentation",n)),Ee=e=>n=>(r.logger("onMoveToSpectators"),e.onSession("participant:move-request-to-spectators",n)),Re=e=>n=>(r.logger("onUseLicense"),e.onSession("useLicense",n)),Me=e=>async({isEnabledCam:n,isEnabledMic:s})=>{if(e.isCallActive)return r.logger("sendMediaState"),e.sendMediaState({cam:n,mic:s})},Te=e=>async()=>{if(e.isCallActive)return r.logger("sendRefusalToTurnOnCam"),e.sendRefusalToTurnOnCam().catch(n=>{r.logger("sendRefusalToTurnOnCam: error",n)})},ye=e=>async()=>{if(e.isCallActive)return r.logger("sendRefusalToTurnOnMic"),e.sendRefusalToTurnOnMic().catch(n=>{r.logger("sendRefusalToTurnOnMic: error",n)})},be=e=>async({mediaStream:n,isP2P:s,maxBitrate:o,degradationPreference:c,contentHint:a},i)=>(r.logger("startPresentation"),e.startPresentation(n,{isP2P:s,maxBitrate:o,degradationPreference:c,contentHint:a},i)),_e=e=>async({isP2P:n=!1}={})=>(r.logger("stopShareSipConnector"),e.stopPresentation({isP2P:n}).catch(s=>{r.logger(s)})),he=e=>async({mediaStream:n,isP2P:s,maxBitrate:o,degradationPreference:c,contentHint:a})=>(r.logger("updatePresentation"),e.updatePresentation(n,{isP2P:s,maxBitrate:o,degradationPreference:c,contentHint:a})),ve=e=>t=>[...t].map(s=>async()=>e(s)),Oe=async({accumulatedKeys:e,sendKey:t,canRunTask:n})=>{const o=ve(t)(e);return J.sequentPromises(o,n)},pe=e=>n=>(r.logger("onStartMainCam"),e.onSession("admin-start-main-cam",n)),Ae=e=>n=>(r.logger("onStartMic"),e.onSession("admin-start-mic",n)),Ne=e=>n=>(r.logger("onStopMainCam"),e.onSession("admin-stop-main-cam",n)),Pe=e=>n=>(r.logger("onStopMic"),e.onSession("admin-stop-mic",n)),Be=({sipConnector:e})=>{const t=(f,R)=>({isSyncForced:M=!1})=>{if(M){f();return}R()},n=pe(e),s=Ne(e),o=Ae(e),c=Pe(e);let a=()=>{},i=()=>{},l=()=>{},d=()=>{};const m=({onStartMainCamForced:f,onStartMainCamNotForced:R,onStopMainCamForced:M,onStopMainCamNotForced:_,onStartMicForced:h,onStartMicNotForced:v,onStopMicForced:T,onStopMicNotForced:y})=>{const N=t(f,R);a=n(N);const b=t(M,_);i=s(b);const O=t(h,v);l=o(O);const p=t(T,y);d=c(p)},S=()=>{a(),i(),l(),d()};return{start:f=>{m(f)},stop:()=>{S()}}},De=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:V,createSyncMediaState:Be,error:ie,getExtraHeaders:ue,getUserAgent:me,hasPurgatory:A,resolveAnswerIncomingCall:ne,resolveAskPermissionToEnableCam:fe,resolveCallToServer:te,resolveConnectToServer:re,resolveDisconnectFromServer:se,resolveGetRemoteStreams:I,resolveOnMoveToSpectators:Ee,resolveOnMustStopPresentation:Ce,resolveOnUseLicense:Re,resolveSendMediaState:Me,resolveSendRefusalToTurnOnCam:Te,resolveSendRefusalToTurnOnMic:ye,resolveStartPresentation:be,resolveStopShareSipConnector:_e,resolveUpdatePresentation:he,resolveUpdateRemoteStreams:w,sendDTMFAccumulated:Oe},Symbol.toStringTag,{value:"Module"})),Ie=e=>[...e.keys()].map(t=>e.get(t)),we=(e,t)=>Ie(e).find(n=>n.type===t),q=async e=>e.getStats().then(t=>{const n=we(t,"codec");return n==null?void 0:n.mimeType}),Fe=e=>e.find(t=>{var n;return((n=t==null?void 0:t.track)==null?void 0:n.kind)==="video"}),X=(e,t)=>e!==void 0&&t!==void 0&&e.toLowerCase().includes(t.toLowerCase()),ke=1e6,E=e=>e*ke,H=E(.06),Ue=E(4),Le=e=>e<=64?H:e<=128?E(.12):e<=256?E(.25):e<=384?E(.32):e<=426?E(.38):e<=640?E(.5):e<=848?E(.7):e<=1280?E(1):e<=1920?E(2):Ue,Ve="av1",xe=e=>X(e,Ve),$e=.6,W=(e,t)=>xe(t)?e*$e:e,qe=e=>W(H,e),j=(e,t)=>{const n=Le(e);return W(n,t)},G=Q.createStackPromises(),Xe=async()=>G().catch(e=>{r.logger("videoSendingBalancer: error",e)}),He=async e=>(G.add(e),Xe()),k=async({sender:e,scaleResolutionDownBy:t,maxBitrate:n,onSetParameters:s})=>He(async()=>r.setEncodingsToSender(e,{scaleResolutionDownBy:t,maxBitrate:n},s)),We=async({sender:e,codec:t},n)=>{const o=qe(t);return k({sender:e,maxBitrate:o,onSetParameters:n,scaleResolutionDownBy:200})},D=async({sender:e,track:t,codec:n},s)=>{const a=t.getSettings().width,i=j(a,n);return k({sender:e,maxBitrate:i,onSetParameters:s,scaleResolutionDownBy:1})},je=async({sender:e,track:t,resolution:n,codec:s},o)=>{const c=t.getSettings(),a=c.width,i=c.height,[l,d]=n.split("x"),m=a/Number(l),S=i/Number(d),C=Math.max(m,S,1),f=j(Number(l),s);return k({sender:e,maxBitrate:f,onSetParameters:o,scaleResolutionDownBy:C})},Ge=async({mainCam:e,resolutionMainCam:t,sender:n,track:s,codec:o},c)=>{switch(e){case r.EEventsMainCAM.PAUSE_MAIN_CAM:return We({sender:n,codec:o},c);case r.EEventsMainCAM.RESUME_MAIN_CAM:return D({sender:n,track:s,codec:o},c);case r.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return t!==void 0?je({sender:n,track:s,codec:o,resolution:t},c):D({sender:n,track:s,codec:o},c);default:return D({sender:n,track:s,codec:o},c)}},U={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},L=async({mainCam:e,resolutionMainCam:t,connection:n,onSetParameters:s,ignoreForCodec:o})=>{const c=n.getSenders(),a=Fe(c);if(!(a!=null&&a.track))return U;const i=await q(a);return X(i,o)?U:Ge({mainCam:e,resolutionMainCam:t,sender:a,codec:i,track:a.track},s)},Ke=(e,{ignoreForCodec:t,onSetParameters:n}={})=>{const s=async()=>{const{connection:l}=e;if(!l)throw new Error("connection is not exist");return L({connection:l,onSetParameters:n,ignoreForCodec:t})};let o=s;const c=async l=>(o=async()=>{const{mainCam:d,resolutionMainCam:m}=l,{connection:S}=e;if(!S)throw new Error("connection is not exist");return L({mainCam:d,resolutionMainCam:m,connection:S,onSetParameters:n,ignoreForCodec:t})},o());return{subscribe:()=>{e.onSession("main-cam-control",c)},unsubscribe:()=>{e.offSession("main-cam-control",c)},balanceByTrack:s,resetMainCamControl(){o=s},async reBalance(){return o()}}};exports.EEventsMainCAM=r.EEventsMainCAM;exports.EEventsMic=r.EEventsMic;exports.EEventsSyncMediaState=r.EEventsSyncMediaState;exports.EUseLicense=r.EUseLicense;exports.causes=r.causes;exports.constants=r.constants;exports.default=r.SipConnector;exports.disableDebug=r.disableDebug;exports.enableDebug=r.enableDebug;exports.eventNames=r.eventNames;exports.hasCanceledCallError=r.hasCanceledCallError;exports.debug=Z;exports.getCodecFromSender=q;exports.resolveVideoSendingBalancer=Ke;exports.tools=De;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const r=require("./SipConnector-BhCqlPz2.cjs"),K=require("ts-debounce"),Y=require("@krivega/cancelable-promise"),z=require("repeated-calls"),J=require("sequent-promises"),Q=require("stack-promises"),Z=require("debug"),V="purgatory",A=e=>e===V,I=e=>()=>(r.logger("getRemoteStreams"),e.getRemoteStreams()),ee=({kind:e,readyState:t})=>e==="video"&&t==="live",x=e=>({track:t})=>{ee(t)&&e()},w=({getRemoteStreams:e,setRemoteStreams:t})=>K.debounce(()=>{const n=e();r.logger("remoteStreams",n),n&&t(n)},200),ne=e=>async n=>{const{mediaStream:s,extraHeaders:o,iceServers:c,degradationPreference:a,contentHint:i,setRemoteStreams:l,onBeforeProgressCall:d,onSuccessProgressCall:m,onEnterPurgatory:S,onEnterConference:g,onFailProgressCall:C,onFinishProgressCall:f,onEndedCall:R}=n,M=w({setRemoteStreams:l,getRemoteStreams:I(e)}),_=x(M);r.logger("answerIncomingCall",n);const h=async()=>e.answerToIncomingCall({mediaStream:s,extraHeaders:o,iceServers:c,contentHint:i,degradationPreference:a,ontrack:_}),v=()=>{const{remoteCallerData:u}=e;return u.incomingNumber};let T=!1,y;const b=(r.logger("subscribeEnterConference: onEnterConference",g),S??g?e.onSession("enterRoom",u=>{r.logger("enterRoom",{_room:u,isSuccessProgressCall:T}),y=u,A(y)?S&&S():g&&g({isSuccessProgressCall:T})}):()=>{}),O=u=>(r.logger("onSuccess"),T=!0,M(),m&&m({isPurgatory:A(y)}),e.onceRaceSession(["ended","failed"],()=>{b(),R&&R()}),u),p=u=>{throw r.logger("onFail"),C&&C(),b(),u},P=()=>{r.logger("onFinish"),f&&f()};if(r.logger("onBeforeProgressCall"),d){const u=v();d(u)}return h().then(O).catch(u=>p(u)).finally(P)},te=e=>async n=>{const{conference:s,mediaStream:o,extraHeaders:c,iceServers:a,degradationPreference:i,contentHint:l,setRemoteStreams:d,onBeforeProgressCall:m,onSuccessProgressCall:S,onEnterPurgatory:g,onEnterConference:C,onFailProgressCall:f,onFinishProgressCall:R,onEndedCall:M}=n,_=w({setRemoteStreams:d,getRemoteStreams:I(e)}),h=x(_);r.logger("callToServer",n);const v=async()=>(r.logger("startCall"),e.call({mediaStream:o,extraHeaders:c,iceServers:a,degradationPreference:i,contentHint:l,number:s,ontrack:h}));let T=!1,y;const b=(r.logger("subscribeEnterConference: onEnterConference",C),g??C?e.onSession("enterRoom",({room:u})=>{r.logger("enterRoom",{_room:u,isSuccessProgressCall:T}),y=u,A(y)?g&&g():C&&C({isSuccessProgressCall:T})}):()=>{}),O=u=>(r.logger("onSuccess"),T=!0,_(),S&&S({isPurgatory:A(y)}),e.onceRaceSession(["ended","failed"],()=>{b(),M&&M()}),u),p=u=>{throw r.logger("onFail"),f&&f(),b(),u},P=()=>{r.logger("onFinish"),R&&R()};return r.logger("onBeforeProgressCall"),m&&m(s),v().then(O).catch(u=>p(u)).finally(P)},B=e=>{if(!Y.isCanceledError(e)&&!z.hasCanceledError(e))throw e;return{isSuccessful:!1}},re=e=>async n=>{const{userAgent:s,sipWebSocketServerURL:o,sipServerUrl:c,remoteAddress:a,displayName:i,name:l,password:d,isRegisteredUser:m,isDisconnectOnFail:S}=n;return r.logger("connectToServer",n),e.connect({userAgent:s,sipWebSocketServerURL:o,sipServerUrl:c,remoteAddress:a,displayName:i,password:d,user:l,register:m}).then(g=>(r.logger("connectToServer then"),{ua:g,isSuccessful:!0})).catch(async g=>(r.logger("connectToServer catch: error",g),S===!0?e.disconnect().then(()=>B(g)).catch(()=>B(g)):B(g)))},se=e=>async()=>(r.logger("disconnectFromServer"),e.disconnect().then(()=>(r.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(t=>(r.logger("disconnectFromServer: catch",t),{isSuccessful:!1}))),F=e=>{const{url:t,cause:n}=e;let s=t;return(n===r.BAD_MEDIA_DESCRIPTION||n===r.NOT_FOUND)&&(s=`${e.message.to.uri.user}@${e.message.to.uri.host}`),s};var $=(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))($||{});const oe=(e=new Error)=>{var o;const{cause:t,socket:n}=e;let s="CONNECT_SERVER_FAILED";switch(t){case"Forbidden":{s="WRONG_USER_OR_PASSWORD";break}case r.BAD_MEDIA_DESCRIPTION:{s="BAD_MEDIA_ERROR";break}case r.NOT_FOUND:{s="NOT_FOUND_ERROR";break}default:n&&((o=n==null?void 0:n._ws)==null?void 0:o.readyState)===3?s="WS_CONNECTION_FAILED":F(e)&&(s="CONNECT_SERVER_FAILED_BY_LINK")}return s},ce=e=>{let t="";try{t=JSON.stringify(e)}catch(n){r.logger("failed to stringify message",n)}return t},ae=(e=new Error)=>{const{code:t,cause:n,message:s}=e,o=F(e),c={code:"",cause:"",message:""};return typeof s=="object"&&s!==null?c.message=ce(s):s&&(c.message=String(s)),o&&(c.link=o),t&&(c.code=t),n&&(c.cause=n),c},ie=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:$,getLinkError:F,getTypeFromError:oe,getValuesFromError:ae},Symbol.toStringTag,{value:"Module"})),ue=({sessionId:e,remoteAddress:t,isMutedAudio:n,isMutedVideo:s,isRegistered:o,isPresentationCall:c})=>{const a=[],i=n?"0":"1",l=s?"0":"1";return a.push(`X-Vinteo-Mic-State: ${i}`,`X-Vinteo-MainCam-State: ${l}`),o||a.push("X-Vinteo-Purgatory-Call: yes"),e&&a.push(`X-Vinteo-Session: ${e}`),c&&a.push("X-Vinteo-Presentation-Call: yes"),t&&a.push(`X-Vinteo-Remote: ${t}`),a},le="[@*!|]",ge="_",Se=e=>{let t=e;return t=t.replaceAll(new RegExp(le,"g"),ge),t},de=({appName:e,appVersion:t,browserName:n,browserVersion:s})=>{const c=`${Se(e)} ${t}`;return`ChromeNew - ${n?`${n} ${s}, ${c}`:c}`},me=({isUnifiedSdpSemantic:e,appVersion:t,browserName:n,browserVersion:s,appName:o})=>e?de({appVersion:t,browserName:n,browserVersion:s,appName:o}):"Chrome",fe=e=>async()=>{if(e.isCallActive)return r.logger("askPermissionToEnableCam"),e.askPermissionToEnableCam()},Ce=e=>n=>(r.logger("onMustStopPresentation"),e.onSession("mustStopPresentation",n)),Ee=e=>n=>(r.logger("onMoveToSpectators"),e.onSession("participant:move-request-to-spectators",n)),Re=e=>n=>(r.logger("onUseLicense"),e.onSession("useLicense",n)),Me=e=>async({isEnabledCam:n,isEnabledMic:s})=>{if(e.isCallActive)return r.logger("sendMediaState"),e.sendMediaState({cam:n,mic:s})},Te=e=>async()=>{if(e.isCallActive)return r.logger("sendRefusalToTurnOnCam"),e.sendRefusalToTurnOnCam().catch(n=>{r.logger("sendRefusalToTurnOnCam: error",n)})},ye=e=>async()=>{if(e.isCallActive)return r.logger("sendRefusalToTurnOnMic"),e.sendRefusalToTurnOnMic().catch(n=>{r.logger("sendRefusalToTurnOnMic: error",n)})},be=e=>async({mediaStream:n,isP2P:s,maxBitrate:o,degradationPreference:c,contentHint:a},i)=>(r.logger("startPresentation"),e.startPresentation(n,{isP2P:s,maxBitrate:o,degradationPreference:c,contentHint:a},i)),_e=e=>async({isP2P:n=!1}={})=>(r.logger("stopShareSipConnector"),e.stopPresentation({isP2P:n}).catch(s=>{r.logger(s)})),he=e=>async({mediaStream:n,isP2P:s,maxBitrate:o,degradationPreference:c,contentHint:a})=>(r.logger("updatePresentation"),e.updatePresentation(n,{isP2P:s,maxBitrate:o,degradationPreference:c,contentHint:a})),ve=e=>t=>[...t].map(s=>async()=>e(s)),Oe=async({accumulatedKeys:e,sendKey:t,canRunTask:n})=>{const o=ve(t)(e);return J.sequentPromises(o,n)},pe=e=>n=>(r.logger("onStartMainCam"),e.onSession("admin-start-main-cam",n)),Ae=e=>n=>(r.logger("onStartMic"),e.onSession("admin-start-mic",n)),Ne=e=>n=>(r.logger("onStopMainCam"),e.onSession("admin-stop-main-cam",n)),Pe=e=>n=>(r.logger("onStopMic"),e.onSession("admin-stop-mic",n)),Be=({sipConnector:e})=>{const t=(f,R)=>({isSyncForced:M=!1})=>{if(M){f();return}R()},n=pe(e),s=Ne(e),o=Ae(e),c=Pe(e);let a=()=>{},i=()=>{},l=()=>{},d=()=>{};const m=({onStartMainCamForced:f,onStartMainCamNotForced:R,onStopMainCamForced:M,onStopMainCamNotForced:_,onStartMicForced:h,onStartMicNotForced:v,onStopMicForced:T,onStopMicNotForced:y})=>{const N=t(f,R);a=n(N);const b=t(M,_);i=s(b);const O=t(h,v);l=o(O);const p=t(T,y);d=c(p)},S=()=>{a(),i(),l(),d()};return{start:f=>{m(f)},stop:()=>{S()}}},De=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:V,createSyncMediaState:Be,error:ie,getExtraHeaders:ue,getUserAgent:me,hasPurgatory:A,resolveAnswerIncomingCall:ne,resolveAskPermissionToEnableCam:fe,resolveCallToServer:te,resolveConnectToServer:re,resolveDisconnectFromServer:se,resolveGetRemoteStreams:I,resolveOnMoveToSpectators:Ee,resolveOnMustStopPresentation:Ce,resolveOnUseLicense:Re,resolveSendMediaState:Me,resolveSendRefusalToTurnOnCam:Te,resolveSendRefusalToTurnOnMic:ye,resolveStartPresentation:be,resolveStopShareSipConnector:_e,resolveUpdatePresentation:he,resolveUpdateRemoteStreams:w,sendDTMFAccumulated:Oe},Symbol.toStringTag,{value:"Module"})),Ie=e=>[...e.keys()].map(t=>e.get(t)),we=(e,t)=>Ie(e).find(n=>n.type===t),q=async e=>e.getStats().then(t=>{const n=we(t,"codec");return n==null?void 0:n.mimeType}),Fe=e=>e.find(t=>{var n;return((n=t==null?void 0:t.track)==null?void 0:n.kind)==="video"}),X=(e,t)=>e!==void 0&&t!==void 0&&e.toLowerCase().includes(t.toLowerCase()),ke=1e6,E=e=>e*ke,H=E(.06),Ue=E(4),Le=e=>e<=64?H:e<=128?E(.12):e<=256?E(.25):e<=384?E(.32):e<=426?E(.38):e<=640?E(.5):e<=848?E(.7):e<=1280?E(1):e<=1920?E(2):Ue,Ve="av1",xe=e=>X(e,Ve),$e=.6,W=(e,t)=>xe(t)?e*$e:e,qe=e=>W(H,e),j=(e,t)=>{const n=Le(e);return W(n,t)},G=Q.createStackPromises(),Xe=async()=>G().catch(e=>{r.logger("videoSendingBalancer: error",e)}),He=async e=>(G.add(e),Xe()),k=async({sender:e,scaleResolutionDownBy:t,maxBitrate:n,onSetParameters:s})=>He(async()=>r.setEncodingsToSender(e,{scaleResolutionDownBy:t,maxBitrate:n},s)),We=async({sender:e,codec:t},n)=>{const o=qe(t);return k({sender:e,maxBitrate:o,onSetParameters:n,scaleResolutionDownBy:200})},D=async({sender:e,track:t,codec:n},s)=>{const a=t.getSettings().width,i=j(a,n);return k({sender:e,maxBitrate:i,onSetParameters:s,scaleResolutionDownBy:1})},je=async({sender:e,track:t,resolution:n,codec:s},o)=>{const c=t.getSettings(),a=c.width,i=c.height,[l,d]=n.split("x"),m=a/Number(l),S=i/Number(d),C=Math.max(m,S,1),f=j(Number(l),s);return k({sender:e,maxBitrate:f,onSetParameters:o,scaleResolutionDownBy:C})},Ge=async({mainCam:e,resolutionMainCam:t,sender:n,track:s,codec:o},c)=>{switch(e){case r.EEventsMainCAM.PAUSE_MAIN_CAM:return We({sender:n,codec:o},c);case r.EEventsMainCAM.RESUME_MAIN_CAM:return D({sender:n,track:s,codec:o},c);case r.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return t!==void 0?je({sender:n,track:s,codec:o,resolution:t},c):D({sender:n,track:s,codec:o},c);default:return D({sender:n,track:s,codec:o},c)}},U={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},L=async({mainCam:e,resolutionMainCam:t,connection:n,onSetParameters:s,ignoreForCodec:o})=>{const c=n.getSenders(),a=Fe(c);if(!(a!=null&&a.track))return U;const i=await q(a);return X(i,o)?U:Ge({mainCam:e,resolutionMainCam:t,sender:a,codec:i,track:a.track},s)},Ke=(e,{ignoreForCodec:t,onSetParameters:n}={})=>{const s=async()=>{const{connection:l}=e;if(!l)throw new Error("connection is not exist");return L({connection:l,onSetParameters:n,ignoreForCodec:t})};let o=s;const c=async l=>(o=async()=>{const{mainCam:d,resolutionMainCam:m}=l,{connection:S}=e;if(!S)throw new Error("connection is not exist");return L({mainCam:d,resolutionMainCam:m,connection:S,onSetParameters:n,ignoreForCodec:t})},o());return{subscribe:()=>{e.onSession("main-cam-control",c)},unsubscribe:()=>{e.offSession("main-cam-control",c)},balanceByTrack:s,resetMainCamControl(){o=s},async reBalance(){return o()}}};exports.EEventsMainCAM=r.EEventsMainCAM;exports.EEventsMic=r.EEventsMic;exports.EEventsSyncMediaState=r.EEventsSyncMediaState;exports.EUseLicense=r.EUseLicense;exports.causes=r.causes;exports.constants=r.constants;exports.default=r.SipConnector;exports.disableDebug=r.disableDebug;exports.enableDebug=r.enableDebug;exports.eventNames=r.eventNames;exports.hasCanceledCallError=r.hasCanceledCallError;exports.debug=Z;exports.getCodecFromSender=q;exports.resolveVideoSendingBalancer=Ke;exports.tools=De;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { l as o, B as x, N as $, E as B, s as z, S as Je } from "./SipConnector-xflR79mb.js";
2
- import { f as cn, g as un, i as ln, c as Sn, a as mn, d as dn, b as fn, e as Cn, h as gn } from "./SipConnector-xflR79mb.js";
1
+ import { l as o, B as x, N as $, E as B, s as z, S as Je } from "./SipConnector-7Qar6pDS.js";
2
+ import { f as cn, g as un, i as ln, c as Sn, a as mn, d as dn, b as fn, e as Cn, h as gn } from "./SipConnector-7Qar6pDS.js";
3
3
  import { debounce as J } from "ts-debounce";
4
4
  import { isCanceledError as Q } from "@krivega/cancelable-promise";
5
5
  import { hasCanceledError as Z } from "repeated-calls";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sip-connector",
3
- "version": "9.2.0",
3
+ "version": "9.2.1",
4
4
  "description": "Module for connect to Vinteo server",
5
5
  "keywords": [
6
6
  "webrtc",
@@ -66,19 +66,19 @@
66
66
  "@krivega/jssip": "^3.24.3",
67
67
  "debug": "^4.3.7",
68
68
  "events-constructor": "^1.2.3",
69
- "repeated-calls": "^2.2.1",
69
+ "repeated-calls": "^2.3.0",
70
70
  "sequent-promises": "^2.0.1",
71
71
  "stack-promises": "^2.0.2",
72
72
  "ts-debounce": "^4.0.0",
73
73
  "webrtc-mock": "^1.1.6"
74
74
  },
75
75
  "devDependencies": {
76
- "@babel/preset-typescript": "^7.24.7",
76
+ "@babel/preset-typescript": "^7.25.7",
77
77
  "@commitlint/cli": "^19.5.0",
78
78
  "@commitlint/config-conventional": "^19.5.0",
79
79
  "@nabla/vite-plugin-eslint": "^2.0.4",
80
80
  "@types/debug": "^4.1.12",
81
- "@types/dom-mediacapture-transform": "^0.1.9",
81
+ "@types/dom-mediacapture-transform": "^0.1.10",
82
82
  "@types/jest": "^29.5.13",
83
83
  "@typescript-eslint/eslint-plugin": "^7.15.0",
84
84
  "@typescript-eslint/parser": "^7.15.0",
@@ -89,10 +89,10 @@
89
89
  "eslint-config-prettier": "^9.1.0",
90
90
  "eslint-import-resolver-typescript": "^3.6.3",
91
91
  "eslint-plugin-flowtype": "^8.0.3",
92
- "eslint-plugin-import": "^2.30.0",
92
+ "eslint-plugin-import": "^2.31.0",
93
93
  "eslint-plugin-jest": "^28.8.3",
94
94
  "eslint-plugin-prettier": "^5.2.1",
95
- "eslint-plugin-unicorn": "^55.0.0",
95
+ "eslint-plugin-unicorn": "^56.0.0",
96
96
  "husky": "^9.1.6",
97
97
  "jest": "^29.7.0",
98
98
  "jest-environment-jsdom": "^29.7.0",
@@ -104,9 +104,9 @@
104
104
  "ts-jest": "^29.2.5",
105
105
  "ts-node": "^10.9.2",
106
106
  "tsc-files": "^1.1.4",
107
- "typescript": "^5.6.2",
108
- "vite": "^5.4.7",
109
- "vite-plugin-dts": "^4.2.2",
107
+ "typescript": "^5.6.3",
108
+ "vite": "^5.4.8",
109
+ "vite-plugin-dts": "^4.2.3",
110
110
  "vite-tsconfig-paths": "^5.0.1"
111
111
  },
112
112
  "peerDependencies": {
@@ -1 +0,0 @@
1
- "use strict";var pt=Object.defineProperty;var Pt=(r,e,t)=>e in r?pt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var i=(r,e,t)=>Pt(r,typeof e!="symbol"?e+"":e,t);const N=require("@krivega/cancelable-promise"),ve=require("events-constructor"),be=require("repeated-calls"),V=require("debug"),Ot="Connection Error",qe="Request Timeout",ft="SIP Failure Code",Dt="Internal Error",Mt="Busy",Y="Rejected",vt="Redirected",bt="Unavailable",ke="Not Found",yt="Address Incomplete",wt="Incompatible SDP",Ut="Missing SDP",Lt="Authentication Error",Fe="Terminated",Ht="WebRTC Error",Be="Canceled",Wt="No Answer",qt="Expires",kt="No ACK",Ft="Dialog Error",Bt="User Denied Media Access",Ve="Bad Media Description",Vt="RTP Timeout",Yt=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:yt,AUTHENTICATION_ERROR:Lt,BAD_MEDIA_DESCRIPTION:Ve,BUSY:Mt,BYE:Fe,CANCELED:Be,CONNECTION_ERROR:Ot,DIALOG_ERROR:Ft,EXPIRES:qt,INCOMPATIBLE_SDP:wt,INTERNAL_ERROR:Dt,MISSING_SDP:Ut,NOT_FOUND:ke,NO_ACK:kt,NO_ANSWER:Wt,REDIRECTED:vt,REJECTED:Y,REQUEST_TIMEOUT:qe,RTP_TIMEOUT:Vt,SIP_FAILURE_CODE:ft,UNAVAILABLE:bt,USER_DENIED_MEDIA_ACCESS:Bt,WEBRTC_ERROR:Ht},Symbol.toStringTag,{value:"Module"})),x="incomingCall",G="declinedIncomingCall",$="failedIncomingCall",X="terminatedIncomingCall",k="connecting",m="connected",S="disconnected",v="newRTCSession",p="registered",J="unregistered",P="registrationFailed",Ye="newMessage",z="sipEvent",Q="availableSecondRemoteStream",j="notAvailableSecondRemoteStream",K="mustStopPresentation",b="shareState",Z="enterRoom",ee="useLicense",te="peerconnection:confirmed",ne="peerconnection:ontrack",y="channels",se="channels:notify",ie="ended:fromserver",re="main-cam-control",oe="admin-stop-main-cam",ae="admin-start-main-cam",ce="admin-stop-mic",_e="admin-start-mic",w="admin-force-sync-media-state",Ee="participant:added-to-list-moderators",le="participant:removed-from-list-moderators",he="participant:move-request-to-stream",de="participant:move-request-to-spectators",Te="participation:accepting-word-request",ue="participation:cancelling-word-request",Se="webcast:started",Ce="webcast:stopped",Ne="account:changed",ge="account:deleted",Ae="conference:participant-token-issued",O="ended",xe="sending",Ge="reinvite",$e="replaces",Xe="refer",Je="progress",ze="accepted",U="confirmed",L="peerconnection",A="failed",Qe="muted",je="unmuted",Re="newDTMF",Ie="newInfo",Ke="hold",Ze="unhold",et="update",tt="sdp",nt="icecandidate",st="getusermediafailed",it="peerconnection:createofferfailed",rt="peerconnection:createanswerfailed",ot="peerconnection:setlocaldescriptionfailed",at="peerconnection:setremotedescriptionfailed",ct="presentation:start",_t="presentation:started",Et="presentation:end",me="presentation:ended",H="presentation:failed",lt="SPECTATOR",ht=1e6,xt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:ze,ACCOUNT_CHANGED:Ne,ACCOUNT_DELETED:ge,ADMIN_FORCE_SYNC_MEDIA_STATE:w,ADMIN_START_MAIN_CAM:ae,ADMIN_START_MIC:_e,ADMIN_STOP_MAIN_CAM:oe,ADMIN_STOP_MIC:ce,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:Q,CHANNELS:y,CHANNELS_NOTIFY:se,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Ae,CONFIRMED:U,CONNECTED:m,CONNECTING:k,DECLINED_INCOMING_CALL:G,DISCONNECTED:S,ENDED:O,ENDED_FROM_SERVER:ie,ENTER_ROOM:Z,FAILED:A,FAILED_INCOMING_CALL:$,GET_USER_MEDIA_FAILED:st,HOLD:Ke,ICE_CANDIDATE:nt,INCOMING_CALL:x,MAIN_CAM_CONTROL:re,MUST_STOP_PRESENTATION_EVENT:K,MUTED:Qe,NEW_DTMF:Re,NEW_INFO:Ie,NEW_MESSAGE:Ye,NEW_RTC_SESSION:v,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:j,ONE_MEGABIT_IN_BITS:ht,PARTICIPANT_ADDED_TO_LIST_MODERATORS:Ee,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:de,PARTICIPANT_MOVE_REQUEST_TO_STREAM:he,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:le,PARTICIPATION_ACCEPTING_WORD_REQUEST:Te,PARTICIPATION_CANCELLING_WORD_REQUEST:ue,PEER_CONNECTION:L,PEER_CONNECTION_CONFIRMED:te,PEER_CONNECTION_CREATE_ANSWER_FAILED:rt,PEER_CONNECTION_CREATE_OFFER_FAILED:it,PEER_CONNECTION_ONTRACK:ne,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:ot,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:at,PRESENTATION_END:Et,PRESENTATION_ENDED:me,PRESENTATION_FAILED:H,PRESENTATION_START:ct,PRESENTATION_STARTED:_t,PROGRESS:Je,REFER:Xe,REGISTERED:p,REGISTRATION_FAILED:P,REINVITE:Ge,REPLACES:$e,SDP:tt,SENDING:xe,SHARE_STATE:b,SIP_EVENT:z,SPECTATOR:lt,TERMINATED_INCOMING_CALL:X,UNHOLD:Ze,UNMUTED:je,UNREGISTERED:J,UPDATE:et,USE_LICENSE:ee,WEBCAST_STARTED:Se,WEBCAST_STOPPED:Ce},Symbol.toStringTag,{value:"Module"})),dt=[x,G,X,$,Te,ue,he,se,Ae,Ne,ge,Se,Ce,Ee,le],pe=[k,m,S,v,p,J,P,Ye,z],Tt=[Q,j,K,b,Z,ee,te,ne,y,ie,re,ae,oe,ce,_e,w,de],Pe=[O,k,xe,Ge,$e,Xe,Je,ze,U,L,A,Qe,je,Re,Ie,Ke,Ze,et,tt,nt,st,it,rt,ot,at,ct,_t,Et,me,H],Oe=[...pe,...dt],fe=[...Pe,...Tt],Gt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:fe,SESSION_JSSIP_EVENT_NAMES:Pe,SESSION_SYNTHETICS_EVENT_NAMES:Tt,UA_EVENT_NAMES:Oe,UA_JSSIP_EVENT_NAMES:pe,UA_SYNTHETICS_EVENT_NAMES:dt},Symbol.toStringTag,{value:"Module"})),$t=r=>{const e=[];return r&&e.push(`X-Vinteo-Remote: ${r}`),e},Xt="content-type",Jt="x-webrtc-enter-room",f="application/vinteo.webrtc.sharedesktop",zt="application/vinteo.webrtc.roomname",Qt="application/vinteo.webrtc.channels",jt="application/vinteo.webrtc.mediastate",Kt="application/vinteo.webrtc.refusal",ye="application/vinteo.webrtc.maincam",Zt="application/vinteo.webrtc.mic",en="application/vinteo.webrtc.uselic",tn="X-WEBRTC-USE-LICENSE",nn="X-WEBRTC-PARTICIPANT-NAME",we="X-WEBRTC-INPUT-CHANNELS",Ue="X-WEBRTC-OUTPUT-CHANNELS",sn="X-WEBRTC-MAINCAM",rn="X-WEBRTC-MIC",Le="X-WEBRTC-SYNC",on="X-WEBRTC-MAINCAM-RESOLUTION",an="X-WEBRTC-MEDIA-STATE",cn="X-Vinteo-Media-Type",_n="X-Vinteo-MainCam-State",En="X-Vinteo-Mic-State",ln="application/vinteo.webrtc.partstate",hn="X-WEBRTC-PARTSTATE",dn="application/vinteo.webrtc.notify",Tn="X-VINTEO-NOTIFY",I="x-webrtc-share-state",un=`${I}: LETMESTARTPRESENTATION`,Sn=`${I}: STOPPRESENTATION`,ut="YOUCANRECEIVECONTENT",St="CONTENTEND",Ct="YOUMUSTSTOPSENDCONTENT",Cn=`${I}: ${Ct}`,Nn=`${I}: ${ut}`,gn=`${I}: ${St}`,An="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Rn=`${An}: LETMESTARTMAINCAM`,De="sip-connector",M=V(De),In=()=>{V.enable(De)},mn=()=>{V.enable(`-${De}`)},pn=(r,e)=>{r.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},D=(r,{videoMode:e,audioMode:t,contentHint:n}={})=>{if(!r||e==="recvonly"&&t==="recvonly")return;const s=t==="recvonly"?[]:r.getAudioTracks(),o=e==="recvonly"?[]:r.getVideoTracks(),a=[...s,...o],c=new MediaStream(a);return c.getTracks=()=>[...c.getAudioTracks(),...c.getVideoTracks()],n&&n!=="none"&&pn(c,n),c};var R=(r=>(r.PAUSE_MAIN_CAM="PAUSEMAINCAM",r.RESUME_MAIN_CAM="RESUMEMAINCAM",r.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",r.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",r.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",r))(R||{}),W=(r=>(r.ADMIN_STOP_MIC="ADMINSTOPMIC",r.ADMIN_START_MIC="ADMINSTARTMIC",r))(W||{}),q=(r=>(r.ADMIN_SYNC_FORCED="1",r.ADMIN_SYNC_NOT_FORCED="0",r))(q||{}),Nt=(r=>(r.AUDIO="AUDIO",r.VIDEO="VIDEO",r.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",r))(Nt||{});function Pn(r){return e=>`sip:${e}@${r}`}const On=(r,e)=>()=>Math.floor(Math.random()*(e-r))+r,He=r=>r.trim().replaceAll(" ","_"),fn=On(1e5,99999999),Dn=r=>r.some(t=>{const{kind:n}=t;return n==="video"}),Mn="Error decline with 603",vn=1006,bn=r=>typeof r=="object"&&r!==null&&"code"in r&&r.code===vn,yn=r=>r.message===Mn,wn=(r,e)=>r.find(t=>t.track&&e.getTracks().includes(t.track)),gt=1,At=r=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==r,Un=At(gt),Ln=(r,e)=>{const t=r===void 0?void 0:Math.max(r,gt);if(t!==void 0&&Un(t,e))return t},Hn=At(),Wn=(r,e)=>{if(Hn(r,e))return r},Rt=async(r,e,t)=>{const n=r.getParameters();(n.encodings===void 0||n.encodings.length===0)&&(n.encodings=[{}]);const[s]=n.encodings,o=s.scaleResolutionDownBy,a=Ln(e.scaleResolutionDownBy,o);let c=!1;a!==void 0&&(n.encodings[0].scaleResolutionDownBy=a,c=!0);const _=s.maxBitrate,E=Wn(e.maxBitrate,_);return E!==void 0&&(n.encodings[0].maxBitrate=E,c=!0),c?(t&&t(n),r.setParameters(n).then(()=>({parameters:n,isChanged:c}))):{parameters:n,isChanged:c}},qn=async(r,e,t)=>{const n=wn(r,e);if(n)return Rt(n,{maxBitrate:t})},kn=486,Fn=487,B="local",We="remote",Bn=3,Vn=1,Yn=(r=new Error)=>{const{originator:e,cause:t}=r;return N.isCanceledError(r)?!0:typeof t=="string"?t===qe||t===Y||e===B&&(t===Be||t===Fe):!1},g="SipConnector",xn="channels",Gn="WebcastStarted",$n="WebcastStopped",Xn="accountChanged",Jn="accountDeleted",zn="addedToListModerators",Qn="removedFromListModerators",jn="ParticipationRequestAccepted",Kn="ParticipationRequestRejected",Zn="ParticipantMovedToWebcast",es="ConferenceParticipantTokenIssued";class ts{constructor({JsSIP:e}){i(this,"_isRegisterConfig",!1);i(this,"_connectionConfiguration",{});i(this,"_remoteStreams",{});i(this,"JsSIP");i(this,"_sessionEvents");i(this,"_uaEvents");i(this,"_cancelableConnect");i(this,"_cancelableConnectWithRepeatedCalls");i(this,"_cancelableSendPresentationWithRepeatedCalls");i(this,"_cancelableInitUa");i(this,"_cancelableDisconnect");i(this,"_cancelableSet");i(this,"_cancelableCall");i(this,"_cancelableAnswer");i(this,"_cancelableSendDTMF");i(this,"getSipServerUrl",e=>e);i(this,"promisePendingStartPresentation");i(this,"promisePendingStopPresentation");i(this,"ua");i(this,"session");i(this,"incomingSession");i(this,"_streamPresentationCurrent");i(this,"socket");i(this,"connect",async(e,t)=>(this._cancelRequests(),this._connectWithDuplicatedCalls(e,t)));i(this,"initUa",async e=>this._cancelableInitUa.request(e));i(this,"set",async e=>this._cancelableSet.request(e));i(this,"call",async e=>this._cancelableCall.request(e));i(this,"disconnect",async()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()));i(this,"answerToIncomingCall",async e=>this._cancelableAnswer.request(e));i(this,"sendDTMF",async e=>this._cancelableSendDTMF.request(e));i(this,"hangUp",async()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()));i(this,"tryRegister",async()=>{if(!this.isRegisterConfig)throw new Error("Config is not registered");this._uaEvents.trigger(k,void 0);try{await this.unregister()}catch(e){M("tryRegister",e)}return this.register()});i(this,"declineToIncomingCall",async({statusCode:e=Fn}={})=>new Promise((t,n)=>{if(!this.isAvailableIncomingCall){n(new Error("no incomingSession"));return}const s=this.incomingSession,o=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(G,o),t(s.terminate({status_code:e}))}));i(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:kn}));i(this,"removeIncomingSession",()=>{delete this.incomingSession});i(this,"_connectWithDuplicatedCalls",async(e,{callLimit:t=Bn}={})=>{let n=!0;const s=async()=>(n=!1,this._cancelableConnect.request(e)),o=a=>{var l;const c=!!((l=this.ua)!=null&&l.isConnected()),_=!n&&c&&this.hasEqualConnectionConfiguration(e),E=!!a&&!bn(a);return _||E};return this._cancelableConnectWithRepeatedCalls=be.repeatedCallsAsync({targetFunction:s,isComplete:o,callLimit:t,isRejectAsValid:!0,onAfterCancel:()=>{this._cancelableConnect.cancelRequest()}}),this._cancelableConnectWithRepeatedCalls.then(a=>{if(a instanceof this.JsSIP.UA)return a;throw a})});i(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===We){this.incomingSession=t;const n=this.remoteCallerData;t.on(A,s=>{this.removeIncomingSession(),s.originator===B?this._uaEvents.trigger(X,n):this._uaEvents.trigger($,n)}),this._uaEvents.trigger(x,n)}});i(this,"_connect",async e=>this.initUa(e).then(async()=>this._start()));i(this,"_initUa",async({user:e,password:t,sipServerUrl:n,sipWebSocketServerURL:s,remoteAddress:o,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:_,connectionRecoveryMaxInterval:E,userAgent:l,displayName:h="",register:d=!1,extraHeaders:T=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!s)throw new Error("sipWebSocketServerURL is required");if(d&&!e)throw new Error("user is required for authorized connection");if(d&&!t)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:n,displayName:h,register:d,user:e,password:t};const{configuration:C,helpers:u}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:s,password:t,displayName:h,register:d,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:_,connectionRecoveryMaxInterval:E,userAgent:l});return this.getSipServerUrl=u.getSipServerUrl,this.socket=u.socket,this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!d,this.ua=this._createUa({...C,remoteAddress:o,extraHeaders:T}),this._uaEvents.eachTriggers((F,It)=>{const Me=pe.find(mt=>mt===It);Me&&this.ua&&this.ua.on(Me,F)}),this.ua});i(this,"_createUa",({remoteAddress:e,extraHeaders:t=[],...n})=>{const s=new this.JsSIP.UA(n),a=[...e?$t(e):[],...t];return a.length>0&&s.registrator().setExtraHeaders(a),s});i(this,"_start",async()=>new Promise((e,t)=>{const{ua:n}=this;if(!n){t(new Error("this.ua is not initialized"));return}const s=()=>{c(),e(n)},o=_=>{c(),t(_)},a=()=>{this.isRegisterConfig?(this.on(p,s),this.on(P,o)):this.on(m,s),this.on(S,o)},c=()=>{this.off(p,s),this.off(P,o),this.off(m,s),this.off(S,o)};a(),this.on(v,this.handleNewRTCSession),n.start()}));i(this,"_set",async({displayName:e,password:t})=>new Promise((n,s)=>{const{ua:o}=this;if(!o){s(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",He(e)),this._connectionConfiguration.displayName=e),t!==void 0&&t!==this._connectionConfiguration.password&&(c=o.set("password",t),this._connectionConfiguration.password=t);const _=a||c;c&&this.isRegisterConfig?this.register().then(()=>{n(_)}).catch(E=>{s(E)}):_?n(_):s(new Error("nothing changed"))}));i(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());i(this,"_disconnect",async()=>{this.off(v,this.handleNewRTCSession);const e=new Promise(t=>{this.once(S,()=>{delete this.ua,t()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(S,void 0)):this._uaEvents.trigger(S,void 0),e});i(this,"_call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:s,iceServers:o,videoMode:a,audioMode:c,degradationPreference:_,contentHint:E,offerToReceiveAudio:l=!0,offerToReceiveVideo:h=!0})=>new Promise((d,T)=>{const{ua:C}=this;if(!C){T(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:s}).then(d).catch(u=>{T(u)}),this.session=C.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:D(t,{videoMode:a,audioMode:c,contentHint:E}),eventHandlers:this._sessionEvents.triggers,videoMode:a,audioMode:c,degradationPreference:_,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:l,offerToReceiveVideo:h}})}));i(this,"_answer",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:s,videoMode:o,audioMode:a,degradationPreference:c,contentHint:_})=>new Promise((E,l)=>{if(!this.isAvailableIncomingCall){l(new Error("no incomingSession"));return}this.session=this.incomingSession,this.removeIncomingSession();const{session:h}=this;if(!h){l(new Error("No session established"));return}this._sessionEvents.eachTriggers((T,C)=>{const u=Pe.find(F=>F===C);u&&h.on(u,T)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=h.remote_identity.uri.user,this._handleCall({ontrack:t}).then(E).catch(T=>{l(T)});const d=D(e,{videoMode:o,audioMode:a,contentHint:_});h.answer({extraHeaders:n,videoMode:o,audioMode:a,degradationPreference:c,mediaStream:d,pcConfig:{iceServers:s}})}));i(this,"_handleCall",async({ontrack:e})=>new Promise((t,n)=>{const s=()=>{this.onSession(L,l),this.onSession(U,h)},o=()=>{this.offSession(L,l),this.offSession(U,h)},a=()=>{this.onSession(A,_),this.onSession(O,_)},c=()=>{this.offSession(A,_),this.offSession(O,_)},_=d=>{o(),c(),n(d)};let E;const l=({peerconnection:d})=>{E=d,E.ontrack=T=>{this._sessionEvents.trigger(ne,E),e&&e(T)}},h=()=>{E&&this._sessionEvents.trigger(te,E),o(),c(),t(E)};s(),a()}));i(this,"_restoreSession",()=>{this._cancelRequestsAndResetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}});i(this,"_sendDTMF",async e=>new Promise((t,n)=>{const{session:s}=this;if(!s){n(new Error("No session established"));return}this.onceSession(Re,({originator:o})=>{o===B&&t()}),s.sendDTMF(e,{duration:120,interToneGap:600})}));i(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.session){const{session:e}=this;if(this._streamPresentationCurrent)try{await this.stopPresentation()}catch(t){M("error stop presentation: ",t)}if(this._restoreSession(),!e.isEnded())return e.terminateAsync()}});i(this,"_handleShareState",e=>{switch(e){case ut:{this._sessionEvents.trigger(Q,void 0);break}case St:{this._sessionEvents.trigger(j,void 0);break}case Ct:{this._sessionEvents.trigger(K,void 0);break}}});i(this,"_maybeTriggerChannels",e=>{const t=e.getHeader(we),n=e.getHeader(Ue);if(t&&n){const s={inputChannels:t,outputChannels:n};this._sessionEvents.trigger(y,s)}});i(this,"_handleNotify",e=>{switch(e.cmd){case xn:{const t=e;this._triggerChannelsNotify(t);break}case Gn:{const t=e;this._triggerWebcastStartedNotify(t);break}case $n:{const t=e;this._triggerWebcastStoppedNotify(t);break}case zn:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case Qn:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case jn:{const t=e;this._triggerParticipationAcceptingWordRequest(t);break}case Kn:{const t=e;this._triggerParticipationCancellingWordRequest(t);break}case Zn:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case Xn:{this._triggerAccountChangedNotify();break}case Jn:{this._triggerAccountDeletedNotify();break}case es:{const t=e;this._triggerConferenceParticipantTokenIssued(t);break}default:M("unknown cmd",e.cmd)}});i(this,"_triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(le,t)});i(this,"_triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(Ee,t)});i(this,"_triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Se,n)});i(this,"_triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Ce,n)});i(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(Ne,void 0)});i(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(ge,void 0)});i(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const s={conference:e,participant:t,jwt:n};this._uaEvents.trigger(Ae,s)});i(this,"_triggerChannelsNotify",e=>{const t=e.input,n=e.output,s={inputChannels:t,outputChannels:n};this._uaEvents.trigger(se,s)});i(this,"_triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Te,t)});i(this,"_triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ue,t)});i(this,"_triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(he,t)});i(this,"_triggerEnterRoom",e=>{const t=e.getHeader(Jt),n=e.getHeader(nn);this._sessionEvents.trigger(Z,{room:t,participantName:n})});i(this,"_triggerShareState",e=>{const t=e.getHeader(I);this._sessionEvents.trigger(b,t)});i(this,"_maybeTriggerParticipantMoveRequestToSpectators",e=>{e.getHeader(hn)===lt&&this._sessionEvents.trigger(de,void 0)});i(this,"_triggerMainCamControl",e=>{const t=e.getHeader(sn),n=e.getHeader(Le),s=n===q.ADMIN_SYNC_FORCED;if(t===R.ADMIN_START_MAIN_CAM){this._sessionEvents.trigger(ae,{isSyncForced:s});return}if(t===R.ADMIN_STOP_MAIN_CAM){this._sessionEvents.trigger(oe,{isSyncForced:s});return}(t===R.RESUME_MAIN_CAM||t===R.PAUSE_MAIN_CAM)&&n&&this._sessionEvents.trigger(w,{isSyncForced:s});const o=e.getHeader(on);this._sessionEvents.trigger(re,{mainCam:t,resolutionMainCam:o})});i(this,"_triggerMicControl",e=>{const t=e.getHeader(rn),s=e.getHeader(Le)===q.ADMIN_SYNC_FORCED;t===W.ADMIN_START_MIC?this._sessionEvents.trigger(_e,{isSyncForced:s}):t===W.ADMIN_STOP_MIC&&this._sessionEvents.trigger(ce,{isSyncForced:s})});i(this,"_triggerUseLicense",e=>{const t=e.getHeader(tn);this._sessionEvents.trigger(ee,t)});i(this,"_handleNewInfo",e=>{const{originator:t}=e;if(t!=="remote")return;const{request:n}=e,s=n.getHeader(Xt);if(s)switch(s){case zt:{this._triggerEnterRoom(n),this._maybeTriggerChannels(n);break}case dn:{this._maybeHandleNotify(n);break}case f:{this._triggerShareState(n);break}case ye:{this._triggerMainCamControl(n);break}case Zt:{this._triggerMicControl(n);break}case en:{this._triggerUseLicense(n);break}case ln:{this._maybeTriggerParticipantMoveRequestToSpectators(n);break}}});i(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});i(this,"_maybeHandleNotify",e=>{const t=e.getHeader(Tn);if(t){const n=JSON.parse(t);this._handleNotify(n)}});i(this,"_handleEnded",e=>{const{originator:t}=e;t===We&&this._sessionEvents.trigger(ie,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new ve(fe),this._uaEvents=new ve(Oe),this._cancelableConnect=new N.CancelableRequest(this._connect,{moduleName:g,afterCancelRequest:()=>{this._cancelableInitUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableInitUa=new N.CancelableRequest(this._initUa,{moduleName:g}),this._cancelableDisconnect=new N.CancelableRequest(this._disconnect,{moduleName:g}),this._cancelableSet=new N.CancelableRequest(this._set,{moduleName:g}),this._cancelableCall=new N.CancelableRequest(this._call,{moduleName:g}),this._cancelableAnswer=new N.CancelableRequest(this._answer,{moduleName:g}),this._cancelableSendDTMF=new N.CancelableRequest(this._sendDTMF,{moduleName:g}),this.onSession(b,this._handleShareState),this.onSession(Ie,this._handleNewInfo),this.on(z,this._handleSipEvent),this.onSession(A,this._handleEnded),this.onSession(O,this._handleEnded)}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(p,e),this.ua.on(P,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(J,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((s,o)=>{try{this.ua.sendOptions(e,t,{extraHeaders:n,eventHandlers:{succeeded:()=>{s()},failed:o}})}catch(a){o(a)}})}async ping(e,t){var s;if(!((s=this.ua)!=null&&s.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:s,remoteAddress:o,extraHeaders:a}){return new Promise((c,_)=>{const{configuration:E}=this.createUaConfiguration({sipWebSocketServerURL:s,displayName:t,userAgent:e,sipServerUrl:n}),l=this._createUa({...E,remoteAddress:o,extraHeaders:a}),h=()=>{const T=new Error("Telephony is not available");_(T)};l.once(S,h);const d=()=>{l.removeAllListeners(),l.once(S,c),l.stop()};l.once(m,d),l.start()})}async replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");const{contentHint:n}=t||{},s=D(e,{contentHint:n});return this.session.replaceMediaStream(s,t)}async askPermissionToEnableCam(e={}){if(!this.session)throw new Error("No session established");const t=[Rn];return this.session.sendInfo(ye,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if(yn(n))throw n})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async _sendPresentationWithDuplicatedCalls({session:e,stream:t,presentationOptions:n,options:s={callLimit:Vn}}){const o=async()=>this._sendPresentation(e,t,n),a=()=>!!this._streamPresentationCurrent;return this._cancelableSendPresentationWithRepeatedCalls=be.repeatedCallsAsync({targetFunction:o,isComplete:a,isRejectAsValid:!0,...s}),this._cancelableSendPresentationWithRepeatedCalls.then(c=>c)}hasEqualConnectionConfiguration(e){var s;const{configuration:t}=this.createUaConfiguration(e),n=(s=this.ua)==null?void 0:s.configuration;return(n==null?void 0:n.password)===t.password&&(n==null?void 0:n.register)===t.register&&(n==null?void 0:n.uri.toString())===t.uri&&(n==null?void 0:n.display_name)===t.display_name&&(n==null?void 0:n.user_agent)===t.user_agent&&(n==null?void 0:n.sockets)===t.sockets&&(n==null?void 0:n.session_timers)===t.session_timers&&(n==null?void 0:n.register_expires)===t.register_expires&&(n==null?void 0:n.connection_recovery_min_interval)===t.connection_recovery_min_interval&&(n==null?void 0:n.connection_recovery_max_interval)===t.connection_recovery_max_interval}createUaConfiguration({user:e,password:t,sipWebSocketServerURL:n,displayName:s="",sipServerUrl:o,register:a=!1,sessionTimers:c=!1,registerExpires:_=60*5,connectionRecoveryMinInterval:E=2,connectionRecoveryMaxInterval:l=6,userAgent:h}){if(a&&!t)throw new Error("password is required for authorized connection");const d=a&&e?e.trim():`${fn()}`,T=Pn(o),C=T(d),u=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:C,display_name:He(s),user_agent:h,sdp_semantics:"unified-plan",sockets:[u],session_timers:c,register_expires:_,connection_recovery_min_interval:E,connection_recovery_max_interval:l},helpers:{socket:u,getSipServerUrl:T}}}async _sendPresentation(e,t,{maxBitrate:n=ht,degradationPreference:s="maintain-resolution",isNeedReinvite:o=!0,isP2P:a=!1,contentHint:c="detail"}){const _=D(t,{contentHint:c});this._streamPresentationCurrent=_;const E=a?[Nn]:[un],l=e.sendInfo(f,void 0,{extraHeaders:E}).then(async()=>e.startPresentation(_,o,s)).then(async()=>{const{connection:h}=this;if(!h||n===void 0)return;const d=h.getSenders();await qn(d,t,n)}).then(()=>t).catch(h=>{throw this._removeStreamPresentationCurrent(),this._sessionEvents.trigger(H,h),h});return this.promisePendingStartPresentation=l,l.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:s,degradationPreference:o,contentHint:a}={},c){const _=this.establishedSession;if(!_)throw new Error("No session established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return n&&await this.sendMustStopPresentation(_),this._sendPresentationWithDuplicatedCalls({session:_,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:s,degradationPreference:o,contentHint:a},options:c})}async sendMustStopPresentation(e){await e.sendInfo(f,void 0,{extraHeaders:[Cn]})}async stopPresentation({isP2P:e=!1}={}){this._cancelSendPresentationWithRepeatedCalls();const t=this._streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve();const s=e?[gn]:[Sn],o=this.establishedSession;return o&&t&&(n=n.then(async()=>o.sendInfo(f,void 0,{extraHeaders:s})).then(async()=>o.stopPresentation(t)).catch(a=>{throw this._sessionEvents.trigger(H,a),a})),!o&&t&&this._sessionEvents.trigger(me,t),this.promisePendingStopPresentation=n,n.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,degradationPreference:s,contentHint:o}={}){const a=this.establishedSession;if(!a)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(a,e,{isP2P:t,maxBitrate:n,degradationPreference:s,contentHint:o,isNeedReinvite:!1})}_removeStreamPresentationCurrent(){delete this._streamPresentationCurrent}_resetPresentation(){this._removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}_cancelRequestsAndResetPresentation(){this._cancelSendPresentationWithRepeatedCalls(),this._resetPresentation()}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)}get connection(){var t;return(t=this.session)==null?void 0:t.connection}get remoteCallerData(){var e,t,n,s,o,a;return{displayName:(t=(e=this.incomingSession)==null?void 0:e.remote_identity)==null?void 0:t.display_name,host:(s=(n=this.incomingSession)==null?void 0:n.remote_identity)==null?void 0:s.uri.host,incomingNumber:(a=(o=this.incomingSession)==null?void 0:o.remote_identity)==null?void 0:a.uri.user,session:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableInitUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){var e;return(e=this.session)!=null&&e.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}_generateStream(e,t){const{id:n}=e,s=this._remoteStreams[n]||new MediaStream;return t&&s.addTrack(t),s.addTrack(e),this._remoteStreams[n]=s,s}_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,s)=>{if(n.kind==="audio")return;const o=n,a=e[s-1];let c;a&&a.kind==="audio"&&(c=a);const _=this._generateStream(o,c);t.push(_)}),t}_generateAudioStreams(e){return e.map(n=>this._generateAudioStream(n))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectWithRepeatedCalls()}_cancelConnectWithRepeatedCalls(){var e;(e=this._cancelableConnectWithRepeatedCalls)==null||e.cancel()}_cancelSendPresentationWithRepeatedCalls(){var e;(e=this._cancelableSendPresentationWithRepeatedCalls)==null||e.cancel()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}async waitChannels(){return this.waitSession(y)}async waitSyncMediaState(){return this.waitSession(w)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const n=`${we}: ${e}`,s=`${Ue}: ${t}`,o=[n,s];return this.session.sendInfo(Qt,void 0,{extraHeaders:o})}async sendMediaState({cam:e,mic:t},n={}){if(!this.session)throw new Error("No session established");const s=`${an}: currentstate`,o=`${_n}: ${Number(e)}`,a=`${En}: ${Number(t)}`,c=[s,o,a];return this.session.sendInfo(jt,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async _sendRefusalToTurnOn(e,t={}){if(!this.session)throw new Error("No session established");const c=[`${cn}: ${e==="mic"?0:1}`];return this.session.sendInfo(Kt,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}}exports.BAD_MEDIA_DESCRIPTION=Ve;exports.EEventsMainCAM=R;exports.EEventsMic=W;exports.EEventsSyncMediaState=q;exports.EUseLicense=Nt;exports.NOT_FOUND=ke;exports.REJECTED=Y;exports.SESSION_EVENT_NAMES=fe;exports.SipConnector=ts;exports.UA_EVENT_NAMES=Oe;exports.causes=Yt;exports.constants=xt;exports.disableDebug=mn;exports.enableDebug=In;exports.eventNames=Gt;exports.hasCanceledCallError=Yn;exports.logger=M;exports.setEncodingsToSender=Rt;