@relaxwork/verto 0.0.0-stage → 1.0.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 +187 -2
- package/dist/base.d.ts +68 -0
- package/dist/index.d.ts +239 -0
- package/dist/index.js +663 -0
- package/dist/json-rpc.d.ts +157 -0
- package/dist/rtc.d.ts +88 -0
- package/package.json +40 -5
package/dist/index.js
ADDED
|
@@ -0,0 +1,663 @@
|
|
|
1
|
+
function generateGUID() {
|
|
2
|
+
const cryptoApi = globalThis.crypto;
|
|
3
|
+
if (cryptoApi?.randomUUID) return cryptoApi.randomUUID();
|
|
4
|
+
if (cryptoApi?.getRandomValues) {
|
|
5
|
+
const bytes = new Uint8Array(16);
|
|
6
|
+
cryptoApi.getRandomValues(bytes);
|
|
7
|
+
bytes[6] = 0x0f & bytes[6] | 0x40;
|
|
8
|
+
bytes[8] = 0x3f & bytes[8] | 0x80;
|
|
9
|
+
const hex = Array.from(bytes, (byte)=>byte.toString(16).padStart(2, '0'));
|
|
10
|
+
return [
|
|
11
|
+
hex.slice(0, 4).join(''),
|
|
12
|
+
hex.slice(4, 6).join(''),
|
|
13
|
+
hex.slice(6, 8).join(''),
|
|
14
|
+
hex.slice(8, 10).join(''),
|
|
15
|
+
hex.slice(10).join('')
|
|
16
|
+
].join('-');
|
|
17
|
+
}
|
|
18
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (token)=>{
|
|
19
|
+
const random = Math.floor(16 * Math.random());
|
|
20
|
+
const value = 'x' === token ? random : 0x3 & random | 0x8;
|
|
21
|
+
return value.toString(16);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
class VertoBase {
|
|
25
|
+
eventHandlers = new Map();
|
|
26
|
+
debug;
|
|
27
|
+
constructor(debug = false){
|
|
28
|
+
this.debug = debug;
|
|
29
|
+
}
|
|
30
|
+
subscribeEvent(name, handler) {
|
|
31
|
+
const id = generateGUID();
|
|
32
|
+
const handlers = this.eventHandlers.get(name) ?? new Map();
|
|
33
|
+
handlers.set(id, handler);
|
|
34
|
+
this.eventHandlers.set(name, handlers);
|
|
35
|
+
return id;
|
|
36
|
+
}
|
|
37
|
+
on(name, handler) {
|
|
38
|
+
return this.subscribeEvent(name, handler);
|
|
39
|
+
}
|
|
40
|
+
unsubscribeEvent(name, handlerId) {
|
|
41
|
+
if (!handlerId) return void this.eventHandlers.delete(name);
|
|
42
|
+
const handlers = this.eventHandlers.get(name);
|
|
43
|
+
handlers?.delete(handlerId);
|
|
44
|
+
if (handlers && 0 === handlers.size) this.eventHandlers.delete(name);
|
|
45
|
+
}
|
|
46
|
+
off(name, handlerId) {
|
|
47
|
+
this.unsubscribeEvent(name, handlerId);
|
|
48
|
+
}
|
|
49
|
+
dispatchEvent(name, data) {
|
|
50
|
+
if (this.debug) console.debug('[verto:event]', name, data);
|
|
51
|
+
const handlers = this.eventHandlers.get(name);
|
|
52
|
+
if (!handlers) return;
|
|
53
|
+
for (const handler of [
|
|
54
|
+
...handlers.values()
|
|
55
|
+
])handler(data);
|
|
56
|
+
}
|
|
57
|
+
removeAllListeners() {
|
|
58
|
+
this.eventHandlers.clear();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
class JsonRpcError extends Error {
|
|
62
|
+
code;
|
|
63
|
+
data;
|
|
64
|
+
constructor(payload){
|
|
65
|
+
super(payload.message ?? 'JSON-RPC request failed');
|
|
66
|
+
this.name = 'JsonRpcError';
|
|
67
|
+
this.code = payload.code;
|
|
68
|
+
this.data = payload.data;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const OPEN = 1;
|
|
72
|
+
function defaultSocketFactory(url) {
|
|
73
|
+
const Socket = globalThis.WebSocket;
|
|
74
|
+
if (!Socket) throw new Error('WebSocket is unavailable. Provide transportConfig.socketFactory in SSR or Node.');
|
|
75
|
+
return new Socket(url);
|
|
76
|
+
}
|
|
77
|
+
class JsonRpcClient extends VertoBase {
|
|
78
|
+
options;
|
|
79
|
+
pending = new Map();
|
|
80
|
+
queuedRequestIds = [];
|
|
81
|
+
requestId = 1;
|
|
82
|
+
socket;
|
|
83
|
+
reconnectTimer;
|
|
84
|
+
reconnectAttempts = 0;
|
|
85
|
+
hasConnected = false;
|
|
86
|
+
closed = false;
|
|
87
|
+
eventHandler;
|
|
88
|
+
reconnectHandler;
|
|
89
|
+
connectionWaiters = [];
|
|
90
|
+
constructor(options, debug = false){
|
|
91
|
+
super(debug);
|
|
92
|
+
this.options = {
|
|
93
|
+
reconnect: true,
|
|
94
|
+
reconnectDelay: 1000,
|
|
95
|
+
...options
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
setEventHandler(handler) {
|
|
99
|
+
this.eventHandler = handler;
|
|
100
|
+
}
|
|
101
|
+
setReconnectHandler(handler) {
|
|
102
|
+
this.reconnectHandler = handler;
|
|
103
|
+
}
|
|
104
|
+
connect() {
|
|
105
|
+
if (this.socket?.readyState === OPEN) return Promise.resolve();
|
|
106
|
+
return new Promise((resolve, reject)=>{
|
|
107
|
+
this.connectionWaiters.push({
|
|
108
|
+
resolve,
|
|
109
|
+
reject
|
|
110
|
+
});
|
|
111
|
+
try {
|
|
112
|
+
this.ensureSocket();
|
|
113
|
+
} catch (error) {
|
|
114
|
+
this.connectionWaiters.splice(this.connectionWaiters.length - 1, 1);
|
|
115
|
+
reject(error);
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
call(method, params = {}, success, failure) {
|
|
120
|
+
return this.createCall(method, params, success, failure, true);
|
|
121
|
+
}
|
|
122
|
+
createCall(method, params, success, failure, authRetryAllowed) {
|
|
123
|
+
const request = {
|
|
124
|
+
jsonrpc: '2.0',
|
|
125
|
+
method,
|
|
126
|
+
params,
|
|
127
|
+
id: this.requestId++
|
|
128
|
+
};
|
|
129
|
+
return new Promise((resolve, reject)=>{
|
|
130
|
+
this.pending.set(request.id, {
|
|
131
|
+
request,
|
|
132
|
+
resolve: resolve,
|
|
133
|
+
reject,
|
|
134
|
+
success: success,
|
|
135
|
+
failure,
|
|
136
|
+
authRetryAllowed,
|
|
137
|
+
authRetryInProgress: false
|
|
138
|
+
});
|
|
139
|
+
this.queuedRequestIds.push(request.id);
|
|
140
|
+
try {
|
|
141
|
+
this.ensureSocket();
|
|
142
|
+
this.flushQueue();
|
|
143
|
+
} catch (error) {
|
|
144
|
+
this.rejectRequest(request.id, error);
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
ensureSocket() {
|
|
149
|
+
if (this.closed) throw new Error('JSON-RPC client is closed');
|
|
150
|
+
if (this.socket && 3 !== this.socket.readyState) return;
|
|
151
|
+
const factory = this.options.socketFactory ?? defaultSocketFactory;
|
|
152
|
+
const socket = factory(this.options.socketUrl);
|
|
153
|
+
this.socket = socket;
|
|
154
|
+
socket.onopen = ()=>this.handleOpen();
|
|
155
|
+
socket.onmessage = (event)=>this.handleMessage(event);
|
|
156
|
+
socket.onerror = ()=>void 0;
|
|
157
|
+
socket.onclose = ()=>this.handleClose();
|
|
158
|
+
}
|
|
159
|
+
handleOpen() {
|
|
160
|
+
const wasReconnect = this.hasConnected;
|
|
161
|
+
this.hasConnected = true;
|
|
162
|
+
this.reconnectAttempts = 0;
|
|
163
|
+
if (wasReconnect) this.reconnectHandler?.();
|
|
164
|
+
for (const waiter of this.connectionWaiters.splice(0))waiter.resolve();
|
|
165
|
+
this.flushQueue();
|
|
166
|
+
}
|
|
167
|
+
flushQueue() {
|
|
168
|
+
if (this.socket?.readyState !== OPEN) return;
|
|
169
|
+
const requestIds = this.queuedRequestIds.splice(0);
|
|
170
|
+
for (const id of requestIds)this.sendRequest(id);
|
|
171
|
+
}
|
|
172
|
+
sendRequest(id) {
|
|
173
|
+
const pending = this.pending.get(id);
|
|
174
|
+
if (!pending) return;
|
|
175
|
+
if (this.socket?.readyState !== OPEN) return void this.queuedRequestIds.push(id);
|
|
176
|
+
try {
|
|
177
|
+
const raw = JSON.stringify(pending.request);
|
|
178
|
+
this.socket.send(raw);
|
|
179
|
+
if (this.debug) console.debug('[verto:send]', pending.request);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
this.rejectRequest(id, error);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
handleMessage(event) {
|
|
185
|
+
this.options.onmessage?.(event);
|
|
186
|
+
if ('string' != typeof event.data) return;
|
|
187
|
+
let response;
|
|
188
|
+
try {
|
|
189
|
+
const parsed = JSON.parse(event.data);
|
|
190
|
+
if (!parsed || 'object' != typeof parsed) return;
|
|
191
|
+
response = parsed;
|
|
192
|
+
} catch {
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if ('2.0' !== response.jsonrpc) return;
|
|
196
|
+
if (response.method) return void this.eventHandler?.(response.method, response.params ?? {});
|
|
197
|
+
if ('number' != typeof response.id) return;
|
|
198
|
+
const pending = this.pending.get(response.id);
|
|
199
|
+
if (!pending) return;
|
|
200
|
+
if ('result' in response) return void this.resolveRequest(response.id, response.result);
|
|
201
|
+
if (!response.error) return;
|
|
202
|
+
const error = new JsonRpcError(response.error);
|
|
203
|
+
if (-32000 === error.code && pending.authRetryAllowed && !pending.authRetryInProgress && this.options.login && this.options.passwd) {
|
|
204
|
+
pending.authRetryInProgress = true;
|
|
205
|
+
this.authenticateAndRetry(response.id);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
this.rejectRequest(response.id, error);
|
|
209
|
+
}
|
|
210
|
+
async authenticateAndRetry(id) {
|
|
211
|
+
try {
|
|
212
|
+
await this.createCall('login', {
|
|
213
|
+
login: this.options.login,
|
|
214
|
+
passwd: this.options.passwd,
|
|
215
|
+
loginParams: this.options.loginParams,
|
|
216
|
+
userVariables: this.options.userVariables
|
|
217
|
+
}, void 0, void 0, false);
|
|
218
|
+
const pending = this.pending.get(id);
|
|
219
|
+
if (pending) {
|
|
220
|
+
pending.authRetryInProgress = false;
|
|
221
|
+
this.sendRequest(id);
|
|
222
|
+
}
|
|
223
|
+
} catch (error) {
|
|
224
|
+
this.rejectRequest(id, error);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
resolveRequest(id, value) {
|
|
228
|
+
const pending = this.pending.get(id);
|
|
229
|
+
if (!pending) return;
|
|
230
|
+
this.pending.delete(id);
|
|
231
|
+
this.invoke(()=>pending.success?.(value));
|
|
232
|
+
pending.resolve(value);
|
|
233
|
+
}
|
|
234
|
+
rejectRequest(id, reason) {
|
|
235
|
+
const pending = this.pending.get(id);
|
|
236
|
+
if (!pending) return;
|
|
237
|
+
this.pending.delete(id);
|
|
238
|
+
const error = reason instanceof JsonRpcError ? reason : new JsonRpcError({
|
|
239
|
+
message: reason instanceof Error ? reason.message : String(reason)
|
|
240
|
+
});
|
|
241
|
+
this.invoke(()=>pending.failure?.(error));
|
|
242
|
+
pending.reject(error);
|
|
243
|
+
}
|
|
244
|
+
invoke(callback) {
|
|
245
|
+
try {
|
|
246
|
+
callback();
|
|
247
|
+
} catch (error) {
|
|
248
|
+
if (this.debug) console.error('[verto:callback]', error);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
handleClose() {
|
|
252
|
+
this.socket = void 0;
|
|
253
|
+
if (this.closed || false === this.options.reconnect) return;
|
|
254
|
+
const queued = new Set(this.queuedRequestIds);
|
|
255
|
+
for (const id of this.pending.keys())if (!queued.has(id)) this.queuedRequestIds.push(id);
|
|
256
|
+
const maxAttempts = this.options.maxReconnectAttempts ?? 1 / 0;
|
|
257
|
+
if (this.reconnectAttempts >= maxAttempts) {
|
|
258
|
+
for (const id of this.pending.keys())this.rejectRequest(id, new Error('WebSocket reconnect attempts exhausted'));
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
this.reconnectAttempts += 1;
|
|
262
|
+
const baseDelay = this.options.reconnectDelay ?? 1000;
|
|
263
|
+
const delay = Math.min(baseDelay * 2 ** (this.reconnectAttempts - 1), 30000);
|
|
264
|
+
this.reconnectTimer = setTimeout(()=>{
|
|
265
|
+
this.reconnectTimer = void 0;
|
|
266
|
+
try {
|
|
267
|
+
this.ensureSocket();
|
|
268
|
+
this.flushQueue();
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (this.debug) console.error('[verto:reconnect]', error);
|
|
271
|
+
this.handleClose();
|
|
272
|
+
}
|
|
273
|
+
}, delay);
|
|
274
|
+
}
|
|
275
|
+
close() {
|
|
276
|
+
this.closed = true;
|
|
277
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
278
|
+
this.reconnectTimer = void 0;
|
|
279
|
+
for (const id of this.pending.keys())this.rejectRequest(id, new Error('JSON-RPC client closed'));
|
|
280
|
+
this.queuedRequestIds.splice(0);
|
|
281
|
+
this.socket?.close(1000, 'Client closed');
|
|
282
|
+
this.socket = void 0;
|
|
283
|
+
this.eventHandler = void 0;
|
|
284
|
+
this.reconnectHandler = void 0;
|
|
285
|
+
for (const waiter of this.connectionWaiters.splice(0))waiter.reject(new Error('JSON-RPC client closed'));
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
var rtc_CallDirection = /*#__PURE__*/ function(CallDirection) {
|
|
289
|
+
CallDirection[CallDirection["Incoming"] = 0] = "Incoming";
|
|
290
|
+
CallDirection[CallDirection["Outgoing"] = 1] = "Outgoing";
|
|
291
|
+
return CallDirection;
|
|
292
|
+
}({});
|
|
293
|
+
function defaultPeerConnectionFactory(configuration) {
|
|
294
|
+
const PeerConnection = globalThis.RTCPeerConnection;
|
|
295
|
+
if (!PeerConnection) throw new Error('RTCPeerConnection is unavailable. Run Verto in a WebRTC-capable browser or provide peerConnectionFactory.');
|
|
296
|
+
return new PeerConnection(configuration);
|
|
297
|
+
}
|
|
298
|
+
class VertoRtc extends VertoBase {
|
|
299
|
+
peerConnection;
|
|
300
|
+
direction;
|
|
301
|
+
iceTimeout;
|
|
302
|
+
state = 'idle';
|
|
303
|
+
pendingOfferSdp;
|
|
304
|
+
negotiationInProgress = false;
|
|
305
|
+
constructor(configuration = {}, direction = 0, iceTimeout = 3000, debug = false, peerConnectionFactory){
|
|
306
|
+
super(debug);
|
|
307
|
+
this.direction = direction;
|
|
308
|
+
this.iceTimeout = Math.max(0, iceTimeout);
|
|
309
|
+
const factory = peerConnectionFactory ?? defaultPeerConnectionFactory;
|
|
310
|
+
this.peerConnection = factory({
|
|
311
|
+
...configuration,
|
|
312
|
+
iceCandidatePoolSize: configuration.iceCandidatePoolSize ?? 1
|
|
313
|
+
});
|
|
314
|
+
this.peerConnection.ontrack = (event)=>this.onTrack(event);
|
|
315
|
+
this.peerConnection.onnegotiationneeded = ()=>{
|
|
316
|
+
if (1 === this.direction) this.createOffer();
|
|
317
|
+
};
|
|
318
|
+
this.peerConnection.onicegatheringstatechange = ()=>void 0;
|
|
319
|
+
}
|
|
320
|
+
get connection() {
|
|
321
|
+
return this.peerConnection;
|
|
322
|
+
}
|
|
323
|
+
onTrack(event) {
|
|
324
|
+
this.dispatchEvent('track', event.track);
|
|
325
|
+
}
|
|
326
|
+
async createOffer() {
|
|
327
|
+
if (this.negotiationInProgress || 'closed' === this.state) return;
|
|
328
|
+
this.negotiationInProgress = true;
|
|
329
|
+
try {
|
|
330
|
+
const offer = await this.peerConnection.createOffer();
|
|
331
|
+
await this.peerConnection.setLocalDescription(offer);
|
|
332
|
+
await this.waitForIceGathering();
|
|
333
|
+
this.dispatchLocalDescription('send-offer');
|
|
334
|
+
} catch (error) {
|
|
335
|
+
this.emitError(error);
|
|
336
|
+
} finally{
|
|
337
|
+
this.negotiationInProgress = false;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
dispatchLocalDescription(event) {
|
|
341
|
+
const description = this.peerConnection.localDescription;
|
|
342
|
+
if (!description || 'closed' === this.state) return;
|
|
343
|
+
if ('sent' === this.state && 'send-offer' === event) return;
|
|
344
|
+
this.state = 'sent';
|
|
345
|
+
this.dispatchEvent(event, {
|
|
346
|
+
type: description.type,
|
|
347
|
+
sdp: description.sdp ?? void 0
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
waitForIceGathering() {
|
|
351
|
+
if ('complete' === this.peerConnection.iceGatheringState) return Promise.resolve();
|
|
352
|
+
return new Promise((resolve)=>{
|
|
353
|
+
const startedAt = Date.now();
|
|
354
|
+
const check = ()=>{
|
|
355
|
+
if ('complete' === this.peerConnection.iceGatheringState || Date.now() - startedAt >= this.iceTimeout) return void resolve();
|
|
356
|
+
setTimeout(check, 10);
|
|
357
|
+
};
|
|
358
|
+
check();
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
emitError(error) {
|
|
362
|
+
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
363
|
+
if (this.debug) console.error('[verto:rtc]', normalized);
|
|
364
|
+
this.dispatchEvent('error', normalized);
|
|
365
|
+
}
|
|
366
|
+
getStats() {
|
|
367
|
+
return this.peerConnection.getStats();
|
|
368
|
+
}
|
|
369
|
+
async onMedia(sdp) {
|
|
370
|
+
try {
|
|
371
|
+
await this.peerConnection.setRemoteDescription({
|
|
372
|
+
type: 'answer',
|
|
373
|
+
sdp
|
|
374
|
+
});
|
|
375
|
+
} catch (error) {
|
|
376
|
+
this.emitError(error);
|
|
377
|
+
throw error;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
preSdp(sdp) {
|
|
381
|
+
this.pendingOfferSdp = sdp;
|
|
382
|
+
}
|
|
383
|
+
addTrack(track) {
|
|
384
|
+
return this.peerConnection.addTrack(track);
|
|
385
|
+
}
|
|
386
|
+
async answer(tracks = []) {
|
|
387
|
+
if (!this.pendingOfferSdp) throw new Error('Cannot answer before an incoming SDP offer is provided.');
|
|
388
|
+
try {
|
|
389
|
+
for (const track of tracks)this.peerConnection.addTrack(track);
|
|
390
|
+
await this.peerConnection.setRemoteDescription({
|
|
391
|
+
type: 'offer',
|
|
392
|
+
sdp: this.pendingOfferSdp
|
|
393
|
+
});
|
|
394
|
+
const answer = await this.peerConnection.createAnswer();
|
|
395
|
+
await this.peerConnection.setLocalDescription(answer);
|
|
396
|
+
this.state = 'gathering';
|
|
397
|
+
await this.waitForIceGathering();
|
|
398
|
+
this.dispatchLocalDescription('send-answer');
|
|
399
|
+
} catch (error) {
|
|
400
|
+
this.emitError(error);
|
|
401
|
+
throw error;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
close() {
|
|
405
|
+
if ('closed' === this.state) return;
|
|
406
|
+
this.state = 'closed';
|
|
407
|
+
this.peerConnection.ontrack = null;
|
|
408
|
+
this.peerConnection.onnegotiationneeded = null;
|
|
409
|
+
this.peerConnection.onicegatheringstatechange = null;
|
|
410
|
+
this.peerConnection.close();
|
|
411
|
+
this.removeAllListeners();
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
const VertoMessage = {
|
|
415
|
+
Invite: 'verto.invite',
|
|
416
|
+
Answer: 'verto.answer',
|
|
417
|
+
Bye: 'verto.bye',
|
|
418
|
+
Media: 'verto.media',
|
|
419
|
+
Attach: 'verto.attach',
|
|
420
|
+
Modify: 'verto.modify',
|
|
421
|
+
Subscribe: 'verto.subscribe',
|
|
422
|
+
Unsubscribe: 'verto.unsubscribe',
|
|
423
|
+
Info: 'verto.info',
|
|
424
|
+
Display: 'verto.display',
|
|
425
|
+
ClientReady: 'verto.clientReady',
|
|
426
|
+
Broadcast: 'verto.broadcast'
|
|
427
|
+
};
|
|
428
|
+
function asString(value) {
|
|
429
|
+
return 'string' == typeof value ? value : void 0;
|
|
430
|
+
}
|
|
431
|
+
function normalizeError(error) {
|
|
432
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
433
|
+
}
|
|
434
|
+
class VertoCall extends VertoBase {
|
|
435
|
+
rtc;
|
|
436
|
+
rpc;
|
|
437
|
+
cleared = false;
|
|
438
|
+
id;
|
|
439
|
+
options;
|
|
440
|
+
direction;
|
|
441
|
+
holdStatus = false;
|
|
442
|
+
constructor(configuration = {}, rpc, destination, id = generateGUID(), options = {}, iceTimeout = 3000, debug = false, peerConnectionFactory){
|
|
443
|
+
super(debug);
|
|
444
|
+
this.id = id;
|
|
445
|
+
this.options = options;
|
|
446
|
+
this.direction = destination ? rtc_CallDirection.Outgoing : rtc_CallDirection.Incoming;
|
|
447
|
+
this.rpc = rpc;
|
|
448
|
+
this.rtc = new VertoRtc(configuration, this.direction, iceTimeout, debug, peerConnectionFactory);
|
|
449
|
+
this.rtc.on('send-offer', (description)=>{
|
|
450
|
+
this.sendSdp(VertoMessage.Invite, description.sdp, destination);
|
|
451
|
+
});
|
|
452
|
+
this.rtc.on('send-answer', (description)=>{
|
|
453
|
+
this.sendSdp(VertoMessage.Answer, description.sdp, destination);
|
|
454
|
+
});
|
|
455
|
+
this.rtc.on('track', (track)=>this.dispatchEvent('track', track));
|
|
456
|
+
this.rtc.on('error', (error)=>this.dispatchEvent('error', error));
|
|
457
|
+
}
|
|
458
|
+
async sendSdp(method, sdp, destination) {
|
|
459
|
+
try {
|
|
460
|
+
await this.rpc.call(method, {
|
|
461
|
+
dialogParams: {
|
|
462
|
+
...this.options,
|
|
463
|
+
destination_number: destination,
|
|
464
|
+
callID: this.id
|
|
465
|
+
},
|
|
466
|
+
sdp
|
|
467
|
+
});
|
|
468
|
+
} catch (error) {
|
|
469
|
+
this.dispatchEvent('error', normalizeError(error));
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
getStats() {
|
|
473
|
+
return this.rtc.getStats();
|
|
474
|
+
}
|
|
475
|
+
async onAnswer(sdp) {
|
|
476
|
+
if (sdp) await this.rtc.onMedia(sdp);
|
|
477
|
+
this.dispatchEvent('answer', void 0);
|
|
478
|
+
}
|
|
479
|
+
async onMedia(sdp) {
|
|
480
|
+
if (sdp) await this.rtc.onMedia(sdp);
|
|
481
|
+
this.dispatchEvent('media', void 0);
|
|
482
|
+
}
|
|
483
|
+
addTrack(track) {
|
|
484
|
+
return this.rtc.addTrack(track);
|
|
485
|
+
}
|
|
486
|
+
preSdp(sdp) {
|
|
487
|
+
this.rtc.preSdp(sdp);
|
|
488
|
+
}
|
|
489
|
+
answer(tracks = []) {
|
|
490
|
+
return this.rtc.answer(tracks);
|
|
491
|
+
}
|
|
492
|
+
async hangup(params = {}) {
|
|
493
|
+
try {
|
|
494
|
+
await this.rpc.call(VertoMessage.Bye, {
|
|
495
|
+
dialogParams: {
|
|
496
|
+
callID: this.id
|
|
497
|
+
},
|
|
498
|
+
...params
|
|
499
|
+
});
|
|
500
|
+
} finally{
|
|
501
|
+
this.clear();
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
clear() {
|
|
505
|
+
if (this.cleared) return;
|
|
506
|
+
this.cleared = true;
|
|
507
|
+
this.rtc.close();
|
|
508
|
+
this.dispatchEvent('bye', this);
|
|
509
|
+
}
|
|
510
|
+
dtmf(input) {
|
|
511
|
+
return this.rpc.call(VertoMessage.Info, {
|
|
512
|
+
dtmf: String(input),
|
|
513
|
+
dialogParams: {
|
|
514
|
+
callID: this.id
|
|
515
|
+
}
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
hold(params = {}) {
|
|
519
|
+
return this.modifyHold('hold', params);
|
|
520
|
+
}
|
|
521
|
+
unhold(params = {}) {
|
|
522
|
+
return this.modifyHold('unhold', params);
|
|
523
|
+
}
|
|
524
|
+
toggleHold(params = {}) {
|
|
525
|
+
return this.modifyHold('toggleHold', params);
|
|
526
|
+
}
|
|
527
|
+
async modifyHold(action, params) {
|
|
528
|
+
try {
|
|
529
|
+
const response = await this.rpc.call(VertoMessage.Modify, {
|
|
530
|
+
action,
|
|
531
|
+
dialogParams: {
|
|
532
|
+
callID: this.id,
|
|
533
|
+
...this.options,
|
|
534
|
+
...params
|
|
535
|
+
}
|
|
536
|
+
});
|
|
537
|
+
this.holdStatus = 'held' === response.holdState;
|
|
538
|
+
this.dispatchEvent(this.holdStatus ? 'hold' : 'unhold', this);
|
|
539
|
+
return response;
|
|
540
|
+
} catch (error) {
|
|
541
|
+
const normalized = normalizeError(error);
|
|
542
|
+
this.dispatchEvent('error', normalized);
|
|
543
|
+
throw normalized;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
class Verto extends VertoBase {
|
|
548
|
+
calls = new Map();
|
|
549
|
+
rpc;
|
|
550
|
+
options;
|
|
551
|
+
loggedIn = false;
|
|
552
|
+
currentSessionId;
|
|
553
|
+
constructor(options){
|
|
554
|
+
super(options.debug ?? false);
|
|
555
|
+
this.options = {
|
|
556
|
+
...options,
|
|
557
|
+
rtcConfig: {
|
|
558
|
+
...options.rtcConfig
|
|
559
|
+
},
|
|
560
|
+
iceTimeout: options.iceTimeout ?? options.ice_timeout ?? 3000
|
|
561
|
+
};
|
|
562
|
+
this.rpc = new JsonRpcClient(options.transportConfig, options.debug ?? false);
|
|
563
|
+
this.rpc.setEventHandler((method, params)=>this.handleMessage(method, params));
|
|
564
|
+
this.rpc.setReconnectHandler(()=>{
|
|
565
|
+
if (this.loggedIn) this.login();
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
handleMessage(method, params) {
|
|
569
|
+
this.dispatchEvent('message', {
|
|
570
|
+
method,
|
|
571
|
+
params
|
|
572
|
+
});
|
|
573
|
+
const callId = asString(params.callID);
|
|
574
|
+
if (!callId && method !== VertoMessage.Invite) return;
|
|
575
|
+
switch(method){
|
|
576
|
+
case VertoMessage.Answer:
|
|
577
|
+
{
|
|
578
|
+
const call = callId ? this.calls.get(callId) : void 0;
|
|
579
|
+
if (call) call.onAnswer(asString(params.sdp)).catch((error)=>call.dispatchEvent('error', normalizeError(error)));
|
|
580
|
+
break;
|
|
581
|
+
}
|
|
582
|
+
case VertoMessage.Media:
|
|
583
|
+
{
|
|
584
|
+
const call = callId ? this.calls.get(callId) : void 0;
|
|
585
|
+
if (call) call.onMedia(asString(params.sdp)).catch((error)=>call.dispatchEvent('error', normalizeError(error)));
|
|
586
|
+
break;
|
|
587
|
+
}
|
|
588
|
+
case VertoMessage.Invite:
|
|
589
|
+
{
|
|
590
|
+
const inviteId = asString(params.callID);
|
|
591
|
+
const sdp = asString(params.sdp);
|
|
592
|
+
if (!inviteId || !sdp) return;
|
|
593
|
+
const call = new VertoCall(this.options.rtcConfig, this.rpc, void 0, inviteId, {
|
|
594
|
+
caller_id_name: asString(params.caller_id_name),
|
|
595
|
+
caller_id_number: asString(params.caller_id_number)
|
|
596
|
+
}, this.options.iceTimeout, this.options.debug, this.options.peerConnectionFactory);
|
|
597
|
+
call.preSdp(sdp);
|
|
598
|
+
this.registerCall(call);
|
|
599
|
+
this.dispatchEvent('invite', call);
|
|
600
|
+
break;
|
|
601
|
+
}
|
|
602
|
+
case VertoMessage.Bye:
|
|
603
|
+
{
|
|
604
|
+
const call = callId ? this.calls.get(callId) : void 0;
|
|
605
|
+
call?.clear();
|
|
606
|
+
if (callId) this.calls.delete(callId);
|
|
607
|
+
break;
|
|
608
|
+
}
|
|
609
|
+
default:
|
|
610
|
+
break;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
login() {
|
|
614
|
+
return this.rpc.call('login', {
|
|
615
|
+
login: this.options.transportConfig.login,
|
|
616
|
+
passwd: this.options.transportConfig.passwd,
|
|
617
|
+
loginParams: this.options.transportConfig.loginParams,
|
|
618
|
+
userVariables: this.options.transportConfig.userVariables
|
|
619
|
+
}).then((data)=>{
|
|
620
|
+
this.currentSessionId = asString(data.sessid);
|
|
621
|
+
this.loggedIn = true;
|
|
622
|
+
return data;
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
call(tracks, destination, options = {}) {
|
|
626
|
+
const call = new VertoCall(this.options.rtcConfig, this.rpc, destination, generateGUID(), options, this.options.iceTimeout, this.options.debug, this.options.peerConnectionFactory);
|
|
627
|
+
for (const track of tracks)call.addTrack(track);
|
|
628
|
+
this.registerCall(call);
|
|
629
|
+
return call;
|
|
630
|
+
}
|
|
631
|
+
registerCall(call) {
|
|
632
|
+
this.calls.set(call.id, call);
|
|
633
|
+
call.on('bye', ()=>{
|
|
634
|
+
if (this.calls.get(call.id) === call) this.calls.delete(call.id);
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
getCall(id) {
|
|
638
|
+
return this.calls.get(id);
|
|
639
|
+
}
|
|
640
|
+
get activeCalls() {
|
|
641
|
+
return [
|
|
642
|
+
...this.calls.values()
|
|
643
|
+
];
|
|
644
|
+
}
|
|
645
|
+
isLogged() {
|
|
646
|
+
return this.loggedIn;
|
|
647
|
+
}
|
|
648
|
+
get sessionId() {
|
|
649
|
+
return this.currentSessionId;
|
|
650
|
+
}
|
|
651
|
+
logout() {
|
|
652
|
+
for (const call of this.calls.values())call.hangup().catch(()=>void 0);
|
|
653
|
+
this.calls.clear();
|
|
654
|
+
this.rpc.close();
|
|
655
|
+
this.currentSessionId = void 0;
|
|
656
|
+
this.loggedIn = false;
|
|
657
|
+
}
|
|
658
|
+
destroy() {
|
|
659
|
+
this.logout();
|
|
660
|
+
this.removeAllListeners();
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
export { JsonRpcClient, JsonRpcError, Verto, VertoBase, VertoCall, VertoMessage, VertoRtc, generateGUID, rtc_CallDirection as CallDirection };
|