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