@micdrop/telephony 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -2
- package/dist/index.d.mts +354 -0
- package/dist/index.d.ts +354 -0
- package/dist/index.js +709 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +673 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +50 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,709 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
PlivoTransport: () => PlivoTransport,
|
|
24
|
+
TelephonyTransport: () => TelephonyTransport,
|
|
25
|
+
TelnyxTransport: () => TelnyxTransport,
|
|
26
|
+
TwilioTransport: () => TwilioTransport,
|
|
27
|
+
VonageTransport: () => VonageTransport,
|
|
28
|
+
alawToPcm16: () => alawToPcm16,
|
|
29
|
+
mulawToPcm16: () => mulawToPcm16,
|
|
30
|
+
parseJson: () => parseJson,
|
|
31
|
+
pcm16ToAlaw: () => pcm16ToAlaw,
|
|
32
|
+
pcm16ToMulaw: () => pcm16ToMulaw,
|
|
33
|
+
plivoStreamXml: () => plivoStreamXml,
|
|
34
|
+
telnyxStreamOptions: () => telnyxStreamOptions,
|
|
35
|
+
twilioStreamTwiml: () => twilioStreamTwiml,
|
|
36
|
+
vonageConnectNcco: () => vonageConnectNcco
|
|
37
|
+
});
|
|
38
|
+
module.exports = __toCommonJS(index_exports);
|
|
39
|
+
|
|
40
|
+
// src/g711.ts
|
|
41
|
+
var MULAW_BIAS = 132;
|
|
42
|
+
var MULAW_CLIP = 32635;
|
|
43
|
+
var MULAW_TO_PCM = new Int16Array(256);
|
|
44
|
+
var ALAW_TO_PCM = new Int16Array(256);
|
|
45
|
+
for (let i = 0; i < 256; i++) {
|
|
46
|
+
MULAW_TO_PCM[i] = decodeMulawSample(i);
|
|
47
|
+
ALAW_TO_PCM[i] = decodeAlawSample(i);
|
|
48
|
+
}
|
|
49
|
+
function decodeMulawSample(byte) {
|
|
50
|
+
const value = ~byte & 255;
|
|
51
|
+
const sign = value & 128;
|
|
52
|
+
const exponent = value >> 4 & 7;
|
|
53
|
+
const mantissa = value & 15;
|
|
54
|
+
const magnitude = (mantissa << 3) + MULAW_BIAS << exponent;
|
|
55
|
+
return sign ? MULAW_BIAS - magnitude : magnitude - MULAW_BIAS;
|
|
56
|
+
}
|
|
57
|
+
function encodeMulawSample(sample) {
|
|
58
|
+
const sign = sample < 0 ? 128 : 0;
|
|
59
|
+
let magnitude = Math.min(Math.abs(sample), MULAW_CLIP) + MULAW_BIAS;
|
|
60
|
+
let exponent = 7;
|
|
61
|
+
for (let mask = 16384; (magnitude & mask) === 0 && exponent > 0; mask >>= 1) {
|
|
62
|
+
exponent--;
|
|
63
|
+
}
|
|
64
|
+
const mantissa = magnitude >> exponent + 3 & 15;
|
|
65
|
+
return ~(sign | exponent << 4 | mantissa) & 255;
|
|
66
|
+
}
|
|
67
|
+
function decodeAlawSample(byte) {
|
|
68
|
+
const value = byte ^ 85;
|
|
69
|
+
const sign = value & 128;
|
|
70
|
+
const exponent = value >> 4 & 7;
|
|
71
|
+
const mantissa = value & 15;
|
|
72
|
+
let magnitude = exponent === 0 ? (mantissa << 4) + 8 : (mantissa << 4) + 264 << exponent - 1;
|
|
73
|
+
return sign ? magnitude : -magnitude;
|
|
74
|
+
}
|
|
75
|
+
function encodeAlawSample(sample) {
|
|
76
|
+
const sign = sample >= 0 ? 128 : 0;
|
|
77
|
+
let magnitude = Math.min(Math.abs(sample), 32767);
|
|
78
|
+
let byte;
|
|
79
|
+
if (magnitude >= 256) {
|
|
80
|
+
let exponent = 7;
|
|
81
|
+
for (let mask = 16384; (magnitude & mask) === 0; mask >>= 1) exponent--;
|
|
82
|
+
const mantissa = magnitude >> exponent + 3 & 15;
|
|
83
|
+
byte = exponent << 4 | mantissa;
|
|
84
|
+
} else {
|
|
85
|
+
byte = magnitude >> 4;
|
|
86
|
+
}
|
|
87
|
+
return (byte | sign) ^ 85;
|
|
88
|
+
}
|
|
89
|
+
function mulawToPcm16(bytes) {
|
|
90
|
+
const pcm = Buffer.alloc(bytes.length * 2);
|
|
91
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
92
|
+
pcm.writeInt16LE(MULAW_TO_PCM[bytes[i]], i * 2);
|
|
93
|
+
}
|
|
94
|
+
return pcm;
|
|
95
|
+
}
|
|
96
|
+
function pcm16ToMulaw(pcm) {
|
|
97
|
+
const count = pcm.length >> 1;
|
|
98
|
+
const bytes = Buffer.alloc(count);
|
|
99
|
+
for (let i = 0; i < count; i++) {
|
|
100
|
+
bytes[i] = encodeMulawSample(pcm.readInt16LE(i * 2));
|
|
101
|
+
}
|
|
102
|
+
return bytes;
|
|
103
|
+
}
|
|
104
|
+
function alawToPcm16(bytes) {
|
|
105
|
+
const pcm = Buffer.alloc(bytes.length * 2);
|
|
106
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
107
|
+
pcm.writeInt16LE(ALAW_TO_PCM[bytes[i]], i * 2);
|
|
108
|
+
}
|
|
109
|
+
return pcm;
|
|
110
|
+
}
|
|
111
|
+
function pcm16ToAlaw(pcm) {
|
|
112
|
+
const count = pcm.length >> 1;
|
|
113
|
+
const bytes = Buffer.alloc(count);
|
|
114
|
+
for (let i = 0; i < count; i++) {
|
|
115
|
+
bytes[i] = encodeAlawSample(pcm.readInt16LE(i * 2));
|
|
116
|
+
}
|
|
117
|
+
return bytes;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/xml.ts
|
|
121
|
+
function escapeXml(value) {
|
|
122
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/TelephonyTransport.ts
|
|
126
|
+
var import_server = require("@micdrop/server");
|
|
127
|
+
var PLAYBACK_MAX_WAIT = 2e4;
|
|
128
|
+
var FRAME_IDLE_FLUSH = 80;
|
|
129
|
+
var TelephonyTransport = class extends import_server.MicdropTransport {
|
|
130
|
+
/**
|
|
131
|
+
* @param socket - The socket the provider opened, as the `ws` server hands it
|
|
132
|
+
*/
|
|
133
|
+
constructor(socket) {
|
|
134
|
+
super();
|
|
135
|
+
this.socket = socket;
|
|
136
|
+
this.clientTurns = false;
|
|
137
|
+
this.hangsUp = true;
|
|
138
|
+
/** What the provider said about the call */
|
|
139
|
+
this.call = {};
|
|
140
|
+
/**
|
|
141
|
+
* Duration of the frames the provider wants, in ms. 0 sends the audio as it
|
|
142
|
+
* comes, for the providers that take any size.
|
|
143
|
+
*/
|
|
144
|
+
this.frameDuration = 20;
|
|
145
|
+
// The provider is ready for audio once its stream has started
|
|
146
|
+
this.ready = false;
|
|
147
|
+
this.pendingWrites = [];
|
|
148
|
+
this.inputRate = 0;
|
|
149
|
+
this.outputRate = 0;
|
|
150
|
+
this.frameRemainder = Buffer.alloc(0);
|
|
151
|
+
this.markCounter = 0;
|
|
152
|
+
this.playbackWaiters = /* @__PURE__ */ new Map();
|
|
153
|
+
this.closed = false;
|
|
154
|
+
this.onSocketMessage = (data, isBinary) => {
|
|
155
|
+
const buffer = Buffer.isBuffer(data) ? data : Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
|
|
156
|
+
try {
|
|
157
|
+
this.onProviderMessage(buffer, isBinary);
|
|
158
|
+
} catch (error) {
|
|
159
|
+
this.log("Unreadable message from the provider:", error);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
this.onSocketClose = (code, reason) => {
|
|
163
|
+
this.closed = true;
|
|
164
|
+
this.cancelFrameFlush();
|
|
165
|
+
this.resolvePlayback();
|
|
166
|
+
this.socket.off("message", this.onSocketMessage);
|
|
167
|
+
this.socket.off("close", this.onSocketClose);
|
|
168
|
+
this.emit("Close", code, reason?.toString() || void 0);
|
|
169
|
+
};
|
|
170
|
+
socket.on("message", this.onSocketMessage);
|
|
171
|
+
socket.on("close", this.onSocketClose);
|
|
172
|
+
}
|
|
173
|
+
get isOpen() {
|
|
174
|
+
return !this.closed && (this.socket.readyState ?? 1) === 1;
|
|
175
|
+
}
|
|
176
|
+
// A phone line has nobody to read the messages of the server
|
|
177
|
+
send(message) {
|
|
178
|
+
if (message.type === "EndCall") this.log("The assistant ends the call");
|
|
179
|
+
}
|
|
180
|
+
sendAudio(audio, sampleRate) {
|
|
181
|
+
if (!this.isOpen) return;
|
|
182
|
+
const pcm = this.toLineRate(audio, sampleRate);
|
|
183
|
+
if (pcm.length === 0) return;
|
|
184
|
+
if (!this.frameDuration) {
|
|
185
|
+
this.whenReady(() => this.writeAudio(pcm));
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const frameBytes = this.frameBytes;
|
|
189
|
+
let data = Buffer.concat([this.frameRemainder, pcm]);
|
|
190
|
+
while (data.length >= frameBytes) {
|
|
191
|
+
const frame = data.subarray(0, frameBytes);
|
|
192
|
+
this.whenReady(() => this.writeAudio(frame));
|
|
193
|
+
data = data.subarray(frameBytes);
|
|
194
|
+
}
|
|
195
|
+
this.frameRemainder = data;
|
|
196
|
+
this.scheduleFrameFlush();
|
|
197
|
+
}
|
|
198
|
+
clearAudio() {
|
|
199
|
+
this.cancelFrameFlush();
|
|
200
|
+
this.frameRemainder = Buffer.alloc(0);
|
|
201
|
+
this.pendingWrites = [];
|
|
202
|
+
if (this.ready && this.isOpen) this.writeClear();
|
|
203
|
+
this.resolvePlayback();
|
|
204
|
+
}
|
|
205
|
+
waitForPlayback() {
|
|
206
|
+
if (!this.isOpen) return Promise.resolve();
|
|
207
|
+
this.flushFrame();
|
|
208
|
+
const name = `micdrop-${++this.markCounter}`;
|
|
209
|
+
return new Promise((resolve) => {
|
|
210
|
+
const timer = setTimeout(() => {
|
|
211
|
+
this.log("The provider never confirmed the playback");
|
|
212
|
+
done();
|
|
213
|
+
}, PLAYBACK_MAX_WAIT);
|
|
214
|
+
const done = () => {
|
|
215
|
+
clearTimeout(timer);
|
|
216
|
+
this.playbackWaiters.delete(name);
|
|
217
|
+
resolve();
|
|
218
|
+
};
|
|
219
|
+
this.playbackWaiters.set(name, done);
|
|
220
|
+
this.whenReady(() => this.writeMark(name));
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Ends the stream, and the call with it: closing the socket is enough for
|
|
225
|
+
* the providers that end the call when nothing follows the stream, the
|
|
226
|
+
* others hang up through their API in `hangUp()`
|
|
227
|
+
*/
|
|
228
|
+
close(code = 1e3, reason) {
|
|
229
|
+
if (this.closed) return;
|
|
230
|
+
this.cancelFrameFlush();
|
|
231
|
+
this.hangUp().catch((error) => this.log("Hang up failed:", error));
|
|
232
|
+
if ((this.socket.readyState ?? 1) <= 1) this.socket.close(code, reason);
|
|
233
|
+
}
|
|
234
|
+
/** Hangs up through the API of the provider, for those that need it */
|
|
235
|
+
async hangUp() {
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The stream has started: keeps what the provider said about the call and
|
|
239
|
+
* sends the audio that waited for it
|
|
240
|
+
* @param call - Identifiers and numbers of the call
|
|
241
|
+
* @param params - Custom parameters of the call, if any
|
|
242
|
+
*/
|
|
243
|
+
startStream(call, params) {
|
|
244
|
+
this.call = { ...this.call, ...call };
|
|
245
|
+
this.log("Stream started", this.call);
|
|
246
|
+
this.ready = true;
|
|
247
|
+
const writes = this.pendingWrites;
|
|
248
|
+
this.pendingWrites = [];
|
|
249
|
+
for (const write of writes) write();
|
|
250
|
+
this.receiveParams(params ?? {});
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Hands audio of the caller to the server
|
|
254
|
+
* @param pcm - PCM16 mono at the rate of the line
|
|
255
|
+
*/
|
|
256
|
+
receiveAudio(pcm) {
|
|
257
|
+
if (pcm.length === 0) return;
|
|
258
|
+
const rate = this.lineRate;
|
|
259
|
+
if (rate !== this.inputRate) {
|
|
260
|
+
this.inputRate = rate;
|
|
261
|
+
this.inputResampler = new import_server.Pcm16Resampler(rate, import_server.DEFAULT_SAMPLE_RATE);
|
|
262
|
+
}
|
|
263
|
+
const audio = this.inputResampler.process(pcm);
|
|
264
|
+
if (audio.length) this.emit("Audio", audio);
|
|
265
|
+
}
|
|
266
|
+
/** The provider played the audio sent before a mark */
|
|
267
|
+
markPlayed(name) {
|
|
268
|
+
this.playbackWaiters.get(name)?.();
|
|
269
|
+
}
|
|
270
|
+
/** A key was pressed on the keypad of the phone */
|
|
271
|
+
receiveDtmf(digit) {
|
|
272
|
+
this.log(`DTMF ${digit}`);
|
|
273
|
+
this.emit("Dtmf", digit);
|
|
274
|
+
}
|
|
275
|
+
/** Bytes in one outgoing frame */
|
|
276
|
+
get frameBytes() {
|
|
277
|
+
return Math.round(this.lineRate * this.frameDuration / 1e3) * 2;
|
|
278
|
+
}
|
|
279
|
+
toLineRate(audio, sampleRate) {
|
|
280
|
+
const rate = this.lineRate;
|
|
281
|
+
if (sampleRate === rate) return audio;
|
|
282
|
+
if (sampleRate !== this.outputRate) {
|
|
283
|
+
this.outputRate = sampleRate;
|
|
284
|
+
this.outputResampler = new import_server.Pcm16Resampler(sampleRate, rate);
|
|
285
|
+
}
|
|
286
|
+
return this.outputResampler.process(audio);
|
|
287
|
+
}
|
|
288
|
+
whenReady(write) {
|
|
289
|
+
if (this.ready) write();
|
|
290
|
+
else this.pendingWrites.push(write);
|
|
291
|
+
}
|
|
292
|
+
/** Sends the incomplete frame left, padded with silence */
|
|
293
|
+
flushFrame() {
|
|
294
|
+
this.cancelFrameFlush();
|
|
295
|
+
if (this.frameRemainder.length === 0) return;
|
|
296
|
+
const frame = Buffer.alloc(this.frameBytes);
|
|
297
|
+
this.frameRemainder.copy(frame);
|
|
298
|
+
this.frameRemainder = Buffer.alloc(0);
|
|
299
|
+
this.whenReady(() => this.writeAudio(frame));
|
|
300
|
+
}
|
|
301
|
+
scheduleFrameFlush() {
|
|
302
|
+
this.cancelFrameFlush();
|
|
303
|
+
if (this.frameRemainder.length === 0) return;
|
|
304
|
+
this.frameTimer = setTimeout(() => this.flushFrame(), FRAME_IDLE_FLUSH);
|
|
305
|
+
}
|
|
306
|
+
cancelFrameFlush() {
|
|
307
|
+
if (!this.frameTimer) return;
|
|
308
|
+
clearTimeout(this.frameTimer);
|
|
309
|
+
this.frameTimer = void 0;
|
|
310
|
+
}
|
|
311
|
+
resolvePlayback() {
|
|
312
|
+
for (const done of [...this.playbackWaiters.values()]) done();
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
function parseJson(data) {
|
|
316
|
+
try {
|
|
317
|
+
return JSON.parse(data.toString());
|
|
318
|
+
} catch {
|
|
319
|
+
return void 0;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// src/plivo.ts
|
|
324
|
+
var PlivoTransport = class extends TelephonyTransport {
|
|
325
|
+
/**
|
|
326
|
+
* @param socket - The socket Plivo opened
|
|
327
|
+
* @param options - Credentials to hang up with
|
|
328
|
+
*/
|
|
329
|
+
constructor(socket, options = {}) {
|
|
330
|
+
super(socket);
|
|
331
|
+
this.options = options;
|
|
332
|
+
}
|
|
333
|
+
get lineRate() {
|
|
334
|
+
return 8e3;
|
|
335
|
+
}
|
|
336
|
+
onProviderMessage(data) {
|
|
337
|
+
const message = parseJson(data);
|
|
338
|
+
switch (message?.event) {
|
|
339
|
+
case "start": {
|
|
340
|
+
const start = message.start ?? {};
|
|
341
|
+
this.startStream(
|
|
342
|
+
{
|
|
343
|
+
callId: start.callId,
|
|
344
|
+
streamId: start.streamId,
|
|
345
|
+
from: start.from,
|
|
346
|
+
to: start.to
|
|
347
|
+
},
|
|
348
|
+
parseExtraHeaders(message.extra_headers)
|
|
349
|
+
);
|
|
350
|
+
break;
|
|
351
|
+
}
|
|
352
|
+
case "media":
|
|
353
|
+
if (message.media?.track && message.media.track !== "inbound") return;
|
|
354
|
+
this.receiveAudio(
|
|
355
|
+
mulawToPcm16(Buffer.from(message.media?.payload ?? "", "base64"))
|
|
356
|
+
);
|
|
357
|
+
break;
|
|
358
|
+
case "playedStream":
|
|
359
|
+
this.markPlayed(message.name);
|
|
360
|
+
break;
|
|
361
|
+
case "dtmf":
|
|
362
|
+
this.receiveDtmf(String(message.dtmf?.digit));
|
|
363
|
+
break;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
writeAudio(pcm) {
|
|
367
|
+
this.sendJson({
|
|
368
|
+
event: "playAudio",
|
|
369
|
+
media: {
|
|
370
|
+
contentType: "audio/x-mulaw",
|
|
371
|
+
sampleRate: 8e3,
|
|
372
|
+
payload: pcm16ToMulaw(pcm).toString("base64")
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
writeClear() {
|
|
377
|
+
this.sendJson({ event: "clearAudio", streamId: this.call.streamId });
|
|
378
|
+
}
|
|
379
|
+
writeMark(name) {
|
|
380
|
+
this.sendJson({ event: "checkpoint", streamId: this.call.streamId, name });
|
|
381
|
+
}
|
|
382
|
+
async hangUp() {
|
|
383
|
+
const { authId, authToken } = this.options;
|
|
384
|
+
const callId = this.call.callId;
|
|
385
|
+
if (!authId || !authToken || !callId) return;
|
|
386
|
+
const credentials = Buffer.from(`${authId}:${authToken}`).toString("base64");
|
|
387
|
+
const response = await fetch(
|
|
388
|
+
`https://api.plivo.com/v1/Account/${encodeURIComponent(authId)}/Call/${encodeURIComponent(callId)}/`,
|
|
389
|
+
{ method: "DELETE", headers: { Authorization: `Basic ${credentials}` } }
|
|
390
|
+
);
|
|
391
|
+
if (!response.ok && response.status !== 404) {
|
|
392
|
+
throw new Error(`Plivo answered ${response.status} to the hang up`);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
sendJson(message) {
|
|
396
|
+
if (this.isOpen) this.socket.send(JSON.stringify(message));
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
function parseExtraHeaders(headers) {
|
|
400
|
+
const params = {};
|
|
401
|
+
if (typeof headers !== "string") return params;
|
|
402
|
+
for (const pair of headers.split(/[;,]/)) {
|
|
403
|
+
const index = pair.indexOf("=");
|
|
404
|
+
if (index <= 0) continue;
|
|
405
|
+
params[pair.substring(0, index).trim()] = pair.substring(index + 1).trim();
|
|
406
|
+
}
|
|
407
|
+
return params;
|
|
408
|
+
}
|
|
409
|
+
function plivoStreamXml({ url, parameters = {} }) {
|
|
410
|
+
const extraHeaders = Object.entries(parameters).map(([name, value]) => `${name}=${value}`).join(";");
|
|
411
|
+
const extra = extraHeaders ? ` extraHeaders="${escapeXml(extraHeaders)}"` : "";
|
|
412
|
+
return `<?xml version="1.0" encoding="UTF-8"?><Response><Stream bidirectional="true" keepCallAlive="true" contentType="audio/x-mulaw;rate=8000"${extra}>${escapeXml(url)}</Stream></Response>`;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// src/telnyx.ts
|
|
416
|
+
var TelnyxTransport = class extends TelephonyTransport {
|
|
417
|
+
/**
|
|
418
|
+
* @param socket - The socket Telnyx opened
|
|
419
|
+
* @param options - Codec of the stream and key to hang up with
|
|
420
|
+
*/
|
|
421
|
+
constructor(socket, options = {}) {
|
|
422
|
+
super(socket);
|
|
423
|
+
this.options = options;
|
|
424
|
+
this.codec = options.codec ?? "PCMU";
|
|
425
|
+
}
|
|
426
|
+
get lineRate() {
|
|
427
|
+
return 8e3;
|
|
428
|
+
}
|
|
429
|
+
onProviderMessage(data) {
|
|
430
|
+
const message = parseJson(data);
|
|
431
|
+
switch (message?.event) {
|
|
432
|
+
case "start": {
|
|
433
|
+
const start = message.start ?? {};
|
|
434
|
+
const encoding = start.media_format?.encoding;
|
|
435
|
+
if (encoding === "PCMU" || encoding === "PCMA") this.codec = encoding;
|
|
436
|
+
this.startStream(
|
|
437
|
+
{
|
|
438
|
+
callId: start.call_control_id,
|
|
439
|
+
streamId: message.stream_id,
|
|
440
|
+
from: start.from,
|
|
441
|
+
to: start.to
|
|
442
|
+
},
|
|
443
|
+
readParams(start)
|
|
444
|
+
);
|
|
445
|
+
break;
|
|
446
|
+
}
|
|
447
|
+
case "media": {
|
|
448
|
+
if (message.media?.track && message.media.track !== "inbound") return;
|
|
449
|
+
const bytes = Buffer.from(message.media?.payload ?? "", "base64");
|
|
450
|
+
this.receiveAudio(
|
|
451
|
+
this.codec === "PCMA" ? alawToPcm16(bytes) : mulawToPcm16(bytes)
|
|
452
|
+
);
|
|
453
|
+
break;
|
|
454
|
+
}
|
|
455
|
+
case "mark":
|
|
456
|
+
this.markPlayed(message.mark?.name);
|
|
457
|
+
break;
|
|
458
|
+
case "dtmf":
|
|
459
|
+
this.receiveDtmf(String(message.dtmf?.digit));
|
|
460
|
+
break;
|
|
461
|
+
case "error":
|
|
462
|
+
this.log("Telnyx error:", message.payload);
|
|
463
|
+
break;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
writeAudio(pcm) {
|
|
467
|
+
const bytes = this.codec === "PCMA" ? pcm16ToAlaw(pcm) : pcm16ToMulaw(pcm);
|
|
468
|
+
this.sendJson({ event: "media", media: { payload: bytes.toString("base64") } });
|
|
469
|
+
}
|
|
470
|
+
writeClear() {
|
|
471
|
+
this.sendJson({ event: "clear" });
|
|
472
|
+
}
|
|
473
|
+
writeMark(name) {
|
|
474
|
+
this.sendJson({ event: "mark", mark: { name } });
|
|
475
|
+
}
|
|
476
|
+
async hangUp() {
|
|
477
|
+
const { apiKey } = this.options;
|
|
478
|
+
const callId = this.call.callId;
|
|
479
|
+
if (!apiKey || !callId) return;
|
|
480
|
+
const response = await fetch(
|
|
481
|
+
`https://api.telnyx.com/v2/calls/${encodeURIComponent(callId)}/actions/hangup`,
|
|
482
|
+
{
|
|
483
|
+
method: "POST",
|
|
484
|
+
headers: {
|
|
485
|
+
Authorization: `Bearer ${apiKey}`,
|
|
486
|
+
"Content-Type": "application/json"
|
|
487
|
+
},
|
|
488
|
+
body: "{}"
|
|
489
|
+
}
|
|
490
|
+
);
|
|
491
|
+
if (!response.ok) {
|
|
492
|
+
throw new Error(`Telnyx answered ${response.status} to the hang up`);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
sendJson(message) {
|
|
496
|
+
if (this.isOpen) this.socket.send(JSON.stringify(message));
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
function readParams(start) {
|
|
500
|
+
const params = {};
|
|
501
|
+
const custom = start.custom_parameters;
|
|
502
|
+
if (Array.isArray(custom)) {
|
|
503
|
+
for (const { name, value } of custom) params[name] = value;
|
|
504
|
+
} else if (custom && typeof custom === "object") {
|
|
505
|
+
Object.assign(params, custom);
|
|
506
|
+
}
|
|
507
|
+
if (typeof start.client_state === "string") {
|
|
508
|
+
try {
|
|
509
|
+
const state = JSON.parse(
|
|
510
|
+
Buffer.from(start.client_state, "base64").toString()
|
|
511
|
+
);
|
|
512
|
+
if (state && typeof state === "object") Object.assign(params, state);
|
|
513
|
+
} catch {
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return params;
|
|
517
|
+
}
|
|
518
|
+
function telnyxStreamOptions({
|
|
519
|
+
url,
|
|
520
|
+
parameters,
|
|
521
|
+
codec = "PCMU"
|
|
522
|
+
}) {
|
|
523
|
+
return {
|
|
524
|
+
stream_url: url,
|
|
525
|
+
stream_track: "inbound_track",
|
|
526
|
+
stream_codec: codec,
|
|
527
|
+
stream_bidirectional_mode: "rtp",
|
|
528
|
+
stream_bidirectional_codec: codec,
|
|
529
|
+
...parameters ? {
|
|
530
|
+
client_state: Buffer.from(JSON.stringify(parameters)).toString(
|
|
531
|
+
"base64"
|
|
532
|
+
)
|
|
533
|
+
} : {}
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// src/twilio.ts
|
|
538
|
+
var TwilioTransport = class extends TelephonyTransport {
|
|
539
|
+
constructor() {
|
|
540
|
+
super(...arguments);
|
|
541
|
+
// Twilio takes audio of any size, and buffers it
|
|
542
|
+
this.frameDuration = 0;
|
|
543
|
+
}
|
|
544
|
+
get lineRate() {
|
|
545
|
+
return 8e3;
|
|
546
|
+
}
|
|
547
|
+
onProviderMessage(data) {
|
|
548
|
+
const message = parseJson(data);
|
|
549
|
+
switch (message?.event) {
|
|
550
|
+
case "start": {
|
|
551
|
+
const start = message.start ?? {};
|
|
552
|
+
this.startStream(
|
|
553
|
+
{
|
|
554
|
+
callId: start.callSid,
|
|
555
|
+
streamId: start.streamSid ?? message.streamSid
|
|
556
|
+
},
|
|
557
|
+
start.customParameters
|
|
558
|
+
);
|
|
559
|
+
break;
|
|
560
|
+
}
|
|
561
|
+
case "media":
|
|
562
|
+
if (message.media?.track && message.media.track !== "inbound") return;
|
|
563
|
+
this.receiveAudio(
|
|
564
|
+
mulawToPcm16(Buffer.from(message.media?.payload ?? "", "base64"))
|
|
565
|
+
);
|
|
566
|
+
break;
|
|
567
|
+
case "mark":
|
|
568
|
+
this.markPlayed(message.mark?.name);
|
|
569
|
+
break;
|
|
570
|
+
case "dtmf":
|
|
571
|
+
this.receiveDtmf(String(message.dtmf?.digit));
|
|
572
|
+
break;
|
|
573
|
+
case "stop":
|
|
574
|
+
this.log("Stream stopped");
|
|
575
|
+
break;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
writeAudio(pcm) {
|
|
579
|
+
this.sendJson({
|
|
580
|
+
event: "media",
|
|
581
|
+
streamSid: this.call.streamId,
|
|
582
|
+
media: { payload: pcm16ToMulaw(pcm).toString("base64") }
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
writeClear() {
|
|
586
|
+
this.sendJson({ event: "clear", streamSid: this.call.streamId });
|
|
587
|
+
}
|
|
588
|
+
writeMark(name) {
|
|
589
|
+
this.sendJson({ event: "mark", streamSid: this.call.streamId, mark: { name } });
|
|
590
|
+
}
|
|
591
|
+
sendJson(message) {
|
|
592
|
+
if (this.isOpen) this.socket.send(JSON.stringify(message));
|
|
593
|
+
}
|
|
594
|
+
};
|
|
595
|
+
function twilioStreamTwiml({
|
|
596
|
+
url,
|
|
597
|
+
parameters = {},
|
|
598
|
+
before = ""
|
|
599
|
+
}) {
|
|
600
|
+
const params = Object.entries(parameters).map(
|
|
601
|
+
([name, value]) => `<Parameter name="${escapeXml(name)}" value="${escapeXml(String(value))}" />`
|
|
602
|
+
).join("");
|
|
603
|
+
return `<?xml version="1.0" encoding="UTF-8"?><Response>${before}<Connect><Stream url="${escapeXml(url)}">${params}</Stream></Connect></Response>`;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// src/vonage.ts
|
|
607
|
+
var CALL_HEADERS = {
|
|
608
|
+
callId: "micdropCallId",
|
|
609
|
+
from: "micdropFrom",
|
|
610
|
+
to: "micdropTo"
|
|
611
|
+
};
|
|
612
|
+
var VonageTransport = class extends TelephonyTransport {
|
|
613
|
+
/**
|
|
614
|
+
* @param socket - The socket Vonage opened
|
|
615
|
+
* @param options - The rate of the NCCO, read again from the first message
|
|
616
|
+
*/
|
|
617
|
+
constructor(socket, options = {}) {
|
|
618
|
+
super(socket);
|
|
619
|
+
this.rate = options.sampleRate ?? 16e3;
|
|
620
|
+
}
|
|
621
|
+
get lineRate() {
|
|
622
|
+
return this.rate;
|
|
623
|
+
}
|
|
624
|
+
onProviderMessage(data, isBinary) {
|
|
625
|
+
if (isBinary) {
|
|
626
|
+
this.receiveAudio(data);
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
const message = parseJson(data);
|
|
630
|
+
switch (message?.event) {
|
|
631
|
+
case "websocket:connected": {
|
|
632
|
+
const { event, "content-type": contentType, ...headers } = message;
|
|
633
|
+
const rate = /rate=(\d+)/.exec(contentType ?? "")?.[1];
|
|
634
|
+
if (rate) this.rate = Number(rate);
|
|
635
|
+
const call = {
|
|
636
|
+
callId: headers[CALL_HEADERS.callId],
|
|
637
|
+
from: headers[CALL_HEADERS.from],
|
|
638
|
+
to: headers[CALL_HEADERS.to]
|
|
639
|
+
};
|
|
640
|
+
for (const key of Object.values(CALL_HEADERS)) delete headers[key];
|
|
641
|
+
delete headers.reconnect_attempt;
|
|
642
|
+
this.startStream(call, headers);
|
|
643
|
+
break;
|
|
644
|
+
}
|
|
645
|
+
case "websocket:notify":
|
|
646
|
+
this.markPlayed(message.payload?.micdropMark);
|
|
647
|
+
break;
|
|
648
|
+
case "websocket:dtmf":
|
|
649
|
+
this.receiveDtmf(String(message.digit));
|
|
650
|
+
break;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
writeAudio(pcm) {
|
|
654
|
+
if (this.isOpen) this.socket.send(pcm);
|
|
655
|
+
}
|
|
656
|
+
writeClear() {
|
|
657
|
+
this.sendJson({ action: "clear" });
|
|
658
|
+
}
|
|
659
|
+
writeMark(name) {
|
|
660
|
+
this.sendJson({ action: "notify", payload: { micdropMark: name } });
|
|
661
|
+
}
|
|
662
|
+
sendJson(message) {
|
|
663
|
+
if (this.isOpen) this.socket.send(JSON.stringify(message));
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
function vonageConnectNcco({
|
|
667
|
+
url,
|
|
668
|
+
parameters = {},
|
|
669
|
+
call,
|
|
670
|
+
sampleRate = 16e3,
|
|
671
|
+
eventUrl
|
|
672
|
+
}) {
|
|
673
|
+
const headers = { ...parameters };
|
|
674
|
+
if (call?.uuid) headers[CALL_HEADERS.callId] = call.uuid;
|
|
675
|
+
if (call?.from) headers[CALL_HEADERS.from] = call.from;
|
|
676
|
+
if (call?.to) headers[CALL_HEADERS.to] = call.to;
|
|
677
|
+
return [
|
|
678
|
+
{
|
|
679
|
+
action: "connect",
|
|
680
|
+
...eventUrl ? { eventUrl: [eventUrl] } : {},
|
|
681
|
+
endpoint: [
|
|
682
|
+
{
|
|
683
|
+
type: "websocket",
|
|
684
|
+
uri: url,
|
|
685
|
+
"content-type": `audio/l16;rate=${sampleRate}`,
|
|
686
|
+
headers
|
|
687
|
+
}
|
|
688
|
+
]
|
|
689
|
+
}
|
|
690
|
+
];
|
|
691
|
+
}
|
|
692
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
693
|
+
0 && (module.exports = {
|
|
694
|
+
PlivoTransport,
|
|
695
|
+
TelephonyTransport,
|
|
696
|
+
TelnyxTransport,
|
|
697
|
+
TwilioTransport,
|
|
698
|
+
VonageTransport,
|
|
699
|
+
alawToPcm16,
|
|
700
|
+
mulawToPcm16,
|
|
701
|
+
parseJson,
|
|
702
|
+
pcm16ToAlaw,
|
|
703
|
+
pcm16ToMulaw,
|
|
704
|
+
plivoStreamXml,
|
|
705
|
+
telnyxStreamOptions,
|
|
706
|
+
twilioStreamTwiml,
|
|
707
|
+
vonageConnectNcco
|
|
708
|
+
});
|
|
709
|
+
//# sourceMappingURL=index.js.map
|