node-datachannel 0.6.0 → 0.7.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.
@@ -0,0 +1,1069 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var DOMException = require('node-domexception');
6
+ var module$1 = require('module');
7
+ var stream = require('stream');
8
+
9
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
10
+ class RTCCertificate {
11
+ #expires;
12
+ #fingerprints;
13
+
14
+ constructor() {
15
+ this.#expires = null;
16
+ this.#fingerprints = [];
17
+ }
18
+
19
+ get expires() {
20
+ return this.#expires;
21
+ }
22
+
23
+ getFingerprints() {
24
+ return this.#fingerprints;
25
+ }
26
+ }
27
+
28
+ class _RTCDataChannel extends EventTarget {
29
+ #dataChannel;
30
+ #readyState;
31
+ #bufferedAmountLowThreshold;
32
+ #binaryType;
33
+ #maxPacketLifeTime;
34
+ #maxRetransmits;
35
+ #negotiated;
36
+ #ordered;
37
+
38
+ onbufferedamountlow;
39
+ onclose;
40
+ onclosing;
41
+ onerror;
42
+ onmessage;
43
+ onopen;
44
+
45
+ constructor(dataChannel, opts = {}) {
46
+ super();
47
+
48
+ this.#dataChannel = dataChannel;
49
+ this.#binaryType = 'arraybuffer';
50
+ this.#readyState = this.#dataChannel.isOpen() ? 'open' : 'connecting';
51
+ this.#bufferedAmountLowThreshold = 0;
52
+ this.#maxPacketLifeTime = opts.maxPacketLifeTime || null;
53
+ this.#maxRetransmits = opts.maxRetransmits || null;
54
+ this.#negotiated = opts.negotiated || false;
55
+ this.#ordered = opts.ordered || true;
56
+
57
+ // forward dataChannel events
58
+ this.#dataChannel.onOpen(() => {
59
+ this.#readyState = 'open';
60
+ this.dispatchEvent(new Event('open'));
61
+ });
62
+
63
+ this.#dataChannel.onClosed(() => {
64
+ this.#readyState = 'closed';
65
+ this.dispatchEvent(new Event('close'));
66
+ });
67
+
68
+ this.#dataChannel.onError((msg) => {
69
+ this.dispatchEvent(
70
+ new RTCErrorEvent('error', {
71
+ error: new RTCError(
72
+ {
73
+ errorDetail: 'data-channel-failure',
74
+ },
75
+ msg,
76
+ ),
77
+ }),
78
+ );
79
+ });
80
+
81
+ this.#dataChannel.onBufferedAmountLow(() => {
82
+ this.dispatchEvent(new Event('bufferedamountlow'));
83
+ });
84
+
85
+ this.#dataChannel.onMessage((data) => {
86
+ if (ArrayBuffer.isView(data)) {
87
+ data = data.buffer;
88
+ }
89
+
90
+ this.dispatchEvent(new MessageEvent('message', { data }));
91
+ });
92
+
93
+ // forward events to properties
94
+ this.addEventListener('message', (e) => {
95
+ if (this.onmessage) this.onmessage(e);
96
+ });
97
+ this.addEventListener('bufferedamountlow', (e) => {
98
+ if (this.onbufferedamountlow) this.onbufferedamountlow(e);
99
+ });
100
+ this.addEventListener('error', (e) => {
101
+ if (this.onerror) this.onerror(e);
102
+ });
103
+ this.addEventListener('close', (e) => {
104
+ if (this.onclose) this.onclose(e);
105
+ });
106
+ this.addEventListener('closing', (e) => {
107
+ if (this.onclosing) this.onclosing(e);
108
+ });
109
+ this.addEventListener('open', (e) => {
110
+ if (this.onopen) this.onopen(e);
111
+ });
112
+ }
113
+
114
+ set binaryType(type) {
115
+ if (type !== 'blob' && type !== 'arraybuffer') {
116
+ throw new DOMException(
117
+ "Failed to set the 'binaryType' property on 'RTCDataChannel': Unknown binary type : " + type,
118
+ 'TypeMismatchError',
119
+ );
120
+ }
121
+ this.#binaryType = type;
122
+ }
123
+
124
+ get binaryType() {
125
+ return this.#binaryType;
126
+ }
127
+
128
+ get bufferedAmount() {
129
+ return this.#dataChannel.bufferedAmount();
130
+ }
131
+
132
+ get bufferedAmountLowThreshold() {
133
+ return this.#bufferedAmountLowThreshold;
134
+ }
135
+
136
+ set bufferedAmountLowThreshold(value) {
137
+ const number = Number(value) || 0;
138
+ this.#bufferedAmountLowThreshold = number;
139
+ this.#dataChannel.setBufferedAmountLowThreshold(number);
140
+ }
141
+
142
+ get id() {
143
+ return this.#dataChannel.getId();
144
+ }
145
+
146
+ get label() {
147
+ return this.#dataChannel.getLabel();
148
+ }
149
+
150
+ get maxPacketLifeTime() {
151
+ return this.#maxPacketLifeTime;
152
+ }
153
+
154
+ get maxRetransmits() {
155
+ return this.#maxRetransmits;
156
+ }
157
+
158
+ get negotiated() {
159
+ return this.#negotiated;
160
+ }
161
+
162
+ get ordered() {
163
+ return this.#ordered;
164
+ }
165
+
166
+ get protocol() {
167
+ return this.#dataChannel.getProtocol();
168
+ }
169
+
170
+ get readyState() {
171
+ return this.#readyState;
172
+ }
173
+
174
+ send(data) {
175
+ if (this.#readyState !== 'open') {
176
+ throw new DOMException(
177
+ "Failed to execute 'send' on 'RTCDataChannel': RTCDataChannel.readyState is not 'open'",
178
+ 'InvalidStateError',
179
+ );
180
+ }
181
+
182
+ // Needs network error, type error implemented
183
+ if (typeof data === 'string') {
184
+ this.#dataChannel.sendMessage(data);
185
+ } else if (data instanceof Blob) {
186
+ data.arrayBuffer().then((ab) => {
187
+ this.#dataChannel.sendMessageBinary(new Uint8Array(ab));
188
+ });
189
+ } else {
190
+ this.#dataChannel.sendMessageBinary(new Uint8Array(data));
191
+ }
192
+ }
193
+
194
+ close() {
195
+ this.#readyState = 'closing';
196
+ this.dispatchEvent(new Event('closing'));
197
+
198
+ this.#dataChannel.close();
199
+ }
200
+ }
201
+
202
+ // https://developer.mozilla.org/docs/Web/API/RTCIceCandidate
203
+ //
204
+ // Example: candidate:123456 1 UDP 123456 192.168.1.1 12345 typ host raddr=10.0.0.1 rport=54321 generation 0
205
+
206
+
207
+ class _RTCIceCandidate {
208
+ #address;
209
+ #candidate;
210
+ #component;
211
+ #foundation;
212
+ #port;
213
+ #priority;
214
+ #protocol;
215
+ #relatedAddress;
216
+ #relatedPort;
217
+ #sdpMLineIndex;
218
+ #sdpMid;
219
+ #tcpType;
220
+ #type;
221
+ #usernameFragment;
222
+ #ip;
223
+
224
+ constructor({ candidate, sdpMLineIndex, sdpMid, usernameFragment }) {
225
+ if (candidate == null) {
226
+ throw new DOMException('candidate must be specified');
227
+ }
228
+
229
+ this.#candidate = candidate;
230
+ this.#sdpMLineIndex = sdpMLineIndex || null;
231
+ this.#sdpMid = sdpMid || null;
232
+ this.#usernameFragment = usernameFragment || null;
233
+
234
+ if (candidate) {
235
+ const fields = candidate.split(' ');
236
+ this.#foundation = fields[0];
237
+ this.#component = fields[1] == '1' ? 'rtp' : 'rtcp';
238
+ this.#protocol = fields[2];
239
+ this.#priority = parseInt(fields[3], 10);
240
+ this.#ip = fields[4];
241
+ this.#port = parseInt(fields[5], 10);
242
+ this.#type = fields[7];
243
+ if (fields[6] === 'typ') {
244
+ this.#tcpType = null;
245
+ } else if (fields[6] === 'tcp') {
246
+ this.#tcpType = fields[7];
247
+ this.#type = fields[8];
248
+ }
249
+
250
+ // Parse the candidate string to extract relatedPort and relatedAddress
251
+ for (let i = 9; i < fields.length; i++) {
252
+ const field = fields[i];
253
+ if (field.startsWith('raddr')) {
254
+ this.#relatedAddress = field.split('=')[1];
255
+ } else if (field.startsWith('rport')) {
256
+ this.#relatedPort = parseInt(field.split('=')[1], 10);
257
+ }
258
+ }
259
+ }
260
+ }
261
+
262
+ get address() {
263
+ return this.#address || null;
264
+ }
265
+
266
+ get candidate() {
267
+ return this.#candidate || '';
268
+ }
269
+
270
+ get component() {
271
+ return this.#component;
272
+ }
273
+
274
+ get foundation() {
275
+ return this.#foundation || null;
276
+ }
277
+
278
+ get port() {
279
+ return this.#port || null;
280
+ }
281
+
282
+ get priority() {
283
+ return this.#priority || null;
284
+ }
285
+
286
+ get protocol() {
287
+ return this.#protocol || null;
288
+ }
289
+
290
+ get relatedAddress() {
291
+ return this.#relatedAddress;
292
+ }
293
+
294
+ get relatedPort() {
295
+ return this.#relatedPort || null;
296
+ }
297
+
298
+ get sdpMLineIndex() {
299
+ return this.#sdpMLineIndex;
300
+ }
301
+
302
+ get sdpMid() {
303
+ return this.#sdpMid;
304
+ }
305
+
306
+ get tcpType() {
307
+ return this.#tcpType;
308
+ }
309
+
310
+ get type() {
311
+ return this.#type || null;
312
+ }
313
+
314
+ get usernameFragment() {
315
+ return this.#usernameFragment;
316
+ }
317
+
318
+ toJSON() {
319
+ return {
320
+ candidate: this.#candidate,
321
+ sdpMLineIndex: this.#sdpMLineIndex,
322
+ sdpMid: this.#sdpMid,
323
+ usernameFragment: this.#usernameFragment,
324
+ };
325
+ }
326
+ }
327
+
328
+ class _RTCIceTransport extends EventTarget {
329
+ #pc = null;
330
+ #extraFunctions = null;
331
+
332
+ ongatheringstatechange = null;
333
+ onselectedcandidatepairchange = null;
334
+ onstatechange = null;
335
+
336
+ constructor({ pc, extraFunctions }) {
337
+ super();
338
+ this.#pc = pc;
339
+ this.#extraFunctions = extraFunctions;
340
+
341
+ // forward peerConnection events
342
+ this.#pc.addEventListener('icegatheringstatechange', () => {
343
+ this.dispatchEvent(new Event('gatheringstatechange'));
344
+ });
345
+ this.#pc.addEventListener('iceconnectionstatechange', () => {
346
+ this.dispatchEvent(new Event('statechange'));
347
+ });
348
+
349
+ // forward events to properties
350
+ this.addEventListener('gatheringstatechange', (e) => {
351
+ if (this.ongatheringstatechange) this.ongatheringstatechange(e);
352
+ });
353
+ this.addEventListener('statechange', (e) => {
354
+ if (this.onstatechange) this.onstatechange(e);
355
+ });
356
+ }
357
+
358
+ get component() {
359
+ let cp = this.getSelectedCandidatePair();
360
+ if (!cp) return null;
361
+ return cp.local.component;
362
+ }
363
+
364
+ get gatheringState() {
365
+ return this.#pc ? this.#pc.iceGatheringState : 'new';
366
+ }
367
+
368
+ get role() {
369
+ return this.#pc.localDescription.type == 'offer' ? 'controlling' : 'controlled';
370
+ }
371
+
372
+ get state() {
373
+ return this.#pc ? this.#pc.iceConnectionState : 'new';
374
+ }
375
+
376
+ getLocalCandidates() {
377
+ return this.#pc ? this.#extraFunctions.localCandidates() : [];
378
+ }
379
+
380
+ getLocalParameters() {
381
+ /** */
382
+ }
383
+
384
+ getRemoteCandidates() {
385
+ return this.#pc ? this.#extraFunctions.remoteCandidates() : [];
386
+ }
387
+
388
+ getRemoteParameters() {
389
+ /** */
390
+ }
391
+
392
+ getSelectedCandidatePair() {
393
+ let cp = this.#extraFunctions.selectedCandidatePair();
394
+ if (!cp) return null;
395
+ return {
396
+ local: new _RTCIceCandidate({
397
+ candidate: cp.local.candidate,
398
+ sdpMid: cp.local.mid,
399
+ }),
400
+ remote: new _RTCIceCandidate({
401
+ candidate: cp.remote.candidate,
402
+ sdpMid: cp.remote.mid,
403
+ }),
404
+ };
405
+ }
406
+ }
407
+
408
+ class _RTCDtlsTransport extends EventTarget {
409
+ #pc = null;
410
+ #extraFunctions = null;
411
+ #iceTransport = null;
412
+
413
+ onerror = null;
414
+ onstatechange = null;
415
+
416
+ constructor({ pc, extraFunctions }) {
417
+ super();
418
+ this.#pc = pc;
419
+ this.#extraFunctions = extraFunctions;
420
+
421
+ this.#iceTransport = new _RTCIceTransport({ pc, extraFunctions });
422
+
423
+ // forward peerConnection events
424
+ this.#pc.addEventListener('connectionstatechange', () => {
425
+ this.dispatchEvent(new Event('statechange'));
426
+ });
427
+
428
+ // forward events to properties
429
+ this.addEventListener('statechange', (e) => {
430
+ if (this.onstatechange) this.onstatechange(e);
431
+ });
432
+ }
433
+
434
+ get iceTransport() {
435
+ return this.#iceTransport;
436
+ }
437
+
438
+ get state() {
439
+ // reduce state from new, connecting, connected, disconnected, failed, closed, unknown
440
+ // to RTCDtlsTRansport states new, connecting, connected, closed, failed
441
+ let state = this.#pc ? this.#pc.connectionState : 'new';
442
+ if (state === 'disconnected' || state === 'unknown') {
443
+ state = 'closed';
444
+ }
445
+ return state;
446
+ }
447
+
448
+ getRemoteCertificates() {
449
+ // TODO: implement
450
+ return new ArrayBuffer(0);
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Turns a node-datachannel DataChannel into a real Node.js stream, complete with buffering,
456
+ * backpressure (up to a point - if the buffer fills up, messages are dropped), and
457
+ * support for piping data elsewhere.
458
+ *
459
+ * Read & written data may be either UTF-8 strings or Buffers - this difference exists at
460
+ * the protocol level, and is preserved here throughout.
461
+ */
462
+ class DataChannelStream extends stream.Duplex {
463
+ constructor(rawChannel, streamOptions) {
464
+ super({
465
+ allowHalfOpen: false, // Default to autoclose on end().
466
+ ...streamOptions,
467
+ objectMode: true, // Preserve the string/buffer distinction (WebRTC treats them differently)
468
+ });
469
+
470
+ this._rawChannel = rawChannel;
471
+ this._readActive = true;
472
+
473
+ rawChannel.onMessage((msg) => {
474
+ if (!this._readActive) return; // If the buffer is full, drop messages.
475
+
476
+ // If the push is rejected, we pause reading until the next call to _read().
477
+ this._readActive = this.push(msg);
478
+ });
479
+
480
+ // When the DataChannel closes, the readable & writable ends close
481
+ rawChannel.onClosed(() => {
482
+ this.push(null);
483
+ this.destroy();
484
+ });
485
+
486
+ rawChannel.onError((errMsg) => {
487
+ this.destroy(new Error(`DataChannel error: ${errMsg}`));
488
+ });
489
+
490
+ // Buffer all writes until the DataChannel opens
491
+ if (!rawChannel.isOpen()) {
492
+ this.cork();
493
+ rawChannel.onOpen(() => this.uncork());
494
+ }
495
+ }
496
+
497
+ _read() {
498
+ // Stop dropping messages, if the buffer filling up meant we were doing so before.
499
+ this._readActive = true;
500
+ }
501
+
502
+ _write(chunk, encoding, callback) {
503
+ let sentOk;
504
+
505
+ try {
506
+ if (Buffer.isBuffer(chunk)) {
507
+ sentOk = this._rawChannel.sendMessageBinary(chunk);
508
+ } else if (typeof chunk === 'string') {
509
+ sentOk = this._rawChannel.sendMessage(chunk);
510
+ } else {
511
+ const typeName = chunk.constructor.name || typeof chunk;
512
+ throw new Error(`Cannot write ${typeName} to DataChannel stream`);
513
+ }
514
+ } catch (err) {
515
+ return callback(err);
516
+ }
517
+
518
+ if (sentOk) {
519
+ callback(null);
520
+ } else {
521
+ callback(new Error('Failed to write to DataChannel'));
522
+ }
523
+ }
524
+
525
+ _final(callback) {
526
+ if (!this.allowHalfOpen) this.destroy();
527
+ callback(null);
528
+ }
529
+
530
+ _destroy(maybeErr, callback) {
531
+ // When the stream is destroyed, we close the DataChannel.
532
+ this._rawChannel.close();
533
+ callback(maybeErr);
534
+ }
535
+
536
+ get label() {
537
+ return this._rawChannel.getLabel();
538
+ }
539
+
540
+ get id() {
541
+ return this._rawChannel.getId();
542
+ }
543
+
544
+ get protocol() {
545
+ return this._rawChannel.getProtocol();
546
+ }
547
+ }
548
+
549
+ // createRequire is native in node version >= 12
550
+ const require$1 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('polyfill.cjs', document.baseURI).href)));
551
+
552
+ const nodeDataChannel = require$1('../build/Release/node_datachannel.node');
553
+
554
+ var NodeDataChannel = {
555
+ ...nodeDataChannel,
556
+ DataChannelStream,
557
+ };
558
+
559
+ // https://developer.mozilla.org/docs/Web/API/RTCSessionDescription
560
+ //
561
+ // Example usage
562
+ // const init = {
563
+ // type: 'offer',
564
+ // sdp: 'v=0\r\no=- 1234567890 1234567890 IN IP4 192.168.1.1\r\ns=-\r\nt=0 0\r\na=ice-ufrag:abcd\r\na=ice-pwd:efgh\r\n'
565
+ // };
566
+
567
+ class _RTCSessionDescription {
568
+ #type;
569
+ #sdp;
570
+
571
+ constructor(init = {}) {
572
+ // Allow Empty Constructor
573
+ // if (!init || !init.type || !init.sdp) {
574
+ // throw new DOMException('Type and sdp properties are required.');
575
+ // }
576
+
577
+ this.#type = init ? init.type : null;
578
+ this.#sdp = init ? init.sdp : null;
579
+ }
580
+
581
+ get type() {
582
+ return this.#type;
583
+ }
584
+
585
+ get sdp() {
586
+ return this.#sdp;
587
+ }
588
+
589
+ toJSON() {
590
+ return {
591
+ sdp: this.#sdp,
592
+ type: this.#type,
593
+ };
594
+ }
595
+ }
596
+
597
+ class RTCPeerConnectionIceEvent extends Event {
598
+ #candidate;
599
+
600
+ constructor(candidate) {
601
+ super('icecandidate');
602
+
603
+ this.#candidate = candidate;
604
+ }
605
+
606
+ get candidate() {
607
+ return this.#candidate;
608
+ }
609
+ }
610
+
611
+ class RTCDataChannelEvent extends Event {
612
+ #channel;
613
+
614
+ constructor(channel) {
615
+ super('datachannel');
616
+
617
+ this.#channel = channel;
618
+ }
619
+
620
+ get channel() {
621
+ return this.#channel;
622
+ }
623
+ }
624
+
625
+ class _RTCSctpTransport extends EventTarget {
626
+ #pc = null;
627
+ #extraFunctions = null;
628
+ #transport = null;
629
+
630
+ onstatechange = null;
631
+
632
+ constructor({ pc, extraFunctions }) {
633
+ super();
634
+ this.#pc = pc;
635
+ this.#extraFunctions = extraFunctions;
636
+
637
+ this.#transport = new _RTCDtlsTransport({ pc, extraFunctions });
638
+
639
+ // forward peerConnection events
640
+ this.#pc.addEventListener('connectionstatechange', () => {
641
+ this.dispatchEvent(new Event('statechange'));
642
+ });
643
+
644
+ // forward events to properties
645
+ this.addEventListener('statechange', (e) => {
646
+ if (this.onstatechange) this.onstatechange(e);
647
+ });
648
+ }
649
+
650
+ get maxChannels() {
651
+ if (this.state !== 'connected') return null;
652
+ return this.#pc ? this.#extraFunctions.maxDataChannelId() : 0;
653
+ }
654
+
655
+ get maxMessageSize() {
656
+ if (this.state !== 'connected') return null;
657
+ return this.#pc ? this.#extraFunctions.maxMessageSize() : 0;
658
+ }
659
+
660
+ get state() {
661
+ // reduce state from new, connecting, connected, disconnected, failed, closed, unknown
662
+ // to RTCSctpTransport states connecting, connected, closed
663
+ let state = this.#pc.connectionState;
664
+ if (state === 'new' || state === 'connecting') {
665
+ state = 'connecting';
666
+ } else if (state === 'disconnected' || state === 'failed' || state === 'closed' || state === 'unknown') {
667
+ state = 'closed';
668
+ }
669
+ return state;
670
+ }
671
+
672
+ get transport() {
673
+ return this.#transport;
674
+ }
675
+ }
676
+
677
+ class _RTCPeerConnection extends EventTarget {
678
+ static async generateCertificate() {
679
+ throw new Error('Not implemented');
680
+ }
681
+
682
+ #peerConnection;
683
+ #localOffer;
684
+ #localAnswer;
685
+ #dataChannels;
686
+ #config;
687
+ #canTrickleIceCandidates;
688
+ #sctp;
689
+
690
+ #localCandidates = [];
691
+ #remoteCandidates = [];
692
+
693
+ onconnectionstatechange;
694
+ ondatachannel;
695
+ onicecandidate;
696
+ onicecandidateerror;
697
+ oniceconnectionstatechange;
698
+ onicegatheringstatechange;
699
+ onnegotiationneeded;
700
+ onsignalingstatechange;
701
+ ontrack;
702
+
703
+ constructor(init = {}) {
704
+ super();
705
+
706
+ this.#config = init;
707
+ this.#localOffer = createDeferredPromise();
708
+ this.#localAnswer = createDeferredPromise();
709
+ this.#dataChannels = new Set();
710
+ this.#canTrickleIceCandidates = null;
711
+
712
+ this.#peerConnection = new NodeDataChannel.PeerConnection(init?.peerIdentity ?? `peer-${getRandomString(7)}`, {
713
+ ...init,
714
+ iceServers:
715
+ init?.iceServers
716
+ ?.map((server) => {
717
+ const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
718
+
719
+ return urls.map((url) => {
720
+ if (server.username && server.credential) {
721
+ const [protocol, rest] = url.split(/:(.*)/);
722
+ return `${protocol}:${server.username}:${server.credential}@${rest}`;
723
+ }
724
+ return url;
725
+ });
726
+ })
727
+ .flat() ?? [],
728
+ });
729
+
730
+ // forward peerConnection events
731
+ this.#peerConnection.onStateChange(() => {
732
+ this.dispatchEvent(new Event('connectionstatechange'));
733
+ });
734
+
735
+ this.#peerConnection.onIceStateChange(() => {
736
+ this.dispatchEvent(new Event('iceconnectionstatechange'));
737
+ });
738
+
739
+ this.#peerConnection.onSignalingStateChange(() => {
740
+ this.dispatchEvent(new Event('signalingstatechange'));
741
+ });
742
+
743
+ this.#peerConnection.onGatheringStateChange(() => {
744
+ this.dispatchEvent(new Event('icegatheringstatechange'));
745
+ });
746
+
747
+ this.#peerConnection.onDataChannel((channel) => {
748
+ const dataChannel = new _RTCDataChannel(channel);
749
+ this.#dataChannels.add(dataChannel);
750
+ this.dispatchEvent(new RTCDataChannelEvent(dataChannel));
751
+ });
752
+
753
+ this.#peerConnection.onLocalDescription((sdp, type) => {
754
+ if (type === 'offer') {
755
+ this.#localOffer.resolve({ sdp, type });
756
+ }
757
+
758
+ if (type === 'answer') {
759
+ this.#localAnswer.resolve({ sdp, type });
760
+ }
761
+ });
762
+
763
+ this.#peerConnection.onLocalCandidate((candidate, sdpMid) => {
764
+ if (sdpMid === 'unspec') {
765
+ this.#localAnswer.reject(new Error(`Invalid description type ${sdpMid}`));
766
+ return;
767
+ }
768
+
769
+ this.#localCandidates.push(new _RTCIceCandidate({ candidate, sdpMid }));
770
+ this.dispatchEvent(new RTCPeerConnectionIceEvent(new _RTCIceCandidate({ candidate, sdpMid })));
771
+ });
772
+
773
+ // forward events to properties
774
+ this.addEventListener('connectionstatechange', (e) => {
775
+ if (this.onconnectionstatechange) this.onconnectionstatechange(e);
776
+ });
777
+ this.addEventListener('signalingstatechange', (e) => {
778
+ if (this.onsignalingstatechange) this.onsignalingstatechange(e);
779
+ });
780
+ this.addEventListener('iceconnectionstatechange', (e) => {
781
+ if (this.oniceconnectionstatechange) this.oniceconnectionstatechange(e);
782
+ });
783
+ this.addEventListener('icegatheringstatechange', (e) => {
784
+ if (this.onicegatheringstatechange) this.onicegatheringstatechange(e);
785
+ });
786
+ this.addEventListener('datachannel', (e) => {
787
+ if (this.ondatachannel) this.ondatachannel(e);
788
+ });
789
+ this.addEventListener('icecandidate', (e) => {
790
+ if (this.onicecandidate) this.onicecandidate(e);
791
+ });
792
+
793
+ this.#sctp = new _RTCSctpTransport({
794
+ pc: this,
795
+ extraFunctions: {
796
+ maxDataChannelId: () => {
797
+ return this.#peerConnection.maxDataChannelId();
798
+ },
799
+ maxMessageSize: () => {
800
+ return this.#peerConnection.maxMessageSize();
801
+ },
802
+ localCandidates: () => {
803
+ return this.#localCandidates;
804
+ },
805
+ remoteCandidates: () => {
806
+ return this.#remoteCandidates;
807
+ },
808
+ selectedCandidatePair: () => {
809
+ return this.#peerConnection.getSelectedCandidatePair();
810
+ },
811
+ },
812
+ });
813
+ }
814
+
815
+ get canTrickleIceCandidates() {
816
+ return this.#canTrickleIceCandidates;
817
+ }
818
+
819
+ get connectionState() {
820
+ return this.#peerConnection.state();
821
+ }
822
+
823
+ get iceConnectionState() {
824
+ return this.#peerConnection.iceState();
825
+ }
826
+
827
+ get iceGatheringState() {
828
+ return this.#peerConnection.gatheringState();
829
+ }
830
+
831
+ get currentLocalDescription() {
832
+ return new _RTCSessionDescription(this.#peerConnection.localDescription());
833
+ }
834
+
835
+ get currentRemoteDescription() {
836
+ return new _RTCSessionDescription(this.#peerConnection.remoteDescription());
837
+ }
838
+
839
+ get localDescription() {
840
+ return new _RTCSessionDescription(this.#peerConnection.localDescription());
841
+ }
842
+
843
+ get pendingLocalDescription() {
844
+ return new _RTCSessionDescription(this.#peerConnection.localDescription());
845
+ }
846
+
847
+ get pendingRemoteDescription() {
848
+ return new _RTCSessionDescription(this.#peerConnection.remoteDescription());
849
+ }
850
+
851
+ get remoteDescription() {
852
+ return new _RTCSessionDescription(this.#peerConnection.remoteDescription());
853
+ }
854
+
855
+ get sctp() {
856
+ return this.#sctp;
857
+ }
858
+
859
+ get signalingState() {
860
+ return this.#peerConnection.signalingState();
861
+ }
862
+
863
+ static generateCertificate(keygenAlgorithm) {
864
+ throw new DOMException('Not implemented');
865
+ }
866
+
867
+ async addIceCandidate(candidate) {
868
+ if (candidate == null || candidate.candidate == null) {
869
+ throw new DOMException('Candidate invalid');
870
+ }
871
+
872
+ this.#remoteCandidates.push(
873
+ new _RTCIceCandidate({ candidate: candidate.candidate, sdpMid: candidate.sdpMid || '0' }),
874
+ );
875
+ this.#peerConnection.addRemoteCandidate(candidate.candidate, candidate.sdpMid || '0');
876
+ }
877
+
878
+ addTrack(track, ...streams) {
879
+ throw new DOMException('Not implemented');
880
+ }
881
+
882
+ addTransceiver(trackOrKind, init) {
883
+ throw new DOMException('Not implemented');
884
+ }
885
+
886
+ close() {
887
+ // close all channels before shutting down
888
+ this.#dataChannels.forEach((channel) => {
889
+ channel.close();
890
+ });
891
+
892
+ this.#peerConnection.close();
893
+ }
894
+
895
+ createAnswer() {
896
+ return this.#localAnswer;
897
+ }
898
+
899
+ createDataChannel(label, opts = {}) {
900
+ const channel = this.#peerConnection.createDataChannel(label, opts);
901
+ const dataChannel = new _RTCDataChannel(channel, opts);
902
+
903
+ // ensure we can close all channels when shutting down
904
+ this.#dataChannels.add(dataChannel);
905
+ dataChannel.addEventListener('close', () => {
906
+ this.#dataChannels.delete(dataChannel);
907
+ });
908
+
909
+ return dataChannel;
910
+ }
911
+
912
+ createOffer() {
913
+ return this.#localOffer;
914
+ }
915
+
916
+ getConfiguration() {
917
+ return this.#config;
918
+ }
919
+
920
+ getReceivers() {
921
+ throw new DOMException('Not implemented');
922
+ }
923
+
924
+ getSenders() {
925
+ throw new DOMException('Not implemented');
926
+ }
927
+
928
+ getStats() {
929
+ return new Promise((resolve) => {
930
+ let report = new Map();
931
+ let cp = this.#peerConnection.getSelectedCandidatePair();
932
+ let bytesSent = this.#peerConnection.bytesSent();
933
+ let bytesReceived = this.#peerConnection.bytesReceived();
934
+ let rtt = this.#peerConnection.rtt();
935
+
936
+ let localIdRs = getRandomString(8);
937
+ let localId = 'RTCIceCandidate_' + localIdRs;
938
+ report.set(localId, {
939
+ id: localId,
940
+ type: 'localcandidate',
941
+ timestamp: Date.now(),
942
+ candidateType: cp.local.type,
943
+ ip: cp.local.address,
944
+ port: cp.local.port,
945
+ });
946
+
947
+ let remoteIdRs = getRandomString(8);
948
+ let remoteId = 'RTCIceCandidate_' + remoteIdRs;
949
+ report.set(remoteId, {
950
+ id: remoteId,
951
+ type: 'remotecandidate',
952
+ timestamp: Date.now(),
953
+ candidateType: cp.remote.type,
954
+ ip: cp.remote.address,
955
+ port: cp.remote.port,
956
+ });
957
+
958
+ let candidateId = 'RTCIceCandidatePair_' + localIdRs + '_' + remoteIdRs;
959
+ report.set(candidateId, {
960
+ id: candidateId,
961
+ type: 'candidate-pair',
962
+ timestamp: Date.now(),
963
+ localCandidateId: localId,
964
+ remoteCandidateId: remoteId,
965
+ state: 'succeeded',
966
+ nominated: true,
967
+ writable: true,
968
+ bytesSent: bytesSent,
969
+ bytesReceived: bytesReceived,
970
+ totalRoundTripTime: rtt,
971
+ currentRoundTripTime: rtt,
972
+ });
973
+
974
+ let transportId = 'RTCTransport_0_1';
975
+ report.set(transportId, {
976
+ id: transportId,
977
+ timestamp: Date.now(),
978
+ type: 'transport',
979
+ bytesSent: bytesSent,
980
+ bytesReceived: bytesReceived,
981
+ dtlsState: 'connected',
982
+ selectedCandidatePairId: candidateId,
983
+ selectedCandidatePairChanges: 1,
984
+ });
985
+
986
+ return resolve(report);
987
+ });
988
+ }
989
+
990
+ getTransceivers() {
991
+ return []; // throw new DOMException('Not implemented');
992
+ }
993
+
994
+ removeTrack() {
995
+ throw new DOMException('Not implemented');
996
+ }
997
+
998
+ restartIce() {
999
+ throw new DOMException('Not implemented');
1000
+ }
1001
+
1002
+ setConfiguration(config) {
1003
+ this.#config = config;
1004
+ }
1005
+
1006
+ async setLocalDescription(description) {
1007
+ if (description == null || description.type == null) {
1008
+ throw new DOMException('Local description type must be set');
1009
+ }
1010
+
1011
+ if (description.type !== 'offer') {
1012
+ // any other type causes libdatachannel to throw
1013
+ return;
1014
+ }
1015
+ this.#peerConnection.setLocalDescription(description.type);
1016
+ }
1017
+
1018
+ async setRemoteDescription(description) {
1019
+ if (description.sdp == null) {
1020
+ throw new DOMException('Remote SDP must be set');
1021
+ }
1022
+
1023
+ this.#peerConnection.setRemoteDescription(description.sdp, description.type);
1024
+ }
1025
+ }
1026
+
1027
+ function createDeferredPromise() {
1028
+ let resolve, reject;
1029
+
1030
+ let promise = new Promise(function (_resolve, _reject) {
1031
+ resolve = _resolve;
1032
+ reject = _reject;
1033
+ });
1034
+
1035
+ promise.resolve = resolve;
1036
+ promise.reject = reject;
1037
+ return promise;
1038
+ }
1039
+
1040
+ function getRandomString(length) {
1041
+ return Math.random()
1042
+ .toString(36)
1043
+ .substring(2, 2 + length);
1044
+ }
1045
+
1046
+ var index = {
1047
+ RTCCertificate,
1048
+ RTCDataChannel: _RTCDataChannel,
1049
+ RTCDtlsTransport: _RTCDtlsTransport,
1050
+ RTCIceCandidate: _RTCIceCandidate,
1051
+ RTCIceTransport: _RTCIceTransport,
1052
+ RTCPeerConnection: _RTCPeerConnection,
1053
+ RTCSctpTransport: _RTCSctpTransport,
1054
+ RTCSessionDescription: _RTCSessionDescription,
1055
+ RTCDataChannelEvent,
1056
+ RTCPeerConnectionIceEvent,
1057
+ };
1058
+
1059
+ exports.RTCCertificate = RTCCertificate;
1060
+ exports.RTCDataChannel = _RTCDataChannel;
1061
+ exports.RTCDataChannelEvent = RTCDataChannelEvent;
1062
+ exports.RTCDtlsTransport = _RTCDtlsTransport;
1063
+ exports.RTCIceCandidate = _RTCIceCandidate;
1064
+ exports.RTCIceTransport = _RTCIceTransport;
1065
+ exports.RTCPeerConnection = _RTCPeerConnection;
1066
+ exports.RTCPeerConnectionIceEvent = RTCPeerConnectionIceEvent;
1067
+ exports.RTCSctpTransport = _RTCSctpTransport;
1068
+ exports.RTCSessionDescription = _RTCSessionDescription;
1069
+ exports.default = index;