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