@tryprojectblue/dialer 0.1.0 → 0.2.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/CHANGELOG.md +12 -0
- package/README.md +86 -39
- package/dist/index.cjs +86 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +31 -2
- package/dist/index.d.ts +31 -2
- package/dist/index.js +86 -13
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @tryprojectblue/dialer
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
- `registered` getter plus `registered`, `unregistered` and `registrationFailed` events. `ready` now reports `{ inboundEnabled, registered }`.
|
|
6
|
+
- Inbound registration retries after 5, 15 and 45 seconds, then waits for the next token refresh.
|
|
7
|
+
- `start({ requireInbound: true })` rejects with `inbound_unavailable` when inbound is not available.
|
|
8
|
+
- Destination allowlists: tokens minted with `allowedDestinations` reject other numbers with `destination_not_allowed` before connecting.
|
|
9
|
+
- Call grants: `call(to, { grant })` for tokens minted with `requireCallGrant: true`. A missing grant rejects with `grant_required`.
|
|
10
|
+
|
|
11
|
+
## 0.1.1
|
|
12
|
+
|
|
13
|
+
- README is customer-facing only; engineering notes moved to the internal wiki. No code changes.
|
|
14
|
+
|
|
3
15
|
## 0.1.0
|
|
4
16
|
|
|
5
17
|
- Initial release: token-provider based session, outbound calls, inbound calls
|
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Browser SDK for placing and receiving calls on your Project Blue lines.
|
|
4
4
|
|
|
5
5
|
Your workspace API key never reaches the browser. Your server exchanges it for
|
|
6
|
-
a short
|
|
6
|
+
a short lived token scoped to one line; the SDK takes a `tokenProvider` that
|
|
7
7
|
calls your server, and handles refresh, call lifecycle and usage limits.
|
|
8
8
|
|
|
9
9
|
```
|
|
@@ -14,7 +14,8 @@ npm install @tryprojectblue/dialer
|
|
|
14
14
|
|
|
15
15
|
`POST https://app.tryprojectblue.com/api/v1/dialer/token` with the workspace
|
|
16
16
|
API key from **Settings → API Keys** and the `lineId` of the line to call from
|
|
17
|
-
(`GET /get-lines
|
|
17
|
+
(`GET https://api.tryprojectblue.com/get-lines`, same API key, returns your line
|
|
18
|
+
ids; note the two hosts: lines come from the messaging API, tokens from the app).
|
|
18
19
|
|
|
19
20
|
```ts
|
|
20
21
|
// Node / any server runtime. Never ship PROJECT_BLUE_API_KEY to a browser.
|
|
@@ -27,8 +28,14 @@ app.post('/dialer-token', requireLogin, async (req, res) => {
|
|
|
27
28
|
},
|
|
28
29
|
body: JSON.stringify({ lineId: req.user.projectBlueLineId }),
|
|
29
30
|
});
|
|
30
|
-
// Forward status and
|
|
31
|
-
|
|
31
|
+
// Forward status, body and the rate limit hint unchanged; the SDK understands them.
|
|
32
|
+
// Never let a non JSON 502/503 from a proxy throw.
|
|
33
|
+
const retryAfter = upstream.headers.get('retry-after');
|
|
34
|
+
if (retryAfter) res.set('Retry-After', retryAfter);
|
|
35
|
+
const body = await upstream
|
|
36
|
+
.json()
|
|
37
|
+
.catch(() => ({ error: 'Token service unavailable', code: 'dialer_unavailable' }));
|
|
38
|
+
res.status(upstream.status).json(body);
|
|
32
39
|
});
|
|
33
40
|
```
|
|
34
41
|
|
|
@@ -42,6 +49,8 @@ Success body:
|
|
|
42
49
|
"lineId": "0b3e0c59-ff0b-4110-faf6-6f976339a8c8",
|
|
43
50
|
"inboundEnabled": true,
|
|
44
51
|
"maxCallsPerToken": 10,
|
|
52
|
+
"allowedDestinations": null,
|
|
53
|
+
"callGrantRequired": false,
|
|
45
54
|
"allowance": {
|
|
46
55
|
"state": "ok",
|
|
47
56
|
"used": 30,
|
|
@@ -104,13 +113,13 @@ hangupButton.onclick = () => call.hangup();
|
|
|
104
113
|
| --- | --- |
|
|
105
114
|
| `tokenProvider` | **required.** Returns the mint response body (or a token string). |
|
|
106
115
|
| `refreshLeadSeconds` | Refresh this long before expiry. Default `60`. |
|
|
107
|
-
| `logger` | `console
|
|
116
|
+
| `logger` | `console` like object, or `null` to silence. |
|
|
108
117
|
| `edge` | Media region hint. Leave unset unless measured. |
|
|
109
118
|
| `playIncomingRingtone` | Default `true`. |
|
|
110
119
|
|
|
111
|
-
Methods: `start()`, `call(to)` (`to` must be E.164 **with** the leading `+`; the SDK never guesses a country code), `refreshToken()`, `destroy()`, `isReady()`.
|
|
112
|
-
Getters: `allowance`, `inboundEnabled`, `activeCall`.
|
|
113
|
-
Events: `ready`, `allowance`, `capReached`, `incoming`, `tokenRefreshFailed`,
|
|
120
|
+
Methods: `start({ requireInbound?: boolean })`, `call(to, { grant?: string })` (`to` must be E.164 **with** the leading `+`; the SDK never guesses a country code), `refreshToken()`, `destroy()`, `isReady()`.
|
|
121
|
+
Getters: `allowance`, `inboundEnabled`, `registered`, `activeCall`.
|
|
122
|
+
Events: `ready`, `registered`, `unregistered`, `registrationFailed`, `allowance`, `capReached`, `incoming`, `tokenRefreshFailed`,
|
|
114
123
|
`error`, `destroyed`.
|
|
115
124
|
|
|
116
125
|
### `DialerCall`
|
|
@@ -130,47 +139,85 @@ Every rejection is a `DialerError` with a `code`:
|
|
|
130
139
|
`subscription_required`, `account_paywalled`, `rate_limited`
|
|
131
140
|
(`DialerRateLimitedError`: `retryAfterSeconds`), `line_unavailable`,
|
|
132
141
|
`not_provisioned`, `token_unavailable`, `invalid_state`,
|
|
142
|
+
`inbound_unavailable`, `destination_not_allowed`, `grant_required`,
|
|
133
143
|
`microphone_unavailable`, `connection_failed`, `call_failed`.
|
|
134
144
|
|
|
135
145
|
## Limits
|
|
136
146
|
|
|
137
147
|
- Tokens live 15 minutes and are scoped to one line. The SDK refreshes them
|
|
138
|
-
automatically, including before a token's per
|
|
148
|
+
automatically, including before a token's per token call limit is reached.
|
|
139
149
|
- Each call is metered against your dialer plan. When the workspace or the line
|
|
140
150
|
hits its daily cap the mint returns `dialer_cap_reached`; calls already in
|
|
141
151
|
progress are never cut off.
|
|
142
152
|
- Inbound calls ring the SDK only while the line is provisioned for inbound and
|
|
143
153
|
someone in your workspace is in its ring set.
|
|
144
154
|
|
|
145
|
-
##
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
+
## Inbound readiness
|
|
156
|
+
|
|
157
|
+
`inboundEnabled` says the token permits inbound calls. `registered` is true
|
|
158
|
+
only while the engine device state is `registered`. The `ready` event carries
|
|
159
|
+
`{ inboundEnabled, registered }` after the initial registration settles and
|
|
160
|
+
after each successful token refresh. An outbound session can be ready while
|
|
161
|
+
inbound registration is unavailable.
|
|
162
|
+
|
|
163
|
+
Listen for `registered`, `unregistered` and `registrationFailed(error)` to keep
|
|
164
|
+
your inbound status current. Registration failures also emit the existing
|
|
165
|
+
`error` event. The SDK retries after 5, 15 and 45 seconds, then waits for the
|
|
166
|
+
next token refresh. Retries wait until an active call ends.
|
|
167
|
+
|
|
168
|
+
For inbound enabled sessions, `unregistered` then `registered` fire on every
|
|
169
|
+
token refresh, about every 14 minutes, because the SDK registers again under
|
|
170
|
+
the new token's identity, so a status indicator should not treat that brief
|
|
171
|
+
gap as a failure.
|
|
172
|
+
|
|
173
|
+
Use `await dialer.start({ requireInbound: true })` when inbound is required.
|
|
174
|
+
If the initial token does not enable inbound or registration fails, the SDK
|
|
175
|
+
destroys the session, rejects with `inbound_unavailable`, and emits no `ready`.
|
|
176
|
+
Create a new dialer instance to try again.
|
|
177
|
+
|
|
178
|
+
## Destination restrictions and call grants
|
|
179
|
+
|
|
180
|
+
Your server can mint with `{ lineId, allowedDestinations, requireCallGrant }`.
|
|
181
|
+
Both restriction fields are optional. `allowedDestinations` accepts 1 to 25
|
|
182
|
+
E.164 strings such as `+15551234567`. The server validates before counting
|
|
183
|
+
the mint request and removes exact duplicates. The response returns the
|
|
184
|
+
validated E.164 strings in `allowedDestinations`, or `null` for any destination,
|
|
185
|
+
and a boolean `callGrantRequired`. Authorization compares E.164 numbers exactly.
|
|
186
|
+
Invalid lists return HTTP 400 `invalid_allowed_destinations`; a non boolean
|
|
187
|
+
`requireCallGrant` returns HTTP 400 `invalid_require_call_grant`.
|
|
188
|
+
|
|
189
|
+
An allowlist or `requireCallGrant: true` makes the token restricted. Restriction
|
|
190
|
+
storage failures return HTTP 503 `dialer_unavailable`. Restricted calls are
|
|
191
|
+
refused if their restriction is missing or cannot be read. Ordinary tokens
|
|
192
|
+
and tokens minted before this feature continue to work without restrictions.
|
|
193
|
+
The SDK checks the current token after any refresh and rejects destinations
|
|
194
|
+
outside its list with `destination_not_allowed` before connecting. The server
|
|
195
|
+
also enforces the list.
|
|
196
|
+
|
|
197
|
+
For a session minted with `requireCallGrant: true`, your server must authorize
|
|
198
|
+
each call by requesting a grant using the same workspace API key:
|
|
199
|
+
|
|
200
|
+
```http
|
|
201
|
+
POST https://app.tryprojectblue.com/api/v1/dialer/grants
|
|
202
|
+
Authorization: Bearer proj_…
|
|
203
|
+
Content-Type: application/json
|
|
204
|
+
|
|
205
|
+
{ "lineId": "…", "to": "+15551234567" }
|
|
155
206
|
```
|
|
156
207
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
What is not covered: a real call. jsdom has no WebRTC and the local stack has
|
|
174
|
-
no Twilio emulator, so placing a call is a manual check on a preview deploy.
|
|
175
|
-
|
|
176
|
-
Publishing needs an npm account on the `@tryprojectblue` org (`npm login`).
|
|
208
|
+
The response is `{ grant, expiresAt, ttlSeconds }`. A grant expires after 120
|
|
209
|
+
seconds and authorizes exactly one call for its workspace, API key, line and
|
|
210
|
+
exact E.164 destination. The endpoint accepts 120 requests per API key per
|
|
211
|
+
minute and returns HTTP 429 `rate_limited` with `retryAfterSeconds` and
|
|
212
|
+
`Retry-After` when exceeded. It applies the same line eligibility rules as
|
|
213
|
+
token minting. Invalid destinations return HTTP 400 `invalid_destination`;
|
|
214
|
+
Redis write failures return HTTP 503 `dialer_unavailable`.
|
|
215
|
+
|
|
216
|
+
Pass the returned grant to `await dialer.call(to, { grant })`. Without it, a
|
|
217
|
+
session requiring grants rejects with `grant_required` before connecting.
|
|
218
|
+
The SDK sends it as `PbCallGrant`. The server consumes it atomically after
|
|
219
|
+
all other calling checks and immediately before the token call slot. Missing,
|
|
220
|
+
expired, reused or mismatched grants are refused. A cap, own number, trial,
|
|
221
|
+
caller ID or destination refusal does not consume the grant. A token call
|
|
222
|
+
limit refusal can consume it because that slot check follows consumption.
|
|
223
|
+
Tokens that do not require grants ignore a supplied `PbCallGrant`.
|
package/dist/index.cjs
CHANGED
|
@@ -273,6 +273,8 @@ var DEFAULT_REFRESH_LEAD_SECONDS = 60;
|
|
|
273
273
|
var FALLBACK_TTL_SECONDS = 15 * 60;
|
|
274
274
|
var MIN_REFRESH_DELAY_MS = 5e3;
|
|
275
275
|
var REFRESH_RETRY_DELAYS_MS = [5e3, 15e3, 45e3];
|
|
276
|
+
var REGISTRATION_RETRY_DELAYS_MS = [5e3, 15e3, 45e3];
|
|
277
|
+
var UNREGISTERED_RETRY_DELAY_MS = 2e3;
|
|
276
278
|
var DEFAULT_MAX_CALLS_PER_TOKEN = 10;
|
|
277
279
|
var quietLogger = {
|
|
278
280
|
debug: () => void 0,
|
|
@@ -297,6 +299,9 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
297
299
|
this.latestAllowance = null;
|
|
298
300
|
this.currentCall = null;
|
|
299
301
|
this.refreshTimer = null;
|
|
302
|
+
this.registrationTimer = null;
|
|
303
|
+
this.registrationFailures = 0;
|
|
304
|
+
this.registrationInProgress = false;
|
|
300
305
|
this.refreshInFlight = null;
|
|
301
306
|
this.refreshFailures = 0;
|
|
302
307
|
this.reregisterWhenCallEnds = false;
|
|
@@ -317,6 +322,10 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
317
322
|
get inboundEnabled() {
|
|
318
323
|
return this.active?.inboundEnabled ?? false;
|
|
319
324
|
}
|
|
325
|
+
/** Whether the engine is currently registered to receive calls. */
|
|
326
|
+
get registered() {
|
|
327
|
+
return this.device?.state === "registered";
|
|
328
|
+
}
|
|
320
329
|
get activeCall() {
|
|
321
330
|
return this.currentCall?.isActive() ? this.currentCall : null;
|
|
322
331
|
}
|
|
@@ -324,7 +333,7 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
324
333
|
return this.started && !this.destroyed && !!this.device && !!this.active;
|
|
325
334
|
}
|
|
326
335
|
/** Fetch the first token and connect. Resolves once calls can be placed. */
|
|
327
|
-
async start() {
|
|
336
|
+
async start(options) {
|
|
328
337
|
this.assertNotDestroyed();
|
|
329
338
|
if (this.started) return;
|
|
330
339
|
const response = await this.fetchToken();
|
|
@@ -343,15 +352,19 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
343
352
|
this.attachDeviceListeners(device);
|
|
344
353
|
this.started = true;
|
|
345
354
|
this.applyToken(response);
|
|
346
|
-
await this.syncRegistration();
|
|
347
|
-
|
|
355
|
+
const registrationSucceeded = await this.syncRegistration();
|
|
356
|
+
if (!!options?.requireInbound && (!this.inboundEnabled || !registrationSucceeded || !this.registered)) {
|
|
357
|
+
await this.destroy();
|
|
358
|
+
throw new DialerError("inbound_unavailable", "Inbound calling is unavailable for this session");
|
|
359
|
+
}
|
|
360
|
+
if (!this.destroyed) this.emit("ready", { inboundEnabled: this.inboundEnabled, registered: this.registered });
|
|
348
361
|
}
|
|
349
362
|
/**
|
|
350
363
|
* Place an outbound call from the line this session is scoped to. `to` must
|
|
351
364
|
* be E.164 (`+15551234567`). Rejects with a `DialerError` (`cap_reached`,
|
|
352
365
|
* `token_unavailable`, `microphone_unavailable`, …) when the call cannot start.
|
|
353
366
|
*/
|
|
354
|
-
async call(to) {
|
|
367
|
+
async call(to, options) {
|
|
355
368
|
this.assertReady();
|
|
356
369
|
const destination = typeof to === "string" ? to.replace(/[\s()-]/g, "") : "";
|
|
357
370
|
if (!/^\+[1-9][0-9]{6,14}$/.test(destination)) {
|
|
@@ -364,7 +377,14 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
364
377
|
if (token.callsPlaced >= token.maxCallsPerToken || this.expiresWithin(this.refreshLeadMs())) {
|
|
365
378
|
await this.refreshToken();
|
|
366
379
|
}
|
|
380
|
+
if (!!this.active.allowedDestinations && !this.active.allowedDestinations.includes(destination)) {
|
|
381
|
+
throw new DialerError("destination_not_allowed", "This number is not approved for this session.");
|
|
382
|
+
}
|
|
383
|
+
if (!!this.active.callGrantRequired && !options?.grant) {
|
|
384
|
+
throw new DialerError("grant_required", "A call grant is required for this session.");
|
|
385
|
+
}
|
|
367
386
|
const params = { To: destination };
|
|
387
|
+
if (!!options?.grant) params.PbCallGrant = options.grant;
|
|
368
388
|
let engineCall;
|
|
369
389
|
try {
|
|
370
390
|
engineCall = await this.device.connect({ params });
|
|
@@ -390,6 +410,8 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
390
410
|
if (this.destroyed) return;
|
|
391
411
|
this.destroyed = true;
|
|
392
412
|
this.clearRefreshTimer();
|
|
413
|
+
this.clearRegistrationTimer();
|
|
414
|
+
this.reregisterWhenCallEnds = false;
|
|
393
415
|
try {
|
|
394
416
|
this.currentCall?.hangup();
|
|
395
417
|
} catch {
|
|
@@ -442,8 +464,13 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
442
464
|
expiresAtMs,
|
|
443
465
|
inboundEnabled: !!response.inboundEnabled,
|
|
444
466
|
maxCallsPerToken: response.maxCallsPerToken && response.maxCallsPerToken > 0 ? response.maxCallsPerToken : DEFAULT_MAX_CALLS_PER_TOKEN,
|
|
445
|
-
callsPlaced: 0
|
|
467
|
+
callsPlaced: 0,
|
|
468
|
+
allowedDestinations: response.allowedDestinations ?? null,
|
|
469
|
+
callGrantRequired: !!response.callGrantRequired
|
|
446
470
|
};
|
|
471
|
+
this.clearRegistrationTimer();
|
|
472
|
+
this.registrationFailures = 0;
|
|
473
|
+
this.reregisterWhenCallEnds = false;
|
|
447
474
|
this.refreshFailures = 0;
|
|
448
475
|
if (response.allowance) {
|
|
449
476
|
this.latestAllowance = response.allowance;
|
|
@@ -475,7 +502,7 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
475
502
|
this.applyToken(response);
|
|
476
503
|
if (this.active.inboundEnabled) await this.reregisterUnderCurrentIdentity();
|
|
477
504
|
else if (wasInbound) await this.syncRegistration();
|
|
478
|
-
this.emit("ready", { inboundEnabled: this.inboundEnabled });
|
|
505
|
+
if (!this.destroyed) this.emit("ready", { inboundEnabled: this.inboundEnabled, registered: this.registered });
|
|
479
506
|
} catch (error) {
|
|
480
507
|
const dialerError = toDialerError(error);
|
|
481
508
|
this.log.warn("token refresh failed", dialerError);
|
|
@@ -502,34 +529,74 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
502
529
|
*/
|
|
503
530
|
async reregisterUnderCurrentIdentity() {
|
|
504
531
|
const device = this.device;
|
|
505
|
-
if (!device || !this.active?.inboundEnabled) return;
|
|
506
|
-
if (this.activeCall) {
|
|
532
|
+
if (!device || !this.active?.inboundEnabled || this.destroyed) return;
|
|
533
|
+
if (!!this.activeCall) {
|
|
507
534
|
this.reregisterWhenCallEnds = true;
|
|
508
535
|
return;
|
|
509
536
|
}
|
|
510
537
|
this.reregisterWhenCallEnds = false;
|
|
538
|
+
this.registrationInProgress = true;
|
|
511
539
|
try {
|
|
512
540
|
if (device.state === "registered") await device.unregister();
|
|
513
541
|
await device.register();
|
|
542
|
+
this.registrationSucceeded();
|
|
514
543
|
} catch (error) {
|
|
515
544
|
this.log.warn("re-registration after token refresh failed", error);
|
|
516
|
-
this.
|
|
545
|
+
this.registrationFailed(toDialerError(error, "connection_failed"));
|
|
546
|
+
} finally {
|
|
547
|
+
this.registrationInProgress = false;
|
|
517
548
|
}
|
|
518
549
|
}
|
|
519
550
|
async syncRegistration() {
|
|
520
551
|
const device = this.device;
|
|
521
|
-
if (!device || !this.active) return;
|
|
552
|
+
if (!device || !this.active || this.destroyed) return false;
|
|
553
|
+
this.registrationInProgress = true;
|
|
522
554
|
try {
|
|
523
555
|
if (this.active.inboundEnabled) {
|
|
556
|
+
if (!!this.activeCall) {
|
|
557
|
+
this.reregisterWhenCallEnds = true;
|
|
558
|
+
return false;
|
|
559
|
+
}
|
|
524
560
|
if (device.state !== "registered") await device.register();
|
|
561
|
+
this.registrationSucceeded();
|
|
525
562
|
} else if (device.state === "registered") {
|
|
526
563
|
await device.unregister();
|
|
527
564
|
}
|
|
565
|
+
return true;
|
|
528
566
|
} catch (error) {
|
|
529
567
|
this.log.warn("inbound registration failed", error);
|
|
530
|
-
this.
|
|
568
|
+
this.registrationFailed(toDialerError(error, "connection_failed"));
|
|
569
|
+
return false;
|
|
570
|
+
} finally {
|
|
571
|
+
this.registrationInProgress = false;
|
|
531
572
|
}
|
|
532
573
|
}
|
|
574
|
+
clearRegistrationTimer() {
|
|
575
|
+
if (this.registrationTimer !== null) {
|
|
576
|
+
clearTimeout(this.registrationTimer);
|
|
577
|
+
this.registrationTimer = null;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
registrationSucceeded() {
|
|
581
|
+
this.clearRegistrationTimer();
|
|
582
|
+
this.registrationFailures = 0;
|
|
583
|
+
}
|
|
584
|
+
registrationFailed(dialerError) {
|
|
585
|
+
if (this.destroyed) return;
|
|
586
|
+
this.emit("registrationFailed", dialerError);
|
|
587
|
+
this.emit("error", dialerError);
|
|
588
|
+
const delay = REGISTRATION_RETRY_DELAYS_MS[this.registrationFailures];
|
|
589
|
+
this.registrationFailures += 1;
|
|
590
|
+
if (!!this.active?.inboundEnabled && delay !== void 0) this.scheduleRegistration(delay);
|
|
591
|
+
}
|
|
592
|
+
scheduleRegistration(delayMs) {
|
|
593
|
+
this.clearRegistrationTimer();
|
|
594
|
+
if (this.destroyed) return;
|
|
595
|
+
this.registrationTimer = setTimeout(() => {
|
|
596
|
+
this.registrationTimer = null;
|
|
597
|
+
void this.reregisterUnderCurrentIdentity();
|
|
598
|
+
}, delayMs);
|
|
599
|
+
}
|
|
533
600
|
attachDeviceListeners(device) {
|
|
534
601
|
device.on("tokenWillExpire", () => void this.refreshToken().catch(() => void 0));
|
|
535
602
|
device.on("tokenExpired", () => void this.refreshToken().catch(() => void 0));
|
|
@@ -538,9 +605,15 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
538
605
|
this.trackCall(call);
|
|
539
606
|
this.emit("incoming", call);
|
|
540
607
|
});
|
|
608
|
+
device.on("registered", () => {
|
|
609
|
+
this.registrationSucceeded();
|
|
610
|
+
if (!this.destroyed) this.emit("registered");
|
|
611
|
+
});
|
|
541
612
|
device.on("unregistered", () => {
|
|
542
|
-
if (this.
|
|
543
|
-
|
|
613
|
+
if (this.destroyed) return;
|
|
614
|
+
this.emit("unregistered");
|
|
615
|
+
if (!!this.active?.inboundEnabled && !this.registrationInProgress && this.registrationFailures === 0) {
|
|
616
|
+
this.scheduleRegistration(UNREGISTERED_RETRY_DELAY_MS);
|
|
544
617
|
}
|
|
545
618
|
});
|
|
546
619
|
device.on("error", (raw) => {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/emitter.ts","../src/errors.ts","../src/call.ts","../src/engine.ts","../src/dialer.ts"],"sourcesContent":["export { ProjectBlueDialer } from './dialer';\nexport { DialerCall } from './call';\nexport {\n DialerError,\n DialerCapReachedError,\n DialerRateLimitedError,\n mintErrorFromResponse,\n type DialerErrorCode,\n} from './errors';\nexport type {\n DialerAllowance,\n DialerAllowanceState,\n DialerCallDirection,\n DialerCallEvents,\n DialerCallStatus,\n DialerEvents,\n DialerLogger,\n DialerMintErrorBody,\n DialerOptions,\n DialerTokenProvider,\n DialerTokenResponse,\n} from './types';\n","type Listener = (...args: never[]) => void;\n\n/** Minimal typed event emitter; avoids a runtime dependency in the browser bundle. */\nexport class TypedEmitter<Events extends { [K in keyof Events]: Listener }> {\n private listeners = new Map<keyof Events, Set<Events[keyof Events]>>();\n\n on<K extends keyof Events>(event: K, listener: Events[K]): () => void {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(listener);\n return () => this.off(event, listener);\n }\n\n once<K extends keyof Events>(event: K, listener: Events[K]): () => void {\n const wrapped = ((...args: Parameters<Events[K]>) => {\n this.off(event, wrapped);\n (listener as (...a: Parameters<Events[K]>) => void)(...args);\n }) as Events[K];\n return this.on(event, wrapped);\n }\n\n off<K extends keyof Events>(event: K, listener: Events[K]): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n protected emit<K extends keyof Events>(event: K, ...args: Parameters<Events[K]>): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const listener of [...set]) {\n try {\n (listener as (...a: Parameters<Events[K]>) => void)(...args);\n } catch (error) {\n // A throwing listener must not break the others or the SDK.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n\n protected removeAllListeners(): void {\n this.listeners.clear();\n }\n}\n","import type { DialerMintErrorBody } from './types';\n\nexport type DialerErrorCode =\n /** The workspace or line has used its daily minute cap (HTTP 402 `dialer_cap_reached`). */\n | 'cap_reached'\n /** No dialer subscription on the workspace (403). */\n | 'subscription_required'\n /** Account is past due / paywalled (402 `account_paywalled`). */\n | 'account_paywalled'\n /** Your server is minting too fast for this key (429). */\n | 'rate_limited'\n /** The line id is unknown, not yours, inbound-only, or a shared/trial line. */\n | 'line_unavailable'\n /** Dialer not provisioned for this workspace yet (404 `dialer_not_provisioned`). */\n | 'not_provisioned'\n /** The token provider threw, returned garbage, or the mint failed for another reason. */\n | 'token_unavailable'\n /** The session was used before `start()` or after `destroy()`. */\n | 'invalid_state'\n /** The browser cannot provide a microphone. */\n | 'microphone_unavailable'\n /** Connection to the voice service failed. */\n | 'connection_failed'\n /** Anything else from the voice engine; see `cause`. */\n | 'call_failed';\n\nexport class DialerError extends Error {\n readonly code: DialerErrorCode;\n /** HTTP status of the mint response, when the error came from one. */\n readonly status: number | null;\n readonly cause?: unknown;\n\n constructor(code: DialerErrorCode, message: string, options: { status?: number; cause?: unknown } = {}) {\n super(message);\n this.name = 'DialerError';\n this.code = code;\n this.status = options.status ?? null;\n if (options.cause !== undefined) this.cause = options.cause;\n }\n}\n\nexport class DialerCapReachedError extends DialerError {\n readonly used: number | null;\n readonly included: number | null;\n readonly cap: number | null;\n /** When calling resumes (midnight UTC), if the server said. */\n readonly periodEnd: Date | null;\n\n constructor(body: Partial<DialerMintErrorBody>, status = 402) {\n const periodEnd = body.periodEnd ? new Date(body.periodEnd) : null;\n const validPeriodEnd = periodEnd && !Number.isNaN(periodEnd.getTime()) ? periodEnd : null;\n const usage = body.used != null && body.cap != null ? ` (${body.used} of ${body.cap} minutes used)` : '';\n const resumes = validPeriodEnd ? ` Calling resumes at ${validPeriodEnd.toISOString()}.` : '';\n super('cap_reached', `This line has reached its daily minute cap${usage}.${resumes}`, { status });\n this.name = 'DialerCapReachedError';\n this.used = body.used ?? null;\n this.included = body.included ?? null;\n this.cap = body.cap ?? null;\n this.periodEnd = validPeriodEnd;\n }\n}\n\nexport class DialerRateLimitedError extends DialerError {\n readonly retryAfterSeconds: number;\n constructor(body: Partial<DialerMintErrorBody>, status = 429) {\n const retryAfterSeconds = body.retryAfterSeconds ?? 60;\n super('rate_limited', `Token requests are rate limited; retry in ${retryAfterSeconds}s.`, { status });\n this.name = 'DialerRateLimitedError';\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\nconst CODE_BY_SERVER_CODE: Record<string, DialerErrorCode> = {\n dialer_cap_reached: 'cap_reached',\n dialer_subscription_required: 'subscription_required',\n account_paywalled: 'account_paywalled',\n rate_limited: 'rate_limited',\n invalid_line_id: 'line_unavailable',\n line_not_found: 'line_unavailable',\n line_inbound_only: 'line_unavailable',\n line_not_eligible: 'line_unavailable',\n dialer_not_provisioned: 'not_provisioned',\n};\n\nexport function isMintErrorBody(value: unknown): value is DialerMintErrorBody {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as { error?: unknown }).error === 'string' &&\n typeof (value as { token?: unknown }).token !== 'string'\n );\n}\n\n/**\n * Turn a non-2xx mint response into the matching typed error, or null when\n * `status` is a success. Use it in your `tokenProvider`:\n *\n * const res = await fetch('/my-server/dialer-token');\n * const body = await res.json();\n * const error = mintErrorFromResponse(res.status, body);\n * if (error) throw error;\n * return body;\n */\nexport function mintErrorFromResponse(status: number, body: unknown): DialerError | null {\n if (status >= 200 && status < 300) return null;\n const parsed: Partial<DialerMintErrorBody> = isMintErrorBody(body) ? body : {};\n const serverCode = parsed.code ?? '';\n if (serverCode === 'dialer_cap_reached' || status === 402 && parsed.error === 'DIALER_CAP_REACHED') {\n return new DialerCapReachedError(parsed, status);\n }\n if (serverCode === 'rate_limited' || status === 429) {\n return new DialerRateLimitedError(parsed, status);\n }\n const code = CODE_BY_SERVER_CODE[serverCode] ?? 'token_unavailable';\n const message = parsed.error ?? `Token request failed with HTTP ${status}`;\n return new DialerError(code, message, { status });\n}\n\nfunction messageOf(value: unknown): string | null {\n if (typeof value === 'string') return value || null;\n if (value && typeof value === 'object') {\n const message = (value as { message?: unknown }).message;\n if (typeof message === 'string' && message) return message;\n }\n return null;\n}\n\n/** Normalize anything thrown or returned by a token provider into a DialerError. */\nexport function toDialerError(value: unknown, fallbackCode: DialerErrorCode = 'token_unavailable'): DialerError {\n if (value instanceof DialerError) return value;\n if (isMintErrorBody(value)) {\n const inferredStatus = value.code === 'dialer_cap_reached' ? 402 : 400;\n const status = typeof value.status === 'number' && value.status >= 400 ? value.status : inferredStatus;\n return mintErrorFromResponse(status, value) as DialerError;\n }\n return new DialerError(fallbackCode, messageOf(value) ?? 'Unknown error', { cause: value });\n}\n\n// Voice engine error codes (they arrive as Error subclasses with a numeric\n// `code`, but the mapping tolerates plain objects too).\nconst MICROPHONE_ERROR_CODES = new Set([31208, 31401, 31402]);\nconst TRANSPORT_ERROR_MIN = 31000;\nconst TRANSPORT_ERROR_MAX = 31009;\nconst TOKEN_ERROR_CODES = new Set([20101, 20104]);\n\nexport function engineErrorCode(raw: unknown): number | undefined {\n const code = (raw as { code?: unknown } | null | undefined)?.code;\n return typeof code === 'number' ? code : undefined;\n}\n\nexport function isEngineTokenError(raw: unknown): boolean {\n const code = engineErrorCode(raw);\n return code !== undefined && TOKEN_ERROR_CODES.has(code);\n}\n\n/**\n * Map an error raised by the voice engine (from a call, a connect() attempt,\n * or the device itself) to a DialerError. `fallback` is the code for anything\n * that is neither a microphone nor a transport problem.\n */\nexport function engineErrorToDialerError(raw: unknown, fallback: DialerErrorCode = 'call_failed'): DialerError {\n if (raw instanceof DialerError) return raw;\n const code = engineErrorCode(raw);\n const message = messageOf(raw) ?? (fallback === 'call_failed' ? 'Call failed' : 'Connection failed');\n if (code !== undefined && MICROPHONE_ERROR_CODES.has(code)) {\n return new DialerError('microphone_unavailable', message, { cause: raw });\n }\n if (code !== undefined && code >= TRANSPORT_ERROR_MIN && code <= TRANSPORT_ERROR_MAX) {\n return new DialerError('connection_failed', message, { cause: raw });\n }\n return new DialerError(fallback, message, { cause: raw });\n}\n","import { TypedEmitter } from './emitter';\nimport type { EngineCall } from './engine';\nimport { engineErrorToDialerError } from './errors';\nimport type { DialerCallDirection, DialerCallEvents, DialerCallStatus } from './types';\n\nconst STATUS_MAP: Record<string, DialerCallStatus> = {\n pending: 'pending',\n connecting: 'connecting',\n ringing: 'ringing',\n open: 'open',\n reconnecting: 'reconnecting',\n closed: 'closed',\n};\n\n/**\n * One call. Outbound calls come from `dialer.call()`; inbound calls arrive via\n * the dialer's `incoming` event and must be `accept()`ed or `reject()`ed.\n */\nexport class DialerCall extends TypedEmitter<DialerCallEvents> {\n readonly direction: DialerCallDirection;\n /** Dialed number (outbound) or caller number (inbound), E.164 when known. */\n readonly remoteNumber: string | null;\n /** Inbound only: caller display name from your CRM, when the line has one. */\n readonly callerName: string | null;\n /** Inbound only: the name of the line being called. */\n readonly lineName: string | null;\n\n private engineCall: EngineCall;\n private ended = false;\n\n /** @internal */\n constructor(engineCall: EngineCall, direction: DialerCallDirection, remoteNumber: string | null) {\n super();\n this.engineCall = engineCall;\n this.direction = direction;\n const custom = engineCall.customParameters;\n this.callerName = custom?.get('callerName') ?? null;\n this.lineName = custom?.get('lineName') ?? null;\n this.remoteNumber = remoteNumber ?? custom?.get('caller') ?? engineCall.parameters?.From ?? null;\n this.attach();\n }\n\n private attach(): void {\n const call = this.engineCall;\n call.on('ringing', (hasEarlyMedia: boolean) => this.emit('ringing', { hasEarlyMedia: !!hasEarlyMedia }));\n call.on('accept', () => this.emit('accepted'));\n call.on('disconnect', () => this.finish('disconnected'));\n call.on('cancel', () => this.finish('cancelled'));\n call.on('reject', () => this.finish('rejected'));\n call.on('error', (raw: unknown) => this.emit('error', engineErrorToDialerError(raw)));\n call.on('reconnecting', (raw: unknown) => this.emit('reconnecting', engineErrorToDialerError(raw)));\n call.on('reconnected', () => this.emit('reconnected'));\n call.on('mute', (muted: boolean) => this.emit('mute', !!muted));\n call.on('warning', (name: string) => this.emit('warning', name));\n call.on('warning-cleared', (name: string) => this.emit('warningCleared', name));\n }\n\n private finish(event: 'disconnected' | 'cancelled' | 'rejected'): void {\n if (this.ended) return;\n this.ended = true;\n this.emit(event);\n }\n\n status(): DialerCallStatus {\n if (this.ended) return 'closed';\n return STATUS_MAP[this.engineCall.status()] ?? 'pending';\n }\n\n isActive(): boolean {\n const status = this.status();\n return status !== 'closed' && status !== 'pending';\n }\n\n /** Inbound only. */\n accept(): void {\n this.engineCall.accept();\n }\n\n /** Inbound only: decline without answering. */\n reject(): void {\n this.engineCall.reject();\n }\n\n hangup(): void {\n this.engineCall.disconnect();\n }\n\n mute(shouldMute = true): void {\n this.engineCall.mute(shouldMute);\n }\n\n isMuted(): boolean {\n return this.engineCall.isMuted();\n }\n\n /** DTMF tones, e.g. `'1'` or `'123#'`. */\n sendDigits(digits: string): void {\n this.engineCall.sendDigits(digits);\n }\n}\n","/**\n * The slice of the voice engine the SDK uses, expressed as plain interfaces so\n * the engine can be swapped in tests and never leaks into the public API.\n */\nexport interface EngineCall {\n on(event: string, listener: (...args: never[]) => void): unknown;\n off?(event: string, listener: (...args: never[]) => void): unknown;\n removeListener?(event: string, listener: (...args: never[]) => void): unknown;\n accept(): void;\n reject(): void;\n disconnect(): void;\n mute(shouldMute?: boolean): void;\n isMuted(): boolean;\n sendDigits(digits: string): void;\n status(): string;\n readonly parameters: Record<string, string>;\n readonly customParameters: Map<string, string>;\n}\n\nexport interface EngineDevice {\n on(event: string, listener: (...args: never[]) => void): unknown;\n connect(options: { params: Record<string, string> }): Promise<EngineCall>;\n register(): Promise<void>;\n unregister(): Promise<void>;\n updateToken(token: string): void;\n destroy(): void;\n readonly state: string;\n}\n\nexport interface EngineDeviceOptions {\n edge?: string | string[];\n tokenRefreshMs?: number;\n sounds?: Record<string, string>;\n disableAudioContextSounds?: boolean;\n allowIncomingWhileBusy?: boolean;\n logLevel?: number;\n closeProtection?: boolean;\n}\n\nexport interface Engine {\n createDevice(token: string, options: EngineDeviceOptions): EngineDevice;\n}\n\nlet enginePromise: Promise<Engine> | null = null;\n\n/**\n * Default engine: the voice SDK, loaded lazily on first use so importing\n * `@tryprojectblue/dialer` costs nothing until a session actually starts.\n */\nexport function defaultEngine(): Promise<Engine> {\n if (!enginePromise) {\n enginePromise = import('@twilio/voice-sdk').then(({ Device }) => ({\n createDevice(token, options) {\n return new Device(token, options as ConstructorParameters<typeof Device>[1]) as unknown as EngineDevice;\n },\n }));\n }\n return enginePromise;\n}\n","import { DialerCall } from './call';\nimport { TypedEmitter } from './emitter';\nimport { defaultEngine, type Engine, type EngineCall, type EngineDevice } from './engine';\nimport {\n DialerCapReachedError,\n DialerError,\n engineErrorToDialerError,\n isEngineTokenError,\n isMintErrorBody,\n toDialerError,\n} from './errors';\nimport type {\n DialerAllowance,\n DialerEvents,\n DialerLogger,\n DialerOptions,\n DialerTokenResponse,\n} from './types';\n\nconst DEFAULT_REFRESH_LEAD_SECONDS = 60;\nconst FALLBACK_TTL_SECONDS = 15 * 60;\nconst MIN_REFRESH_DELAY_MS = 5_000;\nconst REFRESH_RETRY_DELAYS_MS = [5_000, 15_000, 45_000];\nconst DEFAULT_MAX_CALLS_PER_TOKEN = 10;\n\ninterface ActiveToken {\n token: string;\n expiresAtMs: number;\n inboundEnabled: boolean;\n maxCallsPerToken: number;\n callsPlaced: number;\n}\n\ninterface InternalOptions extends DialerOptions {\n /** @internal test seam */\n engine?: Engine | Promise<Engine>;\n /** @internal test seam */\n now?: () => number;\n}\n\nconst quietLogger: DialerLogger = {\n debug: () => undefined,\n info: () => undefined,\n warn: (...args) => console.warn('[projectblue/dialer]', ...args),\n error: (...args) => console.error('[projectblue/dialer]', ...args),\n};\n\nfunction normalizeTokenResponse(value: unknown): DialerTokenResponse {\n if (typeof value === 'string' && value.length > 0) return { token: value };\n if (isMintErrorBody(value)) throw toDialerError(value);\n const body = value as Partial<DialerTokenResponse> | null | undefined;\n if (!body || typeof body.token !== 'string' || body.token.length === 0) {\n throw new DialerError('token_unavailable', 'tokenProvider did not return a token');\n }\n return body as DialerTokenResponse;\n}\n\n/**\n * A calling session for one Project Blue line.\n *\n * const dialer = new ProjectBlueDialer({ tokenProvider });\n * await dialer.start();\n * const call = await dialer.call('+15551234567');\n * call.on('disconnected', () => ...);\n *\n * The session never sees your workspace API key: `tokenProvider` asks YOUR\n * server, which calls `POST /api/v1/dialer/token` and returns the body.\n */\nexport class ProjectBlueDialer extends TypedEmitter<DialerEvents> {\n private readonly options: InternalOptions;\n private readonly log: DialerLogger;\n private readonly now: () => number;\n private device: EngineDevice | null = null;\n private active: ActiveToken | null = null;\n private latestAllowance: DialerAllowance | null = null;\n private currentCall: DialerCall | null = null;\n private refreshTimer: ReturnType<typeof setTimeout> | null = null;\n private refreshInFlight: Promise<void> | null = null;\n private refreshFailures = 0;\n private reregisterWhenCallEnds = false;\n private destroyed = false;\n private started = false;\n\n constructor(options: DialerOptions) {\n super();\n if (typeof options?.tokenProvider !== 'function') {\n throw new DialerError('invalid_state', 'ProjectBlueDialer requires a tokenProvider');\n }\n this.options = options as InternalOptions;\n this.log = options.logger === null ? { ...quietLogger, warn: () => undefined, error: () => undefined } : options.logger ?? quietLogger;\n this.now = this.options.now ?? (() => Date.now());\n }\n\n /** Latest allowance the server reported with a token; null before `start()`. */\n get allowance(): DialerAllowance | null {\n return this.latestAllowance;\n }\n\n /** Whether the current token lets this session receive calls. */\n get inboundEnabled(): boolean {\n return this.active?.inboundEnabled ?? false;\n }\n\n get activeCall(): DialerCall | null {\n return this.currentCall?.isActive() ? this.currentCall : null;\n }\n\n isReady(): boolean {\n return this.started && !this.destroyed && !!this.device && !!this.active;\n }\n\n /** Fetch the first token and connect. Resolves once calls can be placed. */\n async start(): Promise<void> {\n this.assertNotDestroyed();\n if (this.started) return;\n const response = await this.fetchToken();\n const engine = await (this.options.engine ?? defaultEngine());\n if (this.destroyed) return;\n const device = engine.createDevice(response.token, {\n edge: this.options.edge,\n // The engine's own early-expiry event is a second trigger for refresh;\n // our timer below is the first.\n tokenRefreshMs: this.refreshLeadMs(),\n allowIncomingWhileBusy: false,\n closeProtection: false,\n ...(this.options.playIncomingRingtone === false ? { disableAudioContextSounds: true, sounds: {} } : {}),\n });\n this.device = device;\n this.attachDeviceListeners(device);\n this.started = true;\n this.applyToken(response);\n await this.syncRegistration();\n this.emit('ready', { inboundEnabled: this.inboundEnabled });\n }\n\n /**\n * Place an outbound call from the line this session is scoped to. `to` must\n * be E.164 (`+15551234567`). Rejects with a `DialerError` (`cap_reached`,\n * `token_unavailable`, `microphone_unavailable`, …) when the call cannot start.\n */\n async call(to: string): Promise<DialerCall> {\n this.assertReady();\n // E.164 only, `+` required: guessing a country code turns a typo into a\n // call to another country.\n const destination = typeof to === 'string' ? to.replace(/[\\s()-]/g, '') : '';\n if (!/^\\+[1-9][0-9]{6,14}$/.test(destination)) {\n throw new DialerError('call_failed', 'call(to) requires a phone number in E.164 format, e.g. +15551234567');\n }\n if (this.activeCall) {\n throw new DialerError('invalid_state', 'A call is already in progress');\n }\n // A token good for N calls is refreshed BEFORE the (N+1)th, so the server's\n // per-token limit is never hit in the normal path.\n const token = this.active!;\n if (token.callsPlaced >= token.maxCallsPerToken || this.expiresWithin(this.refreshLeadMs())) {\n await this.refreshToken();\n }\n const params: Record<string, string> = { To: destination };\n let engineCall: EngineCall;\n try {\n engineCall = await this.device!.connect({ params });\n } catch (error) {\n // Mic denied / no device → microphone_unavailable; signaling → connection_failed.\n throw engineErrorToDialerError(error, 'call_failed');\n }\n this.active!.callsPlaced += 1;\n const call = new DialerCall(engineCall, 'outbound', params.To ?? null);\n this.trackCall(call);\n return call;\n }\n\n /** Force a token refresh now. Usually unnecessary — the session refreshes itself. */\n async refreshToken(): Promise<void> {\n this.assertNotDestroyed();\n if (this.refreshInFlight) return this.refreshInFlight;\n this.refreshInFlight = this.runRefresh().finally(() => {\n this.refreshInFlight = null;\n });\n return this.refreshInFlight;\n }\n\n /** Hang up any call, stop refreshing, and release the microphone. Idempotent. */\n async destroy(): Promise<void> {\n if (this.destroyed) return;\n this.destroyed = true;\n this.clearRefreshTimer();\n try {\n this.currentCall?.hangup();\n } catch {\n // Best effort.\n }\n const device = this.device;\n this.device = null;\n if (device) {\n try {\n if (this.active?.inboundEnabled) await device.unregister().catch(() => undefined);\n device.destroy();\n } catch (error) {\n this.log.warn('destroy: engine teardown failed', error);\n }\n }\n this.active = null;\n this.emit('destroyed');\n this.removeAllListeners();\n }\n\n // --- internals -----------------------------------------------------------\n\n private refreshLeadMs(): number {\n const seconds = this.options.refreshLeadSeconds ?? DEFAULT_REFRESH_LEAD_SECONDS;\n return Math.max(5, seconds) * 1000;\n }\n\n private assertNotDestroyed(): void {\n if (this.destroyed) throw new DialerError('invalid_state', 'This dialer session has been destroyed');\n }\n\n private assertReady(): void {\n this.assertNotDestroyed();\n if (!this.isReady()) throw new DialerError('invalid_state', 'Call start() before placing calls');\n }\n\n private expiresWithin(windowMs: number): boolean {\n if (!this.active) return true;\n return this.active.expiresAtMs - this.now() <= windowMs;\n }\n\n private async fetchToken(): Promise<DialerTokenResponse> {\n let raw: unknown;\n try {\n raw = await this.options.tokenProvider();\n } catch (error) {\n throw toDialerError(error);\n }\n return normalizeTokenResponse(raw);\n }\n\n private applyToken(response: DialerTokenResponse): void {\n const parsedExpiry = response.expiresAt ? new Date(response.expiresAt).getTime() : NaN;\n const ttlMs = (response.ttlSeconds ?? FALLBACK_TTL_SECONDS) * 1000;\n const expiresAtMs = Number.isFinite(parsedExpiry) ? parsedExpiry : this.now() + ttlMs;\n this.active = {\n token: response.token,\n expiresAtMs,\n inboundEnabled: !!response.inboundEnabled,\n maxCallsPerToken: response.maxCallsPerToken && response.maxCallsPerToken > 0 ? response.maxCallsPerToken : DEFAULT_MAX_CALLS_PER_TOKEN,\n callsPlaced: 0,\n };\n this.refreshFailures = 0;\n if (response.allowance) {\n this.latestAllowance = response.allowance;\n this.emit('allowance', response.allowance);\n }\n this.scheduleRefresh(Math.max(MIN_REFRESH_DELAY_MS, expiresAtMs - this.now() - this.refreshLeadMs()));\n }\n\n private scheduleRefresh(delayMs: number): void {\n this.clearRefreshTimer();\n if (this.destroyed) return;\n this.refreshTimer = setTimeout(() => {\n this.refreshTimer = null;\n void this.refreshToken().catch(() => undefined);\n }, delayMs);\n }\n\n private clearRefreshTimer(): void {\n if (this.refreshTimer !== null) {\n clearTimeout(this.refreshTimer);\n this.refreshTimer = null;\n }\n }\n\n private async runRefresh(): Promise<void> {\n if (!this.device) return;\n try {\n const response = await this.fetchToken();\n if (this.destroyed || !this.device) return;\n this.device.updateToken(response.token);\n const wasInbound = this.active?.inboundEnabled ?? false;\n this.applyToken(response);\n // Every mint issues a new identity (fresh nonce) and registers THAT\n // identity as the line's ring leg. A registration made under the previous\n // identity would never be dialed again, so an inbound-enabled session\n // re-registers after each refresh; a session that just lost inbound\n // unregisters.\n if (this.active!.inboundEnabled) await this.reregisterUnderCurrentIdentity();\n else if (wasInbound) await this.syncRegistration();\n this.emit('ready', { inboundEnabled: this.inboundEnabled });\n } catch (error) {\n const dialerError = toDialerError(error);\n this.log.warn('token refresh failed', dialerError);\n if (dialerError instanceof DialerCapReachedError) {\n // Nothing to retry until the period rolls over. The current token keeps\n // any in-progress call alive; new calls fail at the mint, never mid-call.\n this.emit('capReached', dialerError);\n this.emit('tokenRefreshFailed', dialerError);\n const resumeInMs = dialerError.periodEnd ? dialerError.periodEnd.getTime() - this.now() : NaN;\n // Known period end: wake exactly then. Unknown: poll slowly (one token\n // lifetime) so the session heals on its own without hammering the mint.\n this.scheduleRefresh(\n Number.isFinite(resumeInMs) && resumeInMs > 0 ? resumeInMs + 1_000 : FALLBACK_TTL_SECONDS * 1000\n );\n throw dialerError;\n }\n this.emit('tokenRefreshFailed', dialerError);\n const delay = REFRESH_RETRY_DELAYS_MS[Math.min(this.refreshFailures, REFRESH_RETRY_DELAYS_MS.length - 1)] ?? 45_000;\n this.refreshFailures += 1;\n this.scheduleRefresh(delay);\n throw dialerError;\n }\n }\n\n /**\n * Drop the registration bound to the previous token's identity and register\n * again with the current one. Deferred while a call is up: unregistering\n * mid-call would tear down the signaling the call rides on.\n */\n private async reregisterUnderCurrentIdentity(): Promise<void> {\n const device = this.device;\n if (!device || !this.active?.inboundEnabled) return;\n if (this.activeCall) {\n this.reregisterWhenCallEnds = true;\n return;\n }\n this.reregisterWhenCallEnds = false;\n try {\n if (device.state === 'registered') await device.unregister();\n await device.register();\n } catch (error) {\n this.log.warn('re-registration after token refresh failed', error);\n this.emit('error', toDialerError(error, 'connection_failed'));\n }\n }\n\n private async syncRegistration(): Promise<void> {\n const device = this.device;\n if (!device || !this.active) return;\n try {\n if (this.active.inboundEnabled) {\n if (device.state !== 'registered') await device.register();\n } else if (device.state === 'registered') {\n await device.unregister();\n }\n } catch (error) {\n this.log.warn('inbound registration failed', error);\n this.emit('error', toDialerError(error, 'connection_failed'));\n }\n }\n\n private attachDeviceListeners(device: EngineDevice): void {\n device.on('tokenWillExpire', () => void this.refreshToken().catch(() => undefined));\n device.on('tokenExpired', () => void this.refreshToken().catch(() => undefined));\n device.on('incoming', (engineCall: EngineCall) => {\n const call = new DialerCall(engineCall, 'inbound', null);\n this.trackCall(call);\n this.emit('incoming', call);\n });\n device.on('unregistered', () => {\n // Dropped signaling; re-register on the next refresh cycle.\n if (this.active?.inboundEnabled && !this.destroyed) {\n setTimeout(() => void this.syncRegistration(), 2_000);\n }\n });\n device.on('error', (raw: unknown) => {\n if (isEngineTokenError(raw)) {\n // Invalid / expired token — refresh and carry on.\n void this.refreshToken().catch(() => undefined);\n return;\n }\n this.emit('error', engineErrorToDialerError(raw, 'connection_failed'));\n });\n }\n\n private trackCall(call: DialerCall): void {\n this.currentCall = call;\n const clear = () => {\n if (this.currentCall !== call) return;\n this.currentCall = null;\n if (this.reregisterWhenCallEnds && !this.destroyed) {\n void this.reregisterUnderCurrentIdentity();\n }\n };\n call.on('disconnected', clear);\n call.on('cancelled', clear);\n call.on('rejected', clear);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,eAAN,MAAqE;AAAA,EAArE;AACL,SAAQ,YAAY,oBAAI,IAA6C;AAAA;AAAA,EAErE,GAA2B,OAAU,UAAiC;AACpE,QAAI,MAAM,KAAK,UAAU,IAAI,KAAK;AAClC,QAAI,CAAC,KAAK;AACR,YAAM,oBAAI,IAAI;AACd,WAAK,UAAU,IAAI,OAAO,GAAG;AAAA,IAC/B;AACA,QAAI,IAAI,QAAQ;AAChB,WAAO,MAAM,KAAK,IAAI,OAAO,QAAQ;AAAA,EACvC;AAAA,EAEA,KAA6B,OAAU,UAAiC;AACtE,UAAM,WAAW,IAAI,SAA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ACnB,WAAK,KAAK,YAAY,IAAI;AAAA,IAC5B,CAAC;AACD,WAAO,GAAG,gBAAgB,MAAM;AAE9B,UAAI,KAAK,QAAQ,kBAAkB,CAAC,KAAK,WAAW;AAClD,mBAAW,MAAM,KAAK,KAAK,iBAAiB,GAAG,GAAK;AAAA,MACtD;AAAA,IACF,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAiB;AACnC,UAAI,mBAAmB,GAAG,GAAG;AAE3B,aAAK,KAAK,aAAa,EAAE,MAAM,MAAM,MAAS;AAC9C;AAAA,MACF;AACA,WAAK,KAAK,SAAS,yBAAyB,KAAK,mBAAmB,CAAC;AAAA,IACvE,CAAC;AAAA,EACH;AAAA,EAEQ,UAAU,MAAwB;AACxC,SAAK,cAAc;AACnB,UAAM,QAAQ,MAAM;AAClB,UAAI,KAAK,gBAAgB,KAAM;AAC/B,WAAK,cAAc;AACnB,UAAI,KAAK,0BAA0B,CAAC,KAAK,WAAW;AAClD,aAAK,KAAK,+BAA+B;AAAA,MAC3C;AAAA,IACF;AACA,SAAK,GAAG,gBAAgB,KAAK;AAC7B,SAAK,GAAG,aAAa,KAAK;AAC1B,SAAK,GAAG,YAAY,KAAK;AAAA,EAC3B;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/emitter.ts","../src/errors.ts","../src/call.ts","../src/engine.ts","../src/dialer.ts"],"sourcesContent":["export { ProjectBlueDialer } from './dialer';\nexport { DialerCall } from './call';\nexport {\n DialerError,\n DialerCapReachedError,\n DialerRateLimitedError,\n mintErrorFromResponse,\n type DialerErrorCode,\n} from './errors';\nexport type {\n DialerAllowance,\n DialerAllowanceState,\n DialerCallDirection,\n DialerCallEvents,\n DialerCallStatus,\n DialerEvents,\n DialerLogger,\n DialerMintErrorBody,\n DialerOptions,\n DialerTokenProvider,\n DialerTokenResponse,\n} from './types';\n","type Listener = (...args: never[]) => void;\n\n/** Minimal typed event emitter; avoids a runtime dependency in the browser bundle. */\nexport class TypedEmitter<Events extends { [K in keyof Events]: Listener }> {\n private listeners = new Map<keyof Events, Set<Events[keyof Events]>>();\n\n on<K extends keyof Events>(event: K, listener: Events[K]): () => void {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(listener);\n return () => this.off(event, listener);\n }\n\n once<K extends keyof Events>(event: K, listener: Events[K]): () => void {\n const wrapped = ((...args: Parameters<Events[K]>) => {\n this.off(event, wrapped);\n (listener as (...a: Parameters<Events[K]>) => void)(...args);\n }) as Events[K];\n return this.on(event, wrapped);\n }\n\n off<K extends keyof Events>(event: K, listener: Events[K]): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n protected emit<K extends keyof Events>(event: K, ...args: Parameters<Events[K]>): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const listener of [...set]) {\n try {\n (listener as (...a: Parameters<Events[K]>) => void)(...args);\n } catch (error) {\n // A throwing listener must not break the others or the SDK.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n\n protected removeAllListeners(): void {\n this.listeners.clear();\n }\n}\n","import type { DialerMintErrorBody } from './types';\n\nexport type DialerErrorCode =\n /** The workspace or line has used its daily minute cap (HTTP 402 `dialer_cap_reached`). */\n | 'cap_reached'\n /** No dialer subscription on the workspace (403). */\n | 'subscription_required'\n /** Account is past due / paywalled (402 `account_paywalled`). */\n | 'account_paywalled'\n /** Your server is minting too fast for this key (429). */\n | 'rate_limited'\n /** The line id is unknown, not yours, inbound-only, or a shared/trial line. */\n | 'line_unavailable'\n /** Dialer not provisioned for this workspace yet (404 `dialer_not_provisioned`). */\n | 'not_provisioned'\n /** The token provider threw, returned garbage, or the mint failed for another reason. */\n | 'token_unavailable'\n /** The session was used before `start()` or after `destroy()`. */\n | 'invalid_state'\n /** `start({ requireInbound: true })` received a token without inbound permission or registration failed; the session was destroyed. */\n | 'inbound_unavailable'\n /** The number is not in this token's `allowedDestinations`. */\n | 'destination_not_allowed'\n /** This token requires a call grant and `call()` received none. */\n | 'grant_required'\n /** The browser cannot provide a microphone. */\n | 'microphone_unavailable'\n /** Connection to the voice service failed. */\n | 'connection_failed'\n /** Anything else from the voice engine; see `cause`. */\n | 'call_failed';\n\nexport class DialerError extends Error {\n readonly code: DialerErrorCode;\n /** HTTP status of the mint response, when the error came from one. */\n readonly status: number | null;\n readonly cause?: unknown;\n\n constructor(code: DialerErrorCode, message: string, options: { status?: number; cause?: unknown } = {}) {\n super(message);\n this.name = 'DialerError';\n this.code = code;\n this.status = options.status ?? null;\n if (options.cause !== undefined) this.cause = options.cause;\n }\n}\n\nexport class DialerCapReachedError extends DialerError {\n readonly used: number | null;\n readonly included: number | null;\n readonly cap: number | null;\n /** When calling resumes (midnight UTC), if the server said. */\n readonly periodEnd: Date | null;\n\n constructor(body: Partial<DialerMintErrorBody>, status = 402) {\n const periodEnd = body.periodEnd ? new Date(body.periodEnd) : null;\n const validPeriodEnd = periodEnd && !Number.isNaN(periodEnd.getTime()) ? periodEnd : null;\n const usage = body.used != null && body.cap != null ? ` (${body.used} of ${body.cap} minutes used)` : '';\n const resumes = validPeriodEnd ? ` Calling resumes at ${validPeriodEnd.toISOString()}.` : '';\n super('cap_reached', `This line has reached its daily minute cap${usage}.${resumes}`, { status });\n this.name = 'DialerCapReachedError';\n this.used = body.used ?? null;\n this.included = body.included ?? null;\n this.cap = body.cap ?? null;\n this.periodEnd = validPeriodEnd;\n }\n}\n\nexport class DialerRateLimitedError extends DialerError {\n readonly retryAfterSeconds: number;\n constructor(body: Partial<DialerMintErrorBody>, status = 429) {\n const retryAfterSeconds = body.retryAfterSeconds ?? 60;\n super('rate_limited', `Token requests are rate limited; retry in ${retryAfterSeconds}s.`, { status });\n this.name = 'DialerRateLimitedError';\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\nconst CODE_BY_SERVER_CODE: Record<string, DialerErrorCode> = {\n dialer_cap_reached: 'cap_reached',\n dialer_subscription_required: 'subscription_required',\n account_paywalled: 'account_paywalled',\n rate_limited: 'rate_limited',\n invalid_line_id: 'line_unavailable',\n line_not_found: 'line_unavailable',\n line_inbound_only: 'line_unavailable',\n line_not_eligible: 'line_unavailable',\n dialer_not_provisioned: 'not_provisioned',\n};\n\nexport function isMintErrorBody(value: unknown): value is DialerMintErrorBody {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as { error?: unknown }).error === 'string' &&\n typeof (value as { token?: unknown }).token !== 'string'\n );\n}\n\n/**\n * Turn a non-2xx mint response into the matching typed error, or null when\n * `status` is a success. Use it in your `tokenProvider`:\n *\n * const res = await fetch('/my-server/dialer-token');\n * const body = await res.json();\n * const error = mintErrorFromResponse(res.status, body);\n * if (error) throw error;\n * return body;\n */\nexport function mintErrorFromResponse(status: number, body: unknown): DialerError | null {\n if (status >= 200 && status < 300) return null;\n const parsed: Partial<DialerMintErrorBody> = isMintErrorBody(body) ? body : {};\n const serverCode = parsed.code ?? '';\n if (serverCode === 'dialer_cap_reached' || status === 402 && parsed.error === 'DIALER_CAP_REACHED') {\n return new DialerCapReachedError(parsed, status);\n }\n if (serverCode === 'rate_limited' || status === 429) {\n return new DialerRateLimitedError(parsed, status);\n }\n const code = CODE_BY_SERVER_CODE[serverCode] ?? 'token_unavailable';\n const message = parsed.error ?? `Token request failed with HTTP ${status}`;\n return new DialerError(code, message, { status });\n}\n\nfunction messageOf(value: unknown): string | null {\n if (typeof value === 'string') return value || null;\n if (value && typeof value === 'object') {\n const message = (value as { message?: unknown }).message;\n if (typeof message === 'string' && message) return message;\n }\n return null;\n}\n\n/** Normalize anything thrown or returned by a token provider into a DialerError. */\nexport function toDialerError(value: unknown, fallbackCode: DialerErrorCode = 'token_unavailable'): DialerError {\n if (value instanceof DialerError) return value;\n if (isMintErrorBody(value)) {\n const inferredStatus = value.code === 'dialer_cap_reached' ? 402 : 400;\n const status = typeof value.status === 'number' && value.status >= 400 ? value.status : inferredStatus;\n return mintErrorFromResponse(status, value) as DialerError;\n }\n return new DialerError(fallbackCode, messageOf(value) ?? 'Unknown error', { cause: value });\n}\n\n// Voice engine error codes (they arrive as Error subclasses with a numeric\n// `code`, but the mapping tolerates plain objects too).\nconst MICROPHONE_ERROR_CODES = new Set([31208, 31401, 31402]);\nconst TRANSPORT_ERROR_MIN = 31000;\nconst TRANSPORT_ERROR_MAX = 31009;\nconst TOKEN_ERROR_CODES = new Set([20101, 20104]);\n\nexport function engineErrorCode(raw: unknown): number | undefined {\n const code = (raw as { code?: unknown } | null | undefined)?.code;\n return typeof code === 'number' ? code : undefined;\n}\n\nexport function isEngineTokenError(raw: unknown): boolean {\n const code = engineErrorCode(raw);\n return code !== undefined && TOKEN_ERROR_CODES.has(code);\n}\n\n/**\n * Map an error raised by the voice engine (from a call, a connect() attempt,\n * or the device itself) to a DialerError. `fallback` is the code for anything\n * that is neither a microphone nor a transport problem.\n */\nexport function engineErrorToDialerError(raw: unknown, fallback: DialerErrorCode = 'call_failed'): DialerError {\n if (raw instanceof DialerError) return raw;\n const code = engineErrorCode(raw);\n const message = messageOf(raw) ?? (fallback === 'call_failed' ? 'Call failed' : 'Connection failed');\n if (code !== undefined && MICROPHONE_ERROR_CODES.has(code)) {\n return new DialerError('microphone_unavailable', message, { cause: raw });\n }\n if (code !== undefined && code >= TRANSPORT_ERROR_MIN && code <= TRANSPORT_ERROR_MAX) {\n return new DialerError('connection_failed', message, { cause: raw });\n }\n return new DialerError(fallback, message, { cause: raw });\n}\n","import { TypedEmitter } from './emitter';\nimport type { EngineCall } from './engine';\nimport { engineErrorToDialerError } from './errors';\nimport type { DialerCallDirection, DialerCallEvents, DialerCallStatus } from './types';\n\nconst STATUS_MAP: Record<string, DialerCallStatus> = {\n pending: 'pending',\n connecting: 'connecting',\n ringing: 'ringing',\n open: 'open',\n reconnecting: 'reconnecting',\n closed: 'closed',\n};\n\n/**\n * One call. Outbound calls come from `dialer.call()`; inbound calls arrive via\n * the dialer's `incoming` event and must be `accept()`ed or `reject()`ed.\n */\nexport class DialerCall extends TypedEmitter<DialerCallEvents> {\n readonly direction: DialerCallDirection;\n /** Dialed number (outbound) or caller number (inbound), E.164 when known. */\n readonly remoteNumber: string | null;\n /** Inbound only: caller display name from your CRM, when the line has one. */\n readonly callerName: string | null;\n /** Inbound only: the name of the line being called. */\n readonly lineName: string | null;\n\n private engineCall: EngineCall;\n private ended = false;\n\n /** @internal */\n constructor(engineCall: EngineCall, direction: DialerCallDirection, remoteNumber: string | null) {\n super();\n this.engineCall = engineCall;\n this.direction = direction;\n const custom = engineCall.customParameters;\n this.callerName = custom?.get('callerName') ?? null;\n this.lineName = custom?.get('lineName') ?? null;\n this.remoteNumber = remoteNumber ?? custom?.get('caller') ?? engineCall.parameters?.From ?? null;\n this.attach();\n }\n\n private attach(): void {\n const call = this.engineCall;\n call.on('ringing', (hasEarlyMedia: boolean) => this.emit('ringing', { hasEarlyMedia: !!hasEarlyMedia }));\n call.on('accept', () => this.emit('accepted'));\n call.on('disconnect', () => this.finish('disconnected'));\n call.on('cancel', () => this.finish('cancelled'));\n call.on('reject', () => this.finish('rejected'));\n call.on('error', (raw: unknown) => this.emit('error', engineErrorToDialerError(raw)));\n call.on('reconnecting', (raw: unknown) => this.emit('reconnecting', engineErrorToDialerError(raw)));\n call.on('reconnected', () => this.emit('reconnected'));\n call.on('mute', (muted: boolean) => this.emit('mute', !!muted));\n call.on('warning', (name: string) => this.emit('warning', name));\n call.on('warning-cleared', (name: string) => this.emit('warningCleared', name));\n }\n\n private finish(event: 'disconnected' | 'cancelled' | 'rejected'): void {\n if (this.ended) return;\n this.ended = true;\n this.emit(event);\n }\n\n status(): DialerCallStatus {\n if (this.ended) return 'closed';\n return STATUS_MAP[this.engineCall.status()] ?? 'pending';\n }\n\n isActive(): boolean {\n const status = this.status();\n return status !== 'closed' && status !== 'pending';\n }\n\n /** Inbound only. */\n accept(): void {\n this.engineCall.accept();\n }\n\n /** Inbound only: decline without answering. */\n reject(): void {\n this.engineCall.reject();\n }\n\n hangup(): void {\n this.engineCall.disconnect();\n }\n\n mute(shouldMute = true): void {\n this.engineCall.mute(shouldMute);\n }\n\n isMuted(): boolean {\n return this.engineCall.isMuted();\n }\n\n /** DTMF tones, e.g. `'1'` or `'123#'`. */\n sendDigits(digits: string): void {\n this.engineCall.sendDigits(digits);\n }\n}\n","/**\n * The slice of the voice engine the SDK uses, expressed as plain interfaces so\n * the engine can be swapped in tests and never leaks into the public API.\n */\nexport interface EngineCall {\n on(event: string, listener: (...args: never[]) => void): unknown;\n off?(event: string, listener: (...args: never[]) => void): unknown;\n removeListener?(event: string, listener: (...args: never[]) => void): unknown;\n accept(): void;\n reject(): void;\n disconnect(): void;\n mute(shouldMute?: boolean): void;\n isMuted(): boolean;\n sendDigits(digits: string): void;\n status(): string;\n readonly parameters: Record<string, string>;\n readonly customParameters: Map<string, string>;\n}\n\nexport interface EngineDevice {\n on(event: string, listener: (...args: never[]) => void): unknown;\n connect(options: { params: Record<string, string> }): Promise<EngineCall>;\n register(): Promise<void>;\n unregister(): Promise<void>;\n updateToken(token: string): void;\n destroy(): void;\n readonly state: string;\n}\n\nexport interface EngineDeviceOptions {\n edge?: string | string[];\n tokenRefreshMs?: number;\n sounds?: Record<string, string>;\n disableAudioContextSounds?: boolean;\n allowIncomingWhileBusy?: boolean;\n logLevel?: number;\n closeProtection?: boolean;\n}\n\nexport interface Engine {\n createDevice(token: string, options: EngineDeviceOptions): EngineDevice;\n}\n\nlet enginePromise: Promise<Engine> | null = null;\n\n/**\n * Default engine: the voice SDK, loaded lazily on first use so importing\n * `@tryprojectblue/dialer` costs nothing until a session actually starts.\n */\nexport function defaultEngine(): Promise<Engine> {\n if (!enginePromise) {\n enginePromise = import('@twilio/voice-sdk').then(({ Device }) => ({\n createDevice(token, options) {\n return new Device(token, options as ConstructorParameters<typeof Device>[1]) as unknown as EngineDevice;\n },\n }));\n }\n return enginePromise;\n}\n","import { DialerCall } from './call';\nimport { TypedEmitter } from './emitter';\nimport { defaultEngine, type Engine, type EngineCall, type EngineDevice } from './engine';\nimport {\n DialerCapReachedError,\n DialerError,\n engineErrorToDialerError,\n isEngineTokenError,\n isMintErrorBody,\n toDialerError,\n} from './errors';\nimport type {\n DialerAllowance,\n DialerEvents,\n DialerLogger,\n DialerOptions,\n DialerTokenResponse,\n} from './types';\n\nconst DEFAULT_REFRESH_LEAD_SECONDS = 60;\nconst FALLBACK_TTL_SECONDS = 15 * 60;\nconst MIN_REFRESH_DELAY_MS = 5_000;\nconst REFRESH_RETRY_DELAYS_MS = [5_000, 15_000, 45_000];\nconst REGISTRATION_RETRY_DELAYS_MS = [5_000, 15_000, 45_000];\nconst UNREGISTERED_RETRY_DELAY_MS = 2_000;\nconst DEFAULT_MAX_CALLS_PER_TOKEN = 10;\n\ninterface ActiveToken {\n token: string;\n expiresAtMs: number;\n inboundEnabled: boolean;\n maxCallsPerToken: number;\n callsPlaced: number;\n allowedDestinations: string[] | null;\n callGrantRequired: boolean;\n}\n\ninterface InternalOptions extends DialerOptions {\n /** @internal test seam */\n engine?: Engine | Promise<Engine>;\n /** @internal test seam */\n now?: () => number;\n}\n\nconst quietLogger: DialerLogger = {\n debug: () => undefined,\n info: () => undefined,\n warn: (...args) => console.warn('[projectblue/dialer]', ...args),\n error: (...args) => console.error('[projectblue/dialer]', ...args),\n};\n\nfunction normalizeTokenResponse(value: unknown): DialerTokenResponse {\n if (typeof value === 'string' && value.length > 0) return { token: value };\n if (isMintErrorBody(value)) throw toDialerError(value);\n const body = value as Partial<DialerTokenResponse> | null | undefined;\n if (!body || typeof body.token !== 'string' || body.token.length === 0) {\n throw new DialerError('token_unavailable', 'tokenProvider did not return a token');\n }\n return body as DialerTokenResponse;\n}\n\n/**\n * A calling session for one Project Blue line.\n *\n * const dialer = new ProjectBlueDialer({ tokenProvider });\n * await dialer.start();\n * const call = await dialer.call('+15551234567');\n * call.on('disconnected', () => ...);\n *\n * The session never sees your workspace API key: `tokenProvider` asks YOUR\n * server, which calls `POST /api/v1/dialer/token` and returns the body.\n */\nexport class ProjectBlueDialer extends TypedEmitter<DialerEvents> {\n private readonly options: InternalOptions;\n private readonly log: DialerLogger;\n private readonly now: () => number;\n private device: EngineDevice | null = null;\n private active: ActiveToken | null = null;\n private latestAllowance: DialerAllowance | null = null;\n private currentCall: DialerCall | null = null;\n private refreshTimer: ReturnType<typeof setTimeout> | null = null;\n private registrationTimer: ReturnType<typeof setTimeout> | null = null;\n private registrationFailures = 0;\n private registrationInProgress = false;\n private refreshInFlight: Promise<void> | null = null;\n private refreshFailures = 0;\n private reregisterWhenCallEnds = false;\n private destroyed = false;\n private started = false;\n\n constructor(options: DialerOptions) {\n super();\n if (typeof options?.tokenProvider !== 'function') {\n throw new DialerError('invalid_state', 'ProjectBlueDialer requires a tokenProvider');\n }\n this.options = options as InternalOptions;\n this.log = options.logger === null ? { ...quietLogger, warn: () => undefined, error: () => undefined } : options.logger ?? quietLogger;\n this.now = this.options.now ?? (() => Date.now());\n }\n\n /** Latest allowance the server reported with a token; null before `start()`. */\n get allowance(): DialerAllowance | null {\n return this.latestAllowance;\n }\n\n /** Whether the current token lets this session receive calls. */\n get inboundEnabled(): boolean {\n return this.active?.inboundEnabled ?? false;\n }\n\n /** Whether the engine is currently registered to receive calls. */\n get registered(): boolean {\n return this.device?.state === 'registered';\n }\n\n get activeCall(): DialerCall | null {\n return this.currentCall?.isActive() ? this.currentCall : null;\n }\n\n isReady(): boolean {\n return this.started && !this.destroyed && !!this.device && !!this.active;\n }\n\n /** Fetch the first token and connect. Resolves once calls can be placed. */\n async start(options?: { requireInbound?: boolean }): Promise<void> {\n this.assertNotDestroyed();\n if (this.started) return;\n const response = await this.fetchToken();\n const engine = await (this.options.engine ?? defaultEngine());\n if (this.destroyed) return;\n const device = engine.createDevice(response.token, {\n edge: this.options.edge,\n // The engine's own early-expiry event is a second trigger for refresh;\n // our timer below is the first.\n tokenRefreshMs: this.refreshLeadMs(),\n allowIncomingWhileBusy: false,\n closeProtection: false,\n ...(this.options.playIncomingRingtone === false ? { disableAudioContextSounds: true, sounds: {} } : {}),\n });\n this.device = device;\n this.attachDeviceListeners(device);\n this.started = true;\n this.applyToken(response);\n const registrationSucceeded = await this.syncRegistration();\n if (!!options?.requireInbound && (!this.inboundEnabled || !registrationSucceeded || !this.registered)) {\n await this.destroy();\n throw new DialerError('inbound_unavailable', 'Inbound calling is unavailable for this session');\n }\n if (!this.destroyed) this.emit('ready', { inboundEnabled: this.inboundEnabled, registered: this.registered });\n }\n\n /**\n * Place an outbound call from the line this session is scoped to. `to` must\n * be E.164 (`+15551234567`). Rejects with a `DialerError` (`cap_reached`,\n * `token_unavailable`, `microphone_unavailable`, …) when the call cannot start.\n */\n async call(to: string, options?: { grant?: string }): Promise<DialerCall> {\n this.assertReady();\n // E.164 only, `+` required: guessing a country code turns a typo into a\n // call to another country.\n const destination = typeof to === 'string' ? to.replace(/[\\s()-]/g, '') : '';\n if (!/^\\+[1-9][0-9]{6,14}$/.test(destination)) {\n throw new DialerError('call_failed', 'call(to) requires a phone number in E.164 format, e.g. +15551234567');\n }\n if (this.activeCall) {\n throw new DialerError('invalid_state', 'A call is already in progress');\n }\n // A token good for N calls is refreshed BEFORE the (N+1)th, so the server's\n // per-token limit is never hit in the normal path.\n const token = this.active!;\n if (token.callsPlaced >= token.maxCallsPerToken || this.expiresWithin(this.refreshLeadMs())) {\n await this.refreshToken();\n }\n if (!!this.active!.allowedDestinations && !this.active!.allowedDestinations.includes(destination)) {\n throw new DialerError('destination_not_allowed', 'This number is not approved for this session.');\n }\n if (!!this.active!.callGrantRequired && !options?.grant) {\n throw new DialerError('grant_required', 'A call grant is required for this session.');\n }\n const params: Record<string, string> = { To: destination };\n if (!!options?.grant) params.PbCallGrant = options.grant;\n let engineCall: EngineCall;\n try {\n engineCall = await this.device!.connect({ params });\n } catch (error) {\n // Mic denied / no device → microphone_unavailable; signaling → connection_failed.\n throw engineErrorToDialerError(error, 'call_failed');\n }\n this.active!.callsPlaced += 1;\n const call = new DialerCall(engineCall, 'outbound', params.To ?? null);\n this.trackCall(call);\n return call;\n }\n\n /** Force a token refresh now. Usually unnecessary — the session refreshes itself. */\n async refreshToken(): Promise<void> {\n this.assertNotDestroyed();\n if (this.refreshInFlight) return this.refreshInFlight;\n this.refreshInFlight = this.runRefresh().finally(() => {\n this.refreshInFlight = null;\n });\n return this.refreshInFlight;\n }\n\n /** Hang up any call, stop refreshing, and release the microphone. Idempotent. */\n async destroy(): Promise<void> {\n if (this.destroyed) return;\n this.destroyed = true;\n this.clearRefreshTimer();\n this.clearRegistrationTimer();\n this.reregisterWhenCallEnds = false;\n try {\n this.currentCall?.hangup();\n } catch {\n // Best effort.\n }\n const device = this.device;\n this.device = null;\n if (device) {\n try {\n if (this.active?.inboundEnabled) await device.unregister().catch(() => undefined);\n device.destroy();\n } catch (error) {\n this.log.warn('destroy: engine teardown failed', error);\n }\n }\n this.active = null;\n this.emit('destroyed');\n this.removeAllListeners();\n }\n\n // --- internals -----------------------------------------------------------\n\n private refreshLeadMs(): number {\n const seconds = this.options.refreshLeadSeconds ?? DEFAULT_REFRESH_LEAD_SECONDS;\n return Math.max(5, seconds) * 1000;\n }\n\n private assertNotDestroyed(): void {\n if (this.destroyed) throw new DialerError('invalid_state', 'This dialer session has been destroyed');\n }\n\n private assertReady(): void {\n this.assertNotDestroyed();\n if (!this.isReady()) throw new DialerError('invalid_state', 'Call start() before placing calls');\n }\n\n private expiresWithin(windowMs: number): boolean {\n if (!this.active) return true;\n return this.active.expiresAtMs - this.now() <= windowMs;\n }\n\n private async fetchToken(): Promise<DialerTokenResponse> {\n let raw: unknown;\n try {\n raw = await this.options.tokenProvider();\n } catch (error) {\n throw toDialerError(error);\n }\n return normalizeTokenResponse(raw);\n }\n\n private applyToken(response: DialerTokenResponse): void {\n const parsedExpiry = response.expiresAt ? new Date(response.expiresAt).getTime() : NaN;\n const ttlMs = (response.ttlSeconds ?? FALLBACK_TTL_SECONDS) * 1000;\n const expiresAtMs = Number.isFinite(parsedExpiry) ? parsedExpiry : this.now() + ttlMs;\n this.active = {\n token: response.token,\n expiresAtMs,\n inboundEnabled: !!response.inboundEnabled,\n maxCallsPerToken: response.maxCallsPerToken && response.maxCallsPerToken > 0 ? response.maxCallsPerToken : DEFAULT_MAX_CALLS_PER_TOKEN,\n callsPlaced: 0,\n allowedDestinations: response.allowedDestinations ?? null,\n callGrantRequired: !!response.callGrantRequired,\n };\n this.clearRegistrationTimer();\n this.registrationFailures = 0;\n this.reregisterWhenCallEnds = false;\n this.refreshFailures = 0;\n if (response.allowance) {\n this.latestAllowance = response.allowance;\n this.emit('allowance', response.allowance);\n }\n this.scheduleRefresh(Math.max(MIN_REFRESH_DELAY_MS, expiresAtMs - this.now() - this.refreshLeadMs()));\n }\n\n private scheduleRefresh(delayMs: number): void {\n this.clearRefreshTimer();\n if (this.destroyed) return;\n this.refreshTimer = setTimeout(() => {\n this.refreshTimer = null;\n void this.refreshToken().catch(() => undefined);\n }, delayMs);\n }\n\n private clearRefreshTimer(): void {\n if (this.refreshTimer !== null) {\n clearTimeout(this.refreshTimer);\n this.refreshTimer = null;\n }\n }\n\n private async runRefresh(): Promise<void> {\n if (!this.device) return;\n try {\n const response = await this.fetchToken();\n if (this.destroyed || !this.device) return;\n this.device.updateToken(response.token);\n const wasInbound = this.active?.inboundEnabled ?? false;\n this.applyToken(response);\n // Every mint issues a new identity (fresh nonce) and registers THAT\n // identity as the line's ring leg. A registration made under the previous\n // identity would never be dialed again, so an inbound-enabled session\n // re-registers after each refresh; a session that just lost inbound\n // unregisters.\n if (this.active!.inboundEnabled) await this.reregisterUnderCurrentIdentity();\n else if (wasInbound) await this.syncRegistration();\n if (!this.destroyed) this.emit('ready', { inboundEnabled: this.inboundEnabled, registered: this.registered });\n } catch (error) {\n const dialerError = toDialerError(error);\n this.log.warn('token refresh failed', dialerError);\n if (dialerError instanceof DialerCapReachedError) {\n // Nothing to retry until the period rolls over. The current token keeps\n // any in-progress call alive; new calls fail at the mint, never mid-call.\n this.emit('capReached', dialerError);\n this.emit('tokenRefreshFailed', dialerError);\n const resumeInMs = dialerError.periodEnd ? dialerError.periodEnd.getTime() - this.now() : NaN;\n // Known period end: wake exactly then. Unknown: poll slowly (one token\n // lifetime) so the session heals on its own without hammering the mint.\n this.scheduleRefresh(\n Number.isFinite(resumeInMs) && resumeInMs > 0 ? resumeInMs + 1_000 : FALLBACK_TTL_SECONDS * 1000\n );\n throw dialerError;\n }\n this.emit('tokenRefreshFailed', dialerError);\n const delay = REFRESH_RETRY_DELAYS_MS[Math.min(this.refreshFailures, REFRESH_RETRY_DELAYS_MS.length - 1)] ?? 45_000;\n this.refreshFailures += 1;\n this.scheduleRefresh(delay);\n throw dialerError;\n }\n }\n\n /**\n * Drop the registration bound to the previous token's identity and register\n * again with the current one. Deferred while a call is up: unregistering\n * mid-call would tear down the signaling the call rides on.\n */\n private async reregisterUnderCurrentIdentity(): Promise<void> {\n const device = this.device;\n if (!device || !this.active?.inboundEnabled || this.destroyed) return;\n if (!!this.activeCall) {\n this.reregisterWhenCallEnds = true;\n return;\n }\n this.reregisterWhenCallEnds = false;\n this.registrationInProgress = true;\n try {\n if (device.state === 'registered') await device.unregister();\n await device.register();\n this.registrationSucceeded();\n } catch (error) {\n this.log.warn('re-registration after token refresh failed', error);\n this.registrationFailed(toDialerError(error, 'connection_failed'));\n } finally {\n this.registrationInProgress = false;\n }\n }\n\n private async syncRegistration(): Promise<boolean> {\n const device = this.device;\n if (!device || !this.active || this.destroyed) return false;\n this.registrationInProgress = true;\n try {\n if (this.active.inboundEnabled) {\n if (!!this.activeCall) {\n this.reregisterWhenCallEnds = true;\n return false;\n }\n if (device.state !== 'registered') await device.register();\n this.registrationSucceeded();\n } else if (device.state === 'registered') {\n await device.unregister();\n }\n return true;\n } catch (error) {\n this.log.warn('inbound registration failed', error);\n this.registrationFailed(toDialerError(error, 'connection_failed'));\n return false;\n } finally {\n this.registrationInProgress = false;\n }\n }\n\n private clearRegistrationTimer(): void {\n if (this.registrationTimer !== null) {\n clearTimeout(this.registrationTimer);\n this.registrationTimer = null;\n }\n }\n\n private registrationSucceeded(): void {\n this.clearRegistrationTimer();\n this.registrationFailures = 0;\n }\n\n private registrationFailed(dialerError: DialerError): void {\n if (this.destroyed) return;\n this.emit('registrationFailed', dialerError);\n this.emit('error', dialerError);\n const delay = REGISTRATION_RETRY_DELAYS_MS[this.registrationFailures];\n this.registrationFailures += 1;\n if (!!this.active?.inboundEnabled && delay !== undefined) this.scheduleRegistration(delay);\n }\n\n private scheduleRegistration(delayMs: number): void {\n this.clearRegistrationTimer();\n if (this.destroyed) return;\n this.registrationTimer = setTimeout(() => {\n this.registrationTimer = null;\n void this.reregisterUnderCurrentIdentity();\n }, delayMs);\n }\n\n private attachDeviceListeners(device: EngineDevice): void {\n device.on('tokenWillExpire', () => void this.refreshToken().catch(() => undefined));\n device.on('tokenExpired', () => void this.refreshToken().catch(() => undefined));\n device.on('incoming', (engineCall: EngineCall) => {\n const call = new DialerCall(engineCall, 'inbound', null);\n this.trackCall(call);\n this.emit('incoming', call);\n });\n device.on('registered', () => {\n this.registrationSucceeded();\n if (!this.destroyed) this.emit('registered');\n });\n device.on('unregistered', () => {\n if (this.destroyed) return;\n this.emit('unregistered');\n if (!!this.active?.inboundEnabled && !this.registrationInProgress && this.registrationFailures === 0) {\n this.scheduleRegistration(UNREGISTERED_RETRY_DELAY_MS);\n }\n });\n device.on('error', (raw: unknown) => {\n if (isEngineTokenError(raw)) {\n // Invalid / expired token — refresh and carry on.\n void this.refreshToken().catch(() => undefined);\n return;\n }\n this.emit('error', engineErrorToDialerError(raw, 'connection_failed'));\n });\n }\n\n private trackCall(call: DialerCall): void {\n this.currentCall = call;\n const clear = () => {\n if (this.currentCall !== call) return;\n this.currentCall = null;\n if (this.reregisterWhenCallEnds && !this.destroyed) {\n void this.reregisterUnderCurrentIdentity();\n }\n };\n call.on('disconnected', clear);\n call.on('cancelled', clear);\n call.on('rejected', clear);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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W,MAAK,KAAK,YAAY;AAAA,IAC7C,CAAC;AACD,WAAO,GAAG,gBAAgB,MAAM;AAC9B,UAAI,KAAK,UAAW;AACpB,WAAK,KAAK,cAAc;AACxB,UAAI,CAAC,CAAC,KAAK,QAAQ,kBAAkB,CAAC,KAAK,0BAA0B,KAAK,yBAAyB,GAAG;AACpG,aAAK,qBAAqB,2BAA2B;AAAA,MACvD;AAAA,IACF,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAiB;AACnC,UAAI,mBAAmB,GAAG,GAAG;AAE3B,aAAK,KAAK,aAAa,EAAE,MAAM,MAAM,MAAS;AAC9C;AAAA,MACF;AACA,WAAK,KAAK,SAAS,yBAAyB,KAAK,mBAAmB,CAAC;AAAA,IACvE,CAAC;AAAA,EACH;AAAA,EAEQ,UAAU,MAAwB;AACxC,SAAK,cAAc;AACnB,UAAM,QAAQ,MAAM;AAClB,UAAI,KAAK,gBAAgB,KAAM;AAC/B,WAAK,cAAc;AACnB,UAAI,KAAK,0BAA0B,CAAC,KAAK,WAAW;AAClD,aAAK,KAAK,+BAA+B;AAAA,MAC3C;AAAA,IACF;AACA,SAAK,GAAG,gBAAgB,KAAK;AAC7B,SAAK,GAAG,aAAa,KAAK;AAC1B,SAAK,GAAG,YAAY,KAAK;AAAA,EAC3B;AACF;","names":[]}
|
package/dist/index.d.cts
CHANGED
|
@@ -47,6 +47,12 @@ type DialerErrorCode =
|
|
|
47
47
|
| 'token_unavailable'
|
|
48
48
|
/** The session was used before `start()` or after `destroy()`. */
|
|
49
49
|
| 'invalid_state'
|
|
50
|
+
/** `start({ requireInbound: true })` received a token without inbound permission or registration failed; the session was destroyed. */
|
|
51
|
+
| 'inbound_unavailable'
|
|
52
|
+
/** The number is not in this token's `allowedDestinations`. */
|
|
53
|
+
| 'destination_not_allowed'
|
|
54
|
+
/** This token requires a call grant and `call()` received none. */
|
|
55
|
+
| 'grant_required'
|
|
50
56
|
/** The browser cannot provide a microphone. */
|
|
51
57
|
| 'microphone_unavailable'
|
|
52
58
|
/** Connection to the voice service failed. */
|
|
@@ -124,6 +130,9 @@ interface DialerTokenResponse {
|
|
|
124
130
|
lineId?: string;
|
|
125
131
|
inboundEnabled?: boolean;
|
|
126
132
|
maxCallsPerToken?: number;
|
|
133
|
+
/** E.164 numbers, or null for any destination. */
|
|
134
|
+
allowedDestinations?: string[] | null;
|
|
135
|
+
callGrantRequired?: boolean;
|
|
127
136
|
allowance?: DialerAllowance | null;
|
|
128
137
|
}
|
|
129
138
|
/**
|
|
@@ -215,7 +224,14 @@ interface DialerEvents {
|
|
|
215
224
|
/** Session is ready to place calls. Fires again after every successful token refresh. */
|
|
216
225
|
ready: (info: {
|
|
217
226
|
inboundEnabled: boolean;
|
|
227
|
+
registered: boolean;
|
|
218
228
|
}) => void;
|
|
229
|
+
/** The engine registered to receive inbound calls. */
|
|
230
|
+
registered: () => void;
|
|
231
|
+
/** The engine unregistered, including briefly during each token refresh. */
|
|
232
|
+
unregistered: () => void;
|
|
233
|
+
/** Inbound registration failed; the existing `error` event also fires. */
|
|
234
|
+
registrationFailed: (error: DialerError) => void;
|
|
219
235
|
/** A fresh allowance arrived with a token. Warn your users on `state: 'soft'`. */
|
|
220
236
|
allowance: (allowance: DialerAllowance) => void;
|
|
221
237
|
/** The workspace or line hit its cap: no further tokens until `periodEnd`. */
|
|
@@ -281,6 +297,9 @@ declare class ProjectBlueDialer extends TypedEmitter<DialerEvents> {
|
|
|
281
297
|
private latestAllowance;
|
|
282
298
|
private currentCall;
|
|
283
299
|
private refreshTimer;
|
|
300
|
+
private registrationTimer;
|
|
301
|
+
private registrationFailures;
|
|
302
|
+
private registrationInProgress;
|
|
284
303
|
private refreshInFlight;
|
|
285
304
|
private refreshFailures;
|
|
286
305
|
private reregisterWhenCallEnds;
|
|
@@ -291,16 +310,22 @@ declare class ProjectBlueDialer extends TypedEmitter<DialerEvents> {
|
|
|
291
310
|
get allowance(): DialerAllowance | null;
|
|
292
311
|
/** Whether the current token lets this session receive calls. */
|
|
293
312
|
get inboundEnabled(): boolean;
|
|
313
|
+
/** Whether the engine is currently registered to receive calls. */
|
|
314
|
+
get registered(): boolean;
|
|
294
315
|
get activeCall(): DialerCall | null;
|
|
295
316
|
isReady(): boolean;
|
|
296
317
|
/** Fetch the first token and connect. Resolves once calls can be placed. */
|
|
297
|
-
start(
|
|
318
|
+
start(options?: {
|
|
319
|
+
requireInbound?: boolean;
|
|
320
|
+
}): Promise<void>;
|
|
298
321
|
/**
|
|
299
322
|
* Place an outbound call from the line this session is scoped to. `to` must
|
|
300
323
|
* be E.164 (`+15551234567`). Rejects with a `DialerError` (`cap_reached`,
|
|
301
324
|
* `token_unavailable`, `microphone_unavailable`, …) when the call cannot start.
|
|
302
325
|
*/
|
|
303
|
-
call(to: string
|
|
326
|
+
call(to: string, options?: {
|
|
327
|
+
grant?: string;
|
|
328
|
+
}): Promise<DialerCall>;
|
|
304
329
|
/** Force a token refresh now. Usually unnecessary — the session refreshes itself. */
|
|
305
330
|
refreshToken(): Promise<void>;
|
|
306
331
|
/** Hang up any call, stop refreshing, and release the microphone. Idempotent. */
|
|
@@ -321,6 +346,10 @@ declare class ProjectBlueDialer extends TypedEmitter<DialerEvents> {
|
|
|
321
346
|
*/
|
|
322
347
|
private reregisterUnderCurrentIdentity;
|
|
323
348
|
private syncRegistration;
|
|
349
|
+
private clearRegistrationTimer;
|
|
350
|
+
private registrationSucceeded;
|
|
351
|
+
private registrationFailed;
|
|
352
|
+
private scheduleRegistration;
|
|
324
353
|
private attachDeviceListeners;
|
|
325
354
|
private trackCall;
|
|
326
355
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -47,6 +47,12 @@ type DialerErrorCode =
|
|
|
47
47
|
| 'token_unavailable'
|
|
48
48
|
/** The session was used before `start()` or after `destroy()`. */
|
|
49
49
|
| 'invalid_state'
|
|
50
|
+
/** `start({ requireInbound: true })` received a token without inbound permission or registration failed; the session was destroyed. */
|
|
51
|
+
| 'inbound_unavailable'
|
|
52
|
+
/** The number is not in this token's `allowedDestinations`. */
|
|
53
|
+
| 'destination_not_allowed'
|
|
54
|
+
/** This token requires a call grant and `call()` received none. */
|
|
55
|
+
| 'grant_required'
|
|
50
56
|
/** The browser cannot provide a microphone. */
|
|
51
57
|
| 'microphone_unavailable'
|
|
52
58
|
/** Connection to the voice service failed. */
|
|
@@ -124,6 +130,9 @@ interface DialerTokenResponse {
|
|
|
124
130
|
lineId?: string;
|
|
125
131
|
inboundEnabled?: boolean;
|
|
126
132
|
maxCallsPerToken?: number;
|
|
133
|
+
/** E.164 numbers, or null for any destination. */
|
|
134
|
+
allowedDestinations?: string[] | null;
|
|
135
|
+
callGrantRequired?: boolean;
|
|
127
136
|
allowance?: DialerAllowance | null;
|
|
128
137
|
}
|
|
129
138
|
/**
|
|
@@ -215,7 +224,14 @@ interface DialerEvents {
|
|
|
215
224
|
/** Session is ready to place calls. Fires again after every successful token refresh. */
|
|
216
225
|
ready: (info: {
|
|
217
226
|
inboundEnabled: boolean;
|
|
227
|
+
registered: boolean;
|
|
218
228
|
}) => void;
|
|
229
|
+
/** The engine registered to receive inbound calls. */
|
|
230
|
+
registered: () => void;
|
|
231
|
+
/** The engine unregistered, including briefly during each token refresh. */
|
|
232
|
+
unregistered: () => void;
|
|
233
|
+
/** Inbound registration failed; the existing `error` event also fires. */
|
|
234
|
+
registrationFailed: (error: DialerError) => void;
|
|
219
235
|
/** A fresh allowance arrived with a token. Warn your users on `state: 'soft'`. */
|
|
220
236
|
allowance: (allowance: DialerAllowance) => void;
|
|
221
237
|
/** The workspace or line hit its cap: no further tokens until `periodEnd`. */
|
|
@@ -281,6 +297,9 @@ declare class ProjectBlueDialer extends TypedEmitter<DialerEvents> {
|
|
|
281
297
|
private latestAllowance;
|
|
282
298
|
private currentCall;
|
|
283
299
|
private refreshTimer;
|
|
300
|
+
private registrationTimer;
|
|
301
|
+
private registrationFailures;
|
|
302
|
+
private registrationInProgress;
|
|
284
303
|
private refreshInFlight;
|
|
285
304
|
private refreshFailures;
|
|
286
305
|
private reregisterWhenCallEnds;
|
|
@@ -291,16 +310,22 @@ declare class ProjectBlueDialer extends TypedEmitter<DialerEvents> {
|
|
|
291
310
|
get allowance(): DialerAllowance | null;
|
|
292
311
|
/** Whether the current token lets this session receive calls. */
|
|
293
312
|
get inboundEnabled(): boolean;
|
|
313
|
+
/** Whether the engine is currently registered to receive calls. */
|
|
314
|
+
get registered(): boolean;
|
|
294
315
|
get activeCall(): DialerCall | null;
|
|
295
316
|
isReady(): boolean;
|
|
296
317
|
/** Fetch the first token and connect. Resolves once calls can be placed. */
|
|
297
|
-
start(
|
|
318
|
+
start(options?: {
|
|
319
|
+
requireInbound?: boolean;
|
|
320
|
+
}): Promise<void>;
|
|
298
321
|
/**
|
|
299
322
|
* Place an outbound call from the line this session is scoped to. `to` must
|
|
300
323
|
* be E.164 (`+15551234567`). Rejects with a `DialerError` (`cap_reached`,
|
|
301
324
|
* `token_unavailable`, `microphone_unavailable`, …) when the call cannot start.
|
|
302
325
|
*/
|
|
303
|
-
call(to: string
|
|
326
|
+
call(to: string, options?: {
|
|
327
|
+
grant?: string;
|
|
328
|
+
}): Promise<DialerCall>;
|
|
304
329
|
/** Force a token refresh now. Usually unnecessary — the session refreshes itself. */
|
|
305
330
|
refreshToken(): Promise<void>;
|
|
306
331
|
/** Hang up any call, stop refreshing, and release the microphone. Idempotent. */
|
|
@@ -321,6 +346,10 @@ declare class ProjectBlueDialer extends TypedEmitter<DialerEvents> {
|
|
|
321
346
|
*/
|
|
322
347
|
private reregisterUnderCurrentIdentity;
|
|
323
348
|
private syncRegistration;
|
|
349
|
+
private clearRegistrationTimer;
|
|
350
|
+
private registrationSucceeded;
|
|
351
|
+
private registrationFailed;
|
|
352
|
+
private scheduleRegistration;
|
|
324
353
|
private attachDeviceListeners;
|
|
325
354
|
private trackCall;
|
|
326
355
|
}
|
package/dist/index.js
CHANGED
|
@@ -232,6 +232,8 @@ var DEFAULT_REFRESH_LEAD_SECONDS = 60;
|
|
|
232
232
|
var FALLBACK_TTL_SECONDS = 15 * 60;
|
|
233
233
|
var MIN_REFRESH_DELAY_MS = 5e3;
|
|
234
234
|
var REFRESH_RETRY_DELAYS_MS = [5e3, 15e3, 45e3];
|
|
235
|
+
var REGISTRATION_RETRY_DELAYS_MS = [5e3, 15e3, 45e3];
|
|
236
|
+
var UNREGISTERED_RETRY_DELAY_MS = 2e3;
|
|
235
237
|
var DEFAULT_MAX_CALLS_PER_TOKEN = 10;
|
|
236
238
|
var quietLogger = {
|
|
237
239
|
debug: () => void 0,
|
|
@@ -256,6 +258,9 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
256
258
|
this.latestAllowance = null;
|
|
257
259
|
this.currentCall = null;
|
|
258
260
|
this.refreshTimer = null;
|
|
261
|
+
this.registrationTimer = null;
|
|
262
|
+
this.registrationFailures = 0;
|
|
263
|
+
this.registrationInProgress = false;
|
|
259
264
|
this.refreshInFlight = null;
|
|
260
265
|
this.refreshFailures = 0;
|
|
261
266
|
this.reregisterWhenCallEnds = false;
|
|
@@ -276,6 +281,10 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
276
281
|
get inboundEnabled() {
|
|
277
282
|
return this.active?.inboundEnabled ?? false;
|
|
278
283
|
}
|
|
284
|
+
/** Whether the engine is currently registered to receive calls. */
|
|
285
|
+
get registered() {
|
|
286
|
+
return this.device?.state === "registered";
|
|
287
|
+
}
|
|
279
288
|
get activeCall() {
|
|
280
289
|
return this.currentCall?.isActive() ? this.currentCall : null;
|
|
281
290
|
}
|
|
@@ -283,7 +292,7 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
283
292
|
return this.started && !this.destroyed && !!this.device && !!this.active;
|
|
284
293
|
}
|
|
285
294
|
/** Fetch the first token and connect. Resolves once calls can be placed. */
|
|
286
|
-
async start() {
|
|
295
|
+
async start(options) {
|
|
287
296
|
this.assertNotDestroyed();
|
|
288
297
|
if (this.started) return;
|
|
289
298
|
const response = await this.fetchToken();
|
|
@@ -302,15 +311,19 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
302
311
|
this.attachDeviceListeners(device);
|
|
303
312
|
this.started = true;
|
|
304
313
|
this.applyToken(response);
|
|
305
|
-
await this.syncRegistration();
|
|
306
|
-
|
|
314
|
+
const registrationSucceeded = await this.syncRegistration();
|
|
315
|
+
if (!!options?.requireInbound && (!this.inboundEnabled || !registrationSucceeded || !this.registered)) {
|
|
316
|
+
await this.destroy();
|
|
317
|
+
throw new DialerError("inbound_unavailable", "Inbound calling is unavailable for this session");
|
|
318
|
+
}
|
|
319
|
+
if (!this.destroyed) this.emit("ready", { inboundEnabled: this.inboundEnabled, registered: this.registered });
|
|
307
320
|
}
|
|
308
321
|
/**
|
|
309
322
|
* Place an outbound call from the line this session is scoped to. `to` must
|
|
310
323
|
* be E.164 (`+15551234567`). Rejects with a `DialerError` (`cap_reached`,
|
|
311
324
|
* `token_unavailable`, `microphone_unavailable`, …) when the call cannot start.
|
|
312
325
|
*/
|
|
313
|
-
async call(to) {
|
|
326
|
+
async call(to, options) {
|
|
314
327
|
this.assertReady();
|
|
315
328
|
const destination = typeof to === "string" ? to.replace(/[\s()-]/g, "") : "";
|
|
316
329
|
if (!/^\+[1-9][0-9]{6,14}$/.test(destination)) {
|
|
@@ -323,7 +336,14 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
323
336
|
if (token.callsPlaced >= token.maxCallsPerToken || this.expiresWithin(this.refreshLeadMs())) {
|
|
324
337
|
await this.refreshToken();
|
|
325
338
|
}
|
|
339
|
+
if (!!this.active.allowedDestinations && !this.active.allowedDestinations.includes(destination)) {
|
|
340
|
+
throw new DialerError("destination_not_allowed", "This number is not approved for this session.");
|
|
341
|
+
}
|
|
342
|
+
if (!!this.active.callGrantRequired && !options?.grant) {
|
|
343
|
+
throw new DialerError("grant_required", "A call grant is required for this session.");
|
|
344
|
+
}
|
|
326
345
|
const params = { To: destination };
|
|
346
|
+
if (!!options?.grant) params.PbCallGrant = options.grant;
|
|
327
347
|
let engineCall;
|
|
328
348
|
try {
|
|
329
349
|
engineCall = await this.device.connect({ params });
|
|
@@ -349,6 +369,8 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
349
369
|
if (this.destroyed) return;
|
|
350
370
|
this.destroyed = true;
|
|
351
371
|
this.clearRefreshTimer();
|
|
372
|
+
this.clearRegistrationTimer();
|
|
373
|
+
this.reregisterWhenCallEnds = false;
|
|
352
374
|
try {
|
|
353
375
|
this.currentCall?.hangup();
|
|
354
376
|
} catch {
|
|
@@ -401,8 +423,13 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
401
423
|
expiresAtMs,
|
|
402
424
|
inboundEnabled: !!response.inboundEnabled,
|
|
403
425
|
maxCallsPerToken: response.maxCallsPerToken && response.maxCallsPerToken > 0 ? response.maxCallsPerToken : DEFAULT_MAX_CALLS_PER_TOKEN,
|
|
404
|
-
callsPlaced: 0
|
|
426
|
+
callsPlaced: 0,
|
|
427
|
+
allowedDestinations: response.allowedDestinations ?? null,
|
|
428
|
+
callGrantRequired: !!response.callGrantRequired
|
|
405
429
|
};
|
|
430
|
+
this.clearRegistrationTimer();
|
|
431
|
+
this.registrationFailures = 0;
|
|
432
|
+
this.reregisterWhenCallEnds = false;
|
|
406
433
|
this.refreshFailures = 0;
|
|
407
434
|
if (response.allowance) {
|
|
408
435
|
this.latestAllowance = response.allowance;
|
|
@@ -434,7 +461,7 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
434
461
|
this.applyToken(response);
|
|
435
462
|
if (this.active.inboundEnabled) await this.reregisterUnderCurrentIdentity();
|
|
436
463
|
else if (wasInbound) await this.syncRegistration();
|
|
437
|
-
this.emit("ready", { inboundEnabled: this.inboundEnabled });
|
|
464
|
+
if (!this.destroyed) this.emit("ready", { inboundEnabled: this.inboundEnabled, registered: this.registered });
|
|
438
465
|
} catch (error) {
|
|
439
466
|
const dialerError = toDialerError(error);
|
|
440
467
|
this.log.warn("token refresh failed", dialerError);
|
|
@@ -461,34 +488,74 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
461
488
|
*/
|
|
462
489
|
async reregisterUnderCurrentIdentity() {
|
|
463
490
|
const device = this.device;
|
|
464
|
-
if (!device || !this.active?.inboundEnabled) return;
|
|
465
|
-
if (this.activeCall) {
|
|
491
|
+
if (!device || !this.active?.inboundEnabled || this.destroyed) return;
|
|
492
|
+
if (!!this.activeCall) {
|
|
466
493
|
this.reregisterWhenCallEnds = true;
|
|
467
494
|
return;
|
|
468
495
|
}
|
|
469
496
|
this.reregisterWhenCallEnds = false;
|
|
497
|
+
this.registrationInProgress = true;
|
|
470
498
|
try {
|
|
471
499
|
if (device.state === "registered") await device.unregister();
|
|
472
500
|
await device.register();
|
|
501
|
+
this.registrationSucceeded();
|
|
473
502
|
} catch (error) {
|
|
474
503
|
this.log.warn("re-registration after token refresh failed", error);
|
|
475
|
-
this.
|
|
504
|
+
this.registrationFailed(toDialerError(error, "connection_failed"));
|
|
505
|
+
} finally {
|
|
506
|
+
this.registrationInProgress = false;
|
|
476
507
|
}
|
|
477
508
|
}
|
|
478
509
|
async syncRegistration() {
|
|
479
510
|
const device = this.device;
|
|
480
|
-
if (!device || !this.active) return;
|
|
511
|
+
if (!device || !this.active || this.destroyed) return false;
|
|
512
|
+
this.registrationInProgress = true;
|
|
481
513
|
try {
|
|
482
514
|
if (this.active.inboundEnabled) {
|
|
515
|
+
if (!!this.activeCall) {
|
|
516
|
+
this.reregisterWhenCallEnds = true;
|
|
517
|
+
return false;
|
|
518
|
+
}
|
|
483
519
|
if (device.state !== "registered") await device.register();
|
|
520
|
+
this.registrationSucceeded();
|
|
484
521
|
} else if (device.state === "registered") {
|
|
485
522
|
await device.unregister();
|
|
486
523
|
}
|
|
524
|
+
return true;
|
|
487
525
|
} catch (error) {
|
|
488
526
|
this.log.warn("inbound registration failed", error);
|
|
489
|
-
this.
|
|
527
|
+
this.registrationFailed(toDialerError(error, "connection_failed"));
|
|
528
|
+
return false;
|
|
529
|
+
} finally {
|
|
530
|
+
this.registrationInProgress = false;
|
|
490
531
|
}
|
|
491
532
|
}
|
|
533
|
+
clearRegistrationTimer() {
|
|
534
|
+
if (this.registrationTimer !== null) {
|
|
535
|
+
clearTimeout(this.registrationTimer);
|
|
536
|
+
this.registrationTimer = null;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
registrationSucceeded() {
|
|
540
|
+
this.clearRegistrationTimer();
|
|
541
|
+
this.registrationFailures = 0;
|
|
542
|
+
}
|
|
543
|
+
registrationFailed(dialerError) {
|
|
544
|
+
if (this.destroyed) return;
|
|
545
|
+
this.emit("registrationFailed", dialerError);
|
|
546
|
+
this.emit("error", dialerError);
|
|
547
|
+
const delay = REGISTRATION_RETRY_DELAYS_MS[this.registrationFailures];
|
|
548
|
+
this.registrationFailures += 1;
|
|
549
|
+
if (!!this.active?.inboundEnabled && delay !== void 0) this.scheduleRegistration(delay);
|
|
550
|
+
}
|
|
551
|
+
scheduleRegistration(delayMs) {
|
|
552
|
+
this.clearRegistrationTimer();
|
|
553
|
+
if (this.destroyed) return;
|
|
554
|
+
this.registrationTimer = setTimeout(() => {
|
|
555
|
+
this.registrationTimer = null;
|
|
556
|
+
void this.reregisterUnderCurrentIdentity();
|
|
557
|
+
}, delayMs);
|
|
558
|
+
}
|
|
492
559
|
attachDeviceListeners(device) {
|
|
493
560
|
device.on("tokenWillExpire", () => void this.refreshToken().catch(() => void 0));
|
|
494
561
|
device.on("tokenExpired", () => void this.refreshToken().catch(() => void 0));
|
|
@@ -497,9 +564,15 @@ var ProjectBlueDialer = class extends TypedEmitter {
|
|
|
497
564
|
this.trackCall(call);
|
|
498
565
|
this.emit("incoming", call);
|
|
499
566
|
});
|
|
567
|
+
device.on("registered", () => {
|
|
568
|
+
this.registrationSucceeded();
|
|
569
|
+
if (!this.destroyed) this.emit("registered");
|
|
570
|
+
});
|
|
500
571
|
device.on("unregistered", () => {
|
|
501
|
-
if (this.
|
|
502
|
-
|
|
572
|
+
if (this.destroyed) return;
|
|
573
|
+
this.emit("unregistered");
|
|
574
|
+
if (!!this.active?.inboundEnabled && !this.registrationInProgress && this.registrationFailures === 0) {
|
|
575
|
+
this.scheduleRegistration(UNREGISTERED_RETRY_DELAY_MS);
|
|
503
576
|
}
|
|
504
577
|
});
|
|
505
578
|
device.on("error", (raw) => {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/emitter.ts","../src/errors.ts","../src/call.ts","../src/engine.ts","../src/dialer.ts"],"sourcesContent":["type Listener = (...args: never[]) => void;\n\n/** Minimal typed event emitter; avoids a runtime dependency in the browser bundle. */\nexport class TypedEmitter<Events extends { [K in keyof Events]: Listener }> {\n private listeners = new Map<keyof Events, Set<Events[keyof Events]>>();\n\n on<K extends keyof Events>(event: K, listener: Events[K]): () => void {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(listener);\n return () => this.off(event, listener);\n }\n\n once<K extends keyof Events>(event: K, listener: Events[K]): () => void {\n const wrapped = ((...args: Parameters<Events[K]>) => {\n this.off(event, wrapped);\n (listener as (...a: Parameters<Events[K]>) => void)(...args);\n }) as Events[K];\n return this.on(event, wrapped);\n }\n\n off<K extends keyof Events>(event: K, listener: Events[K]): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n protected emit<K extends keyof Events>(event: K, ...args: Parameters<Events[K]>): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const listener of [...set]) {\n try {\n (listener as (...a: Parameters<Events[K]>) => void)(...args);\n } catch (error) {\n // A throwing listener must not break the others or the SDK.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n\n protected removeAllListeners(): void {\n this.listeners.clear();\n }\n}\n","import type { DialerMintErrorBody } from './types';\n\nexport type DialerErrorCode =\n /** The workspace or line has used its daily minute cap (HTTP 402 `dialer_cap_reached`). */\n | 'cap_reached'\n /** No dialer subscription on the workspace (403). */\n | 'subscription_required'\n /** Account is past due / paywalled (402 `account_paywalled`). */\n | 'account_paywalled'\n /** Your server is minting too fast for this key (429). */\n | 'rate_limited'\n /** The line id is unknown, not yours, inbound-only, or a shared/trial line. */\n | 'line_unavailable'\n /** Dialer not provisioned for this workspace yet (404 `dialer_not_provisioned`). */\n | 'not_provisioned'\n /** The token provider threw, returned garbage, or the mint failed for another reason. */\n | 'token_unavailable'\n /** The session was used before `start()` or after `destroy()`. */\n | 'invalid_state'\n /** The browser cannot provide a microphone. */\n | 'microphone_unavailable'\n /** Connection to the voice service failed. */\n | 'connection_failed'\n /** Anything else from the voice engine; see `cause`. */\n | 'call_failed';\n\nexport class DialerError extends Error {\n readonly code: DialerErrorCode;\n /** HTTP status of the mint response, when the error came from one. */\n readonly status: number | null;\n readonly cause?: unknown;\n\n constructor(code: DialerErrorCode, message: string, options: { status?: number; cause?: unknown } = {}) {\n super(message);\n this.name = 'DialerError';\n this.code = code;\n this.status = options.status ?? null;\n if (options.cause !== undefined) this.cause = options.cause;\n }\n}\n\nexport class DialerCapReachedError extends DialerError {\n readonly used: number | null;\n readonly included: number | null;\n readonly cap: number | null;\n /** When calling resumes (midnight UTC), if the server said. */\n readonly periodEnd: Date | null;\n\n constructor(body: Partial<DialerMintErrorBody>, status = 402) {\n const periodEnd = body.periodEnd ? new Date(body.periodEnd) : null;\n const validPeriodEnd = periodEnd && !Number.isNaN(periodEnd.getTime()) ? periodEnd : null;\n const usage = body.used != null && body.cap != null ? ` (${body.used} of ${body.cap} minutes used)` : '';\n const resumes = validPeriodEnd ? ` Calling resumes at ${validPeriodEnd.toISOString()}.` : '';\n super('cap_reached', `This line has reached its daily minute cap${usage}.${resumes}`, { status });\n this.name = 'DialerCapReachedError';\n this.used = body.used ?? null;\n this.included = body.included ?? null;\n this.cap = body.cap ?? null;\n this.periodEnd = validPeriodEnd;\n }\n}\n\nexport class DialerRateLimitedError extends DialerError {\n readonly retryAfterSeconds: number;\n constructor(body: Partial<DialerMintErrorBody>, status = 429) {\n const retryAfterSeconds = body.retryAfterSeconds ?? 60;\n super('rate_limited', `Token requests are rate limited; retry in ${retryAfterSeconds}s.`, { status });\n this.name = 'DialerRateLimitedError';\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\nconst CODE_BY_SERVER_CODE: Record<string, DialerErrorCode> = {\n dialer_cap_reached: 'cap_reached',\n dialer_subscription_required: 'subscription_required',\n account_paywalled: 'account_paywalled',\n rate_limited: 'rate_limited',\n invalid_line_id: 'line_unavailable',\n line_not_found: 'line_unavailable',\n line_inbound_only: 'line_unavailable',\n line_not_eligible: 'line_unavailable',\n dialer_not_provisioned: 'not_provisioned',\n};\n\nexport function isMintErrorBody(value: unknown): value is DialerMintErrorBody {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as { error?: unknown }).error === 'string' &&\n typeof (value as { token?: unknown }).token !== 'string'\n );\n}\n\n/**\n * Turn a non-2xx mint response into the matching typed error, or null when\n * `status` is a success. Use it in your `tokenProvider`:\n *\n * const res = await fetch('/my-server/dialer-token');\n * const body = await res.json();\n * const error = mintErrorFromResponse(res.status, body);\n * if (error) throw error;\n * return body;\n */\nexport function mintErrorFromResponse(status: number, body: unknown): DialerError | null {\n if (status >= 200 && status < 300) return null;\n const parsed: Partial<DialerMintErrorBody> = isMintErrorBody(body) ? body : {};\n const serverCode = parsed.code ?? '';\n if (serverCode === 'dialer_cap_reached' || status === 402 && parsed.error === 'DIALER_CAP_REACHED') {\n return new DialerCapReachedError(parsed, status);\n }\n if (serverCode === 'rate_limited' || status === 429) {\n return new DialerRateLimitedError(parsed, status);\n }\n const code = CODE_BY_SERVER_CODE[serverCode] ?? 'token_unavailable';\n const message = parsed.error ?? `Token request failed with HTTP ${status}`;\n return new DialerError(code, message, { status });\n}\n\nfunction messageOf(value: unknown): string | null {\n if (typeof value === 'string') return value || null;\n if (value && typeof value === 'object') {\n const message = (value as { message?: unknown }).message;\n if (typeof message === 'string' && message) return message;\n }\n return null;\n}\n\n/** Normalize anything thrown or returned by a token provider into a DialerError. */\nexport function toDialerError(value: unknown, fallbackCode: DialerErrorCode = 'token_unavailable'): DialerError {\n if (value instanceof DialerError) return value;\n if (isMintErrorBody(value)) {\n const inferredStatus = value.code === 'dialer_cap_reached' ? 402 : 400;\n const status = typeof value.status === 'number' && value.status >= 400 ? value.status : inferredStatus;\n return mintErrorFromResponse(status, value) as DialerError;\n }\n return new DialerError(fallbackCode, messageOf(value) ?? 'Unknown error', { cause: value });\n}\n\n// Voice engine error codes (they arrive as Error subclasses with a numeric\n// `code`, but the mapping tolerates plain objects too).\nconst MICROPHONE_ERROR_CODES = new Set([31208, 31401, 31402]);\nconst TRANSPORT_ERROR_MIN = 31000;\nconst TRANSPORT_ERROR_MAX = 31009;\nconst TOKEN_ERROR_CODES = new Set([20101, 20104]);\n\nexport function engineErrorCode(raw: unknown): number | undefined {\n const code = (raw as { code?: unknown } | null | undefined)?.code;\n return typeof code === 'number' ? code : undefined;\n}\n\nexport function isEngineTokenError(raw: unknown): boolean {\n const code = engineErrorCode(raw);\n return code !== undefined && TOKEN_ERROR_CODES.has(code);\n}\n\n/**\n * Map an error raised by the voice engine (from a call, a connect() attempt,\n * or the device itself) to a DialerError. `fallback` is the code for anything\n * that is neither a microphone nor a transport problem.\n */\nexport function engineErrorToDialerError(raw: unknown, fallback: DialerErrorCode = 'call_failed'): DialerError {\n if (raw instanceof DialerError) return raw;\n const code = engineErrorCode(raw);\n const message = messageOf(raw) ?? (fallback === 'call_failed' ? 'Call failed' : 'Connection failed');\n if (code !== undefined && MICROPHONE_ERROR_CODES.has(code)) {\n return new DialerError('microphone_unavailable', message, { cause: raw });\n }\n if (code !== undefined && code >= TRANSPORT_ERROR_MIN && code <= TRANSPORT_ERROR_MAX) {\n return new DialerError('connection_failed', message, { cause: raw });\n }\n return new DialerError(fallback, message, { cause: raw });\n}\n","import { TypedEmitter } from './emitter';\nimport type { EngineCall } from './engine';\nimport { engineErrorToDialerError } from './errors';\nimport type { DialerCallDirection, DialerCallEvents, DialerCallStatus } from './types';\n\nconst STATUS_MAP: Record<string, DialerCallStatus> = {\n pending: 'pending',\n connecting: 'connecting',\n ringing: 'ringing',\n open: 'open',\n reconnecting: 'reconnecting',\n closed: 'closed',\n};\n\n/**\n * One call. Outbound calls come from `dialer.call()`; inbound calls arrive via\n * the dialer's `incoming` event and must be `accept()`ed or `reject()`ed.\n */\nexport class DialerCall extends TypedEmitter<DialerCallEvents> {\n readonly direction: DialerCallDirection;\n /** Dialed number (outbound) or caller number (inbound), E.164 when known. */\n readonly remoteNumber: string | null;\n /** Inbound only: caller display name from your CRM, when the line has one. */\n readonly callerName: string | null;\n /** Inbound only: the name of the line being called. */\n readonly lineName: string | null;\n\n private engineCall: EngineCall;\n private ended = false;\n\n /** @internal */\n constructor(engineCall: EngineCall, direction: DialerCallDirection, remoteNumber: string | null) {\n super();\n this.engineCall = engineCall;\n this.direction = direction;\n const custom = engineCall.customParameters;\n this.callerName = custom?.get('callerName') ?? null;\n this.lineName = custom?.get('lineName') ?? null;\n this.remoteNumber = remoteNumber ?? custom?.get('caller') ?? engineCall.parameters?.From ?? null;\n this.attach();\n }\n\n private attach(): void {\n const call = this.engineCall;\n call.on('ringing', (hasEarlyMedia: boolean) => this.emit('ringing', { hasEarlyMedia: !!hasEarlyMedia }));\n call.on('accept', () => this.emit('accepted'));\n call.on('disconnect', () => this.finish('disconnected'));\n call.on('cancel', () => this.finish('cancelled'));\n call.on('reject', () => this.finish('rejected'));\n call.on('error', (raw: unknown) => this.emit('error', engineErrorToDialerError(raw)));\n call.on('reconnecting', (raw: unknown) => this.emit('reconnecting', engineErrorToDialerError(raw)));\n call.on('reconnected', () => this.emit('reconnected'));\n call.on('mute', (muted: boolean) => this.emit('mute', !!muted));\n call.on('warning', (name: string) => this.emit('warning', name));\n call.on('warning-cleared', (name: string) => this.emit('warningCleared', name));\n }\n\n private finish(event: 'disconnected' | 'cancelled' | 'rejected'): void {\n if (this.ended) return;\n this.ended = true;\n this.emit(event);\n }\n\n status(): DialerCallStatus {\n if (this.ended) return 'closed';\n return STATUS_MAP[this.engineCall.status()] ?? 'pending';\n }\n\n isActive(): boolean {\n const status = this.status();\n return status !== 'closed' && status !== 'pending';\n }\n\n /** Inbound only. */\n accept(): void {\n this.engineCall.accept();\n }\n\n /** Inbound only: decline without answering. */\n reject(): void {\n this.engineCall.reject();\n }\n\n hangup(): void {\n this.engineCall.disconnect();\n }\n\n mute(shouldMute = true): void {\n this.engineCall.mute(shouldMute);\n }\n\n isMuted(): boolean {\n return this.engineCall.isMuted();\n }\n\n /** DTMF tones, e.g. `'1'` or `'123#'`. */\n sendDigits(digits: string): void {\n this.engineCall.sendDigits(digits);\n }\n}\n","/**\n * The slice of the voice engine the SDK uses, expressed as plain interfaces so\n * the engine can be swapped in tests and never leaks into the public API.\n */\nexport interface EngineCall {\n on(event: string, listener: (...args: never[]) => void): unknown;\n off?(event: string, listener: (...args: never[]) => void): unknown;\n removeListener?(event: string, listener: (...args: never[]) => void): unknown;\n accept(): void;\n reject(): void;\n disconnect(): void;\n mute(shouldMute?: boolean): void;\n isMuted(): boolean;\n sendDigits(digits: string): void;\n status(): string;\n readonly parameters: Record<string, string>;\n readonly customParameters: Map<string, string>;\n}\n\nexport interface EngineDevice {\n on(event: string, listener: (...args: never[]) => void): unknown;\n connect(options: { params: Record<string, string> }): Promise<EngineCall>;\n register(): Promise<void>;\n unregister(): Promise<void>;\n updateToken(token: string): void;\n destroy(): void;\n readonly state: string;\n}\n\nexport interface EngineDeviceOptions {\n edge?: string | string[];\n tokenRefreshMs?: number;\n sounds?: Record<string, string>;\n disableAudioContextSounds?: boolean;\n allowIncomingWhileBusy?: boolean;\n logLevel?: number;\n closeProtection?: boolean;\n}\n\nexport interface Engine {\n createDevice(token: string, options: EngineDeviceOptions): EngineDevice;\n}\n\nlet enginePromise: Promise<Engine> | null = null;\n\n/**\n * Default engine: the voice SDK, loaded lazily on first use so importing\n * `@tryprojectblue/dialer` costs nothing until a session actually starts.\n */\nexport function defaultEngine(): Promise<Engine> {\n if (!enginePromise) {\n enginePromise = import('@twilio/voice-sdk').then(({ Device }) => ({\n createDevice(token, options) {\n return new Device(token, options as ConstructorParameters<typeof Device>[1]) as unknown as EngineDevice;\n },\n }));\n }\n return enginePromise;\n}\n","import { DialerCall } from './call';\nimport { TypedEmitter } from './emitter';\nimport { defaultEngine, type Engine, type EngineCall, type EngineDevice } from './engine';\nimport {\n DialerCapReachedError,\n DialerError,\n engineErrorToDialerError,\n isEngineTokenError,\n isMintErrorBody,\n toDialerError,\n} from './errors';\nimport type {\n DialerAllowance,\n DialerEvents,\n DialerLogger,\n DialerOptions,\n DialerTokenResponse,\n} from './types';\n\nconst DEFAULT_REFRESH_LEAD_SECONDS = 60;\nconst FALLBACK_TTL_SECONDS = 15 * 60;\nconst MIN_REFRESH_DELAY_MS = 5_000;\nconst REFRESH_RETRY_DELAYS_MS = [5_000, 15_000, 45_000];\nconst DEFAULT_MAX_CALLS_PER_TOKEN = 10;\n\ninterface ActiveToken {\n token: string;\n expiresAtMs: number;\n inboundEnabled: boolean;\n maxCallsPerToken: number;\n callsPlaced: number;\n}\n\ninterface InternalOptions extends DialerOptions {\n /** @internal test seam */\n engine?: Engine | Promise<Engine>;\n /** @internal test seam */\n now?: () => number;\n}\n\nconst quietLogger: DialerLogger = {\n debug: () => undefined,\n info: () => undefined,\n warn: (...args) => console.warn('[projectblue/dialer]', ...args),\n error: (...args) => console.error('[projectblue/dialer]', ...args),\n};\n\nfunction normalizeTokenResponse(value: unknown): DialerTokenResponse {\n if (typeof value === 'string' && value.length > 0) return { token: value };\n if (isMintErrorBody(value)) throw toDialerError(value);\n const body = value as Partial<DialerTokenResponse> | null | undefined;\n if (!body || typeof body.token !== 'string' || body.token.length === 0) {\n throw new DialerError('token_unavailable', 'tokenProvider did not return a token');\n }\n return body as DialerTokenResponse;\n}\n\n/**\n * A calling session for one Project Blue line.\n *\n * const dialer = new ProjectBlueDialer({ tokenProvider });\n * await dialer.start();\n * const call = await dialer.call('+15551234567');\n * call.on('disconnected', () => ...);\n *\n * The session never sees your workspace API key: `tokenProvider` asks YOUR\n * server, which calls `POST /api/v1/dialer/token` and returns the body.\n */\nexport class ProjectBlueDialer extends TypedEmitter<DialerEvents> {\n private readonly options: InternalOptions;\n private readonly log: DialerLogger;\n private readonly now: () => number;\n private device: EngineDevice | null = null;\n private active: ActiveToken | null = null;\n private latestAllowance: DialerAllowance | null = null;\n private currentCall: DialerCall | null = null;\n private refreshTimer: ReturnType<typeof setTimeout> | null = null;\n private refreshInFlight: Promise<void> | null = null;\n private refreshFailures = 0;\n private reregisterWhenCallEnds = false;\n private destroyed = false;\n private started = false;\n\n constructor(options: DialerOptions) {\n super();\n if (typeof options?.tokenProvider !== 'function') {\n throw new DialerError('invalid_state', 'ProjectBlueDialer requires a tokenProvider');\n }\n this.options = options as InternalOptions;\n this.log = options.logger === null ? { ...quietLogger, warn: () => undefined, error: () => undefined } : options.logger ?? quietLogger;\n this.now = this.options.now ?? (() => Date.now());\n }\n\n /** Latest allowance the server reported with a token; null before `start()`. */\n get allowance(): DialerAllowance | null {\n return this.latestAllowance;\n }\n\n /** Whether the current token lets this session receive calls. */\n get inboundEnabled(): boolean {\n return this.active?.inboundEnabled ?? false;\n }\n\n get activeCall(): DialerCall | null {\n return this.currentCall?.isActive() ? this.currentCall : null;\n }\n\n isReady(): boolean {\n return this.started && !this.destroyed && !!this.device && !!this.active;\n }\n\n /** Fetch the first token and connect. Resolves once calls can be placed. */\n async start(): Promise<void> {\n this.assertNotDestroyed();\n if (this.started) return;\n const response = await this.fetchToken();\n const engine = await (this.options.engine ?? defaultEngine());\n if (this.destroyed) return;\n const device = engine.createDevice(response.token, {\n edge: this.options.edge,\n // The engine's own early-expiry event is a second trigger for refresh;\n // our timer below is the first.\n tokenRefreshMs: this.refreshLeadMs(),\n allowIncomingWhileBusy: false,\n closeProtection: false,\n ...(this.options.playIncomingRingtone === false ? { disableAudioContextSounds: true, sounds: {} } : {}),\n });\n this.device = device;\n this.attachDeviceListeners(device);\n this.started = true;\n this.applyToken(response);\n await this.syncRegistration();\n this.emit('ready', { inboundEnabled: this.inboundEnabled });\n }\n\n /**\n * Place an outbound call from the line this session is scoped to. `to` must\n * be E.164 (`+15551234567`). Rejects with a `DialerError` (`cap_reached`,\n * `token_unavailable`, `microphone_unavailable`, …) when the call cannot start.\n */\n async call(to: string): Promise<DialerCall> {\n this.assertReady();\n // E.164 only, `+` required: guessing a country code turns a typo into a\n // call to another country.\n const destination = typeof to === 'string' ? to.replace(/[\\s()-]/g, '') : '';\n if (!/^\\+[1-9][0-9]{6,14}$/.test(destination)) {\n throw new DialerError('call_failed', 'call(to) requires a phone number in E.164 format, e.g. +15551234567');\n }\n if (this.activeCall) {\n throw new DialerError('invalid_state', 'A call is already in progress');\n }\n // A token good for N calls is refreshed BEFORE the (N+1)th, so the server's\n // per-token limit is never hit in the normal path.\n const token = this.active!;\n if (token.callsPlaced >= token.maxCallsPerToken || this.expiresWithin(this.refreshLeadMs())) {\n await this.refreshToken();\n }\n const params: Record<string, string> = { To: destination };\n let engineCall: EngineCall;\n try {\n engineCall = await this.device!.connect({ params });\n } catch (error) {\n // Mic denied / no device → microphone_unavailable; signaling → connection_failed.\n throw engineErrorToDialerError(error, 'call_failed');\n }\n this.active!.callsPlaced += 1;\n const call = new DialerCall(engineCall, 'outbound', params.To ?? null);\n this.trackCall(call);\n return call;\n }\n\n /** Force a token refresh now. Usually unnecessary — the session refreshes itself. */\n async refreshToken(): Promise<void> {\n this.assertNotDestroyed();\n if (this.refreshInFlight) return this.refreshInFlight;\n this.refreshInFlight = this.runRefresh().finally(() => {\n this.refreshInFlight = null;\n });\n return this.refreshInFlight;\n }\n\n /** Hang up any call, stop refreshing, and release the microphone. Idempotent. */\n async destroy(): Promise<void> {\n if (this.destroyed) return;\n this.destroyed = true;\n this.clearRefreshTimer();\n try {\n this.currentCall?.hangup();\n } catch {\n // Best effort.\n }\n const device = this.device;\n this.device = null;\n if (device) {\n try {\n if (this.active?.inboundEnabled) await device.unregister().catch(() => undefined);\n device.destroy();\n } catch (error) {\n this.log.warn('destroy: engine teardown failed', error);\n }\n }\n this.active = null;\n this.emit('destroyed');\n this.removeAllListeners();\n }\n\n // --- internals -----------------------------------------------------------\n\n private refreshLeadMs(): number {\n const seconds = this.options.refreshLeadSeconds ?? DEFAULT_REFRESH_LEAD_SECONDS;\n return Math.max(5, seconds) * 1000;\n }\n\n private assertNotDestroyed(): void {\n if (this.destroyed) throw new DialerError('invalid_state', 'This dialer session has been destroyed');\n }\n\n private assertReady(): void {\n this.assertNotDestroyed();\n if (!this.isReady()) throw new DialerError('invalid_state', 'Call start() before placing calls');\n }\n\n private expiresWithin(windowMs: number): boolean {\n if (!this.active) return true;\n return this.active.expiresAtMs - this.now() <= windowMs;\n }\n\n private async fetchToken(): Promise<DialerTokenResponse> {\n let raw: unknown;\n try {\n raw = await this.options.tokenProvider();\n } catch (error) {\n throw toDialerError(error);\n }\n return normalizeTokenResponse(raw);\n }\n\n private applyToken(response: DialerTokenResponse): void {\n const parsedExpiry = response.expiresAt ? new Date(response.expiresAt).getTime() : NaN;\n const ttlMs = (response.ttlSeconds ?? FALLBACK_TTL_SECONDS) * 1000;\n const expiresAtMs = Number.isFinite(parsedExpiry) ? parsedExpiry : this.now() + ttlMs;\n this.active = {\n token: response.token,\n expiresAtMs,\n inboundEnabled: !!response.inboundEnabled,\n maxCallsPerToken: response.maxCallsPerToken && response.maxCallsPerToken > 0 ? response.maxCallsPerToken : DEFAULT_MAX_CALLS_PER_TOKEN,\n callsPlaced: 0,\n };\n this.refreshFailures = 0;\n if (response.allowance) {\n this.latestAllowance = response.allowance;\n this.emit('allowance', response.allowance);\n }\n this.scheduleRefresh(Math.max(MIN_REFRESH_DELAY_MS, expiresAtMs - this.now() - this.refreshLeadMs()));\n }\n\n private scheduleRefresh(delayMs: number): void {\n this.clearRefreshTimer();\n if (this.destroyed) return;\n this.refreshTimer = setTimeout(() => {\n this.refreshTimer = null;\n void this.refreshToken().catch(() => undefined);\n }, delayMs);\n }\n\n private clearRefreshTimer(): void {\n if (this.refreshTimer !== null) {\n clearTimeout(this.refreshTimer);\n this.refreshTimer = null;\n }\n }\n\n private async runRefresh(): Promise<void> {\n if (!this.device) return;\n try {\n const response = await this.fetchToken();\n if (this.destroyed || !this.device) return;\n this.device.updateToken(response.token);\n const wasInbound = this.active?.inboundEnabled ?? false;\n this.applyToken(response);\n // Every mint issues a new identity (fresh nonce) and registers THAT\n // identity as the line's ring leg. A registration made under the previous\n // identity would never be dialed again, so an inbound-enabled session\n // re-registers after each refresh; a session that just lost inbound\n // unregisters.\n if (this.active!.inboundEnabled) await this.reregisterUnderCurrentIdentity();\n else if (wasInbound) await this.syncRegistration();\n this.emit('ready', { inboundEnabled: this.inboundEnabled });\n } catch (error) {\n const dialerError = toDialerError(error);\n this.log.warn('token refresh failed', dialerError);\n if (dialerError instanceof DialerCapReachedError) {\n // Nothing to retry until the period rolls over. The current token keeps\n // any in-progress call alive; new calls fail at the mint, never mid-call.\n this.emit('capReached', dialerError);\n this.emit('tokenRefreshFailed', dialerError);\n const resumeInMs = dialerError.periodEnd ? dialerError.periodEnd.getTime() - this.now() : NaN;\n // Known period end: wake exactly then. Unknown: poll slowly (one token\n // lifetime) so the session heals on its own without hammering the mint.\n this.scheduleRefresh(\n Number.isFinite(resumeInMs) && resumeInMs > 0 ? resumeInMs + 1_000 : FALLBACK_TTL_SECONDS * 1000\n );\n throw dialerError;\n }\n this.emit('tokenRefreshFailed', dialerError);\n const delay = REFRESH_RETRY_DELAYS_MS[Math.min(this.refreshFailures, REFRESH_RETRY_DELAYS_MS.length - 1)] ?? 45_000;\n this.refreshFailures += 1;\n this.scheduleRefresh(delay);\n throw dialerError;\n }\n }\n\n /**\n * Drop the registration bound to the previous token's identity and register\n * again with the current one. Deferred while a call is up: unregistering\n * mid-call would tear down the signaling the call rides on.\n */\n private async reregisterUnderCurrentIdentity(): Promise<void> {\n const device = this.device;\n if (!device || !this.active?.inboundEnabled) return;\n if (this.activeCall) {\n this.reregisterWhenCallEnds = true;\n return;\n }\n this.reregisterWhenCallEnds = false;\n try {\n if (device.state === 'registered') await device.unregister();\n await device.register();\n } catch (error) {\n this.log.warn('re-registration after token refresh failed', error);\n this.emit('error', toDialerError(error, 'connection_failed'));\n }\n }\n\n private async syncRegistration(): Promise<void> {\n const device = this.device;\n if (!device || !this.active) return;\n try {\n if (this.active.inboundEnabled) {\n if (device.state !== 'registered') await device.register();\n } else if (device.state === 'registered') {\n await device.unregister();\n }\n } catch (error) {\n this.log.warn('inbound registration failed', error);\n this.emit('error', toDialerError(error, 'connection_failed'));\n }\n }\n\n private attachDeviceListeners(device: EngineDevice): void {\n device.on('tokenWillExpire', () => void this.refreshToken().catch(() => undefined));\n device.on('tokenExpired', () => void this.refreshToken().catch(() => undefined));\n device.on('incoming', (engineCall: EngineCall) => {\n const call = new DialerCall(engineCall, 'inbound', null);\n this.trackCall(call);\n this.emit('incoming', call);\n });\n device.on('unregistered', () => {\n // Dropped signaling; re-register on the next refresh cycle.\n if (this.active?.inboundEnabled && !this.destroyed) {\n setTimeout(() => void this.syncRegistration(), 2_000);\n }\n });\n device.on('error', (raw: unknown) => {\n if (isEngineTokenError(raw)) {\n // Invalid / expired token — refresh and carry on.\n void this.refreshToken().catch(() => undefined);\n return;\n }\n this.emit('error', engineErrorToDialerError(raw, 'connection_failed'));\n });\n }\n\n private trackCall(call: DialerCall): void {\n this.currentCall = call;\n const clear = () => {\n if (this.currentCall !== call) return;\n this.currentCall = null;\n if (this.reregisterWhenCallEnds && !this.destroyed) {\n void this.reregisterUnderCurrentIdentity();\n }\n };\n call.on('disconnected', clear);\n call.on('cancelled', clear);\n call.on('rejected', clear);\n }\n}\n"],"mappings":";AAGO,IAAM,eAAN,MAAqE;AAAA,EAArE;AACL,SAAQ,YAAY,oBAAI,IAA6C;AAAA;AAAA,EAErE,GAA2B,OAAU,UAAiC;AACpE,QAAI,MAAM,KAAK,UAAU,IAAI,KAAK;AAClC,QAAI,CAAC,KAAK;A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MAAM,MAAS,CAAC;AAClF,WAAO,GAAG,gBAAgB,MAAM,KAAK,KAAK,aAAa,EAAE,MAAM,MAAM,MAAS,CAAC;AAC/E,WAAO,GAAG,YAAY,CAAC,eAA2B;AAChD,YAAM,OAAO,IAAI,WAAW,YAAY,WAAW,IAAI;AACvD,WAAK,UAAU,IAAI;AACnB,WAAK,KAAK,YAAY,IAAI;AAAA,IAC5B,CAAC;AACD,WAAO,GAAG,gBAAgB,MAAM;AAE9B,UAAI,KAAK,QAAQ,kBAAkB,CAAC,KAAK,WAAW;AAClD,mBAAW,MAAM,KAAK,KAAK,iBAAiB,GAAG,GAAK;AAAA,MACtD;AAAA,IACF,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAiB;AACnC,UAAI,mBAAmB,GAAG,GAAG;AAE3B,aAAK,KAAK,aAAa,EAAE,MAAM,MAAM,MAAS;AAC9C;AAAA,MACF;AACA,WAAK,KAAK,SAAS,yBAAyB,KAAK,mBAAmB,CAAC;AAAA,IACvE,CAAC;AAAA,EACH;AAAA,EAEQ,UAAU,MAAwB;AACxC,SAAK,cAAc;AACnB,UAAM,QAAQ,MAAM;AAClB,UAAI,KAAK,gBAAgB,KAAM;AAC/B,WAAK,cAAc;AACnB,UAAI,KAAK,0BAA0B,CAAC,KAAK,WAAW;AAClD,aAAK,KAAK,+BAA+B;AAAA,MAC3C;AAAA,IACF;AACA,SAAK,GAAG,gBAAgB,KAAK;AAC7B,SAAK,GAAG,aAAa,KAAK;AAC1B,SAAK,GAAG,YAAY,KAAK;AAAA,EAC3B;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/emitter.ts","../src/errors.ts","../src/call.ts","../src/engine.ts","../src/dialer.ts"],"sourcesContent":["type Listener = (...args: never[]) => void;\n\n/** Minimal typed event emitter; avoids a runtime dependency in the browser bundle. */\nexport class TypedEmitter<Events extends { [K in keyof Events]: Listener }> {\n private listeners = new Map<keyof Events, Set<Events[keyof Events]>>();\n\n on<K extends keyof Events>(event: K, listener: Events[K]): () => void {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(listener);\n return () => this.off(event, listener);\n }\n\n once<K extends keyof Events>(event: K, listener: Events[K]): () => void {\n const wrapped = ((...args: Parameters<Events[K]>) => {\n this.off(event, wrapped);\n (listener as (...a: Parameters<Events[K]>) => void)(...args);\n }) as Events[K];\n return this.on(event, wrapped);\n }\n\n off<K extends keyof Events>(event: K, listener: Events[K]): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n protected emit<K extends keyof Events>(event: K, ...args: Parameters<Events[K]>): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const listener of [...set]) {\n try {\n (listener as (...a: Parameters<Events[K]>) => void)(...args);\n } catch (error) {\n // A throwing listener must not break the others or the SDK.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n\n protected removeAllListeners(): void {\n this.listeners.clear();\n }\n}\n","import type { DialerMintErrorBody } from './types';\n\nexport type DialerErrorCode =\n /** The workspace or line has used its daily minute cap (HTTP 402 `dialer_cap_reached`). */\n | 'cap_reached'\n /** No dialer subscription on the workspace (403). */\n | 'subscription_required'\n /** Account is past due / paywalled (402 `account_paywalled`). */\n | 'account_paywalled'\n /** Your server is minting too fast for this key (429). */\n | 'rate_limited'\n /** The line id is unknown, not yours, inbound-only, or a shared/trial line. */\n | 'line_unavailable'\n /** Dialer not provisioned for this workspace yet (404 `dialer_not_provisioned`). */\n | 'not_provisioned'\n /** The token provider threw, returned garbage, or the mint failed for another reason. */\n | 'token_unavailable'\n /** The session was used before `start()` or after `destroy()`. */\n | 'invalid_state'\n /** `start({ requireInbound: true })` received a token without inbound permission or registration failed; the session was destroyed. */\n | 'inbound_unavailable'\n /** The number is not in this token's `allowedDestinations`. */\n | 'destination_not_allowed'\n /** This token requires a call grant and `call()` received none. */\n | 'grant_required'\n /** The browser cannot provide a microphone. */\n | 'microphone_unavailable'\n /** Connection to the voice service failed. */\n | 'connection_failed'\n /** Anything else from the voice engine; see `cause`. */\n | 'call_failed';\n\nexport class DialerError extends Error {\n readonly code: DialerErrorCode;\n /** HTTP status of the mint response, when the error came from one. */\n readonly status: number | null;\n readonly cause?: unknown;\n\n constructor(code: DialerErrorCode, message: string, options: { status?: number; cause?: unknown } = {}) {\n super(message);\n this.name = 'DialerError';\n this.code = code;\n this.status = options.status ?? null;\n if (options.cause !== undefined) this.cause = options.cause;\n }\n}\n\nexport class DialerCapReachedError extends DialerError {\n readonly used: number | null;\n readonly included: number | null;\n readonly cap: number | null;\n /** When calling resumes (midnight UTC), if the server said. */\n readonly periodEnd: Date | null;\n\n constructor(body: Partial<DialerMintErrorBody>, status = 402) {\n const periodEnd = body.periodEnd ? new Date(body.periodEnd) : null;\n const validPeriodEnd = periodEnd && !Number.isNaN(periodEnd.getTime()) ? periodEnd : null;\n const usage = body.used != null && body.cap != null ? ` (${body.used} of ${body.cap} minutes used)` : '';\n const resumes = validPeriodEnd ? ` Calling resumes at ${validPeriodEnd.toISOString()}.` : '';\n super('cap_reached', `This line has reached its daily minute cap${usage}.${resumes}`, { status });\n this.name = 'DialerCapReachedError';\n this.used = body.used ?? null;\n this.included = body.included ?? null;\n this.cap = body.cap ?? null;\n this.periodEnd = validPeriodEnd;\n }\n}\n\nexport class DialerRateLimitedError extends DialerError {\n readonly retryAfterSeconds: number;\n constructor(body: Partial<DialerMintErrorBody>, status = 429) {\n const retryAfterSeconds = body.retryAfterSeconds ?? 60;\n super('rate_limited', `Token requests are rate limited; retry in ${retryAfterSeconds}s.`, { status });\n this.name = 'DialerRateLimitedError';\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\nconst CODE_BY_SERVER_CODE: Record<string, DialerErrorCode> = {\n dialer_cap_reached: 'cap_reached',\n dialer_subscription_required: 'subscription_required',\n account_paywalled: 'account_paywalled',\n rate_limited: 'rate_limited',\n invalid_line_id: 'line_unavailable',\n line_not_found: 'line_unavailable',\n line_inbound_only: 'line_unavailable',\n line_not_eligible: 'line_unavailable',\n dialer_not_provisioned: 'not_provisioned',\n};\n\nexport function isMintErrorBody(value: unknown): value is DialerMintErrorBody {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as { error?: unknown }).error === 'string' &&\n typeof (value as { token?: unknown }).token !== 'string'\n );\n}\n\n/**\n * Turn a non-2xx mint response into the matching typed error, or null when\n * `status` is a success. Use it in your `tokenProvider`:\n *\n * const res = await fetch('/my-server/dialer-token');\n * const body = await res.json();\n * const error = mintErrorFromResponse(res.status, body);\n * if (error) throw error;\n * return body;\n */\nexport function mintErrorFromResponse(status: number, body: unknown): DialerError | null {\n if (status >= 200 && status < 300) return null;\n const parsed: Partial<DialerMintErrorBody> = isMintErrorBody(body) ? body : {};\n const serverCode = parsed.code ?? '';\n if (serverCode === 'dialer_cap_reached' || status === 402 && parsed.error === 'DIALER_CAP_REACHED') {\n return new DialerCapReachedError(parsed, status);\n }\n if (serverCode === 'rate_limited' || status === 429) {\n return new DialerRateLimitedError(parsed, status);\n }\n const code = CODE_BY_SERVER_CODE[serverCode] ?? 'token_unavailable';\n const message = parsed.error ?? `Token request failed with HTTP ${status}`;\n return new DialerError(code, message, { status });\n}\n\nfunction messageOf(value: unknown): string | null {\n if (typeof value === 'string') return value || null;\n if (value && typeof value === 'object') {\n const message = (value as { message?: unknown }).message;\n if (typeof message === 'string' && message) return message;\n }\n return null;\n}\n\n/** Normalize anything thrown or returned by a token provider into a DialerError. */\nexport function toDialerError(value: unknown, fallbackCode: DialerErrorCode = 'token_unavailable'): DialerError {\n if (value instanceof DialerError) return value;\n if (isMintErrorBody(value)) {\n const inferredStatus = value.code === 'dialer_cap_reached' ? 402 : 400;\n const status = typeof value.status === 'number' && value.status >= 400 ? value.status : inferredStatus;\n return mintErrorFromResponse(status, value) as DialerError;\n }\n return new DialerError(fallbackCode, messageOf(value) ?? 'Unknown error', { cause: value });\n}\n\n// Voice engine error codes (they arrive as Error subclasses with a numeric\n// `code`, but the mapping tolerates plain objects too).\nconst MICROPHONE_ERROR_CODES = new Set([31208, 31401, 31402]);\nconst TRANSPORT_ERROR_MIN = 31000;\nconst TRANSPORT_ERROR_MAX = 31009;\nconst TOKEN_ERROR_CODES = new Set([20101, 20104]);\n\nexport function engineErrorCode(raw: unknown): number | undefined {\n const code = (raw as { code?: unknown } | null | undefined)?.code;\n return typeof code === 'number' ? code : undefined;\n}\n\nexport function isEngineTokenError(raw: unknown): boolean {\n const code = engineErrorCode(raw);\n return code !== undefined && TOKEN_ERROR_CODES.has(code);\n}\n\n/**\n * Map an error raised by the voice engine (from a call, a connect() attempt,\n * or the device itself) to a DialerError. `fallback` is the code for anything\n * that is neither a microphone nor a transport problem.\n */\nexport function engineErrorToDialerError(raw: unknown, fallback: DialerErrorCode = 'call_failed'): DialerError {\n if (raw instanceof DialerError) return raw;\n const code = engineErrorCode(raw);\n const message = messageOf(raw) ?? (fallback === 'call_failed' ? 'Call failed' : 'Connection failed');\n if (code !== undefined && MICROPHONE_ERROR_CODES.has(code)) {\n return new DialerError('microphone_unavailable', message, { cause: raw });\n }\n if (code !== undefined && code >= TRANSPORT_ERROR_MIN && code <= TRANSPORT_ERROR_MAX) {\n return new DialerError('connection_failed', message, { cause: raw });\n }\n return new DialerError(fallback, message, { cause: raw });\n}\n","import { TypedEmitter } from './emitter';\nimport type { EngineCall } from './engine';\nimport { engineErrorToDialerError } from './errors';\nimport type { DialerCallDirection, DialerCallEvents, DialerCallStatus } from './types';\n\nconst STATUS_MAP: Record<string, DialerCallStatus> = {\n pending: 'pending',\n connecting: 'connecting',\n ringing: 'ringing',\n open: 'open',\n reconnecting: 'reconnecting',\n closed: 'closed',\n};\n\n/**\n * One call. Outbound calls come from `dialer.call()`; inbound calls arrive via\n * the dialer's `incoming` event and must be `accept()`ed or `reject()`ed.\n */\nexport class DialerCall extends TypedEmitter<DialerCallEvents> {\n readonly direction: DialerCallDirection;\n /** Dialed number (outbound) or caller number (inbound), E.164 when known. */\n readonly remoteNumber: string | null;\n /** Inbound only: caller display name from your CRM, when the line has one. */\n readonly callerName: string | null;\n /** Inbound only: the name of the line being called. */\n readonly lineName: string | null;\n\n private engineCall: EngineCall;\n private ended = false;\n\n /** @internal */\n constructor(engineCall: EngineCall, direction: DialerCallDirection, remoteNumber: string | null) {\n super();\n this.engineCall = engineCall;\n this.direction = direction;\n const custom = engineCall.customParameters;\n this.callerName = custom?.get('callerName') ?? null;\n this.lineName = custom?.get('lineName') ?? null;\n this.remoteNumber = remoteNumber ?? custom?.get('caller') ?? engineCall.parameters?.From ?? null;\n this.attach();\n }\n\n private attach(): void {\n const call = this.engineCall;\n call.on('ringing', (hasEarlyMedia: boolean) => this.emit('ringing', { hasEarlyMedia: !!hasEarlyMedia }));\n call.on('accept', () => this.emit('accepted'));\n call.on('disconnect', () => this.finish('disconnected'));\n call.on('cancel', () => this.finish('cancelled'));\n call.on('reject', () => this.finish('rejected'));\n call.on('error', (raw: unknown) => this.emit('error', engineErrorToDialerError(raw)));\n call.on('reconnecting', (raw: unknown) => this.emit('reconnecting', engineErrorToDialerError(raw)));\n call.on('reconnected', () => this.emit('reconnected'));\n call.on('mute', (muted: boolean) => this.emit('mute', !!muted));\n call.on('warning', (name: string) => this.emit('warning', name));\n call.on('warning-cleared', (name: string) => this.emit('warningCleared', name));\n }\n\n private finish(event: 'disconnected' | 'cancelled' | 'rejected'): void {\n if (this.ended) return;\n this.ended = true;\n this.emit(event);\n }\n\n status(): DialerCallStatus {\n if (this.ended) return 'closed';\n return STATUS_MAP[this.engineCall.status()] ?? 'pending';\n }\n\n isActive(): boolean {\n const status = this.status();\n return status !== 'closed' && status !== 'pending';\n }\n\n /** Inbound only. */\n accept(): void {\n this.engineCall.accept();\n }\n\n /** Inbound only: decline without answering. */\n reject(): void {\n this.engineCall.reject();\n }\n\n hangup(): void {\n this.engineCall.disconnect();\n }\n\n mute(shouldMute = true): void {\n this.engineCall.mute(shouldMute);\n }\n\n isMuted(): boolean {\n return this.engineCall.isMuted();\n }\n\n /** DTMF tones, e.g. `'1'` or `'123#'`. */\n sendDigits(digits: string): void {\n this.engineCall.sendDigits(digits);\n }\n}\n","/**\n * The slice of the voice engine the SDK uses, expressed as plain interfaces so\n * the engine can be swapped in tests and never leaks into the public API.\n */\nexport interface EngineCall {\n on(event: string, listener: (...args: never[]) => void): unknown;\n off?(event: string, listener: (...args: never[]) => void): unknown;\n removeListener?(event: string, listener: (...args: never[]) => void): unknown;\n accept(): void;\n reject(): void;\n disconnect(): void;\n mute(shouldMute?: boolean): void;\n isMuted(): boolean;\n sendDigits(digits: string): void;\n status(): string;\n readonly parameters: Record<string, string>;\n readonly customParameters: Map<string, string>;\n}\n\nexport interface EngineDevice {\n on(event: string, listener: (...args: never[]) => void): unknown;\n connect(options: { params: Record<string, string> }): Promise<EngineCall>;\n register(): Promise<void>;\n unregister(): Promise<void>;\n updateToken(token: string): void;\n destroy(): void;\n readonly state: string;\n}\n\nexport interface EngineDeviceOptions {\n edge?: string | string[];\n tokenRefreshMs?: number;\n sounds?: Record<string, string>;\n disableAudioContextSounds?: boolean;\n allowIncomingWhileBusy?: boolean;\n logLevel?: number;\n closeProtection?: boolean;\n}\n\nexport interface Engine {\n createDevice(token: string, options: EngineDeviceOptions): EngineDevice;\n}\n\nlet enginePromise: Promise<Engine> | null = null;\n\n/**\n * Default engine: the voice SDK, loaded lazily on first use so importing\n * `@tryprojectblue/dialer` costs nothing until a session actually starts.\n */\nexport function defaultEngine(): Promise<Engine> {\n if (!enginePromise) {\n enginePromise = import('@twilio/voice-sdk').then(({ Device }) => ({\n createDevice(token, options) {\n return new Device(token, options as ConstructorParameters<typeof Device>[1]) as unknown as EngineDevice;\n },\n }));\n }\n return enginePromise;\n}\n","import { DialerCall } from './call';\nimport { TypedEmitter } from './emitter';\nimport { defaultEngine, type Engine, type EngineCall, type EngineDevice } from './engine';\nimport {\n DialerCapReachedError,\n DialerError,\n engineErrorToDialerError,\n isEngineTokenError,\n isMintErrorBody,\n toDialerError,\n} from './errors';\nimport type {\n DialerAllowance,\n DialerEvents,\n DialerLogger,\n DialerOptions,\n DialerTokenResponse,\n} from './types';\n\nconst DEFAULT_REFRESH_LEAD_SECONDS = 60;\nconst FALLBACK_TTL_SECONDS = 15 * 60;\nconst MIN_REFRESH_DELAY_MS = 5_000;\nconst REFRESH_RETRY_DELAYS_MS = [5_000, 15_000, 45_000];\nconst REGISTRATION_RETRY_DELAYS_MS = [5_000, 15_000, 45_000];\nconst UNREGISTERED_RETRY_DELAY_MS = 2_000;\nconst DEFAULT_MAX_CALLS_PER_TOKEN = 10;\n\ninterface ActiveToken {\n token: string;\n expiresAtMs: number;\n inboundEnabled: boolean;\n maxCallsPerToken: number;\n callsPlaced: number;\n allowedDestinations: string[] | null;\n callGrantRequired: boolean;\n}\n\ninterface InternalOptions extends DialerOptions {\n /** @internal test seam */\n engine?: Engine | Promise<Engine>;\n /** @internal test seam */\n now?: () => number;\n}\n\nconst quietLogger: DialerLogger = {\n debug: () => undefined,\n info: () => undefined,\n warn: (...args) => console.warn('[projectblue/dialer]', ...args),\n error: (...args) => console.error('[projectblue/dialer]', ...args),\n};\n\nfunction normalizeTokenResponse(value: unknown): DialerTokenResponse {\n if (typeof value === 'string' && value.length > 0) return { token: value };\n if (isMintErrorBody(value)) throw toDialerError(value);\n const body = value as Partial<DialerTokenResponse> | null | undefined;\n if (!body || typeof body.token !== 'string' || body.token.length === 0) {\n throw new DialerError('token_unavailable', 'tokenProvider did not return a token');\n }\n return body as DialerTokenResponse;\n}\n\n/**\n * A calling session for one Project Blue line.\n *\n * const dialer = new ProjectBlueDialer({ tokenProvider });\n * await dialer.start();\n * const call = await dialer.call('+15551234567');\n * call.on('disconnected', () => ...);\n *\n * The session never sees your workspace API key: `tokenProvider` asks YOUR\n * server, which calls `POST /api/v1/dialer/token` and returns the body.\n */\nexport class ProjectBlueDialer extends TypedEmitter<DialerEvents> {\n private readonly options: InternalOptions;\n private readonly log: DialerLogger;\n private readonly now: () => number;\n private device: EngineDevice | null = null;\n private active: ActiveToken | null = null;\n private latestAllowance: DialerAllowance | null = null;\n private currentCall: DialerCall | null = null;\n private refreshTimer: ReturnType<typeof setTimeout> | null = null;\n private registrationTimer: ReturnType<typeof setTimeout> | null = null;\n private registrationFailures = 0;\n private registrationInProgress = false;\n private refreshInFlight: Promise<void> | null = null;\n private refreshFailures = 0;\n private reregisterWhenCallEnds = false;\n private destroyed = false;\n private started = false;\n\n constructor(options: DialerOptions) {\n super();\n if (typeof options?.tokenProvider !== 'function') {\n throw new DialerError('invalid_state', 'ProjectBlueDialer requires a tokenProvider');\n }\n this.options = options as InternalOptions;\n this.log = options.logger === null ? { ...quietLogger, warn: () => undefined, error: () => undefined } : options.logger ?? quietLogger;\n this.now = this.options.now ?? (() => Date.now());\n }\n\n /** Latest allowance the server reported with a token; null before `start()`. */\n get allowance(): DialerAllowance | null {\n return this.latestAllowance;\n }\n\n /** Whether the current token lets this session receive calls. */\n get inboundEnabled(): boolean {\n return this.active?.inboundEnabled ?? false;\n }\n\n /** Whether the engine is currently registered to receive calls. */\n get registered(): boolean {\n return this.device?.state === 'registered';\n }\n\n get activeCall(): DialerCall | null {\n return this.currentCall?.isActive() ? this.currentCall : null;\n }\n\n isReady(): boolean {\n return this.started && !this.destroyed && !!this.device && !!this.active;\n }\n\n /** Fetch the first token and connect. Resolves once calls can be placed. */\n async start(options?: { requireInbound?: boolean }): Promise<void> {\n this.assertNotDestroyed();\n if (this.started) return;\n const response = await this.fetchToken();\n const engine = await (this.options.engine ?? defaultEngine());\n if (this.destroyed) return;\n const device = engine.createDevice(response.token, {\n edge: this.options.edge,\n // The engine's own early-expiry event is a second trigger for refresh;\n // our timer below is the first.\n tokenRefreshMs: this.refreshLeadMs(),\n allowIncomingWhileBusy: false,\n closeProtection: false,\n ...(this.options.playIncomingRingtone === false ? { disableAudioContextSounds: true, sounds: {} } : {}),\n });\n this.device = device;\n this.attachDeviceListeners(device);\n this.started = true;\n this.applyToken(response);\n const registrationSucceeded = await this.syncRegistration();\n if (!!options?.requireInbound && (!this.inboundEnabled || !registrationSucceeded || !this.registered)) {\n await this.destroy();\n throw new DialerError('inbound_unavailable', 'Inbound calling is unavailable for this session');\n }\n if (!this.destroyed) this.emit('ready', { inboundEnabled: this.inboundEnabled, registered: this.registered });\n }\n\n /**\n * Place an outbound call from the line this session is scoped to. `to` must\n * be E.164 (`+15551234567`). Rejects with a `DialerError` (`cap_reached`,\n * `token_unavailable`, `microphone_unavailable`, …) when the call cannot start.\n */\n async call(to: string, options?: { grant?: string }): Promise<DialerCall> {\n this.assertReady();\n // E.164 only, `+` required: guessing a country code turns a typo into a\n // call to another country.\n const destination = typeof to === 'string' ? to.replace(/[\\s()-]/g, '') : '';\n if (!/^\\+[1-9][0-9]{6,14}$/.test(destination)) {\n throw new DialerError('call_failed', 'call(to) requires a phone number in E.164 format, e.g. +15551234567');\n }\n if (this.activeCall) {\n throw new DialerError('invalid_state', 'A call is already in progress');\n }\n // A token good for N calls is refreshed BEFORE the (N+1)th, so the server's\n // per-token limit is never hit in the normal path.\n const token = this.active!;\n if (token.callsPlaced >= token.maxCallsPerToken || this.expiresWithin(this.refreshLeadMs())) {\n await this.refreshToken();\n }\n if (!!this.active!.allowedDestinations && !this.active!.allowedDestinations.includes(destination)) {\n throw new DialerError('destination_not_allowed', 'This number is not approved for this session.');\n }\n if (!!this.active!.callGrantRequired && !options?.grant) {\n throw new DialerError('grant_required', 'A call grant is required for this session.');\n }\n const params: Record<string, string> = { To: destination };\n if (!!options?.grant) params.PbCallGrant = options.grant;\n let engineCall: EngineCall;\n try {\n engineCall = await this.device!.connect({ params });\n } catch (error) {\n // Mic denied / no device → microphone_unavailable; signaling → connection_failed.\n throw engineErrorToDialerError(error, 'call_failed');\n }\n this.active!.callsPlaced += 1;\n const call = new DialerCall(engineCall, 'outbound', params.To ?? null);\n this.trackCall(call);\n return call;\n }\n\n /** Force a token refresh now. Usually unnecessary — the session refreshes itself. */\n async refreshToken(): Promise<void> {\n this.assertNotDestroyed();\n if (this.refreshInFlight) return this.refreshInFlight;\n this.refreshInFlight = this.runRefresh().finally(() => {\n this.refreshInFlight = null;\n });\n return this.refreshInFlight;\n }\n\n /** Hang up any call, stop refreshing, and release the microphone. Idempotent. */\n async destroy(): Promise<void> {\n if (this.destroyed) return;\n this.destroyed = true;\n this.clearRefreshTimer();\n this.clearRegistrationTimer();\n this.reregisterWhenCallEnds = false;\n try {\n this.currentCall?.hangup();\n } catch {\n // Best effort.\n }\n const device = this.device;\n this.device = null;\n if (device) {\n try {\n if (this.active?.inboundEnabled) await device.unregister().catch(() => undefined);\n device.destroy();\n } catch (error) {\n this.log.warn('destroy: engine teardown failed', error);\n }\n }\n this.active = null;\n this.emit('destroyed');\n this.removeAllListeners();\n }\n\n // --- internals -----------------------------------------------------------\n\n private refreshLeadMs(): number {\n const seconds = this.options.refreshLeadSeconds ?? DEFAULT_REFRESH_LEAD_SECONDS;\n return Math.max(5, seconds) * 1000;\n }\n\n private assertNotDestroyed(): void {\n if (this.destroyed) throw new DialerError('invalid_state', 'This dialer session has been destroyed');\n }\n\n private assertReady(): void {\n this.assertNotDestroyed();\n if (!this.isReady()) throw new DialerError('invalid_state', 'Call start() before placing calls');\n }\n\n private expiresWithin(windowMs: number): boolean {\n if (!this.active) return true;\n return this.active.expiresAtMs - this.now() <= windowMs;\n }\n\n private async fetchToken(): Promise<DialerTokenResponse> {\n let raw: unknown;\n try {\n raw = await this.options.tokenProvider();\n } catch (error) {\n throw toDialerError(error);\n }\n return normalizeTokenResponse(raw);\n }\n\n private applyToken(response: DialerTokenResponse): void {\n const parsedExpiry = response.expiresAt ? new Date(response.expiresAt).getTime() : NaN;\n const ttlMs = (response.ttlSeconds ?? FALLBACK_TTL_SECONDS) * 1000;\n const expiresAtMs = Number.isFinite(parsedExpiry) ? parsedExpiry : this.now() + ttlMs;\n this.active = {\n token: response.token,\n expiresAtMs,\n inboundEnabled: !!response.inboundEnabled,\n maxCallsPerToken: response.maxCallsPerToken && response.maxCallsPerToken > 0 ? response.maxCallsPerToken : DEFAULT_MAX_CALLS_PER_TOKEN,\n callsPlaced: 0,\n allowedDestinations: response.allowedDestinations ?? null,\n callGrantRequired: !!response.callGrantRequired,\n };\n this.clearRegistrationTimer();\n this.registrationFailures = 0;\n this.reregisterWhenCallEnds = false;\n this.refreshFailures = 0;\n if (response.allowance) {\n this.latestAllowance = response.allowance;\n this.emit('allowance', response.allowance);\n }\n this.scheduleRefresh(Math.max(MIN_REFRESH_DELAY_MS, expiresAtMs - this.now() - this.refreshLeadMs()));\n }\n\n private scheduleRefresh(delayMs: number): void {\n this.clearRefreshTimer();\n if (this.destroyed) return;\n this.refreshTimer = setTimeout(() => {\n this.refreshTimer = null;\n void this.refreshToken().catch(() => undefined);\n }, delayMs);\n }\n\n private clearRefreshTimer(): void {\n if (this.refreshTimer !== null) {\n clearTimeout(this.refreshTimer);\n this.refreshTimer = null;\n }\n }\n\n private async runRefresh(): Promise<void> {\n if (!this.device) return;\n try {\n const response = await this.fetchToken();\n if (this.destroyed || !this.device) return;\n this.device.updateToken(response.token);\n const wasInbound = this.active?.inboundEnabled ?? false;\n this.applyToken(response);\n // Every mint issues a new identity (fresh nonce) and registers THAT\n // identity as the line's ring leg. A registration made under the previous\n // identity would never be dialed again, so an inbound-enabled session\n // re-registers after each refresh; a session that just lost inbound\n // unregisters.\n if (this.active!.inboundEnabled) await this.reregisterUnderCurrentIdentity();\n else if (wasInbound) await this.syncRegistration();\n if (!this.destroyed) this.emit('ready', { inboundEnabled: this.inboundEnabled, registered: this.registered });\n } catch (error) {\n const dialerError = toDialerError(error);\n this.log.warn('token refresh failed', dialerError);\n if (dialerError instanceof DialerCapReachedError) {\n // Nothing to retry until the period rolls over. The current token keeps\n // any in-progress call alive; new calls fail at the mint, never mid-call.\n this.emit('capReached', dialerError);\n this.emit('tokenRefreshFailed', dialerError);\n const resumeInMs = dialerError.periodEnd ? dialerError.periodEnd.getTime() - this.now() : NaN;\n // Known period end: wake exactly then. Unknown: poll slowly (one token\n // lifetime) so the session heals on its own without hammering the mint.\n this.scheduleRefresh(\n Number.isFinite(resumeInMs) && resumeInMs > 0 ? resumeInMs + 1_000 : FALLBACK_TTL_SECONDS * 1000\n );\n throw dialerError;\n }\n this.emit('tokenRefreshFailed', dialerError);\n const delay = REFRESH_RETRY_DELAYS_MS[Math.min(this.refreshFailures, REFRESH_RETRY_DELAYS_MS.length - 1)] ?? 45_000;\n this.refreshFailures += 1;\n this.scheduleRefresh(delay);\n throw dialerError;\n }\n }\n\n /**\n * Drop the registration bound to the previous token's identity and register\n * again with the current one. Deferred while a call is up: unregistering\n * mid-call would tear down the signaling the call rides on.\n */\n private async reregisterUnderCurrentIdentity(): Promise<void> {\n const device = this.device;\n if (!device || !this.active?.inboundEnabled || this.destroyed) return;\n if (!!this.activeCall) {\n this.reregisterWhenCallEnds = true;\n return;\n }\n this.reregisterWhenCallEnds = false;\n this.registrationInProgress = true;\n try {\n if (device.state === 'registered') await device.unregister();\n await device.register();\n this.registrationSucceeded();\n } catch (error) {\n this.log.warn('re-registration after token refresh failed', error);\n this.registrationFailed(toDialerError(error, 'connection_failed'));\n } finally {\n this.registrationInProgress = false;\n }\n }\n\n private async syncRegistration(): Promise<boolean> {\n const device = this.device;\n if (!device || !this.active || this.destroyed) return false;\n this.registrationInProgress = true;\n try {\n if (this.active.inboundEnabled) {\n if (!!this.activeCall) {\n this.reregisterWhenCallEnds = true;\n return false;\n }\n if (device.state !== 'registered') await device.register();\n this.registrationSucceeded();\n } else if (device.state === 'registered') {\n await device.unregister();\n }\n return true;\n } catch (error) {\n this.log.warn('inbound registration failed', error);\n this.registrationFailed(toDialerError(error, 'connection_failed'));\n return false;\n } finally {\n this.registrationInProgress = false;\n }\n }\n\n private clearRegistrationTimer(): void {\n if (this.registrationTimer !== null) {\n clearTimeout(this.registrationTimer);\n this.registrationTimer = null;\n }\n }\n\n private registrationSucceeded(): void {\n this.clearRegistrationTimer();\n this.registrationFailures = 0;\n }\n\n private registrationFailed(dialerError: DialerError): void {\n if (this.destroyed) return;\n this.emit('registrationFailed', dialerError);\n this.emit('error', dialerError);\n const delay = REGISTRATION_RETRY_DELAYS_MS[this.registrationFailures];\n this.registrationFailures += 1;\n if (!!this.active?.inboundEnabled && delay !== undefined) this.scheduleRegistration(delay);\n }\n\n private scheduleRegistration(delayMs: number): void {\n this.clearRegistrationTimer();\n if (this.destroyed) return;\n this.registrationTimer = setTimeout(() => {\n this.registrationTimer = null;\n void this.reregisterUnderCurrentIdentity();\n }, delayMs);\n }\n\n private attachDeviceListeners(device: EngineDevice): void {\n device.on('tokenWillExpire', () => void this.refreshToken().catch(() => undefined));\n device.on('tokenExpired', () => void this.refreshToken().catch(() => undefined));\n device.on('incoming', (engineCall: EngineCall) => {\n const call = new DialerCall(engineCall, 'inbound', null);\n this.trackCall(call);\n this.emit('incoming', call);\n });\n device.on('registered', () => {\n this.registrationSucceeded();\n if (!this.destroyed) this.emit('registered');\n });\n device.on('unregistered', () => {\n if (this.destroyed) return;\n this.emit('unregistered');\n if (!!this.active?.inboundEnabled && !this.registrationInProgress && this.registrationFailures === 0) {\n this.scheduleRegistration(UNREGISTERED_RETRY_DELAY_MS);\n }\n });\n device.on('error', (raw: unknown) => {\n if (isEngineTokenError(raw)) {\n // Invalid / expired token — refresh and carry on.\n void this.refreshToken().catch(() => undefined);\n return;\n }\n this.emit('error', engineErrorToDialerError(raw, 'connection_failed'));\n });\n }\n\n private trackCall(call: DialerCall): void {\n this.currentCall = call;\n const clear = () => {\n if (this.currentCall !== call) return;\n this.currentCall = null;\n if (this.reregisterWhenCallEnds && !this.destroyed) {\n void this.reregisterUnderCurrentIdentity();\n }\n };\n call.on('disconnected', clear);\n call.on('cancelled', clear);\n call.on('rejected', clear);\n }\n}\n"],"mappings":";AAGO,IAAM,eAAN,MAAqE;AAAA,EAArE;AACL,SAAQ,YAAY,oBAAI,IAA6C;AAAA;AAAA,EAErE,GAA2B,OAAU,UAAiC;AACpE,QAAI,MAAM,KAAK,UAAU,IAAI,KAAK;AAClC,QAAI,CAAC,KAAK;AACR,Y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B,KAAK,yBAAyB,GAAG;AACpG,aAAK,qBAAqB,2BAA2B;AAAA,MACvD;AAAA,IACF,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAiB;AACnC,UAAI,mBAAmB,GAAG,GAAG;AAE3B,aAAK,KAAK,aAAa,EAAE,MAAM,MAAM,MAAS;AAC9C;AAAA,MACF;AACA,WAAK,KAAK,SAAS,yBAAyB,KAAK,mBAAmB,CAAC;AAAA,IACvE,CAAC;AAAA,EACH;AAAA,EAEQ,UAAU,MAAwB;AACxC,SAAK,cAAc;AACnB,UAAM,QAAQ,MAAM;AAClB,UAAI,KAAK,gBAAgB,KAAM;AAC/B,WAAK,cAAc;AACnB,UAAI,KAAK,0BAA0B,CAAC,KAAK,WAAW;AAClD,aAAK,KAAK,+BAA+B;AAAA,MAC3C;AAAA,IACF;AACA,SAAK,GAAG,gBAAgB,KAAK;AAC7B,SAAK,GAAG,aAAa,KAAK;AAC1B,SAAK,GAAG,YAAY,KAAK;AAAA,EAC3B;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tryprojectblue/dialer",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Browser SDK for placing and receiving Project Blue dialer calls with short
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Browser SDK for placing and receiving Project Blue dialer calls with short lived, single line tokens minted by your own server.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Project Blue",
|
|
7
7
|
"homepage": "https://app.tryprojectblue.com/docs/dialer-sdk.html",
|