sip-connector 17.0.0 → 19.0.0

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.
Files changed (50) hide show
  1. package/README.md +123 -29
  2. package/dist/@SipConnector-DNQcZdY9.cjs +1 -0
  3. package/dist/{@SipConnector-DADbRZIb.js → @SipConnector-Wp8bjnnP.js} +1417 -1072
  4. package/dist/ApiManager/__tests-utils__/helpers.d.ts +2 -4
  5. package/dist/ApiManager/constants.d.ts +1 -2
  6. package/dist/ApiManager/eventNames.d.ts +1 -2
  7. package/dist/AutoConnectorManager/@AutoConnectorManager.d.ts +41 -0
  8. package/dist/AutoConnectorManager/AttemptsState.d.ts +21 -0
  9. package/dist/AutoConnectorManager/CheckTelephonyRequester.d.ts +19 -0
  10. package/dist/AutoConnectorManager/PingServerIfNotActiveCallRequester.d.ts +18 -0
  11. package/dist/AutoConnectorManager/PingServerRequester.d.ts +13 -0
  12. package/dist/AutoConnectorManager/RegistrationFailedOutOfCallSubscriber.d.ts +18 -0
  13. package/dist/AutoConnectorManager/eventNames.d.ts +18 -0
  14. package/dist/AutoConnectorManager/index.d.ts +3 -0
  15. package/dist/AutoConnectorManager/types.d.ts +22 -0
  16. package/dist/AutoConnectorManager/utils/errors.d.ts +2 -0
  17. package/dist/AutoConnectorManager/utils/index.d.ts +1 -0
  18. package/dist/CallManager/@CallManager.d.ts +9 -7
  19. package/dist/CallManager/AbstractCallStrategy.d.ts +2 -6
  20. package/dist/CallManager/MCUCallStrategy.d.ts +1 -9
  21. package/dist/CallManager/eventNames.d.ts +48 -4
  22. package/dist/CallManager/index.d.ts +3 -3
  23. package/dist/CallManager/types.d.ts +1 -13
  24. package/dist/ConnectionManager/@ConnectionManager.d.ts +10 -1
  25. package/dist/ConnectionManager/eventNames.d.ts +6 -2
  26. package/dist/ConnectionManager/index.d.ts +1 -0
  27. package/dist/ConnectionManager/utils/errors.d.ts +2 -0
  28. package/dist/ConnectionManager/utils/index.d.ts +2 -0
  29. package/dist/ConnectionManager/utils/resolveParameters.d.ts +2 -0
  30. package/dist/ConnectionQueueManager/@ConnectionQueueManager.d.ts +1 -7
  31. package/dist/ConnectionQueueManager/index.d.ts +1 -0
  32. package/dist/SipConnector/@SipConnector.d.ts +12 -6
  33. package/dist/SipConnector/eventNames.d.ts +1 -1
  34. package/dist/SipConnectorFacade/{SipConnectorFacade.d.ts → @SipConnectorFacade.d.ts} +16 -10
  35. package/dist/SipConnectorFacade/index.d.ts +1 -1
  36. package/dist/StatsPeerConnection/index.d.ts +1 -1
  37. package/dist/{CallManager/TransceiverManager.d.ts → TransceiverManager/@TransceiverManager.d.ts} +19 -0
  38. package/dist/TransceiverManager/index.d.ts +1 -0
  39. package/dist/TransceiverManager/types.d.ts +11 -0
  40. package/dist/VideoSendingBalancer/index.d.ts +1 -1
  41. package/dist/__fixtures__/eventNames.d.ts +1 -1
  42. package/dist/doMock.cjs +1 -1
  43. package/dist/doMock.js +1 -1
  44. package/dist/index.cjs +1 -1
  45. package/dist/index.d.ts +2 -0
  46. package/dist/index.js +209 -195
  47. package/package.json +13 -13
  48. package/dist/@SipConnector-aB66gnC6.cjs +0 -1
  49. /package/dist/StatsPeerConnection/{StatsPeerConnection.d.ts → @StatsPeerConnection.d.ts} +0 -0
  50. /package/dist/VideoSendingBalancer/{VideoSendingBalancer.d.ts → @VideoSendingBalancer.d.ts} +0 -0
@@ -1,439 +1,19 @@
1
- import { Events as D, TypedEvents as K } from "events-constructor";
2
- import { CancelableRequest as Re } from "@krivega/cancelable-promise";
3
- import q from "debug";
4
- import { hasCanceledError as Ie, repeatedCallsAsync as j } from "repeated-calls";
5
- import { setup as _e, createActor as me } from "xstate";
6
- import { createStackPromises as Z } from "stack-promises";
7
- import { SetTimeoutRequest as ee } from "@krivega/timeout-requester";
1
+ import { Events as U, TypedEvents as k } from "events-constructor";
2
+ import x from "debug";
3
+ import { CancelableRequest as G, isCanceledError as _e } from "@krivega/cancelable-promise";
4
+ import { resolveRequesterByTimeout as Me, requesterByTimeoutsWithFailCalls as ve, DelayRequester as fe, hasCanceledError as Pe, SetTimeoutRequest as Z } from "@krivega/timeout-requester";
5
+ import { hasCanceledError as Oe, repeatedCallsAsync as ee } from "repeated-calls";
6
+ import { setup as De, createActor as ye } from "xstate";
7
+ import { createStackPromises as te, isPromiseIsNotActualError as be } from "stack-promises";
8
8
  import "ua-parser-js";
9
9
  import "sequent-promises";
10
- var N = /* @__PURE__ */ ((n) => (n.PEER_CONNECTION = "peerconnection", n.CONNECTING = "connecting", n.SENDING = "sending", n.PROGRESS = "progress", n.ACCEPTED = "accepted", n.CONFIRMED = "confirmed", n.ENDED = "ended", n.FAILED = "failed", n.NEW_DTMF = "newDTMF", n.NEW_INFO = "newInfo", n.HOLD = "hold", n.UNHOLD = "unhold", n.MUTED = "muted", n.UNMUTED = "unmuted", n.REINVITE = "reinvite", n.UPDATE = "update", n.REFER = "refer", n.REPLACES = "replaces", n.SDP = "sdp", n.ICE_CANDIDATE = "icecandidate", n.GET_USER_MEDIA_FAILED = "getusermediafailed", n.PEER_CONNECTION_CREATE_OFFER_FAILED = "peerconnection:createofferfailed", n.PEER_CONNECTION_CREATE_ANSWER_FAILED = "peerconnection:createanswerfailed", n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED = "peerconnection:setlocaldescriptionfailed", n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED = "peerconnection:setremotedescriptionfailed", n.START_PRESENTATION = "presentation:start", n.STARTED_PRESENTATION = "presentation:started", n.END_PRESENTATION = "presentation:end", n.ENDED_PRESENTATION = "presentation:ended", n.FAILED_PRESENTATION = "presentation:failed", n.PEER_CONNECTION_CONFIRMED = "peerconnection:confirmed", n.PEER_CONNECTION_ONTRACK = "peerconnection:ontrack", n.ENDED_FROM_SERVER = "ended:fromserver", n))(N || {}), F = /* @__PURE__ */ ((n) => (n.LOCAL = "local", n.REMOTE = "remote", n.SYSTEM = "system", n))(F || {});
11
- const te = [
12
- "peerconnection",
13
- "connecting",
14
- "sending",
15
- "progress",
16
- "accepted",
17
- "confirmed",
18
- "ended",
19
- "failed",
20
- "newInfo",
21
- "newDTMF",
22
- "presentation:start",
23
- "presentation:started",
24
- "presentation:end",
25
- "presentation:ended",
26
- "presentation:failed",
27
- "reinvite",
28
- "update",
29
- "refer",
30
- "replaces",
31
- "sdp",
32
- "icecandidate",
33
- "getusermediafailed",
34
- "peerconnection:createofferfailed",
35
- "peerconnection:createanswerfailed",
36
- "peerconnection:setlocaldescriptionfailed",
37
- "peerconnection:setremotedescriptionfailed"
38
- ], Me = [
39
- "peerconnection:confirmed",
40
- "peerconnection:ontrack",
41
- "ended:fromserver"
42
- ], ne = [
43
- ...te,
44
- ...Me
45
- ], pe = (n, e) => {
46
- n.getVideoTracks().forEach((s) => {
47
- "contentHint" in s && s.contentHint !== e && (s.contentHint = e);
48
- });
49
- }, L = (n, {
50
- directionVideo: e,
51
- directionAudio: t,
52
- contentHint: s
53
- } = {}) => {
54
- if (!n || e === "recvonly" && t === "recvonly")
55
- return;
56
- const r = t === "recvonly" ? [] : n.getAudioTracks(), i = e === "recvonly" ? [] : n.getVideoTracks(), a = [...r, ...i], o = new MediaStream(a);
57
- return o.getTracks = () => [...o.getAudioTracks(), ...o.getVideoTracks()], s && s !== "none" && pe(o, s), o;
58
- };
59
- function Pe(n) {
60
- return (e) => `sip:${e}@${n}`;
61
- }
62
- const ve = (n, e) => () => Math.floor(Math.random() * (e - n)) + n, se = (n) => n.trim().replaceAll(" ", "_"), fe = ve(1e5, 99999999), Oe = (n) => n.some((t) => {
63
- const { kind: s } = t;
64
- return s === "video";
65
- });
66
- class De {
67
- isPendingCall = !1;
68
- isPendingAnswer = !1;
69
- rtcSession;
70
- remoteStreams = {};
71
- events;
72
- callConfiguration = {};
73
- constructor(e) {
74
- this.events = e;
75
- }
76
- }
77
- var re = /* @__PURE__ */ ((n) => (n.BYE = "Terminated", n.WEBRTC_ERROR = "WebRTC Error", n.CANCELED = "Canceled", n.REQUEST_TIMEOUT = "Request Timeout", n.REJECTED = "Rejected", n.REDIRECTED = "Redirected", n.UNAVAILABLE = "Unavailable", n.NOT_FOUND = "Not Found", n.ADDRESS_INCOMPLETE = "Address Incomplete", n.INCOMPATIBLE_SDP = "Incompatible SDP", n.BAD_MEDIA_DESCRIPTION = "Bad Media Description", n))(re || {});
78
- class ye {
79
- remoteStreams = {};
80
- reset() {
81
- this.remoteStreams = {};
82
- }
83
- generateStream(e, t) {
84
- const { id: s } = e, r = this.remoteStreams[s] ?? new MediaStream();
85
- return t && r.addTrack(t), r.addTrack(e), this.remoteStreams[s] = r, r;
86
- }
87
- generateAudioStream(e) {
88
- const { id: t } = e, s = this.remoteStreams[t] ?? new MediaStream();
89
- return s.addTrack(e), this.remoteStreams[t] = s, s;
90
- }
91
- generateStreams(e) {
92
- const t = [];
93
- return e.forEach((s, r) => {
94
- if (s.kind === "audio")
95
- return;
96
- const i = s, a = e[r - 1];
97
- let o;
98
- a?.kind === "audio" && (o = a);
99
- const c = this.generateStream(i, o);
100
- t.push(c);
101
- }), t;
102
- }
103
- generateAudioStreams(e) {
104
- return e.map((t) => this.generateAudioStream(t));
105
- }
106
- }
107
- class be {
108
- /**
109
- * Хранилище основных transceiver'ов
110
- */
111
- transceivers = {};
112
- /**
113
- * Сохраняет transceiver в соответствующем хранилище в зависимости от типа трека и mid
114
- */
115
- storeTransceiver(e, t) {
116
- const { kind: s } = t;
117
- if (s === "audio")
118
- this.transceivers.mainAudio ??= e;
119
- else {
120
- const { mid: r } = e;
121
- r === "2" ? this.transceivers.presentationVideo ??= e : this.transceivers.mainVideo ??= e;
122
- }
123
- }
124
- /**
125
- * Возвращает все сохраненные transceiver'ы
126
- */
127
- getTransceivers() {
128
- return { ...this.transceivers };
129
- }
130
- /**
131
- * Возвращает основной аудио transceiver
132
- */
133
- getMainAudioTransceiver() {
134
- return this.transceivers.mainAudio;
135
- }
136
- /**
137
- * Возвращает основной видео transceiver
138
- */
139
- getMainVideoTransceiver() {
140
- return this.transceivers.mainVideo;
141
- }
142
- /**
143
- * Возвращает презентационный видео transceiver
144
- */
145
- getPresentationVideoTransceiver() {
146
- return this.transceivers.presentationVideo;
147
- }
148
- /**
149
- * Проверяет, есть ли сохраненный transceiver для указанного типа
150
- */
151
- hasTransceiver(e) {
152
- return this.transceivers[e] !== void 0;
153
- }
154
- /**
155
- * Очищает все сохраненные transceiver'ы
156
- */
157
- clear() {
158
- this.transceivers.mainVideo = void 0, this.transceivers.mainAudio = void 0, this.transceivers.presentationVideo = void 0;
159
- }
160
- /**
161
- * Возвращает количество сохраненных transceiver'ов
162
- */
163
- getCount() {
164
- let e = 0;
165
- return this.transceivers.mainAudio && (e += 1), this.transceivers.mainVideo && (e += 1), this.transceivers.presentationVideo && (e += 1), e;
166
- }
167
- /**
168
- * Проверяет, пустое ли хранилище
169
- */
170
- isEmpty() {
171
- return this.getCount() === 0;
172
- }
173
- }
174
- class Ue extends De {
175
- remoteStreamsManager = new ye();
176
- disposers = /* @__PURE__ */ new Set();
177
- /**
178
- * Менеджер для управления transceiver'ами
179
- */
180
- transceiverManager = new be();
181
- constructor(e) {
182
- super(e), e.on(N.FAILED, this.handleEnded), e.on(N.ENDED, this.handleEnded);
183
- }
184
- get requested() {
185
- return this.isPendingCall || this.isPendingAnswer;
186
- }
187
- get connection() {
188
- return this.rtcSession?.connection;
189
- }
190
- get isCallActive() {
191
- return this.rtcSession?.isEstablished() === !0;
192
- }
193
- get establishedRTCSession() {
194
- return this.rtcSession?.isEstablished() === !0 ? this.rtcSession : void 0;
195
- }
196
- startCall = async (e, t, {
197
- number: s,
198
- mediaStream: r,
199
- extraHeaders: i = [],
200
- ontrack: a,
201
- iceServers: o,
202
- directionVideo: c,
203
- directionAudio: d,
204
- contentHint: u,
205
- offerToReceiveAudio: T = !0,
206
- offerToReceiveVideo: g = !0,
207
- degradationPreference: S,
208
- sendEncodings: I,
209
- onAddedTransceiver: _
210
- }) => (this.isPendingCall = !0, new Promise((R, y) => {
211
- this.callConfiguration.number = s, this.callConfiguration.answer = !1, this.handleCall({ ontrack: a }).then(R).catch(($) => {
212
- y($);
213
- }), this.rtcSession = e.call(t(s), {
214
- mediaStream: L(r, {
215
- directionVideo: c,
216
- directionAudio: d,
217
- contentHint: u
218
- }),
219
- pcConfig: {
220
- iceServers: o
221
- },
222
- rtcOfferConstraints: {
223
- offerToReceiveAudio: T,
224
- offerToReceiveVideo: g
225
- },
226
- // необходимо передавать в методе call, чтобы подписаться на события peerconnection,
227
- // так как в методе call создается RTCSession
228
- // и после создания нет возможности подписаться на события peerconnection через subscribeToSessionEvents
229
- eventHandlers: this.events.triggers,
230
- extraHeaders: i,
231
- directionVideo: c,
232
- directionAudio: d,
233
- degradationPreference: S,
234
- sendEncodings: I,
235
- onAddedTransceiver: _
236
- });
237
- }).finally(() => {
238
- this.isPendingCall = !1;
239
- }));
240
- async endCall() {
241
- const { rtcSession: e } = this;
242
- if (e && !e.isEnded())
243
- return e.terminateAsync({
244
- cause: re.CANCELED
245
- }).finally(() => {
246
- this.reset();
247
- });
248
- this.reset();
249
- }
250
- answerToIncomingCall = async (e, {
251
- mediaStream: t,
252
- ontrack: s,
253
- extraHeaders: r = [],
254
- iceServers: i,
255
- directionVideo: a,
256
- directionAudio: o,
257
- offerToReceiveAudio: c,
258
- offerToReceiveVideo: d,
259
- contentHint: u,
260
- degradationPreference: T,
261
- sendEncodings: g,
262
- onAddedTransceiver: S
263
- }) => (this.isPendingAnswer = !0, new Promise((I, _) => {
264
- try {
265
- const R = e();
266
- this.rtcSession = R, this.subscribeToSessionEvents(R), this.callConfiguration.answer = !0, this.callConfiguration.number = R.remote_identity.uri.user, this.handleCall({ ontrack: s }).then(I).catch((y) => {
267
- _(y);
268
- }), R.answer({
269
- pcConfig: {
270
- iceServers: i
271
- },
272
- rtcOfferConstraints: {
273
- offerToReceiveAudio: c,
274
- offerToReceiveVideo: d
275
- },
276
- mediaStream: L(t, {
277
- directionVideo: a,
278
- directionAudio: o,
279
- contentHint: u
280
- }),
281
- extraHeaders: r,
282
- directionVideo: a,
283
- directionAudio: o,
284
- degradationPreference: T,
285
- sendEncodings: g,
286
- onAddedTransceiver: S
287
- });
288
- } catch (R) {
289
- _(R);
290
- }
291
- }).finally(() => {
292
- this.isPendingAnswer = !1;
293
- }));
294
- getEstablishedRTCSession() {
295
- return this.rtcSession?.isEstablished() === !0 ? this.rtcSession : void 0;
296
- }
297
- getCallConfiguration() {
298
- return { ...this.callConfiguration };
299
- }
300
- getRemoteStreams() {
301
- if (!this.connection)
302
- return;
303
- const t = this.connection.getReceivers().map(({ track: s }) => s);
304
- return Oe(t) ? this.remoteStreamsManager.generateStreams(t) : this.remoteStreamsManager.generateAudioStreams(t);
305
- }
306
- async replaceMediaStream(e, t) {
307
- if (!this.rtcSession)
308
- throw new Error("No rtcSession established");
309
- const { contentHint: s } = t ?? {}, r = L(e, { contentHint: s });
310
- if (r === void 0)
311
- throw new Error("No preparedMediaStream");
312
- return this.rtcSession.replaceMediaStream(r, t);
313
- }
314
- async restartIce(e) {
315
- if (!this.rtcSession)
316
- throw new Error("No rtcSession established");
317
- return this.rtcSession.restartIce(e);
318
- }
319
- async addTransceiver(e, t) {
320
- if (!this.rtcSession)
321
- throw new Error("No rtcSession established");
322
- return this.rtcSession.addTransceiver(e, t);
323
- }
324
- /**
325
- * Возвращает сохраненные transceiver'ы
326
- */
327
- getTransceivers() {
328
- return this.transceiverManager.getTransceivers();
329
- }
330
- handleCall = async ({
331
- ontrack: e
332
- }) => new Promise((t, s) => {
333
- const r = () => {
334
- this.events.on(N.PEER_CONNECTION, u), this.events.on(N.CONFIRMED, T);
335
- }, i = () => {
336
- this.events.off(N.PEER_CONNECTION, u), this.events.off(N.CONFIRMED, T);
337
- }, a = () => {
338
- this.events.on(N.FAILED, c), this.events.on(N.ENDED, c);
339
- }, o = () => {
340
- this.events.off(N.FAILED, c), this.events.off(N.ENDED, c);
341
- }, c = (g) => {
342
- i(), o(), s(g);
343
- };
344
- let d;
345
- const u = ({ peerconnection: g }) => {
346
- d = g;
347
- const S = (I) => {
348
- this.events.trigger(N.PEER_CONNECTION_ONTRACK, g), this.transceiverManager.storeTransceiver(I.transceiver, I.track), e && e(I);
349
- };
350
- g.addEventListener("track", S), this.disposers.add(() => {
351
- g.removeEventListener("track", S);
352
- });
353
- }, T = () => {
354
- d !== void 0 && this.events.trigger(N.PEER_CONNECTION_CONFIRMED, d), i(), o(), t(d);
355
- };
356
- r(), a();
357
- });
358
- subscribeToSessionEvents(e) {
359
- this.events.eachTriggers((t, s) => {
360
- const r = te.find((i) => i === s);
361
- r && (e.on(r, t), this.disposers.add(() => {
362
- e.off(r, t);
363
- }));
364
- });
365
- }
366
- unsubscribeFromSessionEvents() {
367
- this.disposers.forEach((e) => {
368
- e();
369
- }), this.disposers.clear();
370
- }
371
- handleEnded = (e) => {
372
- const { originator: t } = e;
373
- t === F.REMOTE && this.events.trigger(N.ENDED_FROM_SERVER, e), this.reset();
374
- };
375
- reset = () => {
376
- delete this.rtcSession, this.remoteStreamsManager.reset(), this.unsubscribeFromSessionEvents(), this.callConfiguration.number = void 0, this.callConfiguration.answer = !1, this.transceiverManager.clear();
377
- };
378
- }
379
- class we {
380
- events;
381
- strategy;
382
- constructor(e) {
383
- this.events = new D(ne), this.strategy = e ?? new Ue(this.events);
384
- }
385
- get requested() {
386
- return this.strategy.requested;
387
- }
388
- get connection() {
389
- return this.strategy.connection;
390
- }
391
- get establishedRTCSession() {
392
- return this.strategy.establishedRTCSession;
393
- }
394
- get isCallActive() {
395
- return this.strategy.isCallActive;
396
- }
397
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
398
- on(e, t) {
399
- return this.events.on(e, t);
400
- }
401
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
402
- once(e, t) {
403
- return this.events.once(e, t);
404
- }
405
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
406
- onceRace(e, t) {
407
- return this.events.onceRace(e, t);
408
- }
409
- async wait(e) {
410
- return this.events.wait(e);
411
- }
412
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
413
- off(e, t) {
414
- this.events.off(e, t);
415
- }
416
- setStrategy(e) {
417
- this.strategy = e;
418
- }
419
- startCall = async (...e) => this.strategy.startCall(...e);
420
- endCall = async () => this.strategy.endCall();
421
- answerToIncomingCall = async (...e) => this.strategy.answerToIncomingCall(...e);
422
- getEstablishedRTCSession = () => this.strategy.getEstablishedRTCSession();
423
- getCallConfiguration = () => this.strategy.getCallConfiguration();
424
- getRemoteStreams = () => this.strategy.getRemoteStreams();
425
- getTransceivers = () => this.strategy.getTransceivers();
426
- addTransceiver = async (...e) => this.strategy.addTransceiver(...e);
427
- replaceMediaStream = async (...e) => this.strategy.replaceMediaStream(...e);
428
- restartIce = async (e) => this.strategy.restartIce(e);
429
- }
430
- const G = "sip-connector", E = q(G), Sn = () => {
431
- q.enable(G);
432
- }, Cn = () => {
433
- q.enable(`-${G}`);
434
- }, Le = "Error decline with 603", Be = 1006, ke = (n) => typeof n == "object" && n !== null && "code" in n && n.code === Be, Fe = (n) => n.message === Le;
435
- var h = /* @__PURE__ */ ((n) => (n.CONTENT_TYPE = "content-type", n.CONTENT_ENTER_ROOM = "x-webrtc-enter-room", n.CONTENT_USE_LICENSE = "X-WEBRTC-USE-LICENSE", n.PARTICIPANT_NAME = "X-WEBRTC-PARTICIPANT-NAME", n.INPUT_CHANNELS = "X-WEBRTC-INPUT-CHANNELS", n.OUTPUT_CHANNELS = "X-WEBRTC-OUTPUT-CHANNELS", n.MAIN_CAM = "X-WEBRTC-MAINCAM", n.MIC = "X-WEBRTC-MIC", n.MEDIA_SYNC = "X-WEBRTC-SYNC", n.MAIN_CAM_RESOLUTION = "X-WEBRTC-MAINCAM-RESOLUTION", n.MEDIA_STATE = "X-WEBRTC-MEDIA-STATE", n.MEDIA_TYPE = "X-Vinteo-Media-Type", n.MAIN_CAM_STATE = "X-Vinteo-MainCam-State", n.MIC_STATE = "X-Vinteo-Mic-State", n.CONTENT_PARTICIPANT_STATE = "X-WEBRTC-PARTSTATE", n.NOTIFY = "X-VINTEO-NOTIFY", n.CONTENT_ENABLE_MEDIA_DEVICE = "X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE", n.CONTENT_SHARE_STATE = "x-webrtc-share-state", n.MUST_STOP_PRESENTATION_P2P = "x-webrtc-share-state: YOUMUSTSTOPSENDCONTENT", n.START_PRESENTATION_P2P = "x-webrtc-share-state: YOUCANRECEIVECONTENT", n.STOP_PRESENTATION_P2P = "x-webrtc-share-state: CONTENTEND", n.STOP_PRESENTATION = "x-webrtc-share-state: STOPPRESENTATION", n.START_PRESENTATION = "x-webrtc-share-state: LETMESTARTPRESENTATION", n.ENABLE_MAIN_CAM = "X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM", n.AVAILABLE_INCOMING_BITRATE = "X-WEBRTC-AVAILABLE-INCOMING-BITRATE", n.AUDIO_TRACK_COUNT = "X-WEBRTC-AUDIO-TRACK-COUNT", n.VIDEO_TRACK_COUNT = "X-WEBRTC-VIDEO-TRACK-COUNT", n.TRACKS_DIRECTION = "X-WEBRTC-TRACKS-DIRECTION", n))(h || {}), B = /* @__PURE__ */ ((n) => (n.AVAILABLE_SECOND_REMOTE_STREAM = "YOUCANRECEIVECONTENT", n.NOT_AVAILABLE_SECOND_REMOTE_STREAM = "CONTENTEND", n.MUST_STOP_PRESENTATION = "YOUMUSTSTOPSENDCONTENT", n))(B || {}), k = /* @__PURE__ */ ((n) => (n.SPECTATOR = "SPECTATOR", n.PARTICIPANT = "PARTICIPANT", n.SPECTATOR_OVER_SFU = "SPECTATOROVERSFU", n))(k || {}), v = /* @__PURE__ */ ((n) => (n.ENTER_ROOM = "application/vinteo.webrtc.roomname", n.MIC = "application/vinteo.webrtc.mic", n.USE_LICENSE = "application/vinteo.webrtc.uselic", n.PARTICIPANT_STATE = "application/vinteo.webrtc.partstate", n.NOTIFY = "application/vinteo.webrtc.notify", n.SHARE_STATE = "application/vinteo.webrtc.sharedesktop", n.MAIN_CAM = "application/vinteo.webrtc.maincam", n.RESTART = "application/vinteo.webrtc.restart", n))(v || {}), M = /* @__PURE__ */ ((n) => (n.CHANNELS = "application/vinteo.webrtc.channels", n.MEDIA_STATE = "application/vinteo.webrtc.mediastate", n.REFUSAL = "application/vinteo.webrtc.refusal", n.SHARE_STATE = "application/vinteo.webrtc.sharedesktop", n.MAIN_CAM = "application/vinteo.webrtc.maincam", n.STATS = "application/vinteo.webrtc.stats", n))(M || {}), P = /* @__PURE__ */ ((n) => (n.PAUSE_MAIN_CAM = "PAUSEMAINCAM", n.RESUME_MAIN_CAM = "RESUMEMAINCAM", n.MAX_MAIN_CAM_RESOLUTION = "MAXMAINCAMRESOLUTION", n.ADMIN_STOP_MAIN_CAM = "ADMINSTOPMAINCAM", n.ADMIN_START_MAIN_CAM = "ADMINSTARTMAINCAM", n))(P || {}), W = /* @__PURE__ */ ((n) => (n.ADMIN_STOP_MIC = "ADMINSTOPMIC", n.ADMIN_START_MIC = "ADMINSTARTMIC", n))(W || {}), H = /* @__PURE__ */ ((n) => (n.ADMIN_SYNC_FORCED = "1", n.ADMIN_SYNC_NOT_FORCED = "0", n))(H || {}), $e = /* @__PURE__ */ ((n) => (n.AUDIO = "AUDIO", n.VIDEO = "VIDEO", n.AUDIOPLUSPRESENTATION = "AUDIOPLUSPRESENTATION", n))($e || {}), l = /* @__PURE__ */ ((n) => (n.CHANNELS_NOTIFY = "channels:notify", n.PARTICIPANT_ADDED_TO_LIST_MODERATORS = "participant:added-to-list-moderators", n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS = "participant:removed-from-list-moderators", n.PARTICIPANT_MOVE_REQUEST_TO_STREAM = "participant:move-request-to-stream", n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS = "participant:move-request-to-spectators", n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS = "participant:move-request-to-participants", n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_OVER_SFU = "participant:move-request-to-spectators-over-sfu", n.PARTICIPATION_ACCEPTING_WORD_REQUEST = "participation:accepting-word-request", n.PARTICIPATION_CANCELLING_WORD_REQUEST = "participation:cancelling-word-request", n.WEBCAST_STARTED = "webcast:started", n.WEBCAST_STOPPED = "webcast:stopped", n.ACCOUNT_CHANGED = "account:changed", n.ACCOUNT_DELETED = "account:deleted", n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED = "conference:participant-token-issued", n.CHANNELS = "channels", n.ENTER_ROOM = "enterRoom", n.SHARE_STATE = "shareState", n.MAIN_CAM_CONTROL = "main-cam-control", n.USE_LICENSE = "useLicense", n.ADMIN_START_MAIN_CAM = "admin-start-main-cam", n.ADMIN_STOP_MAIN_CAM = "admin-stop-main-cam", n.ADMIN_START_MIC = "admin-start-mic", n.ADMIN_STOP_MIC = "admin-stop-mic", n.ADMIN_FORCE_SYNC_MEDIA_STATE = "admin-force-sync-media-state", n.AVAILABLE_SECOND_REMOTE_STREAM = "availableSecondRemoteStream", n.NOT_AVAILABLE_SECOND_REMOTE_STREAM = "notAvailableSecondRemoteStream", n.MUST_STOP_PRESENTATION = "mustStopPresentation", n.NEW_DTMF = "newDTMF", n.RESTART = "restart", n))(l || {});
436
- const ie = [
10
+ const Q = "sip-connector", d = x(Q), Hn = () => {
11
+ x.enable(Q);
12
+ }, xn = () => {
13
+ x.enable(`-${Q}`);
14
+ }, we = "Error decline with 603", Ue = 1006, Le = (n) => typeof n == "object" && n !== null && "code" in n && n.code === Ue, Be = (n) => n.message === we;
15
+ var l = /* @__PURE__ */ ((n) => (n.CONTENT_TYPE = "content-type", n.CONTENT_ENTER_ROOM = "x-webrtc-enter-room", n.CONTENT_USE_LICENSE = "X-WEBRTC-USE-LICENSE", n.PARTICIPANT_NAME = "X-WEBRTC-PARTICIPANT-NAME", n.INPUT_CHANNELS = "X-WEBRTC-INPUT-CHANNELS", n.OUTPUT_CHANNELS = "X-WEBRTC-OUTPUT-CHANNELS", n.MAIN_CAM = "X-WEBRTC-MAINCAM", n.MIC = "X-WEBRTC-MIC", n.MEDIA_SYNC = "X-WEBRTC-SYNC", n.MAIN_CAM_RESOLUTION = "X-WEBRTC-MAINCAM-RESOLUTION", n.MEDIA_STATE = "X-WEBRTC-MEDIA-STATE", n.MEDIA_TYPE = "X-Vinteo-Media-Type", n.MAIN_CAM_STATE = "X-Vinteo-MainCam-State", n.MIC_STATE = "X-Vinteo-Mic-State", n.CONTENT_PARTICIPANT_STATE = "X-WEBRTC-PARTSTATE", n.NOTIFY = "X-VINTEO-NOTIFY", n.CONTENT_ENABLE_MEDIA_DEVICE = "X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE", n.CONTENT_SHARE_STATE = "x-webrtc-share-state", n.MUST_STOP_PRESENTATION_P2P = "x-webrtc-share-state: YOUMUSTSTOPSENDCONTENT", n.START_PRESENTATION_P2P = "x-webrtc-share-state: YOUCANRECEIVECONTENT", n.STOP_PRESENTATION_P2P = "x-webrtc-share-state: CONTENTEND", n.STOP_PRESENTATION = "x-webrtc-share-state: STOPPRESENTATION", n.START_PRESENTATION = "x-webrtc-share-state: LETMESTARTPRESENTATION", n.ENABLE_MAIN_CAM = "X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM", n.AVAILABLE_INCOMING_BITRATE = "X-WEBRTC-AVAILABLE-INCOMING-BITRATE", n.AUDIO_TRACK_COUNT = "X-WEBRTC-AUDIO-TRACK-COUNT", n.VIDEO_TRACK_COUNT = "X-WEBRTC-VIDEO-TRACK-COUNT", n.TRACKS_DIRECTION = "X-WEBRTC-TRACKS-DIRECTION", n))(l || {}), B = /* @__PURE__ */ ((n) => (n.AVAILABLE_SECOND_REMOTE_STREAM = "YOUCANRECEIVECONTENT", n.NOT_AVAILABLE_SECOND_REMOTE_STREAM = "CONTENTEND", n.MUST_STOP_PRESENTATION = "YOUMUSTSTOPSENDCONTENT", n))(B || {}), q = /* @__PURE__ */ ((n) => (n.SPECTATOR = "SPECTATOR", n.PARTICIPANT = "PARTICIPANT", n))(q || {}), f = /* @__PURE__ */ ((n) => (n.ENTER_ROOM = "application/vinteo.webrtc.roomname", n.MIC = "application/vinteo.webrtc.mic", n.USE_LICENSE = "application/vinteo.webrtc.uselic", n.PARTICIPANT_STATE = "application/vinteo.webrtc.partstate", n.NOTIFY = "application/vinteo.webrtc.notify", n.SHARE_STATE = "application/vinteo.webrtc.sharedesktop", n.MAIN_CAM = "application/vinteo.webrtc.maincam", n.RESTART = "application/vinteo.webrtc.restart", n))(f || {}), _ = /* @__PURE__ */ ((n) => (n.CHANNELS = "application/vinteo.webrtc.channels", n.MEDIA_STATE = "application/vinteo.webrtc.mediastate", n.REFUSAL = "application/vinteo.webrtc.refusal", n.SHARE_STATE = "application/vinteo.webrtc.sharedesktop", n.MAIN_CAM = "application/vinteo.webrtc.maincam", n.STATS = "application/vinteo.webrtc.stats", n))(_ || {}), v = /* @__PURE__ */ ((n) => (n.PAUSE_MAIN_CAM = "PAUSEMAINCAM", n.RESUME_MAIN_CAM = "RESUMEMAINCAM", n.MAX_MAIN_CAM_RESOLUTION = "MAXMAINCAMRESOLUTION", n.ADMIN_STOP_MAIN_CAM = "ADMINSTOPMAINCAM", n.ADMIN_START_MAIN_CAM = "ADMINSTARTMAINCAM", n))(v || {}), W = /* @__PURE__ */ ((n) => (n.ADMIN_STOP_MIC = "ADMINSTOPMIC", n.ADMIN_START_MIC = "ADMINSTARTMIC", n))(W || {}), H = /* @__PURE__ */ ((n) => (n.ADMIN_SYNC_FORCED = "1", n.ADMIN_SYNC_NOT_FORCED = "0", n))(H || {}), Fe = /* @__PURE__ */ ((n) => (n.AUDIO = "AUDIO", n.VIDEO = "VIDEO", n.AUDIOPLUSPRESENTATION = "AUDIOPLUSPRESENTATION", n))(Fe || {}), u = /* @__PURE__ */ ((n) => (n.CHANNELS_NOTIFY = "channels:notify", n.PARTICIPANT_ADDED_TO_LIST_MODERATORS = "participant:added-to-list-moderators", n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS = "participant:removed-from-list-moderators", n.PARTICIPANT_MOVE_REQUEST_TO_STREAM = "participant:move-request-to-stream", n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS = "participant:move-request-to-spectators", n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS = "participant:move-request-to-participants", n.PARTICIPATION_ACCEPTING_WORD_REQUEST = "participation:accepting-word-request", n.PARTICIPATION_CANCELLING_WORD_REQUEST = "participation:cancelling-word-request", n.WEBCAST_STARTED = "webcast:started", n.WEBCAST_STOPPED = "webcast:stopped", n.ACCOUNT_CHANGED = "account:changed", n.ACCOUNT_DELETED = "account:deleted", n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED = "conference:participant-token-issued", n.CHANNELS = "channels", n.ENTER_ROOM = "enterRoom", n.SHARE_STATE = "shareState", n.MAIN_CAM_CONTROL = "main-cam-control", n.USE_LICENSE = "useLicense", n.ADMIN_START_MAIN_CAM = "admin-start-main-cam", n.ADMIN_STOP_MAIN_CAM = "admin-stop-main-cam", n.ADMIN_START_MIC = "admin-start-mic", n.ADMIN_STOP_MIC = "admin-stop-mic", n.ADMIN_FORCE_SYNC_MEDIA_STATE = "admin-force-sync-media-state", n.AVAILABLE_SECOND_REMOTE_STREAM = "availableSecondRemoteStream", n.NOT_AVAILABLE_SECOND_REMOTE_STREAM = "notAvailableSecondRemoteStream", n.MUST_STOP_PRESENTATION = "mustStopPresentation", n.NEW_DTMF = "newDTMF", n.RESTART = "restart", n))(u || {});
16
+ const ne = [
437
17
  "participation:accepting-word-request",
438
18
  "participation:cancelling-word-request",
439
19
  "participant:move-request-to-stream",
@@ -447,7 +27,6 @@ const ie = [
447
27
  "participant:removed-from-list-moderators",
448
28
  "participant:move-request-to-spectators",
449
29
  "participant:move-request-to-participants",
450
- "participant:move-request-to-spectators-over-sfu",
451
30
  "channels",
452
31
  "enterRoom",
453
32
  "shareState",
@@ -464,8 +43,8 @@ const ie = [
464
43
  "newDTMF",
465
44
  "restart"
466
45
  ];
467
- var m = /* @__PURE__ */ ((n) => (n.CHANNELS = "channels", n.WEBCAST_STARTED = "WebcastStarted", n.WEBCAST_STOPPED = "WebcastStopped", n.ACCOUNT_CHANGED = "accountChanged", n.ACCOUNT_DELETED = "accountDeleted", n.ADDED_TO_LIST_MODERATORS = "addedToListModerators", n.REMOVED_FROM_LIST_MODERATORS = "removedFromListModerators", n.ACCEPTING_WORD_REQUEST = "ParticipationRequestAccepted", n.CANCELLING_WORD_REQUEST = "ParticipationRequestRejected", n.MOVE_REQUEST_TO_STREAM = "ParticipantMovedToWebcast", n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED = "ConferenceParticipantTokenIssued", n))(m || {});
468
- class Ve {
46
+ var p = /* @__PURE__ */ ((n) => (n.CHANNELS = "channels", n.WEBCAST_STARTED = "WebcastStarted", n.WEBCAST_STOPPED = "WebcastStopped", n.ACCOUNT_CHANGED = "accountChanged", n.ACCOUNT_DELETED = "accountDeleted", n.ADDED_TO_LIST_MODERATORS = "addedToListModerators", n.REMOVED_FROM_LIST_MODERATORS = "removedFromListModerators", n.ACCEPTING_WORD_REQUEST = "ParticipationRequestAccepted", n.CANCELLING_WORD_REQUEST = "ParticipationRequestRejected", n.MOVE_REQUEST_TO_STREAM = "ParticipantMovedToWebcast", n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED = "ConferenceParticipantTokenIssued", n))(p || {});
47
+ class ke {
469
48
  events;
470
49
  connectionManager;
471
50
  callManager;
@@ -473,44 +52,44 @@ class Ve {
473
52
  connectionManager: e,
474
53
  callManager: t
475
54
  }) {
476
- this.connectionManager = e, this.callManager = t, this.events = new D(ie), this.subscribe();
55
+ this.connectionManager = e, this.callManager = t, this.events = new U(ne), this.subscribe();
477
56
  }
478
57
  async waitChannels() {
479
- return this.wait(l.CHANNELS);
58
+ return this.wait(u.CHANNELS);
480
59
  }
481
60
  async waitSyncMediaState() {
482
- return this.wait(l.ADMIN_FORCE_SYNC_MEDIA_STATE);
61
+ return this.wait(u.ADMIN_FORCE_SYNC_MEDIA_STATE);
483
62
  }
484
63
  async sendDTMF(e) {
485
64
  return new Promise((t, s) => {
486
- let r;
65
+ let i;
487
66
  try {
488
- r = this.getEstablishedRTCSessionProtected();
489
- } catch (i) {
490
- s(i);
67
+ i = this.getEstablishedRTCSessionProtected();
68
+ } catch (r) {
69
+ s(r);
491
70
  }
492
- r && (this.callManager.once("newDTMF", ({ originator: i }) => {
493
- i === F.LOCAL && t();
494
- }), r.sendDTMF(e, {
71
+ i && (this.callManager.once("newDTMF", ({ originator: r }) => {
72
+ r === "local" && t();
73
+ }), i.sendDTMF(e, {
495
74
  duration: 120,
496
75
  interToneGap: 600
497
76
  }));
498
77
  });
499
78
  }
500
79
  async sendChannels({ inputChannels: e, outputChannels: t }) {
501
- const s = this.getEstablishedRTCSessionProtected(), r = `${h.INPUT_CHANNELS}: ${e}`, i = `${h.OUTPUT_CHANNELS}: ${t}`, a = [
502
- r,
503
- i
80
+ const s = this.getEstablishedRTCSessionProtected(), i = `${l.INPUT_CHANNELS}: ${e}`, r = `${l.OUTPUT_CHANNELS}: ${t}`, a = [
81
+ i,
82
+ r
504
83
  ];
505
- return s.sendInfo(M.CHANNELS, void 0, { extraHeaders: a });
84
+ return s.sendInfo(_.CHANNELS, void 0, { extraHeaders: a });
506
85
  }
507
86
  async sendMediaState({ cam: e, mic: t }, s = {}) {
508
- const r = this.getEstablishedRTCSessionProtected(), i = `${h.MEDIA_STATE}: currentstate`, a = `${h.MAIN_CAM_STATE}: ${Number(e)}`, o = `${h.MIC_STATE}: ${Number(t)}`, c = [
509
- i,
87
+ const i = this.getEstablishedRTCSessionProtected(), r = `${l.MEDIA_STATE}: currentstate`, a = `${l.MAIN_CAM_STATE}: ${Number(e)}`, o = `${l.MIC_STATE}: ${Number(t)}`, c = [
88
+ r,
510
89
  a,
511
90
  o
512
91
  ];
513
- return r.sendInfo(M.MEDIA_STATE, void 0, {
92
+ return i.sendInfo(_.MEDIA_STATE, void 0, {
514
93
  noTerminateWhenError: !0,
515
94
  ...s,
516
95
  extraHeaders: c
@@ -519,15 +98,15 @@ class Ve {
519
98
  async sendStats({
520
99
  availableIncomingBitrate: e
521
100
  }) {
522
- const t = this.getEstablishedRTCSessionProtected(), r = [`${h.AVAILABLE_INCOMING_BITRATE}: ${e}`];
523
- return t.sendInfo(M.STATS, void 0, {
101
+ const t = this.getEstablishedRTCSessionProtected(), i = [`${l.AVAILABLE_INCOMING_BITRATE}: ${e}`];
102
+ return t.sendInfo(_.STATS, void 0, {
524
103
  noTerminateWhenError: !0,
525
- extraHeaders: r
104
+ extraHeaders: i
526
105
  });
527
106
  }
528
107
  async sendRefusalToTurnOn(e, t = {}) {
529
- const s = this.getEstablishedRTCSessionProtected(), a = e === "mic" ? 0 : 1, c = [`${h.MEDIA_TYPE}: ${a}`];
530
- return s.sendInfo(M.REFUSAL, void 0, {
108
+ const s = this.getEstablishedRTCSessionProtected(), a = e === "mic" ? 0 : 1, c = [`${l.MEDIA_TYPE}: ${a}`];
109
+ return s.sendInfo(_.REFUSAL, void 0, {
531
110
  noTerminateWhenError: !0,
532
111
  ...t,
533
112
  extraHeaders: c
@@ -540,39 +119,39 @@ class Ve {
540
119
  return this.sendRefusalToTurnOn("cam", { noTerminateWhenError: !0, ...e });
541
120
  }
542
121
  async sendMustStopPresentationP2P() {
543
- await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE, void 0, {
544
- extraHeaders: [h.MUST_STOP_PRESENTATION_P2P]
122
+ await this.getEstablishedRTCSessionProtected().sendInfo(_.SHARE_STATE, void 0, {
123
+ extraHeaders: [l.MUST_STOP_PRESENTATION_P2P]
545
124
  });
546
125
  }
547
126
  async sendStoppedPresentationP2P() {
548
- await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE, void 0, {
549
- extraHeaders: [h.STOP_PRESENTATION_P2P]
127
+ await this.getEstablishedRTCSessionProtected().sendInfo(_.SHARE_STATE, void 0, {
128
+ extraHeaders: [l.STOP_PRESENTATION_P2P]
550
129
  });
551
130
  }
552
131
  async sendStoppedPresentation() {
553
- await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE, void 0, {
554
- extraHeaders: [h.STOP_PRESENTATION]
132
+ await this.getEstablishedRTCSessionProtected().sendInfo(_.SHARE_STATE, void 0, {
133
+ extraHeaders: [l.STOP_PRESENTATION]
555
134
  });
556
135
  }
557
136
  async askPermissionToStartPresentationP2P() {
558
- await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE, void 0, {
559
- extraHeaders: [h.START_PRESENTATION_P2P]
137
+ await this.getEstablishedRTCSessionProtected().sendInfo(_.SHARE_STATE, void 0, {
138
+ extraHeaders: [l.START_PRESENTATION_P2P]
560
139
  });
561
140
  }
562
141
  async askPermissionToStartPresentation() {
563
- await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE, void 0, {
564
- extraHeaders: [h.START_PRESENTATION]
142
+ await this.getEstablishedRTCSessionProtected().sendInfo(_.SHARE_STATE, void 0, {
143
+ extraHeaders: [l.START_PRESENTATION]
565
144
  });
566
145
  }
567
146
  async askPermissionToEnableCam(e = {}) {
568
- const t = this.getEstablishedRTCSessionProtected(), s = [h.ENABLE_MAIN_CAM];
569
- return t.sendInfo(M.MAIN_CAM, void 0, {
147
+ const t = this.getEstablishedRTCSessionProtected(), s = [l.ENABLE_MAIN_CAM];
148
+ return t.sendInfo(_.MAIN_CAM, void 0, {
570
149
  noTerminateWhenError: !0,
571
150
  ...e,
572
151
  extraHeaders: s
573
- }).catch((r) => {
574
- if (Fe(r))
575
- throw r;
152
+ }).catch((i) => {
153
+ if (Be(i))
154
+ throw i;
576
155
  });
577
156
  }
578
157
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
@@ -610,121 +189,121 @@ class Ve {
610
189
  };
611
190
  maybeHandleNotify = (e) => {
612
191
  try {
613
- const t = e.getHeader(h.NOTIFY);
192
+ const t = e.getHeader(l.NOTIFY);
614
193
  if (t) {
615
194
  const s = JSON.parse(t);
616
195
  this.handleNotify(s);
617
196
  }
618
197
  } catch (t) {
619
- E("error parse notify", t);
198
+ d("error parse notify", t);
620
199
  }
621
200
  };
622
201
  handleNotify = (e) => {
623
202
  switch (e.cmd) {
624
- case m.CHANNELS: {
203
+ case p.CHANNELS: {
625
204
  const t = e;
626
205
  this.triggerChannelsNotify(t);
627
206
  break;
628
207
  }
629
- case m.WEBCAST_STARTED: {
208
+ case p.WEBCAST_STARTED: {
630
209
  const t = e;
631
210
  this.triggerWebcastStartedNotify(t);
632
211
  break;
633
212
  }
634
- case m.WEBCAST_STOPPED: {
213
+ case p.WEBCAST_STOPPED: {
635
214
  const t = e;
636
215
  this.triggerWebcastStoppedNotify(t);
637
216
  break;
638
217
  }
639
- case m.ADDED_TO_LIST_MODERATORS: {
218
+ case p.ADDED_TO_LIST_MODERATORS: {
640
219
  const t = e;
641
220
  this.triggerAddedToListModeratorsNotify(t);
642
221
  break;
643
222
  }
644
- case m.REMOVED_FROM_LIST_MODERATORS: {
223
+ case p.REMOVED_FROM_LIST_MODERATORS: {
645
224
  const t = e;
646
225
  this.triggerRemovedFromListModeratorsNotify(t);
647
226
  break;
648
227
  }
649
- case m.ACCEPTING_WORD_REQUEST: {
228
+ case p.ACCEPTING_WORD_REQUEST: {
650
229
  const t = e;
651
230
  this.triggerParticipationAcceptingWordRequest(t);
652
231
  break;
653
232
  }
654
- case m.CANCELLING_WORD_REQUEST: {
233
+ case p.CANCELLING_WORD_REQUEST: {
655
234
  const t = e;
656
235
  this.triggerParticipationCancellingWordRequest(t);
657
236
  break;
658
237
  }
659
- case m.MOVE_REQUEST_TO_STREAM: {
238
+ case p.MOVE_REQUEST_TO_STREAM: {
660
239
  const t = e;
661
240
  this.triggerParticipantMoveRequestToStream(t);
662
241
  break;
663
242
  }
664
- case m.ACCOUNT_CHANGED: {
243
+ case p.ACCOUNT_CHANGED: {
665
244
  this.triggerAccountChangedNotify();
666
245
  break;
667
246
  }
668
- case m.ACCOUNT_DELETED: {
247
+ case p.ACCOUNT_DELETED: {
669
248
  this.triggerAccountDeletedNotify();
670
249
  break;
671
250
  }
672
- case m.CONFERENCE_PARTICIPANT_TOKEN_ISSUED: {
251
+ case p.CONFERENCE_PARTICIPANT_TOKEN_ISSUED: {
673
252
  const t = e;
674
253
  this.triggerConferenceParticipantTokenIssued(t);
675
254
  break;
676
255
  }
677
256
  default:
678
- E("unknown cmd", e);
257
+ d("unknown cmd", e);
679
258
  }
680
259
  };
681
260
  handleNewInfo = (e) => {
682
261
  const { originator: t } = e;
683
- if (t !== F.REMOTE)
262
+ if (t !== "remote")
684
263
  return;
685
- const { request: s } = e, r = s.getHeader(h.CONTENT_TYPE);
264
+ const { request: s } = e, i = s, r = i.getHeader(l.CONTENT_TYPE);
686
265
  if (r !== void 0)
687
266
  switch (r) {
688
- case v.ENTER_ROOM: {
689
- this.triggerEnterRoom(s), this.maybeTriggerChannels(s);
267
+ case f.ENTER_ROOM: {
268
+ this.triggerEnterRoom(i), this.maybeTriggerChannels(i);
690
269
  break;
691
270
  }
692
- case v.NOTIFY: {
693
- this.maybeHandleNotify(s);
271
+ case f.NOTIFY: {
272
+ this.maybeHandleNotify(i);
694
273
  break;
695
274
  }
696
- case v.SHARE_STATE: {
697
- this.triggerShareState(s);
275
+ case f.SHARE_STATE: {
276
+ this.triggerShareState(i);
698
277
  break;
699
278
  }
700
- case v.MAIN_CAM: {
701
- this.triggerMainCamControl(s);
279
+ case f.MAIN_CAM: {
280
+ this.triggerMainCamControl(i);
702
281
  break;
703
282
  }
704
- case v.MIC: {
705
- this.triggerMicControl(s);
283
+ case f.MIC: {
284
+ this.triggerMicControl(i);
706
285
  break;
707
286
  }
708
- case v.USE_LICENSE: {
709
- this.triggerUseLicense(s);
287
+ case f.USE_LICENSE: {
288
+ this.triggerUseLicense(i);
710
289
  break;
711
290
  }
712
- case v.PARTICIPANT_STATE: {
713
- this.maybeTriggerParticipantMoveRequest(s);
291
+ case f.PARTICIPANT_STATE: {
292
+ this.maybeTriggerParticipantMoveRequest(i);
714
293
  break;
715
294
  }
716
- case v.RESTART: {
717
- this.triggerRestart(s);
295
+ case f.RESTART: {
296
+ this.triggerRestart(i);
718
297
  break;
719
298
  }
720
299
  }
721
300
  };
722
301
  triggerChannelsNotify = (e) => {
723
- const t = e.input, s = e.output, r = {
302
+ const t = e.input, s = e.output, i = {
724
303
  inputChannels: t,
725
304
  outputChannels: s
726
305
  };
727
- this.events.trigger(l.CHANNELS_NOTIFY, r);
306
+ this.events.trigger(u.CHANNELS_NOTIFY, i);
728
307
  };
729
308
  triggerWebcastStartedNotify = ({
730
309
  body: { conference: e, type: t }
@@ -733,7 +312,7 @@ class Ve {
733
312
  conference: e,
734
313
  type: t
735
314
  };
736
- this.events.trigger(l.WEBCAST_STARTED, s);
315
+ this.events.trigger(u.WEBCAST_STARTED, s);
737
316
  };
738
317
  triggerWebcastStoppedNotify = ({
739
318
  body: { conference: e, type: t }
@@ -742,7 +321,7 @@ class Ve {
742
321
  conference: e,
743
322
  type: t
744
323
  };
745
- this.events.trigger(l.WEBCAST_STOPPED, s);
324
+ this.events.trigger(u.WEBCAST_STOPPED, s);
746
325
  };
747
326
  triggerAddedToListModeratorsNotify = ({
748
327
  conference: e
@@ -751,7 +330,7 @@ class Ve {
751
330
  conference: e
752
331
  };
753
332
  this.events.trigger(
754
- l.PARTICIPANT_ADDED_TO_LIST_MODERATORS,
333
+ u.PARTICIPANT_ADDED_TO_LIST_MODERATORS,
755
334
  t
756
335
  );
757
336
  };
@@ -762,7 +341,7 @@ class Ve {
762
341
  conference: e
763
342
  };
764
343
  this.events.trigger(
765
- l.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,
344
+ u.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,
766
345
  t
767
346
  );
768
347
  };
@@ -772,7 +351,7 @@ class Ve {
772
351
  const t = {
773
352
  conference: e
774
353
  };
775
- this.events.trigger(l.PARTICIPATION_ACCEPTING_WORD_REQUEST, t);
354
+ this.events.trigger(u.PARTICIPATION_ACCEPTING_WORD_REQUEST, t);
776
355
  };
777
356
  triggerParticipationCancellingWordRequest = ({
778
357
  body: { conference: e }
@@ -780,7 +359,7 @@ class Ve {
780
359
  const t = {
781
360
  conference: e
782
361
  };
783
- this.events.trigger(l.PARTICIPATION_CANCELLING_WORD_REQUEST, t);
362
+ this.events.trigger(u.PARTICIPATION_CANCELLING_WORD_REQUEST, t);
784
363
  };
785
364
  triggerParticipantMoveRequestToStream = ({
786
365
  body: { conference: e }
@@ -788,132 +367,485 @@ class Ve {
788
367
  const t = {
789
368
  conference: e
790
369
  };
791
- this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_STREAM, t);
370
+ this.events.trigger(u.PARTICIPANT_MOVE_REQUEST_TO_STREAM, t);
792
371
  };
793
372
  triggerAccountChangedNotify = () => {
794
- this.events.trigger(l.ACCOUNT_CHANGED, void 0);
373
+ this.events.trigger(u.ACCOUNT_CHANGED, void 0);
795
374
  };
796
375
  triggerAccountDeletedNotify = () => {
797
- this.events.trigger(l.ACCOUNT_DELETED, void 0);
376
+ this.events.trigger(u.ACCOUNT_DELETED, void 0);
798
377
  };
799
378
  triggerConferenceParticipantTokenIssued = ({
800
379
  body: { conference: e, participant: t, jwt: s }
801
380
  }) => {
802
- const r = {
381
+ const i = {
803
382
  conference: e,
804
383
  participant: t,
805
384
  jwt: s
806
385
  };
807
386
  this.events.trigger(
808
- l.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,
809
- r
387
+ u.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,
388
+ i
810
389
  );
811
390
  };
812
391
  maybeTriggerChannels = (e) => {
813
- const t = e.getHeader(h.INPUT_CHANNELS), s = e.getHeader(h.OUTPUT_CHANNELS);
392
+ const t = e.getHeader(l.INPUT_CHANNELS), s = e.getHeader(l.OUTPUT_CHANNELS);
814
393
  if (t && s) {
815
- const r = {
394
+ const i = {
816
395
  inputChannels: t,
817
396
  outputChannels: s
818
397
  };
819
- this.events.trigger(l.CHANNELS, r);
398
+ this.events.trigger(u.CHANNELS, i);
820
399
  }
821
400
  };
822
401
  triggerEnterRoom = (e) => {
823
- const t = e.getHeader(h.CONTENT_ENTER_ROOM), s = e.getHeader(h.PARTICIPANT_NAME);
824
- this.events.trigger(l.ENTER_ROOM, { room: t, participantName: s });
402
+ const t = e.getHeader(l.CONTENT_ENTER_ROOM), s = e.getHeader(l.PARTICIPANT_NAME);
403
+ this.events.trigger(u.ENTER_ROOM, { room: t, participantName: s });
825
404
  };
826
405
  triggerShareState = (e) => {
827
- const t = e.getHeader(h.CONTENT_SHARE_STATE);
406
+ const t = e.getHeader(l.CONTENT_SHARE_STATE);
828
407
  if (t !== void 0)
829
408
  switch (t) {
830
409
  case B.AVAILABLE_SECOND_REMOTE_STREAM: {
831
- this.events.trigger(l.AVAILABLE_SECOND_REMOTE_STREAM, void 0);
410
+ this.events.trigger(u.AVAILABLE_SECOND_REMOTE_STREAM, void 0);
832
411
  break;
833
412
  }
834
413
  case B.NOT_AVAILABLE_SECOND_REMOTE_STREAM: {
835
- this.events.trigger(l.NOT_AVAILABLE_SECOND_REMOTE_STREAM, void 0);
414
+ this.events.trigger(u.NOT_AVAILABLE_SECOND_REMOTE_STREAM, void 0);
836
415
  break;
837
416
  }
838
417
  case B.MUST_STOP_PRESENTATION: {
839
- this.events.trigger(l.MUST_STOP_PRESENTATION, void 0);
418
+ this.events.trigger(u.MUST_STOP_PRESENTATION, void 0);
840
419
  break;
841
420
  }
842
421
  }
843
422
  };
844
423
  maybeTriggerParticipantMoveRequest = (e) => {
845
- const t = e.getHeader(h.CONTENT_PARTICIPANT_STATE);
846
- t === k.SPECTATOR && this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS, void 0), t === k.PARTICIPANT && this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS, void 0), t === k.SPECTATOR_OVER_SFU && this.events.trigger(l.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_OVER_SFU, void 0);
424
+ const t = e.getHeader(l.CONTENT_PARTICIPANT_STATE);
425
+ t === q.SPECTATOR && this.events.trigger(u.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS, void 0), t === q.PARTICIPANT && this.events.trigger(u.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS, void 0);
847
426
  };
848
427
  triggerMainCamControl = (e) => {
849
- const t = e.getHeader(h.MAIN_CAM), s = e.getHeader(h.MEDIA_SYNC), r = s === H.ADMIN_SYNC_FORCED;
850
- if (t === P.ADMIN_START_MAIN_CAM) {
851
- this.events.trigger(l.ADMIN_START_MAIN_CAM, { isSyncForced: r });
428
+ const t = e.getHeader(l.MAIN_CAM), s = e.getHeader(l.MEDIA_SYNC), i = s === H.ADMIN_SYNC_FORCED;
429
+ if (t === v.ADMIN_START_MAIN_CAM) {
430
+ this.events.trigger(u.ADMIN_START_MAIN_CAM, { isSyncForced: i });
431
+ return;
432
+ }
433
+ if (t === v.ADMIN_STOP_MAIN_CAM) {
434
+ this.events.trigger(u.ADMIN_STOP_MAIN_CAM, { isSyncForced: i });
852
435
  return;
853
436
  }
854
- if (t === P.ADMIN_STOP_MAIN_CAM) {
855
- this.events.trigger(l.ADMIN_STOP_MAIN_CAM, { isSyncForced: r });
437
+ (t === v.RESUME_MAIN_CAM || t === v.PAUSE_MAIN_CAM) && s !== void 0 && this.events.trigger(u.ADMIN_FORCE_SYNC_MEDIA_STATE, { isSyncForced: i });
438
+ const r = e.getHeader(l.MAIN_CAM_RESOLUTION);
439
+ this.events.trigger(u.MAIN_CAM_CONTROL, {
440
+ mainCam: t,
441
+ resolutionMainCam: r
442
+ });
443
+ };
444
+ triggerMicControl = (e) => {
445
+ const t = e.getHeader(l.MIC), i = e.getHeader(l.MEDIA_SYNC) === H.ADMIN_SYNC_FORCED;
446
+ t === W.ADMIN_START_MIC ? this.events.trigger(u.ADMIN_START_MIC, { isSyncForced: i }) : t === W.ADMIN_STOP_MIC && this.events.trigger(u.ADMIN_STOP_MIC, { isSyncForced: i });
447
+ };
448
+ triggerUseLicense = (e) => {
449
+ const t = e.getHeader(l.CONTENT_USE_LICENSE);
450
+ this.events.trigger(u.USE_LICENSE, t);
451
+ };
452
+ triggerRestart = (e) => {
453
+ const t = e.getHeader(
454
+ l.TRACKS_DIRECTION
455
+ ), s = Number(
456
+ e.getHeader(l.AUDIO_TRACK_COUNT)
457
+ ), i = Number(
458
+ e.getHeader(l.VIDEO_TRACK_COUNT)
459
+ ), r = { tracksDirection: t, audioTrackCount: s, videoTrackCount: i };
460
+ this.events.trigger(u.RESTART, r);
461
+ };
462
+ }
463
+ var N = /* @__PURE__ */ ((n) => (n.PEER_CONNECTION = "peerconnection", n.CONNECTING = "connecting", n.SENDING = "sending", n.PROGRESS = "progress", n.ACCEPTED = "accepted", n.CONFIRMED = "confirmed", n.ENDED = "ended", n.FAILED = "failed", n.NEW_DTMF = "newDTMF", n.NEW_INFO = "newInfo", n.HOLD = "hold", n.UNHOLD = "unhold", n.MUTED = "muted", n.UNMUTED = "unmuted", n.REINVITE = "reinvite", n.UPDATE = "update", n.REFER = "refer", n.REPLACES = "replaces", n.SDP = "sdp", n.ICE_CANDIDATE = "icecandidate", n.GET_USER_MEDIA_FAILED = "getusermediafailed", n.PEER_CONNECTION_CREATE_OFFER_FAILED = "peerconnection:createofferfailed", n.PEER_CONNECTION_CREATE_ANSWER_FAILED = "peerconnection:createanswerfailed", n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED = "peerconnection:setlocaldescriptionfailed", n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED = "peerconnection:setremotedescriptionfailed", n.START_PRESENTATION = "presentation:start", n.STARTED_PRESENTATION = "presentation:started", n.END_PRESENTATION = "presentation:end", n.ENDED_PRESENTATION = "presentation:ended", n.FAILED_PRESENTATION = "presentation:failed", n.PEER_CONNECTION_CONFIRMED = "peerconnection:confirmed", n.PEER_CONNECTION_ONTRACK = "peerconnection:ontrack", n.ENDED_FROM_SERVER = "ended:fromserver", n.CALL_STATUS_CHANGED = "call-status-changed", n))(N || {}), $e = /* @__PURE__ */ ((n) => (n.LOCAL = "local", n.REMOTE = "remote", n.SYSTEM = "system", n))($e || {});
464
+ const se = [
465
+ "peerconnection",
466
+ "connecting",
467
+ "sending",
468
+ "progress",
469
+ "accepted",
470
+ "confirmed",
471
+ "ended",
472
+ "failed",
473
+ "newInfo",
474
+ "newDTMF",
475
+ "presentation:start",
476
+ "presentation:started",
477
+ "presentation:end",
478
+ "presentation:ended",
479
+ "presentation:failed",
480
+ "reinvite",
481
+ "update",
482
+ "refer",
483
+ "replaces",
484
+ "sdp",
485
+ "icecandidate",
486
+ "getusermediafailed",
487
+ "peerconnection:createofferfailed",
488
+ "peerconnection:createanswerfailed",
489
+ "peerconnection:setlocaldescriptionfailed",
490
+ "peerconnection:setremotedescriptionfailed"
491
+ ], Ve = [
492
+ "peerconnection:confirmed",
493
+ "peerconnection:ontrack",
494
+ "ended:fromserver",
495
+ "call-status-changed"
496
+ ], ie = [
497
+ ...se,
498
+ ...Ve
499
+ ], qe = (n, e) => {
500
+ n.getVideoTracks().forEach((s) => {
501
+ "contentHint" in s && s.contentHint !== e && (s.contentHint = e);
502
+ });
503
+ }, F = (n, {
504
+ directionVideo: e,
505
+ directionAudio: t,
506
+ contentHint: s
507
+ } = {}) => {
508
+ if (!n || e === "recvonly" && t === "recvonly")
509
+ return;
510
+ const i = t === "recvonly" ? [] : n.getAudioTracks(), r = e === "recvonly" ? [] : n.getVideoTracks(), a = [...i, ...r], o = new MediaStream(a);
511
+ return o.getTracks = () => [...o.getAudioTracks(), ...o.getVideoTracks()], s && s !== "none" && qe(o, s), o;
512
+ };
513
+ function We(n) {
514
+ return (e) => `sip:${e}@${n}`;
515
+ }
516
+ const He = (n, e) => () => Math.floor(Math.random() * (e - n)) + n, re = (n) => n.trim().replaceAll(" ", "_"), xe = He(1e5, 99999999), Ge = (n) => n.some((t) => {
517
+ const { kind: s } = t;
518
+ return s === "video";
519
+ });
520
+ class Qe {
521
+ isPendingCall = !1;
522
+ isPendingAnswer = !1;
523
+ rtcSession;
524
+ remoteStreams = {};
525
+ events;
526
+ callConfiguration = {};
527
+ constructor(e) {
528
+ this.events = e;
529
+ }
530
+ }
531
+ var ae = /* @__PURE__ */ ((n) => (n.BYE = "Terminated", n.WEBRTC_ERROR = "WebRTC Error", n.CANCELED = "Canceled", n.REQUEST_TIMEOUT = "Request Timeout", n.REJECTED = "Rejected", n.REDIRECTED = "Redirected", n.UNAVAILABLE = "Unavailable", n.NOT_FOUND = "Not Found", n.ADDRESS_INCOMPLETE = "Address Incomplete", n.INCOMPATIBLE_SDP = "Incompatible SDP", n.BAD_MEDIA_DESCRIPTION = "Bad Media Description", n))(ae || {});
532
+ class Ye {
533
+ remoteStreams = {};
534
+ reset() {
535
+ this.remoteStreams = {};
536
+ }
537
+ generateStream(e, t) {
538
+ const { id: s } = e, i = this.remoteStreams[s] ?? new MediaStream();
539
+ return t && i.addTrack(t), i.addTrack(e), this.remoteStreams[s] = i, i;
540
+ }
541
+ generateAudioStream(e) {
542
+ const { id: t } = e, s = this.remoteStreams[t] ?? new MediaStream();
543
+ return s.addTrack(e), this.remoteStreams[t] = s, s;
544
+ }
545
+ generateStreams(e) {
546
+ const t = [];
547
+ return e.forEach((s, i) => {
548
+ if (s.kind === "audio")
549
+ return;
550
+ const r = s, a = e[i - 1];
551
+ let o;
552
+ a?.kind === "audio" && (o = a);
553
+ const c = this.generateStream(r, o);
554
+ t.push(c);
555
+ }), t;
556
+ }
557
+ generateAudioStreams(e) {
558
+ return e.map((t) => this.generateAudioStream(t));
559
+ }
560
+ }
561
+ class ze extends Qe {
562
+ remoteStreamsManager = new Ye();
563
+ disposers = /* @__PURE__ */ new Set();
564
+ constructor(e) {
565
+ super(e), e.on(N.FAILED, this.handleEnded), e.on(N.ENDED, this.handleEnded);
566
+ }
567
+ get requested() {
568
+ return this.isPendingCall || this.isPendingAnswer;
569
+ }
570
+ get connection() {
571
+ return this.rtcSession?.connection;
572
+ }
573
+ get isCallActive() {
574
+ return this.rtcSession?.isEstablished() === !0;
575
+ }
576
+ get establishedRTCSession() {
577
+ return this.rtcSession?.isEstablished() === !0 ? this.rtcSession : void 0;
578
+ }
579
+ startCall = async (e, t, {
580
+ number: s,
581
+ mediaStream: i,
582
+ extraHeaders: r = [],
583
+ ontrack: a,
584
+ iceServers: o,
585
+ directionVideo: c,
586
+ directionAudio: h,
587
+ contentHint: T,
588
+ offerToReceiveAudio: S = !0,
589
+ offerToReceiveVideo: g = !0,
590
+ degradationPreference: C,
591
+ sendEncodings: m,
592
+ onAddedTransceiver: I
593
+ }) => (this.isPendingCall = !0, new Promise((R, y) => {
594
+ this.callConfiguration.number = s, this.callConfiguration.answer = !1, this.handleCall({ ontrack: a }).then(R).catch(($) => {
595
+ y($);
596
+ }), this.rtcSession = e.call(t(s), {
597
+ mediaStream: F(i, {
598
+ directionVideo: c,
599
+ directionAudio: h,
600
+ contentHint: T
601
+ }),
602
+ pcConfig: {
603
+ iceServers: o
604
+ },
605
+ rtcOfferConstraints: {
606
+ offerToReceiveAudio: S,
607
+ offerToReceiveVideo: g
608
+ },
609
+ // необходимо передавать в методе call, чтобы подписаться на события peerconnection,
610
+ // так как в методе call создается RTCSession
611
+ // и после создания нет возможности подписаться на события peerconnection через subscribeToSessionEvents
612
+ eventHandlers: this.events.triggers,
613
+ extraHeaders: r,
614
+ directionVideo: c,
615
+ directionAudio: h,
616
+ degradationPreference: C,
617
+ sendEncodings: m,
618
+ onAddedTransceiver: I
619
+ });
620
+ }).finally(() => {
621
+ this.isPendingCall = !1;
622
+ }));
623
+ async endCall() {
624
+ const { rtcSession: e } = this;
625
+ if (e && !e.isEnded())
626
+ return e.terminateAsync({
627
+ cause: ae.CANCELED
628
+ }).finally(() => {
629
+ this.reset();
630
+ });
631
+ this.reset();
632
+ }
633
+ answerToIncomingCall = async (e, {
634
+ mediaStream: t,
635
+ ontrack: s,
636
+ extraHeaders: i = [],
637
+ iceServers: r,
638
+ directionVideo: a,
639
+ directionAudio: o,
640
+ offerToReceiveAudio: c,
641
+ offerToReceiveVideo: h,
642
+ contentHint: T,
643
+ degradationPreference: S,
644
+ sendEncodings: g,
645
+ onAddedTransceiver: C
646
+ }) => (this.isPendingAnswer = !0, new Promise((m, I) => {
647
+ try {
648
+ const R = e();
649
+ this.rtcSession = R, this.subscribeToSessionEvents(R), this.callConfiguration.answer = !0, this.callConfiguration.number = R.remote_identity.uri.user, this.handleCall({ ontrack: s }).then(m).catch((y) => {
650
+ I(y);
651
+ }), R.answer({
652
+ pcConfig: {
653
+ iceServers: r
654
+ },
655
+ rtcOfferConstraints: {
656
+ offerToReceiveAudio: c,
657
+ offerToReceiveVideo: h
658
+ },
659
+ mediaStream: F(t, {
660
+ directionVideo: a,
661
+ directionAudio: o,
662
+ contentHint: T
663
+ }),
664
+ extraHeaders: i,
665
+ directionVideo: a,
666
+ directionAudio: o,
667
+ degradationPreference: S,
668
+ sendEncodings: g,
669
+ onAddedTransceiver: C
670
+ });
671
+ } catch (R) {
672
+ I(R);
673
+ }
674
+ }).finally(() => {
675
+ this.isPendingAnswer = !1;
676
+ }));
677
+ getEstablishedRTCSession() {
678
+ return this.rtcSession?.isEstablished() === !0 ? this.rtcSession : void 0;
679
+ }
680
+ getCallConfiguration() {
681
+ return { ...this.callConfiguration };
682
+ }
683
+ getRemoteStreams() {
684
+ if (!this.connection)
856
685
  return;
857
- }
858
- (t === P.RESUME_MAIN_CAM || t === P.PAUSE_MAIN_CAM) && s !== void 0 && this.events.trigger(l.ADMIN_FORCE_SYNC_MEDIA_STATE, { isSyncForced: r });
859
- const i = e.getHeader(h.MAIN_CAM_RESOLUTION);
860
- this.events.trigger(l.MAIN_CAM_CONTROL, {
861
- mainCam: t,
862
- resolutionMainCam: i
686
+ const t = this.connection.getReceivers().map(({ track: s }) => s);
687
+ return Ge(t) ? this.remoteStreamsManager.generateStreams(t) : this.remoteStreamsManager.generateAudioStreams(t);
688
+ }
689
+ async replaceMediaStream(e, t) {
690
+ if (!this.rtcSession)
691
+ throw new Error("No rtcSession established");
692
+ const { contentHint: s } = t ?? {}, i = F(e, { contentHint: s });
693
+ if (i === void 0)
694
+ throw new Error("No preparedMediaStream");
695
+ return this.rtcSession.replaceMediaStream(i, t);
696
+ }
697
+ async restartIce(e) {
698
+ if (!this.rtcSession)
699
+ throw new Error("No rtcSession established");
700
+ return this.rtcSession.restartIce(e);
701
+ }
702
+ async addTransceiver(e, t) {
703
+ if (!this.rtcSession)
704
+ throw new Error("No rtcSession established");
705
+ return this.rtcSession.addTransceiver(e, t);
706
+ }
707
+ handleCall = async ({
708
+ ontrack: e
709
+ }) => new Promise((t, s) => {
710
+ const i = () => {
711
+ this.events.on(N.PEER_CONNECTION, T), this.events.on(N.CONFIRMED, S);
712
+ }, r = () => {
713
+ this.events.off(N.PEER_CONNECTION, T), this.events.off(N.CONFIRMED, S);
714
+ }, a = () => {
715
+ this.events.on(N.FAILED, c), this.events.on(N.ENDED, c);
716
+ }, o = () => {
717
+ this.events.off(N.FAILED, c), this.events.off(N.ENDED, c);
718
+ }, c = (g) => {
719
+ r(), o(), s(g);
720
+ };
721
+ let h;
722
+ const T = ({ peerconnection: g }) => {
723
+ h = g;
724
+ const C = (m) => {
725
+ this.events.trigger(N.PEER_CONNECTION_ONTRACK, m), e && e(m);
726
+ };
727
+ g.addEventListener("track", C), this.disposers.add(() => {
728
+ g.removeEventListener("track", C);
729
+ });
730
+ }, S = () => {
731
+ h !== void 0 && this.events.trigger(N.PEER_CONNECTION_CONFIRMED, h), r(), o(), t(h);
732
+ };
733
+ i(), a();
734
+ });
735
+ subscribeToSessionEvents(e) {
736
+ this.events.eachTriggers((t, s) => {
737
+ const i = se.find((r) => r === s);
738
+ i && (e.on(i, t), this.disposers.add(() => {
739
+ e.off(i, t);
740
+ }));
863
741
  });
742
+ }
743
+ unsubscribeFromSessionEvents() {
744
+ this.disposers.forEach((e) => {
745
+ e();
746
+ }), this.disposers.clear();
747
+ }
748
+ handleEnded = (e) => {
749
+ const { originator: t } = e;
750
+ t === "remote" && this.events.trigger(N.ENDED_FROM_SERVER, e), this.reset();
864
751
  };
865
- triggerMicControl = (e) => {
866
- const t = e.getHeader(h.MIC), r = e.getHeader(h.MEDIA_SYNC) === H.ADMIN_SYNC_FORCED;
867
- t === W.ADMIN_START_MIC ? this.events.trigger(l.ADMIN_START_MIC, { isSyncForced: r }) : t === W.ADMIN_STOP_MIC && this.events.trigger(l.ADMIN_STOP_MIC, { isSyncForced: r });
868
- };
869
- triggerUseLicense = (e) => {
870
- const t = e.getHeader(h.CONTENT_USE_LICENSE);
871
- this.events.trigger(l.USE_LICENSE, t);
872
- };
873
- triggerRestart = (e) => {
874
- const t = e.getHeader(
875
- h.TRACKS_DIRECTION
876
- ), s = Number(
877
- e.getHeader(h.AUDIO_TRACK_COUNT)
878
- ), r = Number(
879
- e.getHeader(h.VIDEO_TRACK_COUNT)
880
- ), i = { tracksDirection: t, audioTrackCount: s, videoTrackCount: r };
881
- this.events.trigger(l.RESTART, i);
752
+ reset = () => {
753
+ delete this.rtcSession, this.remoteStreamsManager.reset(), this.unsubscribeFromSessionEvents(), this.callConfiguration.number = void 0, this.callConfiguration.answer = !1;
882
754
  };
883
755
  }
884
- const We = (n, e) => (n.degradationPreference = e.degradationPreference, n), He = (n, e) => {
756
+ class Xe {
757
+ events;
758
+ strategy;
759
+ constructor(e) {
760
+ this.events = new k(ie), this.strategy = e ?? new ze(this.events), this.subscribeCallStatusChange();
761
+ }
762
+ get requested() {
763
+ return this.strategy.requested;
764
+ }
765
+ get connection() {
766
+ return this.strategy.connection;
767
+ }
768
+ get establishedRTCSession() {
769
+ return this.strategy.establishedRTCSession;
770
+ }
771
+ get isCallActive() {
772
+ return this.strategy.isCallActive;
773
+ }
774
+ on(e, t) {
775
+ return this.events.on(e, t);
776
+ }
777
+ onRace(e, t) {
778
+ return this.events.onRace(e, t);
779
+ }
780
+ once(e, t) {
781
+ return this.events.once(e, t);
782
+ }
783
+ onceRace(e, t) {
784
+ return this.events.onceRace(e, t);
785
+ }
786
+ async wait(e) {
787
+ return this.events.wait(e);
788
+ }
789
+ off(e, t) {
790
+ this.events.off(e, t);
791
+ }
792
+ setStrategy(e) {
793
+ this.strategy = e;
794
+ }
795
+ startCall = async (...e) => this.strategy.startCall(...e);
796
+ endCall = async () => this.strategy.endCall();
797
+ answerToIncomingCall = async (...e) => this.strategy.answerToIncomingCall(...e);
798
+ getEstablishedRTCSession = () => this.strategy.getEstablishedRTCSession();
799
+ getCallConfiguration = () => this.strategy.getCallConfiguration();
800
+ getRemoteStreams = () => this.strategy.getRemoteStreams();
801
+ addTransceiver = async (...e) => this.strategy.addTransceiver(...e);
802
+ replaceMediaStream = async (...e) => this.strategy.replaceMediaStream(...e);
803
+ restartIce = async (e) => this.strategy.restartIce(e);
804
+ subscribeCallStatusChange() {
805
+ let { isCallActive: e } = this;
806
+ const { ACCEPTED: t, CONFIRMED: s, ENDED: i, FAILED: r } = N;
807
+ this.onRace([t, s, i, r], () => {
808
+ e = this.maybeTriggerCallStatus(e);
809
+ });
810
+ }
811
+ maybeTriggerCallStatus(e) {
812
+ const t = this.isCallActive;
813
+ return t !== e && this.events.trigger(N.CALL_STATUS_CHANGED, { isCallActive: t }), t;
814
+ }
815
+ }
816
+ const Je = (n, e) => (n.degradationPreference = e.degradationPreference, n), Ke = (n, e) => {
885
817
  n.encodings ??= [];
886
818
  for (let t = n.encodings.length; t < e; t += 1)
887
819
  n.encodings.push({});
888
820
  return n;
889
- }, ae = (n) => (e, t) => t !== void 0 && e !== t || t === void 0 && e !== n, xe = ae(), qe = (n, e) => {
890
- if (xe(n, e))
821
+ }, oe = (n) => (e, t) => t !== void 0 && e !== t || t === void 0 && e !== n, je = oe(), Ze = (n, e) => {
822
+ if (je(n, e))
891
823
  return n;
892
- }, Ge = (n, e) => {
893
- const t = n.maxBitrate, s = qe(e, t);
824
+ }, et = (n, e) => {
825
+ const t = n.maxBitrate, s = Ze(e, t);
894
826
  return s !== void 0 && (n.maxBitrate = s), n;
895
- }, oe = 1, Qe = ae(
896
- oe
897
- ), Ye = (n, e) => {
898
- const t = n === void 0 ? void 0 : Math.max(n, oe);
899
- if (t !== void 0 && Qe(
827
+ }, ce = 1, tt = oe(
828
+ ce
829
+ ), nt = (n, e) => {
830
+ const t = n === void 0 ? void 0 : Math.max(n, ce);
831
+ if (t !== void 0 && tt(
900
832
  t,
901
833
  e
902
834
  ))
903
835
  return t;
904
- }, ze = (n, e) => {
905
- const t = n.scaleResolutionDownBy, s = Ye(
836
+ }, st = (n, e) => {
837
+ const t = n.scaleResolutionDownBy, s = nt(
906
838
  e,
907
839
  t
908
840
  );
909
841
  return s !== void 0 && (n.scaleResolutionDownBy = s), n;
910
- }, Xe = (n, e) => {
842
+ }, it = (n, e) => {
911
843
  const t = e.encodings?.length ?? 0;
912
- return He(n, t), n.encodings.forEach((s, r) => {
913
- const i = (e?.encodings ?? [])[r], a = i?.maxBitrate, o = i?.scaleResolutionDownBy;
914
- Ge(s, a), ze(s, o);
844
+ return Ke(n, t), n.encodings.forEach((s, i) => {
845
+ const r = (e?.encodings ?? [])[i], a = r?.maxBitrate, o = r?.scaleResolutionDownBy;
846
+ et(s, a), st(s, o);
915
847
  }), n;
916
- }, Je = (n, e) => {
848
+ }, rt = (n, e) => {
917
849
  if (n.codecs?.length !== e.codecs?.length)
918
850
  return !0;
919
851
  for (let t = 0; t < (n.codecs?.length ?? 0); t++)
@@ -930,15 +862,15 @@ const We = (n, e) => (n.degradationPreference = e.degradationPreference, n), He
930
862
  if (JSON.stringify(n.encodings[t]) !== JSON.stringify(e.encodings[t]))
931
863
  return !0;
932
864
  return n.rtcp?.cname !== e.rtcp?.cname || n.rtcp?.reducedSize !== e.rtcp?.reducedSize || n.degradationPreference !== e.degradationPreference;
933
- }, Ke = async (n, e) => {
865
+ }, at = async (n, e) => {
934
866
  const t = n.getParameters(), s = JSON.parse(
935
867
  JSON.stringify(t)
936
868
  );
937
- Xe(t, e), We(t, e);
938
- const r = Je(s, t);
939
- return r && await n.setParameters(t), { parameters: t, isChanged: r };
940
- }, ce = async (n, e, t) => {
941
- const { isChanged: s, parameters: r } = await Ke(n, {
869
+ it(t, e), Je(t, e);
870
+ const i = rt(s, t);
871
+ return i && await n.setParameters(t), { parameters: t, isChanged: i };
872
+ }, de = async (n, e, t) => {
873
+ const { isChanged: s, parameters: i } = await at(n, {
942
874
  encodings: [
943
875
  {
944
876
  scaleResolutionDownBy: e.scaleResolutionDownBy,
@@ -946,21 +878,21 @@ const We = (n, e) => (n.degradationPreference = e.degradationPreference, n), He
946
878
  }
947
879
  ]
948
880
  });
949
- return s && t && t(r), { isChanged: s, parameters: r };
950
- }, je = (n, e) => n.find((t) => t.track !== null && e.getTracks().includes(t.track)), Ze = async (n, e, t) => {
951
- const s = je(n, e);
881
+ return s && t && t(i), { isChanged: s, parameters: i };
882
+ }, ot = (n, e) => n.find((t) => t.track !== null && e.getTracks().includes(t.track)), ct = async (n, e, t) => {
883
+ const s = ot(n, e);
952
884
  if (s)
953
- return ce(s, { maxBitrate: t });
885
+ return de(s, { maxBitrate: t });
954
886
  };
955
- var f = /* @__PURE__ */ ((n) => (n.START_PRESENTATION = "presentation:start", n.STARTED_PRESENTATION = "presentation:started", n.END_PRESENTATION = "presentation:end", n.ENDED_PRESENTATION = "presentation:ended", n.FAILED_PRESENTATION = "presentation:failed", n))(f || {});
956
- const de = [
887
+ var P = /* @__PURE__ */ ((n) => (n.START_PRESENTATION = "presentation:start", n.STARTED_PRESENTATION = "presentation:started", n.END_PRESENTATION = "presentation:end", n.ENDED_PRESENTATION = "presentation:ended", n.FAILED_PRESENTATION = "presentation:failed", n))(P || {});
888
+ const he = [
957
889
  "presentation:start",
958
890
  "presentation:started",
959
891
  "presentation:end",
960
892
  "presentation:ended",
961
893
  "presentation:failed"
962
- ], et = 1, En = (n) => Ie(n);
963
- class tt {
894
+ ], dt = 1, Gn = (n) => Oe(n);
895
+ class ht {
964
896
  events;
965
897
  promisePendingStartPresentation;
966
898
  promisePendingStopPresentation;
@@ -972,7 +904,7 @@ class tt {
972
904
  callManager: e,
973
905
  maxBitrate: t
974
906
  }) {
975
- this.callManager = e, this.maxBitrate = t, this.events = new D(de), this.subscribe();
907
+ this.callManager = e, this.maxBitrate = t, this.events = new U(he), this.subscribe();
976
908
  }
977
909
  get isPendingPresentation() {
978
910
  return !!this.promisePendingStartPresentation || !!this.promisePendingStopPresentation;
@@ -980,8 +912,8 @@ class tt {
980
912
  // eslint-disable-next-line @typescript-eslint/max-params
981
913
  async startPresentation(e, t, {
982
914
  isNeedReinvite: s,
983
- contentHint: r,
984
- sendEncodings: i,
915
+ contentHint: i,
916
+ sendEncodings: r,
985
917
  onAddedTransceiver: a
986
918
  } = {}, o) {
987
919
  const c = this.getRtcSessionProtected();
@@ -992,8 +924,8 @@ class tt {
992
924
  stream: t,
993
925
  presentationOptions: {
994
926
  isNeedReinvite: s,
995
- contentHint: r,
996
- sendEncodings: i,
927
+ contentHint: i,
928
+ sendEncodings: r,
997
929
  onAddedTransceiver: a
998
930
  },
999
931
  options: o
@@ -1005,17 +937,17 @@ class tt {
1005
937
  let s = this.promisePendingStartPresentation ?? Promise.resolve(void 0);
1006
938
  this.promisePendingStartPresentation && await this.promisePendingStartPresentation.catch(() => {
1007
939
  });
1008
- const r = this.callManager.getEstablishedRTCSession();
1009
- return r && t ? s = e().then(async () => r.stopPresentation(t)).catch((i) => {
1010
- throw this.events.trigger(f.FAILED_PRESENTATION, i), i;
1011
- }) : t && this.events.trigger(f.ENDED_PRESENTATION, t), this.promisePendingStopPresentation = s, s.finally(() => {
940
+ const i = this.callManager.getEstablishedRTCSession();
941
+ return i && t ? s = e().then(async () => i.stopPresentation(t)).catch((r) => {
942
+ throw this.events.trigger(P.FAILED_PRESENTATION, r), r;
943
+ }) : t && this.events.trigger(P.ENDED_PRESENTATION, t), this.promisePendingStopPresentation = s, s.finally(() => {
1012
944
  this.resetPresentation();
1013
945
  });
1014
946
  }
1015
947
  async updatePresentation(e, t, {
1016
948
  contentHint: s,
1017
- sendEncodings: r,
1018
- onAddedTransceiver: i
949
+ sendEncodings: i,
950
+ onAddedTransceiver: r
1019
951
  } = {}) {
1020
952
  const a = this.getRtcSessionProtected();
1021
953
  if (!this.streamPresentationCurrent)
@@ -1023,8 +955,8 @@ class tt {
1023
955
  return this.promisePendingStartPresentation && await this.promisePendingStartPresentation, this.sendPresentation(e, a, t, {
1024
956
  contentHint: s,
1025
957
  isNeedReinvite: !1,
1026
- sendEncodings: r,
1027
- onAddedTransceiver: i
958
+ sendEncodings: i,
959
+ onAddedTransceiver: r
1028
960
  }).then(async (o) => (await this.setMaxBitrate(), o));
1029
961
  }
1030
962
  cancelSendPresentationWithRepeatedCalls() {
@@ -1051,58 +983,58 @@ class tt {
1051
983
  }
1052
984
  subscribe() {
1053
985
  this.callManager.on("presentation:start", (e) => {
1054
- this.events.trigger(f.START_PRESENTATION, e);
986
+ this.events.trigger(P.START_PRESENTATION, e);
1055
987
  }), this.callManager.on("presentation:started", (e) => {
1056
- this.events.trigger(f.STARTED_PRESENTATION, e);
988
+ this.events.trigger(P.STARTED_PRESENTATION, e);
1057
989
  }), this.callManager.on("presentation:end", (e) => {
1058
- this.events.trigger(f.END_PRESENTATION, e);
990
+ this.events.trigger(P.END_PRESENTATION, e);
1059
991
  }), this.callManager.on("presentation:ended", (e) => {
1060
- this.events.trigger(f.ENDED_PRESENTATION, e);
992
+ this.events.trigger(P.ENDED_PRESENTATION, e);
1061
993
  }), this.callManager.on("presentation:failed", (e) => {
1062
- this.events.trigger(f.FAILED_PRESENTATION, e);
994
+ this.events.trigger(P.FAILED_PRESENTATION, e);
1063
995
  }), this.callManager.on("failed", this.handleEnded), this.callManager.on("ended", this.handleEnded);
1064
996
  }
1065
997
  async sendPresentationWithDuplicatedCalls(e, {
1066
998
  rtcSession: t,
1067
999
  stream: s,
1068
- presentationOptions: r,
1069
- options: i = {
1070
- callLimit: et
1000
+ presentationOptions: i,
1001
+ options: r = {
1002
+ callLimit: dt
1071
1003
  }
1072
1004
  }) {
1073
1005
  const a = async () => this.sendPresentation(
1074
1006
  e,
1075
1007
  t,
1076
1008
  s,
1077
- r
1009
+ i
1078
1010
  ), o = () => !!this.streamPresentationCurrent;
1079
- return this.cancelableSendPresentationWithRepeatedCalls = j({
1011
+ return this.cancelableSendPresentationWithRepeatedCalls = ee({
1080
1012
  targetFunction: a,
1081
1013
  isComplete: o,
1082
1014
  isRejectAsValid: !0,
1083
- ...i
1015
+ ...r
1084
1016
  }), this.cancelableSendPresentationWithRepeatedCalls.then((c) => c);
1085
1017
  }
1086
1018
  // eslint-disable-next-line @typescript-eslint/max-params
1087
1019
  async sendPresentation(e, t, s, {
1088
- isNeedReinvite: r = !0,
1089
- contentHint: i = "detail",
1020
+ isNeedReinvite: i = !0,
1021
+ contentHint: r = "detail",
1090
1022
  degradationPreference: a,
1091
1023
  sendEncodings: o,
1092
1024
  onAddedTransceiver: c
1093
1025
  }) {
1094
- const d = L(s, { contentHint: i });
1095
- if (d === void 0)
1026
+ const h = F(s, { contentHint: r });
1027
+ if (h === void 0)
1096
1028
  throw new Error("No streamPresentationTarget");
1097
- this.streamPresentationCurrent = d;
1098
- const u = e().then(async () => t.startPresentation(d, r, {
1029
+ this.streamPresentationCurrent = h;
1030
+ const T = e().then(async () => t.startPresentation(h, i, {
1099
1031
  degradationPreference: a,
1100
1032
  sendEncodings: o,
1101
1033
  onAddedTransceiver: c
1102
- })).then(this.setMaxBitrate).then(() => s).catch((T) => {
1103
- throw this.removeStreamPresentationCurrent(), this.events.trigger(f.FAILED_PRESENTATION, T), T;
1034
+ })).then(this.setMaxBitrate).then(() => s).catch((S) => {
1035
+ throw this.removeStreamPresentationCurrent(), this.events.trigger(P.FAILED_PRESENTATION, S), S;
1104
1036
  });
1105
- return this.promisePendingStartPresentation = u, u.finally(() => {
1037
+ return this.promisePendingStartPresentation = T, T.finally(() => {
1106
1038
  this.promisePendingStartPresentation = void 0;
1107
1039
  });
1108
1040
  }
@@ -1110,8 +1042,8 @@ class tt {
1110
1042
  const { connection: e } = this.callManager, { streamPresentationCurrent: t } = this, { maxBitrate: s } = this;
1111
1043
  if (!e || !t || s === void 0)
1112
1044
  return;
1113
- const r = e.getSenders();
1114
- await Ze(r, t, s);
1045
+ const i = e.getSenders();
1046
+ await ct(i, t, s);
1115
1047
  };
1116
1048
  getRtcSessionProtected = () => {
1117
1049
  const e = this.callManager.getEstablishedRTCSession();
@@ -1132,7 +1064,7 @@ class tt {
1132
1064
  delete this.streamPresentationCurrent;
1133
1065
  }
1134
1066
  }
1135
- class nt {
1067
+ class lt {
1136
1068
  data = {};
1137
1069
  getUa;
1138
1070
  constructor(e) {
@@ -1205,8 +1137,8 @@ class nt {
1205
1137
  return this.data.register === !0;
1206
1138
  }
1207
1139
  }
1208
- var A = /* @__PURE__ */ ((n) => (n.CONNECTING = "connecting", n.CONNECTED = "connected", n.DISCONNECTED = "disconnected", n.NEW_RTC_SESSION = "newRTCSession", n.REGISTERED = "registered", n.UNREGISTERED = "unregistered", n.REGISTRATION_FAILED = "registrationFailed", n.NEW_MESSAGE = "newMessage", n.SIP_EVENT = "sipEvent", n))(A || {});
1209
- const he = [
1140
+ var A = /* @__PURE__ */ ((n) => (n.CONNECTING = "connecting", n.CONNECTED = "connected", n.DISCONNECTED = "disconnected", n.DISCONNECTING = "disconnecting", n.NEW_RTC_SESSION = "newRTCSession", n.REGISTERED = "registered", n.UNREGISTERED = "unregistered", n.REGISTRATION_FAILED = "registrationFailed", n.NEW_MESSAGE = "newMessage", n.SIP_EVENT = "sipEvent", n.CONNECT_STARTED = "connect-started", n.CONNECT_SUCCEEDED = "connect-succeeded", n.CONNECT_FAILED = "connect-failed", n))(A || {});
1141
+ const le = [
1210
1142
  "connecting",
1211
1143
  "connected",
1212
1144
  "disconnected",
@@ -1216,8 +1148,13 @@ const he = [
1216
1148
  "registrationFailed",
1217
1149
  "newMessage",
1218
1150
  "sipEvent"
1219
- ], ge = [...he], st = 3;
1220
- class rt {
1151
+ ], gt = [
1152
+ "disconnecting",
1153
+ "connect-started",
1154
+ "connect-succeeded",
1155
+ "connect-failed"
1156
+ ], ge = [...le, ...gt], ut = 3;
1157
+ class Tt {
1221
1158
  cancelableConnectWithRepeatedCalls;
1222
1159
  JsSIP;
1223
1160
  events;
@@ -1236,18 +1173,19 @@ class rt {
1236
1173
  }
1237
1174
  connect = async (e, t) => (this.cancelRequests(), this.connectWithDuplicatedCalls(e, t));
1238
1175
  set = async ({ displayName: e }) => new Promise((t, s) => {
1239
- const r = this.getUa();
1240
- if (!r) {
1176
+ const i = this.getUa();
1177
+ if (!i) {
1241
1178
  s(new Error("this.ua is not initialized"));
1242
1179
  return;
1243
1180
  }
1244
- let i = !1;
1181
+ let r = !1;
1245
1182
  const a = this.getConnectionConfiguration();
1246
- e !== void 0 && e !== a.displayName && (i = r.set("display_name", se(e)), this.updateConnectionConfiguration("displayName", e));
1247
- const o = i;
1183
+ e !== void 0 && e !== a.displayName && (r = i.set("display_name", re(e)), this.updateConnectionConfiguration("displayName", e));
1184
+ const o = r;
1248
1185
  o ? t(o) : s(new Error("nothing changed"));
1249
1186
  });
1250
1187
  disconnect = async () => {
1188
+ this.events.trigger(A.DISCONNECTING, void 0);
1251
1189
  const e = new Promise((s) => {
1252
1190
  this.events.once(A.DISCONNECTED, () => {
1253
1191
  s();
@@ -1260,69 +1198,69 @@ class rt {
1260
1198
  cancelRequests() {
1261
1199
  this.cancelConnectWithRepeatedCalls();
1262
1200
  }
1263
- connectWithDuplicatedCalls = async (e, { callLimit: t = st } = {}) => {
1264
- const s = async () => this.connectInner(e), r = (i) => {
1265
- const c = this.getUa()?.isConnected() === !0 && this.hasEqualConnectionConfiguration(e), d = i != null && !ke(i);
1266
- return c || d;
1201
+ connectWithDuplicatedCalls = async (e, { callLimit: t = ut } = {}) => {
1202
+ const s = async () => this.connectInner(e), i = (r) => {
1203
+ const c = this.getUa()?.isConnected() === !0 && this.hasEqualConnectionConfiguration(e), h = r != null && !Le(r);
1204
+ return c || h;
1267
1205
  };
1268
- return this.stateMachine.startConnect(), this.cancelableConnectWithRepeatedCalls = j({
1206
+ return this.stateMachine.startConnect(), this.cancelableConnectWithRepeatedCalls = ee({
1269
1207
  targetFunction: s,
1270
- isComplete: r,
1208
+ isComplete: i,
1271
1209
  callLimit: t,
1272
1210
  isRejectAsValid: !0,
1273
1211
  isCheckBeforeCall: !1
1274
- }), this.cancelableConnectWithRepeatedCalls.then((i) => {
1275
- if (i instanceof this.JsSIP.UA)
1276
- return i;
1277
- throw i;
1212
+ }), this.cancelableConnectWithRepeatedCalls.then((r) => {
1213
+ if (r instanceof this.JsSIP.UA)
1214
+ return r;
1215
+ throw r;
1278
1216
  });
1279
1217
  };
1280
1218
  hasEqualConnectionConfiguration(e) {
1281
- const { configuration: t } = this.uaFactory.createConfiguration(e), r = this.getUa()?.configuration;
1282
- return r ? r.password === t.password && r.register === t.register && r.uri.toString() === t.uri && r.display_name === t.display_name && r.user_agent === t.user_agent && r.sockets === t.sockets && r.session_timers === t.session_timers && r.register_expires === t.register_expires && r.connection_recovery_min_interval === t.connection_recovery_min_interval && r.connection_recovery_max_interval === t.connection_recovery_max_interval : !1;
1219
+ const { configuration: t } = this.uaFactory.createConfiguration(e), i = this.getUa()?.configuration;
1220
+ return i ? i.password === t.password && i.register === t.register && i.uri.toString() === t.uri && i.display_name === t.display_name && i.user_agent === t.user_agent && i.sockets === t.sockets && i.session_timers === t.session_timers && i.register_expires === t.register_expires && i.connection_recovery_min_interval === t.connection_recovery_min_interval && i.connection_recovery_max_interval === t.connection_recovery_max_interval : !1;
1283
1221
  }
1284
1222
  connectInner = async (e) => this.initUa(e).then(async () => this.start());
1285
1223
  initUa = async ({
1286
1224
  user: e,
1287
1225
  password: t,
1288
1226
  sipServerUrl: s,
1289
- sipWebSocketServerURL: r,
1290
- remoteAddress: i,
1227
+ sipWebSocketServerURL: i,
1228
+ remoteAddress: r,
1291
1229
  sessionTimers: a,
1292
1230
  registerExpires: o,
1293
1231
  connectionRecoveryMinInterval: c,
1294
- connectionRecoveryMaxInterval: d,
1295
- userAgent: u,
1296
- displayName: T = "",
1232
+ connectionRecoveryMaxInterval: h,
1233
+ userAgent: T,
1234
+ displayName: S = "",
1297
1235
  register: g = !1,
1298
- extraHeaders: S = []
1236
+ extraHeaders: C = []
1299
1237
  }) => {
1300
1238
  this.stateMachine.startInitUa(), this.setConnectionConfiguration({
1301
1239
  sipServerUrl: s,
1302
- displayName: T,
1240
+ displayName: S,
1303
1241
  register: g,
1304
1242
  user: e,
1305
1243
  password: t
1306
1244
  }), this.getUa() && await this.disconnect();
1307
- const { ua: _, helpers: R } = this.uaFactory.createUAWithConfiguration(
1245
+ const { ua: I, helpers: R } = this.uaFactory.createUAWithConfiguration(
1308
1246
  {
1309
1247
  user: e,
1310
1248
  password: t,
1311
1249
  sipServerUrl: s,
1312
- sipWebSocketServerURL: r,
1313
- displayName: T,
1250
+ sipWebSocketServerURL: i,
1251
+ displayName: S,
1314
1252
  register: g,
1315
1253
  sessionTimers: a,
1316
1254
  registerExpires: o,
1317
1255
  connectionRecoveryMinInterval: c,
1318
- connectionRecoveryMaxInterval: d,
1319
- userAgent: u,
1320
- remoteAddress: i,
1321
- extraHeaders: S
1256
+ connectionRecoveryMaxInterval: h,
1257
+ userAgent: T,
1258
+ remoteAddress: r,
1259
+ extraHeaders: C
1322
1260
  },
1323
1261
  this.events
1324
1262
  );
1325
- return this.setUa(_), this.setSipServerUrl(R.getSipServerUrl), this.setSocket(R.socket), _;
1263
+ return this.setUa(I), this.setSipServerUrl(R.getSipServerUrl), this.setSocket(R.socket), I;
1326
1264
  };
1327
1265
  start = async () => new Promise((e, t) => {
1328
1266
  const s = this.getUa();
@@ -1330,40 +1268,40 @@ class rt {
1330
1268
  t(new Error("this.ua is not initialized"));
1331
1269
  return;
1332
1270
  }
1333
- let r;
1334
- r = ((c, d) => {
1271
+ let i;
1272
+ i = ((c, h) => {
1335
1273
  if (this.getConnectionConfiguration().register === !0)
1336
- return this.registrationManager.subscribeToStartEvents(c, d);
1337
- const T = A.CONNECTED, g = [A.DISCONNECTED];
1338
- return this.events.on(T, c), g.forEach((S) => {
1339
- this.events.on(S, d);
1274
+ return this.registrationManager.subscribeToStartEvents(c, h);
1275
+ const S = A.CONNECTED, g = [A.DISCONNECTED];
1276
+ return this.events.on(S, c), g.forEach((C) => {
1277
+ this.events.on(C, h);
1340
1278
  }), () => {
1341
- this.events.off(T, c), g.forEach((S) => {
1342
- this.events.off(S, d);
1279
+ this.events.off(S, c), g.forEach((C) => {
1280
+ this.events.off(C, h);
1343
1281
  });
1344
1282
  };
1345
1283
  })(() => {
1346
- r?.(), e(s);
1284
+ i?.(), e(s);
1347
1285
  }, (c) => {
1348
- r?.(), t(c);
1286
+ i?.(), t(c);
1349
1287
  }), s.start();
1350
1288
  });
1351
1289
  cancelConnectWithRepeatedCalls() {
1352
1290
  this.cancelableConnectWithRepeatedCalls?.cancel();
1353
1291
  }
1354
1292
  }
1355
- var le = /* @__PURE__ */ ((n) => (n.START_CONNECT = "START_CONNECT", n.START_INIT_UA = "START_INIT_UA", n.UA_CONNECTED = "UA_CONNECTED", n.UA_REGISTERED = "UA_REGISTERED", n.UA_UNREGISTERED = "UA_UNREGISTERED", n.UA_DISCONNECTED = "UA_DISCONNECTED", n.CONNECTION_FAILED = "CONNECTION_FAILED", n.RESET = "RESET", n))(le || {});
1356
- const it = _e({
1293
+ var ue = /* @__PURE__ */ ((n) => (n.START_CONNECT = "START_CONNECT", n.START_INIT_UA = "START_INIT_UA", n.UA_CONNECTED = "UA_CONNECTED", n.UA_REGISTERED = "UA_REGISTERED", n.UA_UNREGISTERED = "UA_UNREGISTERED", n.UA_DISCONNECTED = "UA_DISCONNECTED", n.CONNECTION_FAILED = "CONNECTION_FAILED", n.RESET = "RESET", n))(ue || {});
1294
+ const St = De({
1357
1295
  types: {
1358
1296
  context: {},
1359
1297
  events: {}
1360
1298
  },
1361
1299
  actions: {
1362
1300
  logTransition: (n, e) => {
1363
- E(`State transition: ${e.from} -> ${e.to} (${e.event})`);
1301
+ d(`State transition: ${e.from} -> ${e.to} (${e.event})`);
1364
1302
  },
1365
1303
  logStateChange: (n, e) => {
1366
- E("ConnectionStateMachine state changed", e.state);
1304
+ d("ConnectionStateMachine state changed", e.state);
1367
1305
  }
1368
1306
  }
1369
1307
  }).createMachine({
@@ -1667,17 +1605,17 @@ const it = _e({
1667
1605
  }
1668
1606
  }
1669
1607
  });
1670
- class at {
1608
+ class Ct {
1671
1609
  actor;
1672
1610
  stateChangeListeners = /* @__PURE__ */ new Set();
1673
1611
  events;
1674
1612
  unsubscribeFromEvents;
1675
1613
  actorSubscription;
1676
1614
  constructor(e) {
1677
- this.events = e, this.actor = me(it), this.actorSubscription = this.actor.subscribe((t) => {
1615
+ this.events = e, this.actor = ye(St), this.actorSubscription = this.actor.subscribe((t) => {
1678
1616
  const s = t.value;
1679
- this.stateChangeListeners.forEach((r) => {
1680
- r(s);
1617
+ this.stateChangeListeners.forEach((i) => {
1618
+ i(s);
1681
1619
  });
1682
1620
  }), this.actor.start(), this.subscribeToEvents();
1683
1621
  }
@@ -1760,7 +1698,7 @@ class at {
1760
1698
  return this.actor.getSnapshot().can({ type: e });
1761
1699
  }
1762
1700
  getValidEvents() {
1763
- return Object.values(le).filter((e) => this.canTransition(e));
1701
+ return Object.values(ue).filter((e) => this.canTransition(e));
1764
1702
  }
1765
1703
  hasState(e) {
1766
1704
  return this.actor.getSnapshot().matches(e);
@@ -1768,7 +1706,7 @@ class at {
1768
1706
  sendEvent(e) {
1769
1707
  const t = this.actor.getSnapshot(), s = { type: e };
1770
1708
  if (!t.can(s)) {
1771
- E(
1709
+ d(
1772
1710
  `Invalid transition: ${s.type} from ${this.state}. Event cannot be processed in current state.`
1773
1711
  );
1774
1712
  return;
@@ -1829,7 +1767,7 @@ class at {
1829
1767
  };
1830
1768
  }
1831
1769
  }
1832
- class ot {
1770
+ class Et {
1833
1771
  events;
1834
1772
  getUaProtected;
1835
1773
  constructor(e) {
@@ -1851,22 +1789,22 @@ class ot {
1851
1789
  try {
1852
1790
  await this.unregister();
1853
1791
  } catch (e) {
1854
- E("tryRegister", e);
1792
+ d("tryRegister", e);
1855
1793
  }
1856
1794
  return this.register();
1857
1795
  }
1858
1796
  subscribeToStartEvents(e, t) {
1859
- const s = A.REGISTERED, r = [A.REGISTRATION_FAILED, A.DISCONNECTED];
1860
- return this.events.on(s, e), r.forEach((i) => {
1861
- this.events.on(i, t);
1797
+ const s = A.REGISTERED, i = [A.REGISTRATION_FAILED, A.DISCONNECTED];
1798
+ return this.events.on(s, e), i.forEach((r) => {
1799
+ this.events.on(r, t);
1862
1800
  }), () => {
1863
- this.events.off(s, e), r.forEach((i) => {
1864
- this.events.off(i, t);
1801
+ this.events.off(s, e), i.forEach((r) => {
1802
+ this.events.off(r, t);
1865
1803
  });
1866
1804
  };
1867
1805
  }
1868
1806
  }
1869
- class ct {
1807
+ class At {
1870
1808
  uaFactory;
1871
1809
  getUaProtected;
1872
1810
  constructor(e) {
@@ -1876,14 +1814,14 @@ class ct {
1876
1814
  * Отправляет SIP OPTIONS запрос к указанному адресу
1877
1815
  */
1878
1816
  async sendOptions(e, t, s) {
1879
- const r = this.getUaProtected();
1880
- return new Promise((i, a) => {
1817
+ const i = this.getUaProtected();
1818
+ return new Promise((r, a) => {
1881
1819
  try {
1882
- r.sendOptions(e, t, {
1820
+ i.sendOptions(e, t, {
1883
1821
  extraHeaders: s,
1884
1822
  eventHandlers: {
1885
1823
  succeeded: () => {
1886
- i();
1824
+ r();
1887
1825
  },
1888
1826
  failed: a
1889
1827
  }
@@ -1897,8 +1835,8 @@ class ct {
1897
1835
  * Отправляет SIP OPTIONS запрос к собственному URI (ping)
1898
1836
  */
1899
1837
  async ping(e, t) {
1900
- const r = this.getUaProtected().configuration.uri;
1901
- return this.sendOptions(r, e, t);
1838
+ const i = this.getUaProtected().configuration.uri;
1839
+ return this.sendOptions(i, e, t);
1902
1840
  }
1903
1841
  /**
1904
1842
  * Проверяет доступность телефонии, создавая временное соединение
@@ -1907,35 +1845,35 @@ class ct {
1907
1845
  userAgent: e,
1908
1846
  displayName: t,
1909
1847
  sipServerUrl: s,
1910
- sipWebSocketServerURL: r,
1911
- remoteAddress: i,
1848
+ sipWebSocketServerURL: i,
1849
+ remoteAddress: r,
1912
1850
  extraHeaders: a
1913
1851
  }) {
1914
1852
  return new Promise((o, c) => {
1915
- const { configuration: d } = this.uaFactory.createConfiguration({
1916
- sipWebSocketServerURL: r,
1853
+ const { configuration: h } = this.uaFactory.createConfiguration({
1854
+ sipWebSocketServerURL: i,
1917
1855
  displayName: t,
1918
1856
  userAgent: e,
1919
1857
  sipServerUrl: s
1920
- }), u = this.uaFactory.createUA({ ...d, remoteAddress: i, extraHeaders: a }), T = () => {
1921
- const S = new Error("Telephony is not available");
1922
- c(S);
1858
+ }), T = this.uaFactory.createUA({ ...h, remoteAddress: r, extraHeaders: a }), S = () => {
1859
+ const C = new Error("Telephony is not available");
1860
+ c(C);
1923
1861
  };
1924
- u.once(A.DISCONNECTED, T);
1862
+ T.once(A.DISCONNECTED, S);
1925
1863
  const g = () => {
1926
- u.removeAllListeners(), u.once(A.DISCONNECTED, () => {
1864
+ T.removeAllListeners(), T.once(A.DISCONNECTED, () => {
1927
1865
  o();
1928
- }), u.stop();
1866
+ }), T.stop();
1929
1867
  };
1930
- u.once(A.CONNECTED, g), u.start();
1868
+ T.once(A.CONNECTED, g), T.start();
1931
1869
  });
1932
1870
  }
1933
1871
  }
1934
- const dt = (n) => {
1872
+ const Nt = (n) => {
1935
1873
  const e = [];
1936
1874
  return n !== void 0 && n !== "" && e.push(`X-Vinteo-Remote: ${n}`), e;
1937
1875
  };
1938
- class O {
1876
+ class D {
1939
1877
  JsSIP;
1940
1878
  constructor(e) {
1941
1879
  this.JsSIP = e;
@@ -1947,12 +1885,12 @@ class O {
1947
1885
  register: e,
1948
1886
  password: t,
1949
1887
  user: s,
1950
- sipServerUrl: r,
1951
- sipWebSocketServerURL: i
1888
+ sipServerUrl: i,
1889
+ sipWebSocketServerURL: r
1952
1890
  }) {
1953
- if (!r)
1954
- throw new Error("sipServerUrl is required");
1955
1891
  if (!i)
1892
+ throw new Error("sipServerUrl is required");
1893
+ if (!r)
1956
1894
  throw new Error("sipWebSocketServerURL is required");
1957
1895
  if (e && (t === void 0 || t === ""))
1958
1896
  throw new Error("password is required for authorized connection");
@@ -1960,74 +1898,75 @@ class O {
1960
1898
  throw new Error("user is required for authorized connection");
1961
1899
  }
1962
1900
  static resolveAuthorizationUser(e, t) {
1963
- return e && t !== void 0 && t.trim() !== "" ? t.trim() : `${fe()}`;
1901
+ return e && t !== void 0 && t.trim() !== "" ? t.trim() : `${xe()}`;
1964
1902
  }
1965
1903
  static buildExtraHeaders(e, t) {
1966
- const s = e !== void 0 && e !== "" ? dt(e) : [];
1904
+ const s = e !== void 0 && e !== "" ? Nt(e) : [];
1967
1905
  return t === void 0 ? s : [...s, ...t];
1968
1906
  }
1969
1907
  createConfiguration({
1970
1908
  user: e,
1971
1909
  password: t,
1972
1910
  sipWebSocketServerURL: s,
1973
- displayName: r = "",
1974
- sipServerUrl: i,
1911
+ displayName: i = "",
1912
+ sipServerUrl: r,
1975
1913
  register: a = !1,
1976
1914
  sessionTimers: o = !1,
1977
1915
  registerExpires: c = 300,
1978
1916
  // 5 minutes in sec
1979
- connectionRecoveryMinInterval: d = 2,
1980
- connectionRecoveryMaxInterval: u = 6,
1981
- userAgent: T
1917
+ connectionRecoveryMinInterval: h = 2,
1918
+ connectionRecoveryMaxInterval: T = 6,
1919
+ userAgent: S
1982
1920
  }) {
1983
- O.validateConfiguration({
1921
+ D.validateConfiguration({
1984
1922
  register: a,
1985
1923
  password: t,
1986
1924
  user: e,
1987
- sipServerUrl: i,
1925
+ sipServerUrl: r,
1988
1926
  sipWebSocketServerURL: s
1989
1927
  });
1990
- const g = O.resolveAuthorizationUser(a, e), S = Pe(i), I = S(g), _ = new this.JsSIP.WebSocketInterface(s);
1928
+ const g = D.resolveAuthorizationUser(a, e), C = We(r), m = C(g), I = new this.JsSIP.WebSocketInterface(s);
1991
1929
  return {
1992
1930
  configuration: {
1993
1931
  password: t,
1994
1932
  register: a,
1995
- uri: I,
1996
- display_name: se(r),
1997
- user_agent: T,
1933
+ uri: m,
1934
+ display_name: re(i),
1935
+ user_agent: S,
1998
1936
  sdpSemantics: "unified-plan",
1999
- sockets: [_],
1937
+ sockets: [I],
2000
1938
  session_timers: o,
2001
1939
  register_expires: c,
2002
- connection_recovery_min_interval: d,
2003
- connection_recovery_max_interval: u
1940
+ connection_recovery_min_interval: h,
1941
+ connection_recovery_max_interval: T
2004
1942
  },
2005
1943
  helpers: {
2006
- socket: _,
2007
- getSipServerUrl: S
1944
+ socket: I,
1945
+ getSipServerUrl: C
2008
1946
  }
2009
1947
  };
2010
1948
  }
2011
1949
  createUA({ remoteAddress: e, extraHeaders: t, ...s }) {
2012
- const r = new this.JsSIP.UA(s), i = O.buildExtraHeaders(e, t);
2013
- return i.length > 0 && r.registrator().setExtraHeaders(i), r;
1950
+ const i = new this.JsSIP.UA(s), r = D.buildExtraHeaders(e, t);
1951
+ return r.length > 0 && i.registrator().setExtraHeaders(r), i;
2014
1952
  }
2015
1953
  /**
2016
1954
  * Создает UA с полным жизненным циклом - конфигурация + создание + настройка событий
2017
1955
  */
2018
1956
  createUAWithConfiguration(e, t) {
2019
- const { configuration: s, helpers: r } = this.createConfiguration(e), i = this.createUA({
1957
+ const { configuration: s, helpers: i } = this.createConfiguration(e), r = this.createUA({
2020
1958
  ...s,
2021
1959
  remoteAddress: e.remoteAddress,
2022
1960
  extraHeaders: e.extraHeaders
2023
1961
  });
2024
1962
  return t.eachTriggers((a, o) => {
2025
- const c = he.find((d) => d === o);
2026
- c && i.on(c, a);
2027
- }), { ua: i, helpers: r };
1963
+ const c = le.find((h) => h === o);
1964
+ c && r.on(c, a);
1965
+ }), { ua: r, helpers: i };
2028
1966
  }
2029
1967
  }
2030
- class ht {
1968
+ const Te = "Not ready for connection", Rt = (n) => n instanceof Error && n.message === Te, It = () => new Error(Te), pt = async (n) => typeof n == "function" ? n() : n;
1969
+ class mt {
2031
1970
  events;
2032
1971
  ua;
2033
1972
  socket;
@@ -2039,15 +1978,15 @@ class ht {
2039
1978
  configurationManager;
2040
1979
  JsSIP;
2041
1980
  constructor({ JsSIP: e }) {
2042
- this.JsSIP = e, this.events = new D(ge), this.uaFactory = new O(e), this.registrationManager = new ot({
1981
+ this.JsSIP = e, this.events = new U(ge), this.uaFactory = new D(e), this.registrationManager = new Et({
2043
1982
  events: this.events,
2044
1983
  getUaProtected: this.getUaProtected
2045
- }), this.stateMachine = new at(this.events), this.configurationManager = new nt({
1984
+ }), this.stateMachine = new Ct(this.events), this.configurationManager = new lt({
2046
1985
  getUa: this.getUa
2047
- }), this.sipOperations = new ct({
1986
+ }), this.sipOperations = new At({
2048
1987
  uaFactory: this.uaFactory,
2049
1988
  getUaProtected: this.getUaProtected
2050
- }), this.connectionFlow = new rt({
1989
+ }), this.connectionFlow = new Tt({
2051
1990
  JsSIP: this.JsSIP,
2052
1991
  events: this.events,
2053
1992
  uaFactory: this.uaFactory,
@@ -2067,108 +2006,426 @@ class ht {
2067
2006
  setSipServerUrl: (t) => {
2068
2007
  this.getSipServerUrl = t;
2069
2008
  },
2070
- setSocket: (t) => {
2071
- this.socket = t;
2072
- }
2009
+ setSocket: (t) => {
2010
+ this.socket = t;
2011
+ }
2012
+ });
2013
+ }
2014
+ get requested() {
2015
+ return this.stateMachine.isPending;
2016
+ }
2017
+ get isPendingConnect() {
2018
+ return this.stateMachine.isPendingConnect;
2019
+ }
2020
+ get isPendingInitUa() {
2021
+ return this.stateMachine.isPendingInitUa;
2022
+ }
2023
+ get isDisconnected() {
2024
+ return this.stateMachine.isDisconnected;
2025
+ }
2026
+ get isFailed() {
2027
+ return this.stateMachine.isFailed;
2028
+ }
2029
+ get connectionState() {
2030
+ return this.stateMachine.state;
2031
+ }
2032
+ get isRegistered() {
2033
+ return D.isRegisteredUA(this.ua);
2034
+ }
2035
+ get isRegisterConfig() {
2036
+ return this.configurationManager.isRegister();
2037
+ }
2038
+ connect = async (e, t) => this.disconnect().catch((s) => {
2039
+ d("connect: disconnect error", s);
2040
+ }).then(async () => this.connectWithProcessError(e, t));
2041
+ set = async ({ displayName: e }) => this.connectionFlow.set({ displayName: e });
2042
+ disconnect = async () => {
2043
+ if (this.isConfigured())
2044
+ return this.connectionFlow.disconnect();
2045
+ };
2046
+ async register() {
2047
+ return this.registrationManager.register();
2048
+ }
2049
+ async unregister() {
2050
+ return this.registrationManager.unregister();
2051
+ }
2052
+ tryRegister = async () => this.registrationManager.tryRegister();
2053
+ sendOptions = async (e, t, s) => this.sipOperations.sendOptions(e, t, s);
2054
+ ping = async (e, t) => this.sipOperations.ping(e, t);
2055
+ checkTelephony = async (e) => this.sipOperations.checkTelephony(e);
2056
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2057
+ on(e, t) {
2058
+ return this.events.on(e, t);
2059
+ }
2060
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2061
+ once(e, t) {
2062
+ return this.events.once(e, t);
2063
+ }
2064
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2065
+ onceRace(e, t) {
2066
+ return this.events.onceRace(e, t);
2067
+ }
2068
+ async wait(e) {
2069
+ return this.events.wait(e);
2070
+ }
2071
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2072
+ off(e, t) {
2073
+ this.events.off(e, t);
2074
+ }
2075
+ isConfigured() {
2076
+ return this.configurationManager.isConfigured();
2077
+ }
2078
+ getConnectionConfiguration = () => this.configurationManager.get();
2079
+ destroy() {
2080
+ this.stateMachine.destroy();
2081
+ }
2082
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
2083
+ getSipServerUrl = (e) => e;
2084
+ getUaProtected = () => {
2085
+ if (!this.ua)
2086
+ throw new Error("UA not initialized");
2087
+ return this.ua;
2088
+ };
2089
+ getUa = () => this.ua;
2090
+ connectWithProcessError = async (e, t) => {
2091
+ if (!(t?.hasReadyForConnection?.() ?? !0))
2092
+ throw It();
2093
+ return this.processConnect(e, t).catch(async (i) => {
2094
+ const r = i;
2095
+ return this.disconnect().then(() => {
2096
+ throw r;
2097
+ }).catch(() => {
2098
+ throw r;
2099
+ });
2100
+ });
2101
+ };
2102
+ processConnect = async (e, t) => (this.events.trigger(A.CONNECT_STARTED, {}), pt(e).then(async (s) => this.connectionFlow.connect(s, t)).then((s) => (this.events.trigger(A.CONNECT_SUCCEEDED, { ua: s }), s)).catch((s) => {
2103
+ const i = s ?? new Error("Failed to connect to server");
2104
+ throw this.events.trigger(A.CONNECT_FAILED, i), i;
2105
+ }));
2106
+ }
2107
+ class _t {
2108
+ connectionManager;
2109
+ stackPromises = te({
2110
+ noRunIsNotActual: !0
2111
+ });
2112
+ constructor({ connectionManager: e }) {
2113
+ this.connectionManager = e;
2114
+ }
2115
+ connect = async (...e) => this.stackPromises.run(async () => this.connectionManager.connect(...e));
2116
+ disconnect = async () => this.stackPromises.run(async () => this.connectionManager.disconnect());
2117
+ stop() {
2118
+ this.stackPromises.stop();
2119
+ }
2120
+ }
2121
+ var O = /* @__PURE__ */ ((n) => (n.BEFORE_ATTEMPT = "before-attempt", n.SUCCEEDED_ATTEMPT = "succeeded-attempt", n.FAILED_ATTEMPT = "failed-attempt", n.CANCELLED_ATTEMPT = "cancelled-attempt", n.CHANGED_ATTEMPT_STATUS = "changed-attempt-status", n))(O || {});
2122
+ const Se = [
2123
+ "before-attempt",
2124
+ "succeeded-attempt",
2125
+ "failed-attempt",
2126
+ "cancelled-attempt",
2127
+ "changed-attempt-status"
2128
+ ], z = 0, Mt = 30;
2129
+ class vt {
2130
+ events;
2131
+ countInner = z;
2132
+ initialCount = z;
2133
+ limitInner = Mt;
2134
+ isInProgress = !1;
2135
+ constructor({ events: e }) {
2136
+ this.events = e;
2137
+ }
2138
+ get count() {
2139
+ return this.countInner;
2140
+ }
2141
+ get limit() {
2142
+ return this.limitInner;
2143
+ }
2144
+ get isAttemptInProgress() {
2145
+ return this.isInProgress;
2146
+ }
2147
+ hasLimitReached() {
2148
+ return this.countInner >= this.limitInner;
2149
+ }
2150
+ startAttempt() {
2151
+ this.isInProgress || (this.isInProgress = !0, this.emitStatusChange());
2152
+ }
2153
+ finishAttempt() {
2154
+ this.isInProgress && (this.isInProgress = !1, this.emitStatusChange());
2155
+ }
2156
+ increment() {
2157
+ this.count < this.limit && (this.countInner += 1);
2158
+ }
2159
+ reset() {
2160
+ this.countInner = this.initialCount, this.finishAttempt();
2161
+ }
2162
+ emitStatusChange() {
2163
+ this.events.trigger(O.CHANGED_ATTEMPT_STATUS, { isInProgress: this.isInProgress });
2164
+ }
2165
+ }
2166
+ class ft {
2167
+ connectionManager;
2168
+ interval;
2169
+ checkTelephonyByTimeout = void 0;
2170
+ cancelableBeforeRequest = void 0;
2171
+ constructor({
2172
+ connectionManager: e,
2173
+ interval: t
2174
+ }) {
2175
+ this.connectionManager = e, this.interval = t;
2176
+ }
2177
+ start({
2178
+ onBeforeRequest: e,
2179
+ onSuccessRequest: t,
2180
+ onFailRequest: s
2181
+ }) {
2182
+ this.stop(), this.cancelableBeforeRequest = new G(e), this.checkTelephonyByTimeout = Me({
2183
+ isDontStopOnFail: !0,
2184
+ requestInterval: this.interval,
2185
+ request: async () => {
2186
+ if (!this.cancelableBeforeRequest)
2187
+ throw new Error("cancelableBeforeRequest is not defined");
2188
+ const i = await this.cancelableBeforeRequest.request();
2189
+ return this.connectionManager.checkTelephony(i);
2190
+ }
2191
+ }), this.checkTelephonyByTimeout.start(void 0, {
2192
+ onFailRequest: s,
2193
+ onSuccessRequest: () => {
2194
+ this.stop(), t();
2195
+ }
2196
+ });
2197
+ }
2198
+ stop() {
2199
+ this.checkTelephonyByTimeout?.stop(), this.checkTelephonyByTimeout = void 0, this.cancelableBeforeRequest?.cancelRequest(), this.cancelableBeforeRequest = void 0;
2200
+ }
2201
+ }
2202
+ const Pt = 15e3, Ot = 2;
2203
+ class Dt {
2204
+ connectionManager;
2205
+ pingServerByTimeoutWithFailCalls;
2206
+ constructor({ connectionManager: e }) {
2207
+ this.connectionManager = e, this.pingServerByTimeoutWithFailCalls = ve(Ot, {
2208
+ whenPossibleRequest: async () => {
2209
+ },
2210
+ requestInterval: Pt,
2211
+ request: async () => (d("ping"), this.connectionManager.ping().then(() => {
2212
+ d("ping success");
2213
+ }))
2073
2214
  });
2074
2215
  }
2075
- get requested() {
2076
- return this.stateMachine.isPending;
2216
+ start({ onFailRequest: e }) {
2217
+ this.pingServerByTimeoutWithFailCalls.start(void 0, { onFailRequest: e }).catch(d);
2077
2218
  }
2078
- get isPendingConnect() {
2079
- return this.stateMachine.isPendingConnect;
2219
+ stop() {
2220
+ this.pingServerByTimeoutWithFailCalls.stop();
2080
2221
  }
2081
- get isPendingInitUa() {
2082
- return this.stateMachine.isPendingInitUa;
2222
+ }
2223
+ class yt {
2224
+ callManager;
2225
+ pingServerRequester;
2226
+ disposeCallStatusChange;
2227
+ constructor({
2228
+ connectionManager: e,
2229
+ callManager: t
2230
+ }) {
2231
+ this.callManager = t, this.pingServerRequester = new Dt({
2232
+ connectionManager: e
2233
+ });
2083
2234
  }
2084
- get connectionState() {
2085
- return this.stateMachine.state;
2235
+ start({ onFailRequest: e }) {
2236
+ d("start"), this.disposeCallStatusChange = this.callManager.on("call-status-changed", () => {
2237
+ this.handleCallStatusChange({ onFailRequest: e });
2238
+ }), this.handleCallStatusChange({ onFailRequest: e });
2086
2239
  }
2087
- get isRegistered() {
2088
- return O.isRegisteredUA(this.ua);
2240
+ stop() {
2241
+ d("stop"), this.pingServerRequester.stop(), this.unsubscribeCallStatusChange();
2089
2242
  }
2090
- get isRegisterConfig() {
2091
- return this.configurationManager.isRegister();
2243
+ unsubscribeCallStatusChange() {
2244
+ this.disposeCallStatusChange?.(), this.disposeCallStatusChange = void 0;
2092
2245
  }
2093
- connect = async (e, t) => this.connectionFlow.connect(e, t);
2094
- set = async ({ displayName: e }) => this.connectionFlow.set({ displayName: e });
2095
- disconnect = async () => this.connectionFlow.disconnect();
2096
- async register() {
2097
- return this.registrationManager.register();
2246
+ handleCallStatusChange({ onFailRequest: e }) {
2247
+ this.callManager.isCallActive ? this.pingServerRequester.stop() : this.pingServerRequester.start({ onFailRequest: e });
2098
2248
  }
2099
- async unregister() {
2100
- return this.registrationManager.unregister();
2249
+ }
2250
+ class bt {
2251
+ connectionManager;
2252
+ callManager;
2253
+ isRegistrationFailed = !1;
2254
+ disposers = [];
2255
+ constructor({
2256
+ connectionManager: e,
2257
+ callManager: t
2258
+ }) {
2259
+ this.connectionManager = e, this.callManager = t;
2260
+ }
2261
+ subscribe(e) {
2262
+ this.unsubscribe(), this.disposers.push(
2263
+ this.connectionManager.on("registrationFailed", () => {
2264
+ this.setIsRegistrationFailed();
2265
+ })
2266
+ ), this.disposers.push(
2267
+ this.callManager.on("call-status-changed", ({ isCallActive: t }) => {
2268
+ !t && this.isRegistrationFailed && e();
2269
+ })
2270
+ );
2271
+ }
2272
+ unsubscribe() {
2273
+ this.disposers.forEach((e) => {
2274
+ e();
2275
+ }), this.disposers = [], this.resetIsRegistrationFailed();
2276
+ }
2277
+ setIsRegistrationFailed() {
2278
+ this.isRegistrationFailed = !0;
2279
+ }
2280
+ resetIsRegistrationFailed() {
2281
+ this.isRegistrationFailed = !1;
2282
+ }
2283
+ }
2284
+ const Ce = "Parameters are missing", wt = (n) => n instanceof Error && n.message === Ce, Qn = () => new Error(Ce), Ut = 3e3, Lt = 15e3, Bt = async () => {
2285
+ };
2286
+ class Ft {
2287
+ events;
2288
+ connectionManager;
2289
+ connectionQueueManager;
2290
+ checkTelephonyRequester;
2291
+ pingServerIfNotActiveCallRequester;
2292
+ registrationFailedOutOfCallSubscriber;
2293
+ attemptsState;
2294
+ delayBetweenAttempts;
2295
+ cancelableRequestBeforeRetry;
2296
+ onBeforeRetry;
2297
+ constructor({
2298
+ connectionQueueManager: e,
2299
+ connectionManager: t,
2300
+ callManager: s
2301
+ }, i) {
2302
+ const r = i?.onBeforeRetry ?? Bt;
2303
+ this.connectionQueueManager = e, this.connectionManager = t, this.onBeforeRetry = r, this.events = new k(Se), this.checkTelephonyRequester = new ft({
2304
+ connectionManager: t,
2305
+ interval: i?.checkTelephonyRequestInterval ?? Lt
2306
+ }), this.pingServerIfNotActiveCallRequester = new yt({
2307
+ connectionManager: t,
2308
+ callManager: s
2309
+ }), this.registrationFailedOutOfCallSubscriber = new bt({
2310
+ connectionManager: t,
2311
+ callManager: s
2312
+ }), this.attemptsState = new vt({
2313
+ events: this.events
2314
+ }), this.cancelableRequestBeforeRetry = new G(r), this.delayBetweenAttempts = new fe(
2315
+ i?.timeoutBetweenAttempts ?? Ut
2316
+ );
2317
+ }
2318
+ start(e) {
2319
+ d("auto connector start"), this.stop(), this.connect(e).catch((t) => {
2320
+ d("auto connector failed to connect:", t);
2321
+ });
2322
+ }
2323
+ stop() {
2324
+ d("auto connector stop"), this.stopAttempts(), this.stopConnectTriggers(), this.connectionQueueManager.disconnect().catch((e) => {
2325
+ d("auto connector disconnect: error", e);
2326
+ });
2101
2327
  }
2102
- tryRegister = async () => this.registrationManager.tryRegister();
2103
- sendOptions = async (e, t, s) => this.sipOperations.sendOptions(e, t, s);
2104
- ping = async (e, t) => this.sipOperations.ping(e, t);
2105
- checkTelephony = async (e) => this.sipOperations.checkTelephony(e);
2106
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2107
2328
  on(e, t) {
2108
2329
  return this.events.on(e, t);
2109
2330
  }
2110
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2111
2331
  once(e, t) {
2112
2332
  return this.events.once(e, t);
2113
2333
  }
2114
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2115
2334
  onceRace(e, t) {
2116
2335
  return this.events.onceRace(e, t);
2117
2336
  }
2118
2337
  async wait(e) {
2119
2338
  return this.events.wait(e);
2120
2339
  }
2121
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2122
2340
  off(e, t) {
2123
2341
  this.events.off(e, t);
2124
2342
  }
2125
- isConfigured() {
2126
- return this.configurationManager.isConfigured();
2343
+ stopAttempts() {
2344
+ this.attemptsState.isAttemptInProgress && this.connectionQueueManager.stop(), this.delayBetweenAttempts.cancelRequest(), this.cancelableRequestBeforeRetry.cancelRequest(), this.attemptsState.reset();
2127
2345
  }
2128
- getConnectionConfiguration = () => this.configurationManager.get();
2129
- destroy() {
2130
- this.stateMachine.destroy();
2346
+ stopConnectTriggers() {
2347
+ d("stopConnectTriggers"), this.pingServerIfNotActiveCallRequester.stop(), this.checkTelephonyRequester.stop(), this.registrationFailedOutOfCallSubscriber.unsubscribe();
2131
2348
  }
2132
- // eslint-disable-next-line @typescript-eslint/class-methods-use-this
2133
- getSipServerUrl = (e) => e;
2134
- getUaProtected = () => {
2135
- if (!this.ua)
2136
- throw new Error("UA not initialized");
2137
- return this.ua;
2138
- };
2139
- getUa = () => this.ua;
2140
- }
2141
- class gt {
2142
- connectionManager;
2143
- stackPromises = Z({
2144
- noRunIsNotActual: !0
2145
- });
2146
- constructor({ connectionManager: e }) {
2147
- this.connectionManager = e;
2349
+ runCheckTelephony(e) {
2350
+ d("runCheckTelephony"), this.checkTelephonyRequester.start({
2351
+ onBeforeRequest: async () => (await this.onBeforeRetry(), e.getParameters()),
2352
+ onSuccessRequest: () => {
2353
+ d("runCheckTelephony: onSuccessRequest"), this.connectIfDisconnected(e);
2354
+ },
2355
+ onFailRequest: (t) => {
2356
+ d("runCheckTelephony: onFailRequest", t.message);
2357
+ }
2358
+ });
2359
+ }
2360
+ async connect(e) {
2361
+ if (d("connect: attempts.count", this.attemptsState.count), this.events.trigger(O.BEFORE_ATTEMPT, {}), this.stopConnectTriggers(), this.attemptsState.hasLimitReached()) {
2362
+ d("connect: isLimitReached!"), this.handleLimitReached(e);
2363
+ return;
2364
+ }
2365
+ return this.attemptsState.startAttempt(), this.attemptsState.increment(), this.processConnect(e);
2366
+ }
2367
+ async processConnect(e) {
2368
+ try {
2369
+ await this.connectionQueueManager.connect(e.getParameters, e.options), d("processConnect success"), this.handleSucceededAttempt(e);
2370
+ } catch (t) {
2371
+ if (Rt(t)) {
2372
+ this.handleSucceededAttempt(e);
2373
+ return;
2374
+ }
2375
+ if (wt(t)) {
2376
+ d("processConnect: parameters not exist error", t);
2377
+ return;
2378
+ }
2379
+ if (be(t)) {
2380
+ d("processConnect: not actual error", t), this.events.trigger(O.CANCELLED_ATTEMPT, t);
2381
+ return;
2382
+ }
2383
+ d("processConnect: error", t), this.reconnect(e);
2384
+ }
2385
+ }
2386
+ handleLimitReached(e) {
2387
+ this.attemptsState.finishAttempt(), this.events.trigger(O.FAILED_ATTEMPT, new Error("Limit reached")), this.runCheckTelephony(e);
2388
+ }
2389
+ handleSucceededAttempt(e) {
2390
+ d("handleSucceededAttempt"), this.subscribeToConnectTriggers(e), this.events.trigger(O.SUCCEEDED_ATTEMPT, {});
2391
+ }
2392
+ subscribeToConnectTriggers(e) {
2393
+ this.pingServerIfNotActiveCallRequester.start({
2394
+ onFailRequest: () => {
2395
+ d("pingServer onFailRequest"), this.start(e);
2396
+ }
2397
+ }), this.registrationFailedOutOfCallSubscriber.subscribe(() => {
2398
+ d("registrationFailedOutOfCallListener callback"), this.start(e);
2399
+ });
2400
+ }
2401
+ connectIfDisconnected(e) {
2402
+ const t = this.hasFailedOrDisconnectedConnection();
2403
+ d("connectIfDisconnected: isFailedOrDisconnected", t), t ? this.start(e) : (this.stopConnectTriggers(), this.events.trigger(O.SUCCEEDED_ATTEMPT, {}));
2404
+ }
2405
+ reconnect(e) {
2406
+ d("reconnect"), this.delayBetweenAttempts.request().then(async () => (d("reconnect: delayBetweenAttempts success"), this.cancelableRequestBeforeRetry.request())).then(async () => (d("reconnect: onBeforeRetry success"), this.connect(e))).catch((t) => {
2407
+ const s = t instanceof Error ? t : new Error("Failed to reconnect");
2408
+ _e(t) || Pe(t) ? this.events.trigger(O.CANCELLED_ATTEMPT, s) : this.events.trigger(O.FAILED_ATTEMPT, s), d("reconnect: error", t);
2409
+ });
2410
+ }
2411
+ hasFailedOrDisconnectedConnection() {
2412
+ const { isFailed: e, isDisconnected: t } = this.connectionManager;
2413
+ return e || t;
2148
2414
  }
2149
- connect = async (...e) => this.stackPromises.run(async () => this.connectionManager.connect(...e));
2150
- disconnect = async () => this.stackPromises.run(async () => this.connectionManager.disconnect());
2151
- register = async () => this.stackPromises.run(async () => this.connectionManager.register());
2152
- unregister = async () => this.stackPromises.run(async () => this.connectionManager.unregister());
2153
- tryRegister = async () => this.stackPromises.run(async () => this.connectionManager.tryRegister());
2154
- checkTelephony = async (...e) => this.stackPromises.run(async () => this.connectionManager.checkTelephony(...e));
2155
- sendOptions = async (...e) => this.stackPromises.run(async () => this.connectionManager.sendOptions(...e));
2156
- ping = async (...e) => this.stackPromises.run(async () => this.connectionManager.ping(...e));
2157
- set = async (...e) => this.stackPromises.run(async () => this.connectionManager.set(...e));
2158
2415
  }
2159
- var U = /* @__PURE__ */ ((n) => (n.INCOMING_CALL = "incomingCall", n.DECLINED_INCOMING_CALL = "declinedIncomingCall", n.TERMINATED_INCOMING_CALL = "terminatedIncomingCall", n.FAILED_INCOMING_CALL = "failedIncomingCall", n))(U || {}), x = /* @__PURE__ */ ((n) => (n.LOCAL = "local", n.REMOTE = "remote", n.SYSTEM = "system", n))(x || {});
2160
- const ue = [
2416
+ var w = /* @__PURE__ */ ((n) => (n.INCOMING_CALL = "incomingCall", n.DECLINED_INCOMING_CALL = "declinedIncomingCall", n.TERMINATED_INCOMING_CALL = "terminatedIncomingCall", n.FAILED_INCOMING_CALL = "failedIncomingCall", n))(w || {});
2417
+ const Ee = [
2161
2418
  "incomingCall",
2162
2419
  "declinedIncomingCall",
2163
2420
  "terminatedIncomingCall",
2164
2421
  "failedIncomingCall"
2165
- ], lt = 486, ut = 487;
2166
- class Tt {
2422
+ ], kt = 486, $t = 487;
2423
+ class Vt {
2167
2424
  events;
2168
2425
  incomingRTCSession;
2169
2426
  connectionManager;
2170
2427
  constructor(e) {
2171
- this.connectionManager = e, this.events = new D(ue), this.start();
2428
+ this.connectionManager = e, this.events = new U(Ee), this.start();
2172
2429
  }
2173
2430
  get remoteCallerData() {
2174
2431
  return {
@@ -2198,19 +2455,19 @@ class Tt {
2198
2455
  return this.removeIncomingSession(), e;
2199
2456
  };
2200
2457
  async declineToIncomingCall({
2201
- statusCode: e = ut
2458
+ statusCode: e = $t
2202
2459
  } = {}) {
2203
2460
  return new Promise((t, s) => {
2204
2461
  try {
2205
- const r = this.getIncomingRTCSession(), i = this.remoteCallerData;
2206
- this.removeIncomingSession(), this.events.trigger(U.DECLINED_INCOMING_CALL, i), r.terminate({ status_code: e }), t();
2207
- } catch (r) {
2208
- s(r);
2462
+ const i = this.getIncomingRTCSession(), r = this.remoteCallerData;
2463
+ this.removeIncomingSession(), this.events.trigger(w.DECLINED_INCOMING_CALL, r), i.terminate({ status_code: e }), t();
2464
+ } catch (i) {
2465
+ s(i);
2209
2466
  }
2210
2467
  });
2211
2468
  }
2212
2469
  async busyIncomingCall() {
2213
- return this.declineToIncomingCall({ statusCode: lt });
2470
+ return this.declineToIncomingCall({ statusCode: kt });
2214
2471
  }
2215
2472
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2216
2473
  on(e, t) {
@@ -2241,25 +2498,25 @@ class Tt {
2241
2498
  originator: e,
2242
2499
  session: t
2243
2500
  }) => {
2244
- e === x.REMOTE && this.setIncomingSession(t);
2501
+ e === "remote" && this.setIncomingSession(t);
2245
2502
  };
2246
2503
  setIncomingSession(e) {
2247
2504
  this.incomingRTCSession = e;
2248
2505
  const t = this.remoteCallerData;
2249
2506
  e.on("failed", (s) => {
2250
- this.removeIncomingSession(), s.originator === x.LOCAL ? this.events.trigger(U.TERMINATED_INCOMING_CALL, t) : this.events.trigger(U.FAILED_INCOMING_CALL, t);
2251
- }), this.events.trigger(U.INCOMING_CALL, t);
2507
+ this.removeIncomingSession(), s.originator === "local" ? this.events.trigger(w.TERMINATED_INCOMING_CALL, t) : this.events.trigger(w.FAILED_INCOMING_CALL, t);
2508
+ }), this.events.trigger(w.INCOMING_CALL, t);
2252
2509
  }
2253
2510
  removeIncomingSession() {
2254
2511
  delete this.incomingRTCSession;
2255
2512
  }
2256
2513
  }
2257
2514
  const b = 1e3;
2258
- var C = /* @__PURE__ */ ((n) => (n.INBOUND_RTP = "inbound-rtp", n.REMOTE_OUTBOUND_RTP = "remote-outbound-rtp", n.MEDIA_SOURCE = "media-source", n.OUTBOUND_RTP = "outbound-rtp", n.REMOTE_INBOUND_RTP = "remote-inbound-rtp", n.CODEC = "codec", n.CANDIDATE_PAIR = "candidate-pair", n.CERTIFICATE = "certificate", n.TRANSPORT = "transport", n.LOCAL_CANDIDATE = "local-candidate", n.REMOTE_CANDIDATE = "remote-candidate", n))(C || {});
2259
- const Te = ["collected"], Y = () => "performance" in window ? performance.now() : Date.now(), w = (n) => [...n.keys()].reduce((e, t) => {
2515
+ var E = /* @__PURE__ */ ((n) => (n.INBOUND_RTP = "inbound-rtp", n.REMOTE_OUTBOUND_RTP = "remote-outbound-rtp", n.MEDIA_SOURCE = "media-source", n.OUTBOUND_RTP = "outbound-rtp", n.REMOTE_INBOUND_RTP = "remote-inbound-rtp", n.CODEC = "codec", n.CANDIDATE_PAIR = "candidate-pair", n.CERTIFICATE = "certificate", n.TRANSPORT = "transport", n.LOCAL_CANDIDATE = "local-candidate", n.REMOTE_CANDIDATE = "remote-candidate", n))(E || {});
2516
+ const Ae = ["collected"], X = () => "performance" in window ? performance.now() : Date.now(), L = (n) => [...n.keys()].reduce((e, t) => {
2260
2517
  const s = n.get(t);
2261
2518
  return s === void 0 ? e : { ...e, [s.type]: s };
2262
- }, {}), St = (n) => {
2519
+ }, {}), qt = (n) => {
2263
2520
  if (!n)
2264
2521
  return {
2265
2522
  outboundRtp: void 0,
@@ -2267,14 +2524,14 @@ const Te = ["collected"], Y = () => "performance" in window ? performance.now()
2267
2524
  mediaSource: void 0,
2268
2525
  remoteInboundRtp: void 0
2269
2526
  };
2270
- const e = w(n);
2527
+ const e = L(n);
2271
2528
  return {
2272
- outboundRtp: e[C.OUTBOUND_RTP],
2273
- codec: e[C.CODEC],
2274
- mediaSource: e[C.MEDIA_SOURCE],
2275
- remoteInboundRtp: e[C.REMOTE_INBOUND_RTP]
2529
+ outboundRtp: e[E.OUTBOUND_RTP],
2530
+ codec: e[E.CODEC],
2531
+ mediaSource: e[E.MEDIA_SOURCE],
2532
+ remoteInboundRtp: e[E.REMOTE_INBOUND_RTP]
2276
2533
  };
2277
- }, z = (n) => {
2534
+ }, J = (n) => {
2278
2535
  if (!n)
2279
2536
  return {
2280
2537
  outboundRtp: void 0,
@@ -2282,14 +2539,14 @@ const Te = ["collected"], Y = () => "performance" in window ? performance.now()
2282
2539
  mediaSource: void 0,
2283
2540
  remoteInboundRtp: void 0
2284
2541
  };
2285
- const e = w(n);
2542
+ const e = L(n);
2286
2543
  return {
2287
- outboundRtp: e[C.OUTBOUND_RTP],
2288
- codec: e[C.CODEC],
2289
- mediaSource: e[C.MEDIA_SOURCE],
2290
- remoteInboundRtp: e[C.REMOTE_INBOUND_RTP]
2544
+ outboundRtp: e[E.OUTBOUND_RTP],
2545
+ codec: e[E.CODEC],
2546
+ mediaSource: e[E.MEDIA_SOURCE],
2547
+ remoteInboundRtp: e[E.REMOTE_INBOUND_RTP]
2291
2548
  };
2292
- }, X = ({
2549
+ }, K = ({
2293
2550
  videoReceiversStats: n,
2294
2551
  synchronizationSourcesVideo: e
2295
2552
  }) => {
@@ -2299,13 +2556,13 @@ const Te = ["collected"], Y = () => "performance" in window ? performance.now()
2299
2556
  codec: void 0,
2300
2557
  synchronizationSources: e
2301
2558
  };
2302
- const t = w(n);
2559
+ const t = L(n);
2303
2560
  return {
2304
- inboundRtp: t[C.INBOUND_RTP],
2305
- codec: t[C.CODEC],
2561
+ inboundRtp: t[E.INBOUND_RTP],
2562
+ codec: t[E.CODEC],
2306
2563
  synchronizationSources: e
2307
2564
  };
2308
- }, Ct = ({
2565
+ }, Wt = ({
2309
2566
  audioReceiverStats: n,
2310
2567
  synchronizationSourcesAudio: e
2311
2568
  }) => {
@@ -2316,14 +2573,14 @@ const Te = ["collected"], Y = () => "performance" in window ? performance.now()
2316
2573
  remoteOutboundRtp: void 0,
2317
2574
  synchronizationSources: e
2318
2575
  };
2319
- const t = w(n);
2576
+ const t = L(n);
2320
2577
  return {
2321
- inboundRtp: t[C.INBOUND_RTP],
2322
- codec: t[C.CODEC],
2323
- remoteOutboundRtp: t[C.REMOTE_OUTBOUND_RTP],
2578
+ inboundRtp: t[E.INBOUND_RTP],
2579
+ codec: t[E.CODEC],
2580
+ remoteOutboundRtp: t[E.REMOTE_OUTBOUND_RTP],
2324
2581
  synchronizationSources: e
2325
2582
  };
2326
- }, Se = (n) => {
2583
+ }, Ne = (n) => {
2327
2584
  if (!n)
2328
2585
  return {
2329
2586
  candidatePair: void 0,
@@ -2332,122 +2589,122 @@ const Te = ["collected"], Y = () => "performance" in window ? performance.now()
2332
2589
  remoteCandidate: void 0,
2333
2590
  transport: void 0
2334
2591
  };
2335
- const e = w(n);
2592
+ const e = L(n);
2336
2593
  return {
2337
- candidatePair: e[C.CANDIDATE_PAIR],
2338
- certificate: e[C.CERTIFICATE],
2339
- localCandidate: e[C.LOCAL_CANDIDATE],
2340
- remoteCandidate: e[C.REMOTE_CANDIDATE],
2341
- transport: e[C.TRANSPORT]
2594
+ candidatePair: e[E.CANDIDATE_PAIR],
2595
+ certificate: e[E.CERTIFICATE],
2596
+ localCandidate: e[E.LOCAL_CANDIDATE],
2597
+ remoteCandidate: e[E.REMOTE_CANDIDATE],
2598
+ transport: e[E.TRANSPORT]
2342
2599
  };
2343
- }, Et = ({
2600
+ }, Ht = ({
2344
2601
  audioSenderStats: n,
2345
2602
  videoSenderFirstStats: e,
2346
2603
  videoSenderSecondStats: t
2347
2604
  }) => ({
2348
- video: z(e),
2349
- secondVideo: z(t),
2350
- audio: St(n),
2351
- additional: Se(
2605
+ video: J(e),
2606
+ secondVideo: J(t),
2607
+ audio: qt(n),
2608
+ additional: Ne(
2352
2609
  n ?? e ?? t
2353
2610
  )
2354
- }), Nt = ({
2611
+ }), xt = ({
2355
2612
  audioReceiverStats: n,
2356
2613
  videoReceiverFirstStats: e,
2357
2614
  videoReceiverSecondStats: t,
2358
2615
  synchronizationSources: s
2359
2616
  }) => ({
2360
- video: X({
2617
+ video: K({
2361
2618
  videoReceiversStats: e,
2362
2619
  synchronizationSourcesVideo: s.video
2363
2620
  }),
2364
- secondVideo: X({
2621
+ secondVideo: K({
2365
2622
  videoReceiversStats: t,
2366
2623
  synchronizationSourcesVideo: s.video
2367
2624
  }),
2368
- audio: Ct({
2625
+ audio: Wt({
2369
2626
  audioReceiverStats: n,
2370
2627
  synchronizationSourcesAudio: s.audio
2371
2628
  }),
2372
- additional: Se(
2629
+ additional: Ne(
2373
2630
  n ?? e ?? t
2374
2631
  )
2375
- }), At = ({
2632
+ }), Gt = ({
2376
2633
  audioSenderStats: n,
2377
2634
  videoSenderFirstStats: e,
2378
2635
  videoSenderSecondStats: t,
2379
2636
  audioReceiverStats: s,
2380
- videoReceiverFirstStats: r,
2381
- videoReceiverSecondStats: i,
2637
+ videoReceiverFirstStats: i,
2638
+ videoReceiverSecondStats: r,
2382
2639
  synchronizationSources: a
2383
2640
  }) => {
2384
- const o = Et({
2641
+ const o = Ht({
2385
2642
  audioSenderStats: n,
2386
2643
  videoSenderFirstStats: e,
2387
2644
  videoSenderSecondStats: t
2388
- }), c = Nt({
2645
+ }), c = xt({
2389
2646
  audioReceiverStats: s,
2390
- videoReceiverFirstStats: r,
2391
- videoReceiverSecondStats: i,
2647
+ videoReceiverFirstStats: i,
2648
+ videoReceiverSecondStats: r,
2392
2649
  synchronizationSources: a
2393
2650
  });
2394
2651
  return {
2395
2652
  outbound: o,
2396
2653
  inbound: c
2397
2654
  };
2398
- }, Rt = async (n) => {
2399
- const e = "audio", t = "video", s = n.getSenders(), r = s.find((g) => g.track?.kind === e), i = s.filter((g) => g.track?.kind === t), a = n.getReceivers(), o = a.find((g) => g.track.kind === e), c = a.filter((g) => g.track.kind === t), d = {
2655
+ }, Qt = async (n) => {
2656
+ const e = "audio", t = "video", s = n.getSenders(), i = s.find((g) => g.track?.kind === e), r = s.filter((g) => g.track?.kind === t), a = n.getReceivers(), o = a.find((g) => g.track.kind === e), c = a.filter((g) => g.track.kind === t), h = {
2400
2657
  trackIdentifier: o?.track.id,
2401
2658
  item: o?.getSynchronizationSources()[0]
2402
- }, u = {
2659
+ }, T = {
2403
2660
  trackIdentifier: c[0]?.track.id,
2404
2661
  item: c[0]?.getSynchronizationSources()[0]
2405
- }, T = {
2406
- audio: d,
2407
- video: u
2662
+ }, S = {
2663
+ audio: h,
2664
+ video: T
2408
2665
  };
2409
2666
  return Promise.all([
2410
- r?.getStats() ?? Promise.resolve(void 0),
2411
- i[0]?.getStats() ?? Promise.resolve(void 0),
2412
- i[1]?.getStats() ?? Promise.resolve(void 0),
2667
+ i?.getStats() ?? Promise.resolve(void 0),
2668
+ r[0]?.getStats() ?? Promise.resolve(void 0),
2669
+ r[1]?.getStats() ?? Promise.resolve(void 0),
2413
2670
  o?.getStats() ?? Promise.resolve(void 0),
2414
2671
  c[0]?.getStats() ?? Promise.resolve(void 0),
2415
2672
  c[1]?.getStats() ?? Promise.resolve(void 0)
2416
2673
  ]).then((g) => {
2417
2674
  const [
2418
- S,
2675
+ C,
2676
+ m,
2419
2677
  I,
2420
- _,
2421
2678
  R,
2422
2679
  y,
2423
2680
  $
2424
2681
  ] = g;
2425
2682
  return {
2426
- synchronizationSources: T,
2427
- audioSenderStats: S,
2428
- videoSenderFirstStats: I,
2429
- videoSenderSecondStats: _,
2683
+ synchronizationSources: S,
2684
+ audioSenderStats: C,
2685
+ videoSenderFirstStats: m,
2686
+ videoSenderSecondStats: I,
2430
2687
  audioReceiverStats: R,
2431
2688
  videoReceiverFirstStats: y,
2432
2689
  videoReceiverSecondStats: $
2433
2690
  };
2434
2691
  });
2435
- }, It = (n) => {
2436
- E(String(n));
2692
+ }, Yt = (n) => {
2693
+ d(String(n));
2437
2694
  };
2438
- class _t {
2695
+ class zt {
2439
2696
  events;
2440
2697
  setTimeoutRequest;
2441
- requesterAllStatistics = new Re(Rt);
2698
+ requesterAllStatistics = new G(Qt);
2442
2699
  constructor() {
2443
- this.events = new K(Te), this.setTimeoutRequest = new ee();
2700
+ this.events = new k(Ae), this.setTimeoutRequest = new Z();
2444
2701
  }
2445
2702
  get requested() {
2446
2703
  return this.setTimeoutRequest.requested;
2447
2704
  }
2448
2705
  start(e, {
2449
2706
  interval: t = b,
2450
- onError: s = It
2707
+ onError: s = Yt
2451
2708
  } = {}) {
2452
2709
  this.stop(), this.setTimeoutRequest.request(() => {
2453
2710
  this.collectStatistics(e, {
@@ -2476,21 +2733,21 @@ class _t {
2476
2733
  collectStatistics = (e, {
2477
2734
  onError: t
2478
2735
  }) => {
2479
- const s = Y();
2480
- this.requesterAllStatistics.request(e).then((r) => {
2481
- this.events.trigger("collected", At(r));
2482
- const a = Y() - s;
2736
+ const s = X();
2737
+ this.requesterAllStatistics.request(e).then((i) => {
2738
+ this.events.trigger("collected", Gt(i));
2739
+ const a = X() - s;
2483
2740
  let o = b;
2484
2741
  a > 48 ? o = b * 4 : a > 32 ? o = b * 3 : a > 16 && (o = b * 2), this.start(e, {
2485
2742
  onError: t,
2486
2743
  interval: o
2487
2744
  });
2488
- }).catch((r) => {
2489
- t && t(r);
2745
+ }).catch((i) => {
2746
+ t && t(i);
2490
2747
  });
2491
2748
  };
2492
2749
  }
2493
- class mt {
2750
+ class Xt {
2494
2751
  availableIncomingBitrate;
2495
2752
  statsPeerConnection;
2496
2753
  callManager;
@@ -2500,7 +2757,7 @@ class mt {
2500
2757
  callManager: e,
2501
2758
  apiManager: t
2502
2759
  }) {
2503
- this.callManager = e, this.apiManager = t, this.statsPeerConnection = new _t(), this.subscribe();
2760
+ this.callManager = e, this.apiManager = t, this.statsPeerConnection = new zt(), this.subscribe();
2504
2761
  }
2505
2762
  get events() {
2506
2763
  return this.statsPeerConnection.events;
@@ -2538,37 +2795,145 @@ class mt {
2538
2795
  };
2539
2796
  maybeSendStats() {
2540
2797
  this.availableIncomingBitrate !== void 0 && this.hasAvailableIncomingBitrateChangedQuarter() && this.apiManager.sendStats({ availableIncomingBitrate: this.availableIncomingBitrate }).catch((e) => {
2541
- E("Failed to send stats", e);
2798
+ d("Failed to send stats", e);
2542
2799
  });
2543
2800
  }
2544
2801
  }
2545
- const Mt = (n, e) => n.filter((s) => e.some((r) => r.clockRate === s.clockRate && r.mimeType === s.mimeType && r.channels === s.channels && r.sdpFmtpLine === s.sdpFmtpLine)), pt = (n) => {
2546
- const e = RTCRtpSender.getCapabilities(n), t = RTCRtpReceiver.getCapabilities(n), s = e === null ? [] : e.codecs, r = t === null ? [] : t.codecs;
2547
- return Mt(s, r);
2548
- }, Pt = (n, e) => e === void 0 || e.length === 0 ? n : n.sort((t, s) => {
2549
- const r = e.indexOf(t.mimeType), i = e.indexOf(s.mimeType), a = r === -1 ? Number.MAX_VALUE : r, o = i === -1 ? Number.MAX_VALUE : i;
2802
+ const Jt = (n, e) => n.filter((s) => e.some((i) => i.clockRate === s.clockRate && i.mimeType === s.mimeType && i.channels === s.channels && i.sdpFmtpLine === s.sdpFmtpLine)), Kt = (n) => {
2803
+ const e = RTCRtpSender.getCapabilities(n), t = RTCRtpReceiver.getCapabilities(n), s = e === null ? [] : e.codecs, i = t === null ? [] : t.codecs;
2804
+ return Jt(s, i);
2805
+ }, jt = (n, e) => e === void 0 || e.length === 0 ? n : n.sort((t, s) => {
2806
+ const i = e.indexOf(t.mimeType), r = e.indexOf(s.mimeType), a = i === -1 ? Number.MAX_VALUE : i, o = r === -1 ? Number.MAX_VALUE : r;
2550
2807
  return a - o;
2551
- }), vt = (n, e) => e === void 0 || e.length === 0 ? n : n.filter((t) => !e.includes(t.mimeType)), ft = (n, {
2808
+ }), Zt = (n, e) => e === void 0 || e.length === 0 ? n : n.filter((t) => !e.includes(t.mimeType)), en = (n, {
2552
2809
  preferredMimeTypesVideoCodecs: e,
2553
2810
  excludeMimeTypesVideoCodecs: t
2554
2811
  }) => {
2555
2812
  try {
2556
2813
  if (typeof n.setCodecPreferences == "function" && n.sender.track?.kind === "video" && (e !== void 0 && e.length > 0 || t !== void 0 && t.length > 0)) {
2557
- const s = pt("video"), r = vt(s, t), i = Pt(r, e);
2558
- n.setCodecPreferences(i);
2814
+ const s = Kt("video"), i = Zt(s, t), r = jt(i, e);
2815
+ n.setCodecPreferences(r);
2559
2816
  }
2560
2817
  } catch (s) {
2561
- E("setCodecPreferences error", s);
2818
+ d("setCodecPreferences error", s);
2562
2819
  }
2563
- }, Ot = (n) => [...n.keys()].map((e) => n.get(e)), Dt = (n, e) => Ot(n).find((t) => t?.type === e), yt = async (n) => n.getStats().then((e) => Dt(e, "codec")?.mimeType);
2564
- class bt {
2820
+ };
2821
+ class tn {
2822
+ /**
2823
+ * Хранилище основных transceiver'ов
2824
+ */
2825
+ transceivers = {};
2826
+ callManager;
2827
+ apiManager;
2828
+ constructor({
2829
+ callManager: e,
2830
+ apiManager: t
2831
+ }) {
2832
+ this.callManager = e, this.apiManager = t, this.subscribe();
2833
+ }
2834
+ /**
2835
+ * Сохраняет transceiver в соответствующем хранилище в зависимости от типа трека и mid
2836
+ */
2837
+ storeTransceiver(e, t) {
2838
+ const { kind: s } = t;
2839
+ if (s === "audio")
2840
+ this.transceivers.mainAudio ??= e;
2841
+ else {
2842
+ const { mid: i } = e;
2843
+ i === "2" ? this.transceivers.presentationVideo ??= e : this.transceivers.mainVideo ??= e;
2844
+ }
2845
+ }
2846
+ /**
2847
+ * Возвращает все сохраненные transceiver'ы
2848
+ */
2849
+ getTransceivers() {
2850
+ return { ...this.transceivers };
2851
+ }
2852
+ /**
2853
+ * Возвращает основной аудио transceiver
2854
+ */
2855
+ getMainAudioTransceiver() {
2856
+ return this.transceivers.mainAudio;
2857
+ }
2858
+ /**
2859
+ * Возвращает основной видео transceiver
2860
+ */
2861
+ getMainVideoTransceiver() {
2862
+ return this.transceivers.mainVideo;
2863
+ }
2864
+ /**
2865
+ * Возвращает презентационный видео transceiver
2866
+ */
2867
+ getPresentationVideoTransceiver() {
2868
+ return this.transceivers.presentationVideo;
2869
+ }
2870
+ /**
2871
+ * Проверяет, есть ли сохраненный transceiver для указанного типа
2872
+ */
2873
+ hasTransceiver(e) {
2874
+ return this.transceivers[e] !== void 0;
2875
+ }
2876
+ /**
2877
+ * Очищает все сохраненные transceiver'ы
2878
+ */
2879
+ clear() {
2880
+ this.transceivers.mainVideo = void 0, this.transceivers.mainAudio = void 0, this.transceivers.presentationVideo = void 0;
2881
+ }
2882
+ /**
2883
+ * Возвращает количество сохраненных transceiver'ов
2884
+ */
2885
+ getCount() {
2886
+ let e = 0;
2887
+ return this.transceivers.mainAudio && (e += 1), this.transceivers.mainVideo && (e += 1), this.transceivers.presentationVideo && (e += 1), e;
2888
+ }
2889
+ /**
2890
+ * Проверяет, пустое ли хранилище
2891
+ */
2892
+ isEmpty() {
2893
+ return this.getCount() === 0;
2894
+ }
2895
+ /**
2896
+ * Обрабатывает событие restart от ApiManager
2897
+ */
2898
+ handleRestart = (e) => {
2899
+ this.updateTransceivers(e).catch((t) => {
2900
+ d("Failed to update transceivers", t);
2901
+ }).finally(() => {
2902
+ this.callManager.restartIce().catch((t) => {
2903
+ d("Failed to restart ICE", t);
2904
+ });
2905
+ });
2906
+ };
2907
+ /**
2908
+ * Обновляет transceiver'ы в соответствии с данными restart
2909
+ */
2910
+ updateTransceivers = async (e) => {
2911
+ const { videoTrackCount: t } = e;
2912
+ t === 2 && (this.getTransceivers().presentationVideo !== void 0 || await this.callManager.addTransceiver("video", {
2913
+ direction: "recvonly"
2914
+ }).catch((r) => {
2915
+ d("Failed to add presentation video transceiver", r);
2916
+ }));
2917
+ };
2918
+ subscribe() {
2919
+ this.callManager.on("peerconnection:ontrack", this.handleTrack), this.callManager.on("failed", this.handleEnded), this.callManager.on("ended", this.handleEnded), this.apiManager.on("restart", this.handleRestart);
2920
+ }
2921
+ handleTrack = (e) => {
2922
+ this.storeTransceiver(e.transceiver, e.track);
2923
+ };
2924
+ handleEnded = () => {
2925
+ this.clear();
2926
+ };
2927
+ }
2928
+ const nn = (n) => [...n.keys()].map((e) => n.get(e)), sn = (n, e) => nn(n).find((t) => t?.type === e), rn = async (n) => n.getStats().then((e) => sn(e, "codec")?.mimeType);
2929
+ class an {
2565
2930
  // eslint-disable-next-line @typescript-eslint/class-methods-use-this
2566
2931
  async getCodecFromSender(e) {
2567
- return await yt(e) ?? "";
2932
+ return await rn(e) ?? "";
2568
2933
  }
2569
2934
  }
2570
- class Ut {
2571
- stackPromises = Z({
2935
+ class on {
2936
+ stackPromises = te({
2572
2937
  noRunIsNotActual: !0
2573
2938
  });
2574
2939
  /**
@@ -2588,34 +2953,34 @@ class Ut {
2588
2953
  */
2589
2954
  async run() {
2590
2955
  return this.stackPromises().catch((e) => {
2591
- E("TaskQueue: error", e);
2956
+ d("TaskQueue: error", e);
2592
2957
  });
2593
2958
  }
2594
2959
  }
2595
- class wt {
2960
+ class cn {
2596
2961
  taskQueue;
2597
2962
  onSetParameters;
2598
2963
  constructor(e) {
2599
- this.onSetParameters = e, this.taskQueue = new Ut();
2964
+ this.onSetParameters = e, this.taskQueue = new on();
2600
2965
  }
2601
2966
  async setEncodingsToSender(e, t) {
2602
- return this.taskQueue.add(async () => ce(e, t, this.onSetParameters));
2967
+ return this.taskQueue.add(async () => de(e, t, this.onSetParameters));
2603
2968
  }
2604
2969
  stop() {
2605
2970
  this.taskQueue.stop();
2606
2971
  }
2607
2972
  }
2608
- const Ce = (n, e) => n !== void 0 && e !== void 0 && n.toLowerCase().includes(e.toLowerCase()), Lt = 1e6, p = (n) => n * Lt, Ee = p(0.06), Ne = p(4), Bt = (n) => n <= 64 ? Ee : n <= 128 ? p(0.12) : n <= 256 ? p(0.25) : n <= 384 ? p(0.32) : n <= 426 ? p(0.38) : n <= 640 ? p(0.5) : n <= 848 ? p(0.7) : n <= 1280 ? p(1) : n <= 1920 ? p(2) : Ne, kt = "av1", Ft = (n) => Ce(n, kt), $t = 0.6, Q = (n, e) => Ft(e) ? n * $t : n, Vt = (n) => Q(Ee, n), Wt = (n) => Q(Ne, n), J = (n, e) => {
2609
- const t = Bt(n);
2610
- return Q(t, e);
2611
- }, V = 1, Ht = ({
2973
+ const Re = (n, e) => n !== void 0 && e !== void 0 && n.toLowerCase().includes(e.toLowerCase()), dn = 1e6, M = (n) => n * dn, Ie = M(0.06), pe = M(4), hn = (n) => n <= 64 ? Ie : n <= 128 ? M(0.12) : n <= 256 ? M(0.25) : n <= 384 ? M(0.32) : n <= 426 ? M(0.38) : n <= 640 ? M(0.5) : n <= 848 ? M(0.7) : n <= 1280 ? M(1) : n <= 1920 ? M(2) : pe, ln = "av1", gn = (n) => Re(n, ln), un = 0.6, Y = (n, e) => gn(e) ? n * un : n, Tn = (n) => Y(Ie, n), Sn = (n) => Y(pe, n), j = (n, e) => {
2974
+ const t = hn(n);
2975
+ return Y(t, e);
2976
+ }, V = 1, Cn = ({
2612
2977
  videoTrack: n,
2613
2978
  targetSize: e
2614
2979
  }) => {
2615
- const t = n.getSettings(), s = t.width, r = t.height, i = s === void 0 ? V : s / e.width, a = r === void 0 ? V : r / e.height;
2616
- return Math.max(i, a, V);
2980
+ const t = n.getSettings(), s = t.width, i = t.height, r = s === void 0 ? V : s / e.width, a = i === void 0 ? V : i / e.height;
2981
+ return Math.max(r, a, V);
2617
2982
  };
2618
- class xt {
2983
+ class En {
2619
2984
  ignoreForCodec;
2620
2985
  senderFinder;
2621
2986
  codecProvider;
@@ -2634,8 +2999,8 @@ class xt {
2634
2999
  senderFinder: e,
2635
3000
  codecProvider: t,
2636
3001
  parametersSetter: s
2637
- }, r) {
2638
- this.senderFinder = e, this.codecProvider = t, this.parametersSetter = s, this.ignoreForCodec = r.ignoreForCodec;
3002
+ }, i) {
3003
+ this.senderFinder = e, this.codecProvider = t, this.parametersSetter = s, this.ignoreForCodec = i.ignoreForCodec;
2639
3004
  }
2640
3005
  /**
2641
3006
  * Выполняет балансировку на основе заголовков от сервера
@@ -2644,21 +3009,21 @@ class xt {
2644
3009
  * @returns Promise с результатом балансировки
2645
3010
  */
2646
3011
  async balance(e, t) {
2647
- const s = e.getSenders(), r = this.senderFinder.findVideoSender(s);
2648
- if (!r?.track)
2649
- return { ...this.resultNoChanged, sender: r };
2650
- const i = await this.codecProvider.getCodecFromSender(r);
2651
- if (Ce(i, this.ignoreForCodec))
2652
- return { ...this.resultNoChanged, sender: r };
3012
+ const s = e.getSenders(), i = this.senderFinder.findVideoSender(s);
3013
+ if (!i?.track)
3014
+ return { ...this.resultNoChanged, sender: i };
3015
+ const r = await this.codecProvider.getCodecFromSender(i);
3016
+ if (Re(r, this.ignoreForCodec))
3017
+ return { ...this.resultNoChanged, sender: i };
2653
3018
  const { mainCam: a, resolutionMainCam: o } = t ?? {};
2654
3019
  return this.processSender(
2655
3020
  { mainCam: a, resolutionMainCam: o },
2656
3021
  {
2657
- sender: r,
2658
- codec: i,
2659
- videoTrack: r.track
3022
+ sender: i,
3023
+ codec: r,
3024
+ videoTrack: i.track
2660
3025
  }
2661
- ).then((c) => ({ ...c, sender: r }));
3026
+ ).then((c) => ({ ...c, sender: i }));
2662
3027
  }
2663
3028
  /**
2664
3029
  * Обрабатывает отправитель в зависимости от команды управления
@@ -2666,16 +3031,16 @@ class xt {
2666
3031
  * @returns Promise с результатом обработки
2667
3032
  */
2668
3033
  async processSender(e, t) {
2669
- const { mainCam: s, resolutionMainCam: r } = e;
3034
+ const { mainCam: s, resolutionMainCam: i } = e;
2670
3035
  switch (s) {
2671
- case P.PAUSE_MAIN_CAM:
3036
+ case v.PAUSE_MAIN_CAM:
2672
3037
  return this.downgradeResolutionSender(t);
2673
- case P.RESUME_MAIN_CAM:
3038
+ case v.RESUME_MAIN_CAM:
2674
3039
  return this.setBitrateByTrackResolution(t);
2675
- case P.MAX_MAIN_CAM_RESOLUTION:
2676
- return r !== void 0 ? this.setResolutionSender(r, t) : this.setBitrateByTrackResolution(t);
2677
- case P.ADMIN_STOP_MAIN_CAM:
2678
- case P.ADMIN_START_MAIN_CAM:
3040
+ case v.MAX_MAIN_CAM_RESOLUTION:
3041
+ return i !== void 0 ? this.setResolutionSender(i, t) : this.setBitrateByTrackResolution(t);
3042
+ case v.ADMIN_STOP_MAIN_CAM:
3043
+ case v.ADMIN_START_MAIN_CAM:
2679
3044
  case void 0:
2680
3045
  return this.setBitrateByTrackResolution(t);
2681
3046
  default:
@@ -2688,11 +3053,11 @@ class xt {
2688
3053
  * @returns Promise с результатом
2689
3054
  */
2690
3055
  async downgradeResolutionSender(e) {
2691
- const { sender: t, codec: s } = e, r = {
3056
+ const { sender: t, codec: s } = e, i = {
2692
3057
  scaleResolutionDownBy: 200,
2693
- maxBitrate: Vt(s)
3058
+ maxBitrate: Tn(s)
2694
3059
  };
2695
- return this.parametersSetter.setEncodingsToSender(t, r);
3060
+ return this.parametersSetter.setEncodingsToSender(t, i);
2696
3061
  }
2697
3062
  /**
2698
3063
  * Устанавливает битрейт на основе разрешения трека
@@ -2700,7 +3065,7 @@ class xt {
2700
3065
  * @returns Promise с результатом
2701
3066
  */
2702
3067
  async setBitrateByTrackResolution(e) {
2703
- const { sender: t, videoTrack: s, codec: r } = e, a = s.getSettings().width, o = a === void 0 ? Wt(r) : J(a, r);
3068
+ const { sender: t, videoTrack: s, codec: i } = e, a = s.getSettings().width, o = a === void 0 ? Sn(i) : j(a, i);
2704
3069
  return this.parametersSetter.setEncodingsToSender(t, {
2705
3070
  scaleResolutionDownBy: 1,
2706
3071
  maxBitrate: o
@@ -2713,27 +3078,27 @@ class xt {
2713
3078
  * @returns Promise с результатом
2714
3079
  */
2715
3080
  async setResolutionSender(e, t) {
2716
- const [s, r] = e.split("x"), { sender: i, videoTrack: a, codec: o } = t, c = {
3081
+ const [s, i] = e.split("x"), { sender: r, videoTrack: a, codec: o } = t, c = {
2717
3082
  width: Number(s),
2718
- height: Number(r)
2719
- }, d = Ht({
3083
+ height: Number(i)
3084
+ }, h = Cn({
2720
3085
  videoTrack: a,
2721
3086
  targetSize: c
2722
- }), u = J(c.width, o), T = {
2723
- scaleResolutionDownBy: d,
2724
- maxBitrate: u
3087
+ }), T = j(c.width, o), S = {
3088
+ scaleResolutionDownBy: h,
3089
+ maxBitrate: T
2725
3090
  };
2726
- return this.parametersSetter.setEncodingsToSender(i, T);
3091
+ return this.parametersSetter.setEncodingsToSender(r, S);
2727
3092
  }
2728
3093
  }
2729
- const qt = (n) => n.find((e) => e.track?.kind === "video");
2730
- class Gt {
3094
+ const An = (n) => n.find((e) => e.track?.kind === "video");
3095
+ class Nn {
2731
3096
  // eslint-disable-next-line @typescript-eslint/class-methods-use-this
2732
3097
  findVideoSender(e) {
2733
- return qt(e);
3098
+ return An(e);
2734
3099
  }
2735
3100
  }
2736
- class Qt {
3101
+ class Rn {
2737
3102
  currentSender;
2738
3103
  originalReplaceTrack;
2739
3104
  lastWidth;
@@ -2746,7 +3111,7 @@ class Qt {
2746
3111
  pollIntervalMs: e = 1e3,
2747
3112
  maxPollIntervalMs: t
2748
3113
  }) {
2749
- this.pollIntervalMs = e, this.maxPollIntervalMs = t ?? e * 16, this.currentPollIntervalMs = this.pollIntervalMs, this.setTimeoutRequest = new ee();
3114
+ this.pollIntervalMs = e, this.maxPollIntervalMs = t ?? e * 16, this.currentPollIntervalMs = this.pollIntervalMs, this.setTimeoutRequest = new Z();
2750
3115
  }
2751
3116
  /**
2752
3117
  * Проверяет актуальный video-sender и (при необходимости) перенастраивает наблюдение.
@@ -2765,8 +3130,8 @@ class Qt {
2765
3130
  attachSender(e, t) {
2766
3131
  this.currentSender = e;
2767
3132
  const s = e.replaceTrack.bind(e);
2768
- this.originalReplaceTrack = s, e.replaceTrack = async (r) => {
2769
- await s(r), this.attachTrack(t, r ?? void 0), t();
3133
+ this.originalReplaceTrack = s, e.replaceTrack = async (i) => {
3134
+ await s(i), this.attachTrack(t, i ?? void 0), t();
2770
3135
  }, this.attachTrack(t, e.track);
2771
3136
  }
2772
3137
  detachSender() {
@@ -2775,8 +3140,8 @@ class Qt {
2775
3140
  attachTrack(e, t) {
2776
3141
  if (this.detachTrack(), !t)
2777
3142
  return;
2778
- const { width: s, height: r } = t.getSettings();
2779
- this.lastWidth = s, this.lastHeight = r, this.currentPollIntervalMs = this.pollIntervalMs, this.schedulePoll(t, e);
3143
+ const { width: s, height: i } = t.getSettings();
3144
+ this.lastWidth = s, this.lastHeight = i, this.currentPollIntervalMs = this.pollIntervalMs, this.schedulePoll(t, e);
2780
3145
  }
2781
3146
  /**
2782
3147
  * Периодически опрашивает track с экспоненциальной адаптацией частоты.
@@ -2785,8 +3150,8 @@ class Qt {
2785
3150
  */
2786
3151
  schedulePoll(e, t) {
2787
3152
  const s = () => {
2788
- const { width: r, height: i } = e.getSettings();
2789
- r !== this.lastWidth || i !== this.lastHeight ? (this.lastWidth = r, this.lastHeight = i, this.currentPollIntervalMs = this.pollIntervalMs, t()) : this.currentPollIntervalMs = Math.min(
3153
+ const { width: i, height: r } = e.getSettings();
3154
+ i !== this.lastWidth || r !== this.lastHeight ? (this.lastWidth = i, this.lastHeight = r, this.currentPollIntervalMs = this.pollIntervalMs, t()) : this.currentPollIntervalMs = Math.min(
2790
3155
  this.currentPollIntervalMs * 2,
2791
3156
  this.maxPollIntervalMs
2792
3157
  ), this.setTimeoutRequest.request(s, this.currentPollIntervalMs);
@@ -2797,7 +3162,7 @@ class Qt {
2797
3162
  this.setTimeoutRequest.cancelRequest(), this.lastWidth = void 0, this.lastHeight = void 0;
2798
3163
  }
2799
3164
  }
2800
- class Yt {
3165
+ class In {
2801
3166
  apiManager;
2802
3167
  currentHandler;
2803
3168
  constructor(e) {
@@ -2817,7 +3182,7 @@ class Yt {
2817
3182
  this.currentHandler && (this.apiManager.off("main-cam-control", this.currentHandler), this.currentHandler = void 0);
2818
3183
  }
2819
3184
  }
2820
- class zt {
3185
+ class pn {
2821
3186
  eventHandler;
2822
3187
  senderBalancer;
2823
3188
  parametersSetterWithQueue;
@@ -2826,19 +3191,19 @@ class zt {
2826
3191
  trackMonitor;
2827
3192
  constructor(e, t, {
2828
3193
  ignoreForCodec: s,
2829
- onSetParameters: r,
2830
- pollIntervalMs: i
3194
+ onSetParameters: i,
3195
+ pollIntervalMs: r
2831
3196
  } = {}) {
2832
- this.getConnection = t, this.eventHandler = new Yt(e), this.parametersSetterWithQueue = new wt(r), this.senderBalancer = new xt(
3197
+ this.getConnection = t, this.eventHandler = new In(e), this.parametersSetterWithQueue = new cn(i), this.senderBalancer = new En(
2833
3198
  {
2834
- senderFinder: new Gt(),
2835
- codecProvider: new bt(),
3199
+ senderFinder: new Nn(),
3200
+ codecProvider: new an(),
2836
3201
  parametersSetter: this.parametersSetterWithQueue
2837
3202
  },
2838
3203
  {
2839
3204
  ignoreForCodec: s
2840
3205
  }
2841
- ), this.trackMonitor = new Qt({ pollIntervalMs: i });
3206
+ ), this.trackMonitor = new Rn({ pollIntervalMs: r });
2842
3207
  }
2843
3208
  /**
2844
3209
  * Подписывается на события управления главной камерой
@@ -2869,7 +3234,7 @@ class zt {
2869
3234
  const t = await this.senderBalancer.balance(e, this.serverHeaders);
2870
3235
  return this.trackMonitor.subscribe(t.sender, () => {
2871
3236
  this.balance().catch((s) => {
2872
- E("balance on track change: error", s);
3237
+ d("balance on track change: error", s);
2873
3238
  });
2874
3239
  }), t;
2875
3240
  }
@@ -2879,17 +3244,17 @@ class zt {
2879
3244
  */
2880
3245
  handleMainCamControl = (e) => {
2881
3246
  this.serverHeaders = e, this.balance().catch((t) => {
2882
- E("handleMainCamControl: error", t);
3247
+ d("handleMainCamControl: error", t);
2883
3248
  });
2884
3249
  };
2885
3250
  }
2886
- const Ae = [
3251
+ const me = [
2887
3252
  "balancing-scheduled",
2888
3253
  "balancing-started",
2889
3254
  "balancing-stopped",
2890
3255
  "parameters-updated"
2891
3256
  ];
2892
- class Xt {
3257
+ class mn {
2893
3258
  isBalancingActive = !1;
2894
3259
  events;
2895
3260
  callManager;
@@ -2897,13 +3262,13 @@ class Xt {
2897
3262
  videoSendingBalancer;
2898
3263
  startBalancingTimer;
2899
3264
  constructor(e, t, s = {}) {
2900
- this.events = new K(Ae), this.callManager = e, this.balancingStartDelay = s.balancingStartDelay ?? 1e4, this.videoSendingBalancer = new zt(
3265
+ this.events = new k(me), this.callManager = e, this.balancingStartDelay = s.balancingStartDelay ?? 1e4, this.videoSendingBalancer = new pn(
2901
3266
  t,
2902
3267
  () => e.connection,
2903
3268
  {
2904
3269
  ...s,
2905
- onSetParameters: (r) => {
2906
- this.events.trigger("parameters-updated", r), s.onSetParameters?.(r);
3270
+ onSetParameters: (i) => {
3271
+ this.events.trigger("parameters-updated", i), s.onSetParameters?.(i);
2907
3272
  }
2908
3273
  }
2909
3274
  ), this.subscribe();
@@ -2959,7 +3324,7 @@ class Xt {
2959
3324
  scheduleBalancingStart() {
2960
3325
  this.clearStartTimer(), this.startBalancingTimer = setTimeout(() => {
2961
3326
  this.startBalancingTimer = void 0, this.startBalancing().catch((e) => {
2962
- E("startBalancing: error", e);
3327
+ d("startBalancing: error", e);
2963
3328
  });
2964
3329
  }, this.balancingStartDelay), this.events.trigger("balancing-scheduled", { delay: this.balancingStartDelay });
2965
3330
  }
@@ -2967,47 +3332,61 @@ class Xt {
2967
3332
  this.startBalancingTimer && (clearTimeout(this.startBalancingTimer), this.startBalancingTimer = void 0);
2968
3333
  }
2969
3334
  }
2970
- const Jt = 1e6, Kt = ge.map((n) => `connection:${n}`), jt = ne.map((n) => `call:${n}`), Zt = ie.map((n) => `api:${n}`), en = ue.map((n) => `incoming-call:${n}`), tn = de.map((n) => `presentation:${n}`), nn = Te.map((n) => `stats:${n}`), sn = Ae.map((n) => `video-balancer:${n}`), rn = [
2971
- ...Kt,
2972
- ...jt,
2973
- ...Zt,
2974
- ...en,
2975
- ...tn,
2976
- ...nn,
2977
- ...sn
3335
+ const _n = 1e6, Mn = Se.map((n) => `auto-connect:${n}`), vn = ge.map((n) => `connection:${n}`), fn = ie.map((n) => `call:${n}`), Pn = ne.map((n) => `api:${n}`), On = Ee.map((n) => `incoming-call:${n}`), Dn = he.map((n) => `presentation:${n}`), yn = Ae.map((n) => `stats:${n}`), bn = me.map((n) => `video-balancer:${n}`), wn = [
3336
+ ...Mn,
3337
+ ...vn,
3338
+ ...fn,
3339
+ ...Pn,
3340
+ ...On,
3341
+ ...Dn,
3342
+ ...yn,
3343
+ ...bn
2978
3344
  ];
2979
- class Nn {
3345
+ class Yn {
2980
3346
  events;
2981
3347
  connectionManager;
2982
3348
  connectionQueueManager;
2983
3349
  callManager;
3350
+ autoConnectorManager;
2984
3351
  apiManager;
2985
3352
  incomingCallManager;
2986
3353
  presentationManager;
2987
3354
  statsManager;
2988
3355
  videoSendingBalancerManager;
3356
+ transceiverManager;
2989
3357
  preferredMimeTypesVideoCodecs;
2990
3358
  excludeMimeTypesVideoCodecs;
2991
3359
  constructor({ JsSIP: e }, {
2992
3360
  preferredMimeTypesVideoCodecs: t,
2993
3361
  excludeMimeTypesVideoCodecs: s,
2994
- videoBalancerOptions: r
3362
+ videoBalancerOptions: i,
3363
+ autoConnectorOptions: r
2995
3364
  } = {}) {
2996
- this.preferredMimeTypesVideoCodecs = t, this.excludeMimeTypesVideoCodecs = s, this.events = new D(rn), this.connectionManager = new ht({ JsSIP: e }), this.connectionQueueManager = new gt({
3365
+ this.preferredMimeTypesVideoCodecs = t, this.excludeMimeTypesVideoCodecs = s, this.events = new U(wn), this.connectionManager = new mt({ JsSIP: e }), this.connectionQueueManager = new _t({
2997
3366
  connectionManager: this.connectionManager
2998
- }), this.callManager = new we(), this.apiManager = new Ve({
3367
+ }), this.callManager = new Xe(), this.apiManager = new ke({
2999
3368
  connectionManager: this.connectionManager,
3000
3369
  callManager: this.callManager
3001
- }), this.incomingCallManager = new Tt(this.connectionManager), this.presentationManager = new tt({
3370
+ }), this.incomingCallManager = new Vt(this.connectionManager), this.presentationManager = new ht({
3371
+ callManager: this.callManager,
3372
+ maxBitrate: _n
3373
+ }), this.statsManager = new Xt({
3002
3374
  callManager: this.callManager,
3003
- maxBitrate: Jt
3004
- }), this.statsManager = new mt({
3375
+ apiManager: this.apiManager
3376
+ }), this.autoConnectorManager = new Ft(
3377
+ {
3378
+ connectionQueueManager: this.connectionQueueManager,
3379
+ connectionManager: this.connectionManager,
3380
+ callManager: this.callManager
3381
+ },
3382
+ r
3383
+ ), this.transceiverManager = new tn({
3005
3384
  callManager: this.callManager,
3006
3385
  apiManager: this.apiManager
3007
- }), this.videoSendingBalancerManager = new Xt(
3386
+ }), this.videoSendingBalancerManager = new mn(
3008
3387
  this.callManager,
3009
3388
  this.apiManager,
3010
- r
3389
+ i
3011
3390
  ), this.subscribe();
3012
3391
  }
3013
3392
  get requestedConnection() {
@@ -3069,17 +3448,23 @@ class Nn {
3069
3448
  this.events.off(e, t);
3070
3449
  }
3071
3450
  connect = async (...e) => this.connectionQueueManager.connect(...e);
3072
- set = async (...e) => this.connectionQueueManager.set(...e);
3073
3451
  disconnect = async () => this.connectionQueueManager.disconnect();
3074
- register = async () => this.connectionQueueManager.register();
3075
- unregister = async () => this.connectionQueueManager.unregister();
3076
- tryRegister = async () => this.connectionQueueManager.tryRegister();
3077
- sendOptions = async (e, t, s) => this.connectionQueueManager.sendOptions(e, t, s);
3078
- ping = async (e, t) => this.connectionQueueManager.ping(e, t);
3079
- checkTelephony = async (e) => this.connectionQueueManager.checkTelephony(e);
3452
+ register = async () => this.connectionManager.register();
3453
+ unregister = async () => this.connectionManager.unregister();
3454
+ tryRegister = async () => this.connectionManager.tryRegister();
3455
+ set = async (...e) => this.connectionManager.set(...e);
3456
+ sendOptions = async (e, t, s) => this.connectionManager.sendOptions(e, t, s);
3457
+ ping = async (e, t) => this.connectionManager.ping(e, t);
3458
+ checkTelephony = async (e) => this.connectionManager.checkTelephony(e);
3080
3459
  isConfigured = () => this.connectionManager.isConfigured();
3081
3460
  getConnectionConfiguration = () => this.connectionManager.getConnectionConfiguration();
3082
3461
  getSipServerUrl = (e) => this.connectionManager.getSipServerUrl(e);
3462
+ startAutoConnect = (...e) => {
3463
+ this.autoConnectorManager.start(...e);
3464
+ };
3465
+ stopAutoConnect = () => {
3466
+ this.autoConnectorManager.stop();
3467
+ };
3083
3468
  call = async (e) => {
3084
3469
  const { onAddedTransceiver: t, ...s } = e;
3085
3470
  return this.callManager.startCall(
@@ -3087,9 +3472,7 @@ class Nn {
3087
3472
  this.getSipServerUrl,
3088
3473
  {
3089
3474
  ...s,
3090
- onAddedTransceiver: async (r, i, a) => {
3091
- this.setCodecPreferences(r), await t?.(r, i, a);
3092
- }
3475
+ onAddedTransceiver: this.resolveHandleAddTransceiver(t)
3093
3476
  }
3094
3477
  );
3095
3478
  };
@@ -3100,9 +3483,7 @@ class Nn {
3100
3483
  this.incomingCallManager.extractIncomingRTCSession,
3101
3484
  {
3102
3485
  ...s,
3103
- onAddedTransceiver: async (r, i, a) => {
3104
- this.setCodecPreferences(r), await t?.(r, i, a);
3105
- }
3486
+ onAddedTransceiver: this.resolveHandleAddTransceiver(t)
3106
3487
  }
3107
3488
  );
3108
3489
  };
@@ -3112,7 +3493,7 @@ class Nn {
3112
3493
  getRemoteStreams = () => this.callManager.getRemoteStreams();
3113
3494
  replaceMediaStream = async (...e) => this.callManager.replaceMediaStream(...e);
3114
3495
  async startPresentation(e, t = {}) {
3115
- const { isP2P: s, callLimit: r, onAddedTransceiver: i, ...a } = t;
3496
+ const { isP2P: s, callLimit: i, onAddedTransceiver: r, ...a } = t;
3116
3497
  return this.presentationManager.startPresentation(
3117
3498
  async () => {
3118
3499
  s === !0 ? (await this.apiManager.sendMustStopPresentationP2P(), await this.apiManager.askPermissionToStartPresentationP2P()) : await this.apiManager.askPermissionToStartPresentation();
@@ -3120,11 +3501,9 @@ class Nn {
3120
3501
  e,
3121
3502
  {
3122
3503
  ...a,
3123
- onAddedTransceiver: async (o, c, d) => {
3124
- this.setCodecPreferences(o), await i?.(o, c, d);
3125
- }
3504
+ onAddedTransceiver: this.resolveHandleAddTransceiver(r)
3126
3505
  },
3127
- r === void 0 ? void 0 : { callLimit: r }
3506
+ i === void 0 ? void 0 : { callLimit: i }
3128
3507
  );
3129
3508
  }
3130
3509
  async stopPresentation(e = {}) {
@@ -3134,17 +3513,15 @@ class Nn {
3134
3513
  });
3135
3514
  }
3136
3515
  async updatePresentation(e, t = {}) {
3137
- const { isP2P: s, onAddedTransceiver: r, ...i } = t;
3516
+ const { isP2P: s, onAddedTransceiver: i, ...r } = t;
3138
3517
  return this.presentationManager.updatePresentation(
3139
3518
  async () => {
3140
3519
  s === !0 ? (await this.apiManager.sendMustStopPresentationP2P(), await this.apiManager.askPermissionToStartPresentationP2P()) : await this.apiManager.askPermissionToStartPresentation();
3141
3520
  },
3142
3521
  e,
3143
3522
  {
3144
- ...i,
3145
- onAddedTransceiver: async (a, o, c) => {
3146
- this.setCodecPreferences(a), await r?.(a, o, c);
3147
- }
3523
+ ...r,
3524
+ onAddedTransceiver: this.resolveHandleAddTransceiver(i)
3148
3525
  }
3149
3526
  );
3150
3527
  }
@@ -3191,73 +3568,41 @@ class Nn {
3191
3568
  return this.apiManager.askPermissionToEnableCam(...e);
3192
3569
  }
3193
3570
  setCodecPreferences(e) {
3194
- ft(e, {
3571
+ en(e, {
3195
3572
  preferredMimeTypesVideoCodecs: this.preferredMimeTypesVideoCodecs,
3196
3573
  excludeMimeTypesVideoCodecs: this.excludeMimeTypesVideoCodecs
3197
3574
  });
3198
3575
  }
3199
3576
  subscribe() {
3200
- this.connectionManager.events.eachTriggers((e, t) => {
3201
- this.connectionManager.on(t, (s) => {
3202
- this.events.trigger(`connection:${t}`, s);
3203
- });
3204
- }), this.callManager.events.eachTriggers((e, t) => {
3205
- this.callManager.on(t, (s) => {
3206
- this.events.trigger(`call:${t}`, s);
3207
- });
3208
- }), this.apiManager.events.eachTriggers((e, t) => {
3209
- this.apiManager.on(t, (s) => {
3210
- this.events.trigger(`api:${t}`, s);
3211
- });
3212
- }), this.incomingCallManager.events.eachTriggers((e, t) => {
3213
- this.incomingCallManager.on(t, (s) => {
3214
- this.events.trigger(`incoming-call:${t}`, s);
3215
- });
3216
- }), this.presentationManager.events.eachTriggers((e, t) => {
3217
- this.presentationManager.on(t, (s) => {
3218
- this.events.trigger(`presentation:${t}`, s);
3219
- });
3220
- }), this.statsManager.events.eachTriggers((e, t) => {
3221
- this.statsManager.on(t, (s) => {
3222
- this.events.trigger(`stats:${t}`, s);
3223
- });
3224
- }), this.videoSendingBalancerManager.events.eachTriggers((e, t) => {
3225
- this.videoSendingBalancerManager.on(t, (s) => {
3226
- this.events.trigger(`video-balancer:${t}`, s);
3227
- });
3228
- }), this.apiManager.on("restart", this.handleRestart);
3577
+ this.bridgeEvents("auto-connect", this.autoConnectorManager), this.bridgeEvents("connection", this.connectionManager), this.bridgeEvents("call", this.callManager), this.bridgeEvents("api", this.apiManager), this.bridgeEvents("incoming-call", this.incomingCallManager), this.bridgeEvents("presentation", this.presentationManager), this.bridgeEvents("stats", this.statsManager), this.bridgeEvents("video-balancer", this.videoSendingBalancerManager);
3229
3578
  }
3230
- handleRestart = (e) => {
3231
- this.updateTransceivers(e).catch((t) => {
3232
- E("Failed to update transceivers", t);
3233
- }).finally(() => {
3234
- this.callManager.restartIce().catch((t) => {
3235
- E("Failed to restart ICE", t);
3579
+ bridgeEvents = (e, t) => {
3580
+ t.events.eachTriggers((s, i) => {
3581
+ t.on(i, (r) => {
3582
+ this.events.trigger(`${e}:${i}`, r);
3236
3583
  });
3237
3584
  });
3238
3585
  };
3239
- updateTransceivers = async (e) => {
3240
- const { videoTrackCount: t } = e;
3241
- t === 2 && (this.callManager.getTransceivers().presentationVideo !== void 0 || await this.callManager.addTransceiver("video", {
3242
- direction: "recvonly"
3243
- }).catch((i) => {
3244
- E("Failed to add presentation video transceiver", i);
3245
- }));
3586
+ resolveHandleAddTransceiver = (e) => async (t, s, i) => {
3587
+ this.setCodecPreferences(t), await e?.(t, s, i);
3246
3588
  };
3247
3589
  }
3248
3590
  export {
3249
- re as E,
3250
- F as O,
3251
- Nn as S,
3252
- Ke as a,
3253
- $e as b,
3254
- C as c,
3255
- Cn as d,
3256
- Sn as e,
3257
- _t as f,
3258
- yt as g,
3259
- En as h,
3260
- E as l,
3261
- L as p,
3262
- ce as s
3591
+ ae as E,
3592
+ $e as O,
3593
+ Yn as S,
3594
+ at as a,
3595
+ Fe as b,
3596
+ Gn as c,
3597
+ xn as d,
3598
+ Hn as e,
3599
+ E as f,
3600
+ zt as g,
3601
+ Rt as h,
3602
+ rn as i,
3603
+ Qn as j,
3604
+ d as l,
3605
+ F as p,
3606
+ pt as r,
3607
+ de as s
3263
3608
  };