@coventia/softphone 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/{call-C6YpT6uR.d.cts → call-iGvr2ZnO.d.cts} +130 -13
  2. package/dist/{call-C6YpT6uR.d.ts → call-iGvr2ZnO.d.ts} +130 -13
  3. package/dist/chunk-3UTUWGVG.js +1891 -0
  4. package/dist/chunk-3UTUWGVG.js.map +1 -0
  5. package/dist/chunk-DZRSSZWB.js +39 -0
  6. package/dist/chunk-DZRSSZWB.js.map +1 -0
  7. package/dist/{chunk-2ZSOGGPO.js → chunk-FRXHEHQA.js} +15 -2
  8. package/dist/chunk-FRXHEHQA.js.map +1 -0
  9. package/dist/{chunk-UHNLEBBO.js → chunk-I3RSC52R.js} +28 -3
  10. package/dist/chunk-I3RSC52R.js.map +1 -0
  11. package/dist/chunk-M76SAXXM.js +13 -0
  12. package/dist/chunk-M76SAXXM.js.map +1 -0
  13. package/dist/{chunk-7R6LOOAI.js → chunk-N4PLEYFJ.js} +4 -2
  14. package/dist/chunk-N4PLEYFJ.js.map +1 -0
  15. package/dist/element/index.d.ts +167 -7
  16. package/dist/element/index.js +138 -43
  17. package/dist/element/index.js.map +1 -1
  18. package/dist/{engine-DPft99Wj.d.ts → engine-BKoT_Pj7.d.cts} +10 -1
  19. package/dist/{engine-CDdaSojx.d.cts → engine-CeGh5Yai.d.ts} +10 -1
  20. package/dist/index.cjs +1596 -145
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +5 -5
  23. package/dist/index.d.ts +5 -5
  24. package/dist/index.js +618 -42
  25. package/dist/index.js.map +1 -1
  26. package/dist/react/index.cjs +26 -0
  27. package/dist/react/index.cjs.map +1 -1
  28. package/dist/react/index.d.cts +24 -5
  29. package/dist/react/index.d.ts +24 -5
  30. package/dist/react/index.js +2 -2
  31. package/dist/{softphone-CY5d2WWY.d.cts → softphone-D0ao5W4z.d.ts} +42 -3
  32. package/dist/{softphone-DXgmTyrX.d.ts → softphone-DRoS0jJR.d.cts} +42 -3
  33. package/dist/{sources-ONYQW733.js → sources-LGFJG7W2.js} +27 -38
  34. package/dist/sources-LGFJG7W2.js.map +1 -0
  35. package/dist/testing/index.cjs +13 -0
  36. package/dist/testing/index.cjs.map +1 -1
  37. package/dist/testing/index.d.cts +2 -2
  38. package/dist/testing/index.d.ts +2 -2
  39. package/dist/testing/index.js +1 -1
  40. package/dist/ui/index.cjs +92 -2
  41. package/dist/ui/index.cjs.map +1 -1
  42. package/dist/ui/index.d.cts +2 -2
  43. package/dist/ui/index.d.ts +2 -2
  44. package/dist/ui/index.js +69 -4
  45. package/dist/ui/index.js.map +1 -1
  46. package/dist/zadarma/index.cjs +950 -104
  47. package/dist/zadarma/index.cjs.map +1 -1
  48. package/dist/zadarma/index.d.cts +40 -14
  49. package/dist/zadarma/index.d.ts +40 -14
  50. package/dist/zadarma/index.js +4 -2
  51. package/dist/zadarma-engine-VYIXLBQG.js +7 -0
  52. package/dist/{zadarma-engine-L5DEFXUS.js.map → zadarma-engine-VYIXLBQG.js.map} +1 -1
  53. package/package.json +1 -1
  54. package/dist/chunk-2ZSOGGPO.js.map +0 -1
  55. package/dist/chunk-7R6LOOAI.js.map +0 -1
  56. package/dist/chunk-EYEDPD7Y.js +0 -1071
  57. package/dist/chunk-EYEDPD7Y.js.map +0 -1
  58. package/dist/chunk-UHNLEBBO.js.map +0 -1
  59. package/dist/sources-ONYQW733.js.map +0 -1
  60. package/dist/zadarma-engine-L5DEFXUS.js +0 -5
@@ -1,1071 +0,0 @@
1
- import { createError, isSoftphoneError } from './chunk-2ZSOGGPO.js';
2
- import { cachedTokenSource, invalidateToken } from './chunk-MHOJHG5E.js';
3
-
4
- // src/transports/sip/media.ts
5
- function buildAudioConstraints(deviceId) {
6
- return { audio: deviceId ? { deviceId: { exact: deviceId } } : true, video: false };
7
- }
8
- function capIceGathering(session, capMs) {
9
- let settled = false;
10
- let timer;
11
- const settle = (ready) => {
12
- if (settled) return;
13
- settled = true;
14
- if (timer) clearTimeout(timer);
15
- try {
16
- ready();
17
- } catch {
18
- }
19
- };
20
- session.on("icecandidate", ({ ready }) => {
21
- if (!timer) timer = setTimeout(() => settle(ready), capMs);
22
- });
23
- return () => {
24
- if (timer) clearTimeout(timer);
25
- };
26
- }
27
-
28
- // src/transports/sip/ice.ts
29
- var DEFAULT_ICE_SERVERS = [
30
- { urls: "stun:stun.l.google.com:19302" }
31
- ];
32
- var PC_CONFIG = { iceServers: [...DEFAULT_ICE_SERVERS] };
33
-
34
- // src/transports/sip/session.ts
35
- function mapEndReason(e) {
36
- if (e.originator === "local") return "local";
37
- if (e.originator === "remote") return "remote";
38
- return "failed";
39
- }
40
- function mapFailReason(e) {
41
- switch (e.cause) {
42
- // 486 Busy Here, 600 Busy Everywhere. Also what most endpoints send for a MANUAL DECLINE — SIP
43
- // does not distinguish the two, and neither can we, which is why the copy covers both.
44
- case "Busy":
45
- return "busy";
46
- /*
47
- `Rejected` is 403 / 603 Decline — an explicit refusal, sent by the endpoints that bother to.
48
- `Redirected` is 3xx: not literally a rejection, but it ends the same way — not connected, and
49
- nothing to retry.
50
-
51
- (Both comments sit ABOVE the group rather than between the labels. A comment between two `case`
52
- lines makes the first one non-empty to `no-fallthrough`, which then demands a `break` that
53
- would be unreachable.)
54
- */
55
- case "Rejected":
56
- case "Redirected":
57
- return "rejected";
58
- /*
59
- `Unavailable` is 480 Temporarily Unavailable / 410 / 408 Request Timeout / 430 — THE ring-out
60
- case, and the one that was missing. `No Answer` and `Expires` are local: our own no-answer
61
- timer, and a session that expired.
62
- */
63
- case "Unavailable":
64
- case "No Answer":
65
- case "Expires":
66
- return "no-answer";
67
- case "Canceled":
68
- return e.originator === "local" ? "local" : "remote";
69
- // Everything else is a genuine failure worth naming: Not Found (404/604), Address Incomplete,
70
- // Incompatible SDP, Authentication Error, WebRTC Error, RTP Timeout, Connection Error…
71
- default:
72
- return "failed";
73
- }
74
- }
75
- function remoteNumberOf(session) {
76
- const id = session.remote_identity;
77
- return id?.uri?.user ?? id?.uri?.toString() ?? "";
78
- }
79
- var SipEngineCall = class {
80
- id;
81
- direction;
82
- remoteNumber;
83
- #session;
84
- #deps;
85
- #listeners = /* @__PURE__ */ new Set();
86
- #ended = false;
87
- #cancelIceCap = null;
88
- /**
89
- * The stream behind a LIVE device swap (`swapInputDevice`), if one has happened. Distinct from
90
- * JsSIP's own original capture: that one is `_localMediaStreamLocallyGenerated` and JsSIP stops it
91
- * itself on close (see `#end`'s comment). This one is ours — obtained with our own `getUserMedia`
92
- * call, attached via `replaceTrack`, and never known to JsSIP at all — so nothing else will ever
93
- * stop it unless we do, here.
94
- */
95
- #swappedStream = null;
96
- constructor(session, deps) {
97
- this.#session = session;
98
- this.#deps = deps;
99
- this.id = deps.id;
100
- this.direction = session.direction === "incoming" ? "inbound" : "outbound";
101
- this.remoteNumber = remoteNumberOf(session);
102
- this.#wire();
103
- }
104
- /** @internal — the underlying session, for `completeTransfer`'s REFER…Replaces. */
105
- get session() {
106
- return this.#session;
107
- }
108
- onEvent(listener) {
109
- this.#listeners.add(listener);
110
- return () => this.#listeners.delete(listener);
111
- }
112
- // ── JsSIP events → raw engine signals ─────────────────────────────────────
113
- #wire() {
114
- const s = this.#session;
115
- if (this.direction === "outbound") {
116
- s.on("progress", () => this.#fire({ type: "progress", response: "ringing" }));
117
- }
118
- const wireRemoteTrack = (pc) => {
119
- pc.ontrack = ({ streams }) => {
120
- if (streams[0]) this.#fire({ type: "stream", stream: streams[0] });
121
- };
122
- };
123
- s.on("peerconnection", ({ peerconnection }) => wireRemoteTrack(peerconnection));
124
- if (s.connection) wireRemoteTrack(s.connection);
125
- if (this.direction === "outbound" && this.#deps.iceGatheringCapMs) {
126
- this.#cancelIceCap = capIceGathering(s, this.#deps.iceGatheringCapMs);
127
- }
128
- s.on("accepted", () => this.#onAccepted());
129
- s.on("ended", (e) => this.#end(mapEndReason(e), e.cause));
130
- s.on("failed", (e) => this.#end(mapFailReason(e), e.cause));
131
- s.on("hold", ({ originator }) => this.#fire({ type: "held", originator }));
132
- s.on("unhold", ({ originator }) => this.#fire({ type: "unheld", originator }));
133
- }
134
- /**
135
- * The call is live. Nothing to swap: JsSIP opened the real microphone when the session was created,
136
- * so the far end has had our actual audio from the first packet.
137
- *
138
- * There used to be a silent-mic dance here — place the call with a synthetic AudioContext track,
139
- * swap the real mic in on accept — so a Bluetooth headset stayed in A2DP while the phone rang. It
140
- * cost more than it bought: with no active capture, Firefox restricts ICE gathering and the offer
141
- * goes out with no candidates at all, which no STUN or TURN server can fix.
142
- */
143
- #onAccepted() {
144
- this.#fire({ type: "accepted" });
145
- }
146
- // ── Commands ───────────────────────────────────────────────────────────────
147
- async answer() {
148
- const deviceId = this.#deps.getInputDeviceId?.() ?? null;
149
- this.#session.answer({
150
- mediaConstraints: buildAudioConstraints(deviceId),
151
- pcConfig: this.#deps.pcConfig ?? PC_CONFIG
152
- });
153
- }
154
- /**
155
- * Live-swap the outgoing microphone track — `CallEngine.setInputDevice` on a call that is already
156
- * connected. Never touches the FIRST call's capture: that one is JsSIP's own `getUserMedia`, opened
157
- * inside `answer()`/`ua.call()` (see `#onAccepted`'s comment on why that stays that way). This is
158
- * only for a device chosen AFTER the call is already live.
159
- *
160
- * `RTCRtpSender.replaceTrack` rather than a fresh `answer()`/re-INVITE: it needs no SDP
161
- * renegotiation and the far end never sees an interruption — exactly the mechanism real softphones
162
- * use for "switch mic mid-call."
163
- */
164
- async swapInputDevice(deviceId) {
165
- const pc = this.#session.connection;
166
- if (!pc || this.#ended) return;
167
- const sender = pc.getSenders().find((s) => s.track?.kind === "audio");
168
- if (!sender) return;
169
- let stream;
170
- try {
171
- stream = await navigator.mediaDevices.getUserMedia(buildAudioConstraints(deviceId));
172
- } catch {
173
- return;
174
- }
175
- if (this.#ended) {
176
- for (const track2 of stream.getTracks()) track2.stop();
177
- return;
178
- }
179
- const [track] = stream.getAudioTracks();
180
- if (!track) return;
181
- await sender.replaceTrack(track);
182
- for (const oldTrack of this.#swappedStream?.getTracks() ?? []) oldTrack.stop();
183
- this.#swappedStream = stream;
184
- }
185
- async reject() {
186
- this.#deps.onReject?.();
187
- this.#session.terminate({ status_code: 486, reason_phrase: "Busy Here" });
188
- }
189
- async hangup() {
190
- this.#session.terminate();
191
- }
192
- mute(muted) {
193
- if (muted) this.#session.mute({ audio: true });
194
- else this.#session.unmute({ audio: true });
195
- }
196
- async hold() {
197
- this.#session.hold();
198
- }
199
- async unhold() {
200
- this.#session.unhold();
201
- }
202
- sendDigits(digits) {
203
- this.#session.sendDTMF(digits);
204
- }
205
- async transfer(target) {
206
- this.#session.refer(this.#deps.buildTarget(target));
207
- }
208
- async startConsult(target) {
209
- return this.#deps.placeConsult(target);
210
- }
211
- async completeTransfer(consult) {
212
- const consultSession = consult.session;
213
- this.#session.refer(consultSession.remote_identity.uri.toString(), { replaces: consultSession });
214
- }
215
- // ── internals ──────────────────────────────────────────────────────────────
216
- #end(reason, cause) {
217
- if (this.#ended) return;
218
- this.#ended = true;
219
- this.#cancelIceCap?.();
220
- for (const track of this.#swappedStream?.getTracks() ?? []) track.stop();
221
- this.#swappedStream = null;
222
- this.#fire({ type: "ended", reason, cause });
223
- this.#listeners.clear();
224
- }
225
- #fire(event) {
226
- if (this.#ended && event.type !== "ended") return;
227
- for (const listener of [...this.#listeners]) listener(event);
228
- }
229
- };
230
-
231
- // src/transports/sip/ua.ts
232
- var DEFAULT_ICE_CAP_MS = 3e3;
233
- var REGISTER_EXPIRES = 580;
234
- var SIGNAL_REFRESH_DEBOUNCE_MS = 3e4;
235
- var ERROR_DEBOUNCE_MS = 3e4;
236
- var CALL_END_CODES = {
237
- busy: "call/busy",
238
- "no-answer": "call/no-answer",
239
- rejected: "call/rejected",
240
- failed: "call/failed"
241
- };
242
- function domainOf(credentials) {
243
- const at = credentials.uri.lastIndexOf("@");
244
- return at === -1 ? "" : credentials.uri.slice(at + 1);
245
- }
246
- var callSeq = 0;
247
- var nextCallId = () => `sip-${++callSeq}`;
248
- var SipCallEngine = class {
249
- constructor(provider, factory, options = {}) {
250
- this.provider = provider;
251
- this.factory = factory;
252
- this.now = options.now ?? Date.now;
253
- }
254
- provider;
255
- factory;
256
- #state = "stopped";
257
- #ua = null;
258
- /** In-flight `#createUA()`. THE concurrency guard — see `#ensureUA`. */
259
- #uaInFlight = null;
260
- #domain = "";
261
- #activeCall = null;
262
- /**
263
- * The consult leg from `startConsult` (SPEC §5.6), if one is live on this UA right now.
264
- *
265
- * Tracked separately from `#activeCall` so `#maybeTeardownUA` can tell "both legs are actually gone"
266
- * apart from "the main leg ended, but a consult is still up" — see that method's own comment for the
267
- * bug this exists to prevent.
268
- */
269
- #consultCall = null;
270
- /** The chosen microphone, or `null` for the browser default. Read fresh by every new leg's
271
- * `mediaConstraints`, and pushed live to `#activeCall` by `setInputDevice`. */
272
- #inputDeviceId = null;
273
- #incomingListeners = /* @__PURE__ */ new Set();
274
- #stateListeners = /* @__PURE__ */ new Set();
275
- #errorListeners = /* @__PURE__ */ new Set();
276
- #signalUnsub = null;
277
- #signalConnectionUnsub = null;
278
- #noInviteTimer;
279
- #rejectGuardUntil = 0;
280
- #signalRefreshAfter = 0;
281
- #errorSentAfter = /* @__PURE__ */ new Map();
282
- now;
283
- #resolvedFactory = null;
284
- async #resolveFactory() {
285
- if (this.#resolvedFactory) return this.#resolvedFactory;
286
- this.#resolvedFactory = typeof this.factory === "function" ? await this.factory() : this.factory;
287
- return this.#resolvedFactory;
288
- }
289
- get state() {
290
- return this.#state;
291
- }
292
- onIncoming(listener) {
293
- this.#incomingListeners.add(listener);
294
- return () => this.#incomingListeners.delete(listener);
295
- }
296
- onStateChange(listener) {
297
- this.#stateListeners.add(listener);
298
- return () => this.#stateListeners.delete(listener);
299
- }
300
- onError(listener) {
301
- this.#errorListeners.add(listener);
302
- return () => this.#errorListeners.delete(listener);
303
- }
304
- /**
305
- * Switch the microphone: stored for every FUTURE leg's `mediaConstraints`, and — if a call is live
306
- * right now — pushed to it immediately via `SipEngineCall.swapInputDevice` (SPEC §7 Phase 2, device
307
- * management). `null` resets to the browser's own default device.
308
- */
309
- async setInputDevice(deviceId) {
310
- this.#inputDeviceId = deviceId;
311
- await this.#activeCall?.swapInputDevice(deviceId);
312
- }
313
- /**
314
- * Report a failure, at most once per code per `ERROR_DEBOUNCE_MS`.
315
- *
316
- * A failing registrar retries, and one emission per attempt would flood a host's logging and make
317
- * whatever the widget shows flicker. Debounced per CODE rather than globally, so a transport
318
- * failure is never swallowed because a registration failure happened to precede it.
319
- */
320
- #reportError(code, cause) {
321
- this.#emitError(createError(code, cause));
322
- }
323
- /**
324
- * Emit, debouncing FATAL codes only.
325
- *
326
- * A failing registrar retries, and one emission per attempt would flood a host's logging and make
327
- * whatever the widget shows flicker — so the same fatal code is reported at most once per window,
328
- * per CODE, so a transport failure is never swallowed because a registration failure preceded it.
329
- *
330
- * Non-fatal codes are never debounced: they describe one call each, and two busy tones in a row are
331
- * two facts, not a repeated one.
332
- */
333
- #emitError(error) {
334
- if (error.fatal) {
335
- const now = this.now();
336
- if (now < (this.#errorSentAfter.get(error.code) ?? 0)) return;
337
- this.#errorSentAfter.set(error.code, now + ERROR_DEBOUNCE_MS);
338
- }
339
- for (const listener of [...this.#errorListeners]) listener(error);
340
- }
341
- async start() {
342
- this.#setState("starting");
343
- if (this.provider.registrationMode === "persistent") {
344
- await this.#ensureUA();
345
- this.#setState("online");
346
- } else {
347
- const signal = this.provider.incomingSignal;
348
- if (signal) {
349
- await signal.connect();
350
- this.#signalUnsub = signal.onSignal(() => void this.#onIncomingSignal());
351
- this.#signalConnectionUnsub = signal.onConnectionChange?.(
352
- (connected) => this.#setState(connected ? "online" : "offline")
353
- ) ?? null;
354
- }
355
- this.#setState(signal?.onConnectionChange ? signal.connected ? "online" : "offline" : "online");
356
- }
357
- }
358
- async stop() {
359
- this.#clearNoInviteTimer();
360
- this.#signalUnsub?.();
361
- this.#signalUnsub = null;
362
- this.#signalConnectionUnsub?.();
363
- this.#signalConnectionUnsub = null;
364
- this.provider.incomingSignal?.disconnect();
365
- this.#teardownUA();
366
- this.#setState("stopped");
367
- }
368
- async placeCall(destination, _options) {
369
- const ua = await this.#ensureUA();
370
- const session = await this.#callWhenRegistered(ua, this.#buildTarget(destination));
371
- return this.#wrapCall(session);
372
- }
373
- // ── incoming (on-demand: push → register → INVITE) ────────────────────────
374
- async #onIncomingSignal() {
375
- if (this.now() < this.#rejectGuardUntil) return;
376
- if (this.#activeCall) return;
377
- try {
378
- await this.#ensureUA();
379
- this.#armNoInviteTeardown();
380
- } catch {
381
- this.#teardownUA();
382
- }
383
- }
384
- #armNoInviteTeardown() {
385
- const ms = this.provider.quirks?.noInviteTeardownMs;
386
- if (!ms) return;
387
- this.#clearNoInviteTimer();
388
- this.#noInviteTimer = setTimeout(() => this.#maybeTeardownUA(), ms);
389
- }
390
- /**
391
- * Rebuild the incoming-signal channel with fresh credentials, after a registration failure.
392
- *
393
- * Registration fails when the credentials behind it have gone stale — and for Zadarma those come
394
- * from the same WebRTC key the push socket is holding. Tearing down the UA alone leaves that stale
395
- * key in place, so every subsequent attempt fails the same way and the phone is dead until the page
396
- * is reloaded. Reconnecting re-fetches the key. The legacy hook did exactly this from both of its
397
- * `registrationFailed` handlers.
398
- *
399
- * Debounced, which the legacy was not: a provider failing every attempt would otherwise become a
400
- * tight loop against our backend and theirs.
401
- */
402
- async #refreshSignal() {
403
- const signal = this.provider.incomingSignal;
404
- if (!signal) return;
405
- if (this.now() < this.#signalRefreshAfter) return;
406
- this.#signalRefreshAfter = this.now() + SIGNAL_REFRESH_DEBOUNCE_MS;
407
- try {
408
- signal.disconnect();
409
- await signal.connect();
410
- } catch {
411
- }
412
- }
413
- #clearNoInviteTimer() {
414
- if (this.#noInviteTimer) clearTimeout(this.#noInviteTimer);
415
- this.#noInviteTimer = void 0;
416
- }
417
- #onNewSession(session, originator) {
418
- if (originator !== "remote") return;
419
- this.#clearNoInviteTimer();
420
- if (this.#activeCall || this.now() < this.#rejectGuardUntil) {
421
- session.terminate({ status_code: 486, reason_phrase: "Busy Here" });
422
- return;
423
- }
424
- const call = this.#wrapCall(session);
425
- for (const listener of [...this.#incomingListeners]) listener(call);
426
- }
427
- // ── UA lifecycle ───────────────────────────────────────────────────────────
428
- /**
429
- * The single UA, created at most once — even under concurrent callers.
430
- *
431
- * **The `#ua` check alone is not a guard**, because everything after it awaits: two callers both
432
- * see `null`, both `provision()`, both build a UA, and both REGISTER the same extension. Zadarma
433
- * rejects the loser, `registrationFailed` tears down, and the survivor may be the one that was
434
- * torn down. The visible symptom is two `get_webphone_data.php` calls at startup and a phone that
435
- * never registers.
436
- *
437
- * Concurrency is the normal case here, not an edge: the push socket can signal twice in a
438
- * heartbeat (SPEC §3.3 — a push is not an INVITE; it fires for transfers, retries and hangups),
439
- * and `placeCall` can land on top of one. So the in-flight promise IS the guard.
440
- */
441
- async #ensureUA() {
442
- if (this.#ua) return this.#ua;
443
- this.#uaInFlight ??= this.#createUA().finally(() => {
444
- this.#uaInFlight = null;
445
- });
446
- return this.#uaInFlight;
447
- }
448
- async #createUA() {
449
- const factory = await this.#resolveFactory();
450
- let credentials;
451
- try {
452
- credentials = await this.provider.provision();
453
- } catch (cause) {
454
- if (isSoftphoneError(cause)) this.#emitError(cause);
455
- else this.#reportError("provider/provision-failed", cause);
456
- throw cause;
457
- }
458
- this.#domain = domainOf(credentials);
459
- const config = this.#uaConfig(credentials, factory);
460
- const ua = factory.createUA(config);
461
- ua.on("newRTCSession", ({ session, originator }) => this.#onNewSession(session, originator));
462
- ua.on("disconnected", ({ error }) => {
463
- if (!error) return;
464
- this.#setState("reconnecting");
465
- this.#reportError("net/transport-failed", error);
466
- });
467
- ua.on("connected", () => this.#setState("online"));
468
- ua.on("registrationFailed", (e) => {
469
- const detail = e;
470
- this.#reportError("net/registration-failed", {
471
- cause: detail?.cause,
472
- status: detail?.response?.status_code,
473
- domain: this.#domain,
474
- hint: "A bare 401 with no auth challenge usually means the registrar is in the wrong datacenter (SPEC \xA73.1)."
475
- });
476
- this.#teardownUA();
477
- void this.#refreshSignal();
478
- });
479
- this.#ua = ua;
480
- ua.start();
481
- return ua;
482
- }
483
- #uaConfig(credentials, factory) {
484
- return {
485
- sockets: [factory.createWebSocket(credentials.wsUrl)],
486
- uri: credentials.uri,
487
- authorization_user: credentials.authUser,
488
- password: credentials.password,
489
- register: true,
490
- register_expires: REGISTER_EXPIRES,
491
- connection_recovery_min_interval: 2,
492
- connection_recovery_max_interval: 30,
493
- // Generic — NOT a provider brand string. If a provider ever requires a specific UA header it
494
- // belongs in the provider, not hard-coded here.
495
- // NOT ours to choose: Zadarma refuses to register any client whose User-Agent it does not
496
- // recognise (see ProviderQuirks.userAgent). The provider decides; the engine just sends it.
497
- user_agent: this.provider.quirks?.userAgent ?? "Coventia Softphone"
498
- };
499
- }
500
- #teardownUA() {
501
- this.#uaInFlight = null;
502
- if (!this.#ua) return;
503
- try {
504
- this.#ua.terminateSessions({ status_code: 487 });
505
- this.#ua.stop();
506
- } catch {
507
- }
508
- this.#ua = null;
509
- this.#activeCall = null;
510
- this.#consultCall = null;
511
- }
512
- /** Place a call once the UA is registered (its 200 OK for REGISTER has arrived). */
513
- /**
514
- * **No `mediaStream`** — JsSIP calls `getUserMedia` itself, which is what opens a real capture.
515
- *
516
- * That is load-bearing, not incidental. Firefox restricts ICE gathering on a page with no active
517
- * capture: it discards every address but the default route's ("Ignoring addr from interface other
518
- * than …" in about:webrtc) and can end up gathering NOTHING, so the INVITE goes out with
519
- * `c=IN IP4 0.0.0.0` and no candidates at all. No STUN or TURN server can rescue an offer that
520
- * contains no candidates. The legacy hook passed `mediaConstraints` and nothing else, for what
521
- * turns out to be a very good reason.
522
- */
523
- #callWhenRegistered(ua, target) {
524
- const options = { mediaConstraints: buildAudioConstraints(this.#inputDeviceId), pcConfig: PC_CONFIG };
525
- if (ua.isRegistered()) return Promise.resolve(ua.call(target, options));
526
- return new Promise((resolve) => {
527
- ua.on("registered", () => resolve(ua.call(target, options)));
528
- });
529
- }
530
- #wrapCall(session) {
531
- const call = new SipEngineCall(session, {
532
- id: nextCallId(),
533
- buildTarget: (t) => this.#buildTarget(t),
534
- placeConsult: (t) => this.#placeConsult(t),
535
- // The guard is tied to the reject ACTION, not to `ended` — a normal hangup must not arm it.
536
- onReject: () => this.#startRejectGuard(),
537
- iceGatheringCapMs: this.provider.quirks?.iceGatheringCapMs ?? DEFAULT_ICE_CAP_MS,
538
- // Inbound answers open their own peer connection, so they need the same ICE servers the
539
- // outbound leg got. Missing here, an ANSWERED call is the one that fails — the half nobody
540
- // tests until a real person picks up.
541
- pcConfig: PC_CONFIG,
542
- // Read fresh at answer() time, not captured now — a device chosen while the phone is still
543
- // ringing must still apply once it is picked up.
544
- getInputDeviceId: () => this.#inputDeviceId
545
- });
546
- this.#activeCall = call;
547
- call.onEvent((event) => {
548
- if (event.type === "ended") {
549
- const missed = call.direction === "inbound" && event.cause === "Canceled";
550
- const code = missed ? "call/missed" : CALL_END_CODES[event.reason];
551
- if (code) this.#reportError(code, event.cause);
552
- if (this.#activeCall === call) this.#activeCall = null;
553
- this.#maybeTeardownUA();
554
- }
555
- });
556
- return call;
557
- }
558
- async #placeConsult(target) {
559
- const ua = await this.#ensureUA();
560
- const consultSession = ua.call(this.#buildTarget(target), {
561
- mediaConstraints: buildAudioConstraints(this.#inputDeviceId),
562
- pcConfig: PC_CONFIG
563
- });
564
- const consultCall = new SipEngineCall(consultSession, {
565
- id: nextCallId(),
566
- buildTarget: (x) => this.#buildTarget(x),
567
- placeConsult: () => Promise.reject(new Error("cannot consult from a consult leg")),
568
- iceGatheringCapMs: this.provider.quirks?.iceGatheringCapMs ?? DEFAULT_ICE_CAP_MS
569
- });
570
- this.#consultCall = consultCall;
571
- consultCall.onEvent((event) => {
572
- if (event.type === "ended") {
573
- if (this.#consultCall === consultCall) this.#consultCall = null;
574
- this.#maybeTeardownUA();
575
- }
576
- });
577
- return consultCall;
578
- }
579
- /**
580
- * On-demand registration (SPEC §3.3): the UA is disposable once NOTHING is left on it — but "the
581
- * main leg ended" (or "no INVITE followed this push") is not the same fact as "nothing is left."
582
- * `completeTransfer()` (SPEC §5.6) ends the main leg via a REFER…Replaces BYE *while the consult leg
583
- * is still what the PBX needs to bridge the caller onto* — tearing the UA down (and with it, EVERY
584
- * session on it, via `terminateSessions`) the instant the main leg's `ended` fires killed that
585
- * consult leg out from under the transfer before the bridge could use it, and the caller was simply
586
- * gone. Two real call sites hit this independently (found live, 2026-08-04): the main leg's own
587
- * `ended` handler, and `#armNoInviteTeardown`'s 5s timer — the latter re-arms on EVERY push,
588
- * including unrelated "answered" pushes Zadarma sends around other account activity, so it can fire
589
- * minutes after a transfer with no `#activeCall` and no idea a consult leg is mid-handoff. Both now
590
- * route through here rather than checking `#activeCall` alone.
591
- */
592
- #maybeTeardownUA() {
593
- if (this.provider.registrationMode !== "on-demand") return;
594
- if (this.#activeCall || this.#consultCall) return;
595
- this.#teardownUA();
596
- }
597
- #startRejectGuard() {
598
- const ms = this.provider.quirks?.rejectGuardMs;
599
- if (ms) this.#rejectGuardUntil = this.now() + ms;
600
- }
601
- #buildTarget(target) {
602
- return target.includes("@") ? target : `sip:${target}@${this.#domain}`;
603
- }
604
- #setState(state) {
605
- if (state === this.#state) return;
606
- this.#state = state;
607
- for (const listener of [...this.#stateListeners]) listener(state);
608
- }
609
- };
610
-
611
- // src/transports/sip/real-factory.ts
612
- var cached = null;
613
- async function loadJsSipFactory() {
614
- if (cached) return cached;
615
- const mod = await import('jssip');
616
- const JsSIP = mod.default ?? mod;
617
- if (!JsSIP?.UA || !JsSIP?.WebSocketInterface) {
618
- throw new Error("jssip: unexpected module shape (no UA / WebSocketInterface)");
619
- }
620
- cached = {
621
- createWebSocket: (wsUrl) => new JsSIP.WebSocketInterface(wsUrl),
622
- createUA: (config) => new JsSIP.UA(config)
623
- };
624
- return cached;
625
- }
626
-
627
- // src/transports/providers/zadarma.ts
628
- var PING = { localMs: 3e4, globalMs: 6e4 };
629
- var KEY_REFRESH_BUFFER_MS = 2 * 60 * 60 * 1e3;
630
- var REBUILD_CONNECT_TIMEOUT_MS = 1e4;
631
- var REBUILD_RETRY_MS = 3e4;
632
- var ZADARMA_QUIRKS = {
633
- // Zadarma's registrar REFUSES to register a WebRTC client with any other User-Agent — a clean 401
634
- // after a valid digest challenge, indistinguishable from a wrong password (§3.1). The old CRM
635
- // hook carried this string; the port dropped it, and registration failed for exactly that reason.
636
- userAgent: "Zadarma webRTC",
637
- // Zadarma re-rings a declined call for ~30 s (return_timeout). Swallow those (§3.4).
638
- rejectGuardMs: 35e3,
639
- // A push is not an INVITE (§3.3). If none arrives, tear the fresh UA down.
640
- noInviteTeardownMs: 5e3,
641
- // A ceiling on ICE gathering, not a target: JsSIP sends as soon as gathering completes. 3 s leaves
642
- // room for a TURN allocation (whose relay candidates arrive last) while still bounding the ~40 s
643
- // Chrome can spend against an unreachable server. See `capIceGathering`.
644
- iceGatheringCapMs: 3e3
645
- };
646
- function buildPushUrl(key, sip) {
647
- const params = new URLSearchParams({ key, integrationType: "site", sipId: sip });
648
- return `wss://ws.zadarma.com/webrtc_pushes?${params.toString()}`;
649
- }
650
- var ZadarmaPushSignal = class {
651
- constructor(deps) {
652
- this.deps = deps;
653
- }
654
- deps;
655
- #socket = null;
656
- #connected = false;
657
- #pingTimers = [];
658
- #refreshTimer;
659
- /** The replacement socket of a rebuild in flight, not yet current. */
660
- #candidate = null;
661
- /** Abandons the rebuild in flight (closing its candidate). */
662
- #abortRebuild = null;
663
- #rebuilding = false;
664
- #retryTimer;
665
- #unwatchBackground;
666
- #closed = false;
667
- #listeners = /* @__PURE__ */ new Set();
668
- #connectionListeners = /* @__PURE__ */ new Set();
669
- async connect() {
670
- if (this.#socket) return;
671
- this.#closed = false;
672
- this.#unwatchBackground ??= this.deps.watchBackgroundReconnect?.(() => void this.#reopen());
673
- await this.#open();
674
- }
675
- async #open() {
676
- const { key, sip, keyExpiresAt } = await this.deps.fetchKey();
677
- if (this.#closed) return;
678
- const socket = this.deps.createPushSocket(buildPushUrl(key, sip));
679
- this.#socket = socket;
680
- this.#attach(socket);
681
- this.#armRefresh(keyExpiresAt);
682
- }
683
- /**
684
- * Wires one socket's events. `this.#socket` is read when an event FIRES, not when it is wired: a socket that
685
- * has been replaced must stop driving connectivity (our own `close()` of it emits `disconnect`, which would
686
- * otherwise flip the state to offline right after a perfectly healthy swap). `update` is the exception — it is
687
- * forwarded from any socket not yet closed, because a push seen twice is harmless (the engine ignores a
688
- * repeated signal mid-call and reuses a UA that already exists) while one seen by neither is a missed call.
689
- *
690
- * With `hooks`, the socket is a rebuild's candidate: its first `connect` or failure goes to the rebuild instead
691
- * of changing the connection state (it is not current yet).
692
- */
693
- #attach(socket, hooks) {
694
- socket.on("connect", () => {
695
- if (hooks && socket === this.#candidate) return hooks.onConnect();
696
- if (socket !== this.#socket) return;
697
- this.#setConnected(true);
698
- this.#startPings(socket);
699
- });
700
- socket.on("update", () => this.#emit());
701
- const lost = () => {
702
- if (hooks && socket === this.#candidate) return hooks.onFailure();
703
- if (socket !== this.#socket) return;
704
- this.#stopPings();
705
- this.#setConnected(false);
706
- };
707
- socket.on("disconnect", lost);
708
- socket.on("connect_error", lost);
709
- }
710
- /**
711
- * Presence pings — **the reason an idle tab keeps receiving calls**.
712
- *
713
- * Zadarma's gateway decides whether the extension is online, and it decides from these. Without
714
- * them the socket goes quiet, Zadarma marks the extension offline within minutes, and INVITEs stop
715
- * being routed — with no error anywhere, because nothing failed. The only visible symptom is that
716
- * the phone silently stops ringing until the page is reloaded.
717
- *
718
- * The names and intervals are Zadarma's, taken from the CRM hook that ran this in production for
719
- * years. They are not ours to tune.
720
- */
721
- #startPings(socket) {
722
- this.#stopPings();
723
- this.#pingTimers = [
724
- setInterval(() => socket.emit("localPing", {}), PING.localMs),
725
- setInterval(() => socket.emit("globalPing", {}), PING.globalMs)
726
- ];
727
- }
728
- #stopPings() {
729
- for (const t of this.#pingTimers) clearInterval(t);
730
- this.#pingTimers = [];
731
- }
732
- /**
733
- * Rebuild the socket before the WebRTC key expires.
734
- *
735
- * The key is baked into the socket URL, so socket.io's own reconnection re-presents whatever it was
736
- * given at construction. A tab left open past the key's 72 h lifetime would reconnect forever with
737
- * a dead credential. Absolute, from the backend's `key_expires_at`, so it targets the real expiry
738
- * rather than restarting a countdown on every reconnect.
739
- */
740
- #armRefresh(keyExpiresAt) {
741
- clearTimeout(this.#refreshTimer);
742
- if (!keyExpiresAt) return;
743
- const ms = new Date(keyExpiresAt).getTime() - Date.now() - KEY_REFRESH_BUFFER_MS;
744
- if (!Number.isFinite(ms) || ms <= 0) return;
745
- this.#refreshTimer = setTimeout(() => void this.#reopen(), ms);
746
- }
747
- /**
748
- * Replaces the push socket with a fresh one — MAKE-BEFORE-BREAK (presence-client-reporting.md §4.1, T8).
749
- *
750
- * Why it must happen at all: Zadarma's gateway decides the extension is alive from the raw Engine.IO ping, which
751
- * a hidden tab's throttled timers silently stop sending, so while the tab is hidden the socket is rebuilt every
752
- * 20 s (`push-socket-reliability.md` §5.3), and once before the key expires. Why it must not leave a gap: the
753
- * old close-then-reopen reported `connected = false` for the ~0.5 s in between, which took the softphone
754
- * `offline`, tore down the presence socket and left Zadarma with no socket to push an incoming call to.
755
- *
756
- * Now the OLD socket stays up and stays current until the NEW one has actually connected; only then do we swap,
757
- * move the pings and close the old one. A healthy rebuild never changes `connected`. A failed one — the key fetch
758
- * throws, the socket errors, or it has not connected within `REBUILD_CONNECT_TIMEOUT_MS` — keeps the old socket
759
- * and retries, instead of leaving the tab disconnected. Zadarma does not evict the older of two sockets for one
760
- * sip (multi-tab-leader-election.md §1), so the overlap is safe.
761
- */
762
- async #reopen() {
763
- if (this.#closed || this.#rebuilding) return;
764
- if (!this.#socket) {
765
- try {
766
- await this.#open();
767
- } catch {
768
- }
769
- return;
770
- }
771
- this.#rebuilding = true;
772
- try {
773
- const { key, sip, keyExpiresAt } = await this.deps.fetchKey();
774
- if (this.#closed) return;
775
- const swapped = await new Promise((resolve) => {
776
- const socket = this.deps.createPushSocket(buildPushUrl(key, sip));
777
- this.#candidate = socket;
778
- let settled = false;
779
- const finish = (ok) => {
780
- if (settled) return;
781
- settled = true;
782
- clearTimeout(timer);
783
- this.#abortRebuild = null;
784
- if (ok && socket.connected) {
785
- this.#swapIn(socket, keyExpiresAt);
786
- } else {
787
- this.#candidate = null;
788
- socket.close();
789
- }
790
- resolve(ok && socket.connected);
791
- };
792
- const timer = setTimeout(() => finish(false), REBUILD_CONNECT_TIMEOUT_MS);
793
- this.#abortRebuild = () => finish(false);
794
- this.#attach(socket, { onConnect: () => finish(true), onFailure: () => finish(false) });
795
- });
796
- if (!swapped) this.#armRetry();
797
- } catch {
798
- this.#armRetry();
799
- } finally {
800
- this.#rebuilding = false;
801
- }
802
- }
803
- /**
804
- * The moment of the swap — synchronous, called from the candidate's own `connect` event so nothing can run
805
- * between "the new socket is up" and "it is the current one". Order matters: `#socket` moves first, so the old
806
- * socket's `disconnect` (our own `close()` of it, just below) is ignored by `#attach`.
807
- */
808
- #swapIn(socket, keyExpiresAt) {
809
- const previous = this.#socket;
810
- this.#socket = socket;
811
- this.#candidate = null;
812
- clearTimeout(this.#retryTimer);
813
- this.#retryTimer = void 0;
814
- this.#stopPings();
815
- this.#startPings(socket);
816
- this.#setConnected(true);
817
- previous?.close();
818
- this.#armRefresh(keyExpiresAt);
819
- }
820
- #armRetry() {
821
- if (this.#closed) return;
822
- clearTimeout(this.#retryTimer);
823
- this.#retryTimer = setTimeout(() => void this.#reopen(), REBUILD_RETRY_MS);
824
- }
825
- disconnect() {
826
- this.#closed = true;
827
- this.#stopPings();
828
- clearTimeout(this.#refreshTimer);
829
- this.#refreshTimer = void 0;
830
- clearTimeout(this.#retryTimer);
831
- this.#retryTimer = void 0;
832
- this.#abortRebuild?.();
833
- this.#unwatchBackground?.();
834
- this.#unwatchBackground = void 0;
835
- this.#socket?.close();
836
- this.#socket = null;
837
- this.#setConnected(false);
838
- }
839
- onSignal(listener) {
840
- this.#listeners.add(listener);
841
- return () => this.#listeners.delete(listener);
842
- }
843
- onConnectionChange(listener) {
844
- this.#connectionListeners.add(listener);
845
- return () => this.#connectionListeners.delete(listener);
846
- }
847
- get connected() {
848
- return this.#connected;
849
- }
850
- #setConnected(connected) {
851
- if (this.#connected === connected) return;
852
- this.#connected = connected;
853
- for (const listener of [...this.#connectionListeners]) listener(connected);
854
- }
855
- #emit() {
856
- for (const listener of [...this.#listeners]) listener();
857
- }
858
- };
859
- var ZadarmaProvider = class {
860
- constructor(deps) {
861
- this.deps = deps;
862
- this.incomingSignal = new ZadarmaPushSignal(deps);
863
- }
864
- deps;
865
- name = "zadarma";
866
- // Zadarma's PBX ignores a standing registration — it routes INVITEs only to a UA that registered
867
- // in response to a push (SPEC §3.2). Hence on-demand.
868
- registrationMode = "on-demand";
869
- quirks = ZADARMA_QUIRKS;
870
- incomingSignal;
871
- /**
872
- * Per-registration credentialing: fetch a scoped key, then exchange it in the browser for
873
- * ephemeral SIP creds. The key fetch is cheap and backend-cached; doing it here (rather than
874
- * sharing state with the push signal) keeps the two paths independent.
875
- */
876
- async provision() {
877
- const { key, sip } = await this.deps.fetchKey();
878
- const { pass, domain } = await this.deps.exchangeWebphoneData(key, sip);
879
- return {
880
- uri: `sip:${sip}@${domain}`,
881
- authUser: sip,
882
- password: pass,
883
- wsUrl: `wss://${domain}:4443`
884
- };
885
- }
886
- };
887
-
888
- // src/transports/providers/zadarma-browser.ts
889
- var UnauthorizedKeyError = class extends Error {
890
- };
891
- function makeFetchKey(config) {
892
- const attempt = async () => {
893
- let token;
894
- try {
895
- ({ token } = await config.tokenSource.getToken());
896
- } catch (cause) {
897
- throw createError("auth/token-fetch-failed", cause);
898
- }
899
- const qs = config.organizationId ? `?organization_id=${encodeURIComponent(config.organizationId)}` : "";
900
- const res = await fetch(`${config.apiBase}/phone/webrtc/key${qs}`, {
901
- headers: { Authorization: token }
902
- });
903
- if (!res.ok) {
904
- const body = await res.json().catch(() => null);
905
- const message = body?.message ?? `webrtc/key HTTP ${res.status}`;
906
- throw res.status === 401 ? new UnauthorizedKeyError(message) : new Error(message);
907
- }
908
- const data = await res.json();
909
- return {
910
- key: data.key,
911
- sip: data.sip,
912
- ...data.key_expires_at ? { keyExpiresAt: data.key_expires_at } : {}
913
- };
914
- };
915
- return async () => {
916
- try {
917
- return await attempt();
918
- } catch (error) {
919
- if (!(error instanceof UnauthorizedKeyError)) throw error;
920
- invalidateToken(config.tokenSource);
921
- try {
922
- return await attempt();
923
- } catch (retryError) {
924
- if (retryError instanceof UnauthorizedKeyError) {
925
- throw createError("auth/token-rejected", retryError);
926
- }
927
- throw retryError;
928
- }
929
- }
930
- };
931
- }
932
- async function exchangeWebphoneData(key, sip, timeoutMs = 1e4) {
933
- const params = new URLSearchParams({
934
- // Still sent: the endpoint wraps its response either way, and naming the callback keeps the
935
- // wrapper predictable rather than relying on their default.
936
- jsonpCallback: "cv",
937
- integrationType: "site",
938
- key,
939
- sipId: sip
940
- });
941
- let res;
942
- try {
943
- res = await fetch(
944
- `https://api.zadarma.com/sys/webrtc/get_webphone_data.php?${params.toString()}`,
945
- { signal: AbortSignal.timeout(timeoutMs) }
946
- );
947
- } catch (cause) {
948
- const timedOut = cause instanceof DOMException && cause.name === "TimeoutError";
949
- throw new Error(timedOut ? "get_webphone_data timed out" : "get_webphone_data network error", {
950
- cause
951
- });
952
- }
953
- if (!res.ok) throw new Error(`get_webphone_data HTTP ${res.status}`);
954
- const data = parseJsonp(await res.text());
955
- if (!data || data.error || !data.pass || !data.domain) {
956
- throw new Error(data?.error?.content ?? "get_webphone_data: missing SIP credentials");
957
- }
958
- return { pass: data.pass, domain: data.domain };
959
- }
960
- function parseJsonp(text) {
961
- const open = text.indexOf("(");
962
- const close = text.lastIndexOf(")");
963
- const body = open !== -1 && close > open ? text.slice(open + 1, close) : text;
964
- try {
965
- return JSON.parse(body);
966
- } catch {
967
- return null;
968
- }
969
- }
970
- function createPushSocket(url) {
971
- const handlers = /* @__PURE__ */ new Map();
972
- let client = null;
973
- let closed = false;
974
- void (async () => {
975
- const mod = await import('socket.io-client-v2');
976
- if (closed) return;
977
- const connect = mod.default ?? mod.io;
978
- if (!connect) throw new Error("socket.io-client-v2: no connect export");
979
- const c = connect(url, {
980
- transports: ["websocket"],
981
- reconnection: true,
982
- // The push socket drops on a schedule under background-tab timer throttling, NOT from network
983
- // flakiness — every reconnect observed succeeds on the first attempt (push-socket-reliability.md
984
- // §2.3, §5.1). There is nothing to back off from on that first attempt, so waiting the old 10s
985
- // before retrying was pure, uncontested exposure — an inbound call landing in that window is
986
- // lost, unqueued (Zadarma's gateway speaks EIO3, no offline redelivery). `reconnectionDelayMax`
987
- // stays as the ceiling for a genuinely down gateway, where backing off still matters.
988
- reconnectionDelay: 300,
989
- reconnectionDelayMax: 3e4
990
- });
991
- client = c;
992
- for (const [event, cbs] of handlers) for (const cb of cbs) c.on(event, cb);
993
- })();
994
- return {
995
- on(event, cb) {
996
- const list = handlers.get(event) ?? [];
997
- list.push(cb);
998
- handlers.set(event, list);
999
- client?.on(event, cb);
1000
- },
1001
- emit(event, payload) {
1002
- client?.emit(event, payload);
1003
- },
1004
- close() {
1005
- closed = true;
1006
- client?.close();
1007
- },
1008
- get connected() {
1009
- return client?.connected ?? false;
1010
- }
1011
- };
1012
- }
1013
- var BACKGROUND_RECONNECT_MS = 2e4;
1014
- var HEARTBEAT_WORKER_SOURCE = `
1015
- let timer;
1016
- self.onmessage = (e) => {
1017
- if (e.data.type === 'start') timer = setInterval(() => self.postMessage('tick'), e.data.intervalMs);
1018
- else if (e.data.type === 'stop') { clearInterval(timer); timer = undefined; }
1019
- };
1020
- `;
1021
- function watchBackgroundReconnect(cb) {
1022
- if (typeof document === "undefined" || typeof Worker === "undefined") return () => {
1023
- };
1024
- let worker = null;
1025
- let blobUrl = null;
1026
- const ensureWorker = () => {
1027
- if (!worker) {
1028
- blobUrl = URL.createObjectURL(new Blob([HEARTBEAT_WORKER_SOURCE], { type: "application/javascript" }));
1029
- worker = new Worker(blobUrl);
1030
- worker.onmessage = (e) => {
1031
- if (e.data === "tick") cb();
1032
- };
1033
- }
1034
- return worker;
1035
- };
1036
- const onVisibilityChange = () => {
1037
- if (document.visibilityState === "hidden") {
1038
- ensureWorker().postMessage({ type: "start", intervalMs: BACKGROUND_RECONNECT_MS });
1039
- } else {
1040
- worker?.postMessage({ type: "stop" });
1041
- }
1042
- };
1043
- document.addEventListener("visibilitychange", onVisibilityChange);
1044
- if (document.visibilityState === "hidden") onVisibilityChange();
1045
- return () => {
1046
- document.removeEventListener("visibilitychange", onVisibilityChange);
1047
- worker?.postMessage({ type: "stop" });
1048
- worker?.terminate();
1049
- if (blobUrl) URL.revokeObjectURL(blobUrl);
1050
- };
1051
- }
1052
- function makeZadarmaBrowserDeps(config) {
1053
- return {
1054
- fetchKey: makeFetchKey(config),
1055
- exchangeWebphoneData: (key, sip) => exchangeWebphoneData(key, sip),
1056
- createPushSocket,
1057
- watchBackgroundReconnect
1058
- };
1059
- }
1060
-
1061
- // src/transports/zadarma-engine.ts
1062
- function createZadarmaEngine(config) {
1063
- const provider = new ZadarmaProvider(
1064
- makeZadarmaBrowserDeps({ ...config, tokenSource: cachedTokenSource(config.tokenSource) })
1065
- );
1066
- return new SipCallEngine(provider, loadJsSipFactory);
1067
- }
1068
-
1069
- export { ZADARMA_QUIRKS, createZadarmaEngine };
1070
- //# sourceMappingURL=chunk-EYEDPD7Y.js.map
1071
- //# sourceMappingURL=chunk-EYEDPD7Y.js.map