@leofcoin/peernet 0.14.18 → 0.14.20

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,829 @@
1
+ (self["webpackChunk_leofcoin_peernet"] = self["webpackChunk_leofcoin_peernet"] || []).push([[629],{
2
+
3
+ /***/ 96:
4
+ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
5
+
6
+ "use strict";
7
+ // ESM COMPAT FLAG
8
+ __webpack_require__.r(__webpack_exports__);
9
+
10
+ // EXPORTS
11
+ __webpack_require__.d(__webpack_exports__, {
12
+ "default": function() { return /* binding */ Client; }
13
+ });
14
+
15
+ ;// CONCATENATED MODULE: ./node_modules/socket-request-client/dist/es/index.js
16
+ /* provided dependency */ var process = __webpack_require__(155);
17
+ /* socket-request-client version 1.6.3 */
18
+ const ENVIRONMENT = {version: '1.6.3', production: true};
19
+
20
+ class LittlePubSub {
21
+ constructor(verbose = true) {
22
+ this.subscribers = {};
23
+ this.verbose = verbose;
24
+ }
25
+ subscribe(event, handler, context) {
26
+ if (typeof context === 'undefined') {
27
+ context = handler;
28
+ }
29
+ this.subscribers[event] = this.subscribers[event] || { handlers: [], value: null};
30
+ this.subscribers[event].handlers.push(handler.bind(context));
31
+ }
32
+ unsubscribe(event, handler, context) {
33
+ if (typeof context === 'undefined') {
34
+ context = handler;
35
+ }
36
+ if (this.subscribers[event]) {
37
+ const index = this.subscribers[event].handlers.indexOf(handler.bind(context));
38
+ this.subscribers[event].handlers.splice(index);
39
+ if (this.subscribers[event].handlers.length === 0) delete this.subscribers[event];
40
+ }
41
+ }
42
+ publish(event, change) {
43
+ if (this.subscribers[event]) {
44
+ if (this.verbose || this.subscribers[event].value !== change) {
45
+ this.subscribers[event].value = change;
46
+ this.subscribers[event].handlers.forEach(handler => {
47
+ handler(change, this.subscribers[event].value);
48
+ });
49
+ }
50
+ }
51
+ }
52
+ }
53
+
54
+ var clientApi = _pubsub => {
55
+ const subscribe = (topic, cb) => {
56
+ _pubsub.subscribe(topic, cb);
57
+ };
58
+ const unsubscribe = (topic, cb) => {
59
+ _pubsub.unsubscribe(topic, cb);
60
+ };
61
+ const publish = (topic, value) => {
62
+ _pubsub.publish(topic, value);
63
+ };
64
+ const _connectionState = (state) => {
65
+ switch (state) {
66
+ case 0:
67
+ return 'connecting'
68
+ case 1:
69
+ return 'open'
70
+ case 2:
71
+ return 'closing'
72
+ case 3:
73
+ return 'closed'
74
+ }
75
+ };
76
+ const request = (client, request) => {
77
+ return new Promise((resolve, reject) => {
78
+ const state = _connectionState(client.readyState);
79
+ if (state !== 'open') return reject(`coudn't send request to ${client.id}, no open connection found.`)
80
+ request.id = Math.random().toString(36).slice(-12);
81
+ const handler = result => {
82
+ if (result && result.error) return reject(result.error)
83
+ resolve({result, id: request.id, handler});
84
+ unsubscribe(request.id, handler);
85
+ };
86
+ subscribe(request.id, handler);
87
+ send(client, request);
88
+ });
89
+ };
90
+ const send = async (client, request) => {
91
+ return client.send(JSON.stringify(request))
92
+ };
93
+ const pubsub = client => {
94
+ return {
95
+ publish: (topic = 'pubsub', value) => {
96
+ return send(client, {url: 'pubsub', params: { topic, value }})
97
+ },
98
+ subscribe: (topic = 'pubsub', cb) => {
99
+ subscribe(topic, cb);
100
+ return send(client, {url: 'pubsub', params: { topic, subscribe: true }})
101
+ },
102
+ unsubscribe: (topic = 'pubsub', cb) => {
103
+ unsubscribe(topic, cb);
104
+ return send(client, {url: 'pubsub', params: { topic, unsubscribe: true }})
105
+ },
106
+ subscribers: _pubsub.subscribers
107
+ }
108
+ };
109
+ const server = (client) => {
110
+ return {
111
+ uptime: async () => {
112
+ try {
113
+ const { result, id, handler } = await request(client, {url: 'uptime'});
114
+ unsubscribe(id, handler);
115
+ return result
116
+ } catch (e) {
117
+ throw e
118
+ }
119
+ },
120
+ ping: async () => {
121
+ try {
122
+ const now = new Date().getTime();
123
+ const { result, id, handler } = await request(client, {url: 'ping'});
124
+ unsubscribe(id, handler);
125
+ return (Number(result) - now)
126
+ } catch (e) {
127
+ throw e
128
+ }
129
+ }
130
+ }
131
+ };
132
+ const peernet = (client) => {
133
+ return {
134
+ join: async (params) => {
135
+ try {
136
+ params.join = true;
137
+ const requested = { url: 'peernet', params };
138
+ const { result, id, handler } = await request(client, requested);
139
+ unsubscribe(id, handler);
140
+ return result
141
+ } catch (e) {
142
+ throw e
143
+ }
144
+ },
145
+ leave: async (params) => {
146
+ try {
147
+ params.join = false;
148
+ const requested = { url: 'peernet', params };
149
+ const { result, id, handler } = await request(client, requested);
150
+ unsubscribe(id, handler);
151
+ return result
152
+ } catch (e) {
153
+ throw e
154
+ }
155
+ }
156
+ }
157
+ };
158
+ return { send, request, pubsub, server, subscribe, unsubscribe, publish, peernet }
159
+ };
160
+
161
+ if (!globalThis.PubSub) globalThis.PubSub = LittlePubSub;
162
+ if (!globalThis.pubsub) globalThis.pubsub = new LittlePubSub({verbose: false});
163
+ const socketRequestClient = (url, protocols = 'echo-protocol', options = { retry: false }) => {
164
+ const { retry } = options;
165
+ const api = clientApi(pubsub);
166
+ let tries = 0;
167
+ const onerror = error => {
168
+ if (pubsub.subscribers['error']) {
169
+ pubsub.publish('error', error);
170
+ } else {
171
+ console.error(error);
172
+ }
173
+ };
174
+ const onmessage = message => {
175
+ const {value, url, status, id} = JSON.parse(message.data.toString());
176
+ const publisher = id ? id : url;
177
+ if (status === 200) {
178
+ pubsub.publish(publisher, value);
179
+ } else {
180
+ pubsub.publish(publisher, {error: value});
181
+ }
182
+ };
183
+ const clientConnection = client => {
184
+ const startTime = new Date().getTime();
185
+ return {
186
+ client,
187
+ request: async req => {
188
+ const { result, id, handler } = await api.request(client, req);
189
+ pubsub.unsubscribe(id, handler);
190
+ return result
191
+ },
192
+ send: req => api.send(client, req),
193
+ subscribe: api.subscribe,
194
+ unsubscribe: api.unsubscribe,
195
+ subscribers: api.subscribers,
196
+ publish: api.publish,
197
+ pubsub: api.pubsub(client),
198
+ uptime: () => {
199
+ const now = new Date().getTime();
200
+ return (now - startTime)
201
+ },
202
+ peernet: api.peernet(client),
203
+ server: api.server(client),
204
+ close: exit => {
205
+ client.close();
206
+ }
207
+ }
208
+ };
209
+ return new Promise((resolve, reject) => {
210
+ const init = () => {
211
+ let ws;
212
+ if (typeof process === 'object' && !globalThis.WebSocket) {
213
+ ws = (__webpack_require__(840).w3cwebsocket);
214
+ } else {
215
+ ws = WebSocket;
216
+ }
217
+ const client = new ws(url, protocols);
218
+ client.onmessage = onmessage;
219
+ client.onerror = onerror;
220
+ client.onopen = () => {
221
+ tries = 0;
222
+ resolve(clientConnection(client));
223
+ };
224
+ client.onclose = message => {
225
+ tries++;
226
+ if (!retry) return reject(options)
227
+ if (tries > 5) {
228
+ console.log(`${protocols} Client Closed`);
229
+ console.error(`could not connect to - ${url}/`);
230
+ return resolve(clientConnection(client))
231
+ }
232
+ if (message.code === 1006) {
233
+ console.log('Retrying in 10 seconds');
234
+ setTimeout(() => {
235
+ return init();
236
+ }, retry);
237
+ }
238
+ };
239
+ };
240
+ return init();
241
+ });
242
+ };
243
+
244
+
245
+
246
+ // EXTERNAL MODULE: ./node_modules/@vandeurenglenn/debug/debug.js
247
+ var debug_debug = __webpack_require__(307);
248
+ ;// CONCATENATED MODULE: ./node_modules/@leofcoin/peernet-swarm/src/client/peer.js
249
+
250
+
251
+ class Peer {
252
+ #connection
253
+ #connected = false
254
+ #messageQue = []
255
+ #chunksQue = {}
256
+ #channel
257
+ #peerId
258
+ #channelName
259
+ #chunkSize = 16 * 1024 // 16384
260
+ #queRunning = false
261
+ #MAX_BUFFERED_AMOUNT = 16 * 1024 * 1024
262
+
263
+ get connection() {
264
+ return this.#connection
265
+ }
266
+
267
+ get connected() {
268
+ return this.#connected
269
+ }
270
+
271
+ get readyState() {
272
+ return this.#channel?.readyState
273
+ }
274
+
275
+ /**
276
+ * @params {Object} options
277
+ * @params {string} options.channelName - this peerid : otherpeer id
278
+ */
279
+ constructor(options = {}) {
280
+ this._in = this._in.bind(this);
281
+ this.offerOptions = options.offerOptions
282
+ this.initiator = options.initiator
283
+ this.streams = options.streams
284
+ this.socketClient = options.socketClient
285
+ this.id = options.id
286
+ this.to = options.to
287
+ this.bw = {
288
+ up: 0,
289
+ down: 0
290
+ }
291
+
292
+ this.#channelName = options.channelName
293
+
294
+ this.#peerId = options.peerId
295
+ this.options = options
296
+ return this.#init()
297
+ }
298
+
299
+ get peerId() {
300
+ return this.#peerId
301
+ }
302
+
303
+ set socketClient(value) {
304
+ // this.socketClient?.pubsub.unsubscribe('signal', this._in)
305
+ this._socketClient = value
306
+ this._socketClient.pubsub.subscribe('signal', this._in)
307
+ }
308
+
309
+ get socketClient() {
310
+ return this._socketClient
311
+ }
312
+
313
+ splitMessage(message) {
314
+ const chunks = []
315
+ message = pako.deflate(message)
316
+ const size = message.byteLength || message.length
317
+ let offset = 0
318
+ return new Promise((resolve, reject) => {
319
+ const splitMessage = () => {
320
+ const chunk = message.slice(offset, offset + this.#chunkSize > size ? size : offset + this.#chunkSize)
321
+ offset += this.#chunkSize
322
+ chunks.push(chunk)
323
+ if (offset < size) return splitMessage()
324
+ else resolve({chunks, size})
325
+ }
326
+
327
+ splitMessage()
328
+ })
329
+ }
330
+
331
+ async #runQue() {
332
+ this.#queRunning = true
333
+ if (this.#messageQue.length > 0 && this.#channel?.bufferedAmount + this.#messageQue[0]?.length < this.#MAX_BUFFERED_AMOUNT) {
334
+ const message = this.#messageQue.shift()
335
+
336
+ switch (this.#channel?.readyState) {
337
+ case 'open':
338
+ await this.#channel.send(message);
339
+ if (this.#messageQue.length > 0) return this.#runQue()
340
+ else this.#queRunning = false
341
+ break;
342
+ case 'closed':
343
+ case 'closing':
344
+ this.#messageQue = []
345
+ this.#queRunning = false
346
+ debug('channel already closed, this usually means a bad implementation, try checking the readyState or check if the peer is connected before sending');
347
+ break;
348
+ case undefined:
349
+ this.#messageQue = []
350
+ this.#queRunning = false
351
+ debug(`trying to send before a channel is created`);
352
+ break;
353
+ }
354
+
355
+
356
+ } else {
357
+ return setTimeout(() => this.#runQue(), 50)
358
+ }
359
+ }
360
+
361
+ #trySend({ size, id, chunks }) {
362
+ let offset = 0
363
+
364
+ for (const chunk of chunks) {
365
+ const start = offset
366
+ const end = offset + chunk.length
367
+
368
+ const message = new TextEncoder().encode(JSON.stringify({ size, id, chunk, start, end }));
369
+ this.#messageQue.push(message)
370
+ }
371
+
372
+ if (!this.queRunning) return this.#runQue()
373
+ }
374
+
375
+ async send(message, id) {
376
+ const { chunks, size } = await this.splitMessage(message)
377
+ return this.#trySend({ size, id, chunks })
378
+ }
379
+
380
+ request(data) {
381
+ return new Promise((resolve, reject) => {
382
+ const id = Math.random().toString(36).slice(-12)
383
+
384
+ const _onData = message => {
385
+ if (message.id === id) {
386
+ resolve(message.data)
387
+ pubsub.unsubscribe(`peer:data`, _onData)
388
+ }
389
+ }
390
+
391
+ pubsub.subscribe(`peer:data`, _onData)
392
+
393
+ // cleanup subscriptions
394
+ // setTimeout(() => {
395
+ // pubsub.unsubscribe(`peer:data-request-${id}`, _onData)
396
+ // }, 5000);
397
+
398
+ this.send(data, id)
399
+ })
400
+ }
401
+
402
+ async #init() {
403
+ try {
404
+
405
+ if (!globalThis.pako) {
406
+ const importee = await __webpack_require__.e(/* import() | pako */ 682).then(__webpack_require__.bind(__webpack_require__, 885))
407
+ globalThis.pako = importee.default
408
+ }
409
+
410
+ const iceServers = [{
411
+ urls: 'stun:stun.l.google.com:19302' // Google's public STUN server
412
+ }, {
413
+ urls: "stun:openrelay.metered.ca:80",
414
+ }, {
415
+ urls: "turn:openrelay.metered.ca:443",
416
+ username: "openrelayproject",
417
+ credential: "openrelayproject",
418
+ }, {
419
+ urls: "turn:openrelay.metered.ca:443?transport=tcp",
420
+ username: "openrelayproject",
421
+ credential: "openrelayproject",
422
+ }]
423
+
424
+ this.#connection = new wrtc.RTCPeerConnection({iceServers});
425
+
426
+ this.#connection.onicecandidate = ({ candidate }) => {
427
+ if (candidate) {
428
+ this.address = candidate.address
429
+ this.port = candidate.port
430
+ this.protocol = candidate.protocol
431
+ this.ipFamily = this.address.includes('::') ? 'ipv6': 'ipv4'
432
+ this._sendMessage({candidate})
433
+ }
434
+ }
435
+ // if (this.initiator) this.#connection.onnegotiationneeded = () => {
436
+ // console.log('create offer');
437
+ this.#connection.ondatachannel = (message) => {
438
+ message.channel.onopen = () => {
439
+ this.#connected = true
440
+ pubsub.publish('peer:connected', this)
441
+ }
442
+ message.channel.onclose = () => this.close.bind(this)
443
+
444
+ message.channel.onmessage = (message) => {
445
+ this._handleMessage(this.id, message)
446
+ }
447
+ this.#channel = message.channel
448
+ }
449
+ if (this.initiator) {
450
+
451
+ this.#channel = this.#connection.createDataChannel('messageChannel')
452
+ this.#channel.onopen = () => {
453
+ this.#connected = true
454
+ pubsub.publish('peer:connected', this)
455
+ // this.#channel.send('hi')
456
+ }
457
+ this.#channel.onclose = () => this.close.bind(this)
458
+
459
+ this.#channel.onmessage = (message) => {
460
+ this._handleMessage(this.peerId, message)
461
+ }
462
+
463
+ const offer = await this.#connection.createOffer()
464
+ await this.#connection.setLocalDescription(offer)
465
+
466
+ this._sendMessage({'sdp': this.#connection.localDescription})
467
+ }
468
+ } catch (e) {
469
+ console.log(e);
470
+ }
471
+
472
+ return this
473
+ }
474
+
475
+ _handleMessage(peerId, message) {
476
+ debug(`incoming message from ${peerId}`)
477
+
478
+ message = JSON.parse(new TextDecoder().decode(message.data))
479
+ // allow sharding (multiple peers share data)
480
+ pubsub.publish('peernet:shard', message)
481
+ const { id } = message
482
+
483
+ if (!this.#chunksQue[id]) this.#chunksQue[id] = []
484
+
485
+ if (message.size > this.#chunksQue[id].length || message.size === this.#chunksQue[id].length) {
486
+ for (const value of Object.values(message.chunk)) {
487
+ this.#chunksQue[id].push(value)
488
+ }
489
+ }
490
+
491
+ if (message.size === this.#chunksQue[id].length) {
492
+ let data = new Uint8Array(Object.values(this.#chunksQue[id]))
493
+ delete this.#chunksQue[id]
494
+ data = pako.inflate(data)
495
+ pubsub.publish('peer:data', { id, data, from: this.peerId })
496
+ }
497
+ this.bw.down += message.byteLength || message.length
498
+ }
499
+
500
+ _sendMessage(message) {
501
+ this.socketClient.send({url: 'signal', params: {
502
+ to: this.to,
503
+ from: this.id,
504
+ channelName: this.options.channelName,
505
+ ...message
506
+ }})
507
+ }
508
+
509
+ async _in(message, data) {
510
+ // message = JSON.parse(message);
511
+ if (message.to !== this.id) return
512
+ // if (data.videocall) return this._startStream(true, false); // start video and audio stream
513
+ // if (data.call) return this._startStream(true, true); // start audio stream
514
+ const signalinState = this.#connection.signalinState
515
+ if (signalinState === 'stable' && this.#connection.remoteDescription !== null && this.#connection.localDescription !== null) return
516
+
517
+ if (message.candidate) {
518
+ debug(`incoming candidate ${this.#channelName}`)
519
+ // debug(message.candidate.candidate)
520
+ this.remoteAddress = message.candidate.address
521
+ this.remotePort = message.candidate.port
522
+ this.remoteProtocol = message.candidate.protocol
523
+ this.remoteIpFamily = this.remoteAddress?.includes('::') ? 'ipv6': 'ipv4'
524
+ return this.#connection.addIceCandidate(new wrtc.RTCIceCandidate(message.candidate));
525
+ }
526
+ try {
527
+ if (message.sdp) {
528
+ if (message.sdp.type === 'offer') {
529
+ debug(`incoming offer ${this.#channelName}`)
530
+ await this.#connection.setRemoteDescription(new wrtc.RTCSessionDescription(message.sdp))
531
+ const answer = await this.#connection.createAnswer();
532
+ await this.#connection.setLocalDescription(answer)
533
+ this._sendMessage({'sdp': this.#connection.localDescription})
534
+ }
535
+ if (message.sdp.type === 'answer') {
536
+ debug(`incoming answer ${this.#channelName}`)
537
+ await this.#connection.setRemoteDescription(new wrtc.RTCSessionDescription(message.sdp))
538
+ }
539
+ }
540
+ } catch (e) {
541
+ console.log(e);
542
+ }
543
+ }
544
+
545
+ close() {
546
+ debug(`closing ${this.peerId}`)
547
+ this.#connected = false
548
+ this.#channel?.close()
549
+ this.#connection?.close()
550
+
551
+ this.socketClient.pubsub.unsubscribe('signal', this._in)
552
+ }
553
+ }
554
+
555
+ ;// CONCATENATED MODULE: ./node_modules/@leofcoin/peernet-swarm/src/client/client.js
556
+
557
+
558
+
559
+
560
+ class Client {
561
+ #peerConnection
562
+ #connections = {}
563
+ #stars = {}
564
+
565
+ get connections() {
566
+ return { ...this.#connections }
567
+ }
568
+
569
+ get peers() {
570
+ return Object.entries(this.#connections)
571
+ }
572
+
573
+ constructor(id, identifiers = ['peernet-v0.1.0'], stars = []) {
574
+ this.id = id || Math.random().toString(36).slice(-12);
575
+ if (!Array.isArray(identifiers)) identifiers = [identifiers]
576
+ this.peerJoined = this.peerJoined.bind(this)
577
+ this.peerLeft = this.peerLeft.bind(this)
578
+ this.starLeft = this.starLeft.bind(this)
579
+ this.starJoined = this.starJoined.bind(this)
580
+
581
+ this._init(identifiers, stars)
582
+ }
583
+
584
+ async _init(identifiers, stars = []) {
585
+ if (stars.length === 0) {
586
+ stars.push('wss://star.leofcoin.org')
587
+ }
588
+ this.identifiers = identifiers
589
+ this.starsConfig = stars
590
+ // reconnectJob()
591
+
592
+ if (!globalThis.RTCPeerConnection) globalThis.wrtc = await __webpack_require__.e(/* import() | wrtc */ 228).then(__webpack_require__.t.bind(__webpack_require__, 347, 19))
593
+ else globalThis.wrtc = {
594
+ RTCPeerConnection,
595
+ RTCSessionDescription,
596
+ RTCIceCandidate
597
+ }
598
+
599
+ for (const star of stars) {
600
+ try {
601
+ this.socketClient = await socketRequestClient(star, identifiers[0])
602
+ const id = await this.socketClient.request({url: 'id', params: {from: this.id}})
603
+ this.socketClient.peerId = id
604
+ this.#stars[id] = this.socketClient
605
+ } catch (e) {
606
+ if (stars.indexOf(star) === stars.length -1 && !this.socketClient) throw new Error(`No star available to connect`);
607
+ }
608
+ }
609
+ const peers = await this.socketClient.peernet.join({id: this.id})
610
+ for (const id of peers) {
611
+ if (id !== this.id && !this.#connections[id]) this.#connections[id] = await new Peer({channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id})
612
+ }
613
+ this.setupListeners()
614
+ }
615
+
616
+ setupListeners() {
617
+ this.socketClient.subscribe('peer:joined', this.peerJoined)
618
+ this.socketClient.subscribe('peer:left', this.peerLeft)
619
+ this.socketClient.subscribe('star:left', this.starLeft)
620
+ }
621
+
622
+ starJoined(id) {
623
+ if (this.#stars[id]) {
624
+ this.#stars[id].close()
625
+ delete this.#stars[id]
626
+ }
627
+ console.log(`star ${id} joined`);
628
+ }
629
+
630
+ async starLeft(id) {
631
+ if (this.#stars[id]) {
632
+ this.#stars[id].close()
633
+ delete this.#stars[id]
634
+ }
635
+ if (this.socketClient?.peerId === id) {
636
+
637
+ this.socketClient.unsubscribe('peer:joined', this.peerJoined)
638
+ this.socketClient.unsubscribe('peer:left', this.peerLeft)
639
+ this.socketClient.unsubscribe('star:left', this.starLeft)
640
+ this.socketClient.close()
641
+ this.socketClient = undefined
642
+
643
+ for (const star of this.starsConfig) {
644
+ try {
645
+ this.socketClient = await socketRequestClient(star, this.identifiers[0])
646
+ if (!this.socketClient?.client?._connection.connected) return
647
+ const id = await this.socketClient.request({url: 'id', params: {from: this.id}})
648
+ this.#stars[id] = this.socketClient
649
+
650
+ this.socketClient.peerId = id
651
+
652
+ const peers = await this.socketClient.peernet.join({id: this.id})
653
+ this.setupListeners()
654
+ for (const id of peers) {
655
+ if (id !== this.id) {
656
+ // close connection
657
+ if (this.#connections[id]) {
658
+ if (this.#connections[id].connected) await this.#connections[id].close()
659
+ delete this.#connections[id]
660
+ }
661
+ // reconnect
662
+ if (id !== this.id) this.#connections[id] = await new Peer({channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id})
663
+ }
664
+
665
+ }
666
+ } catch (e) {
667
+ console.log(e);
668
+ if (this.starsConfig.indexOf(star) === this.starsConfig.length -1 && !this.socketClient) throw new Error(`No star available to connect`);
669
+ }
670
+ }
671
+ }
672
+ debug(`star ${id} left`);
673
+ }
674
+
675
+ peerLeft(peer) {
676
+ const id = peer.peerId || peer
677
+ if (this.#connections[id]) {
678
+ this.#connections[id].close()
679
+ delete this.#connections[id]
680
+ }
681
+ debug(`peer ${id} left`)
682
+ }
683
+
684
+ async peerJoined(peer, signal) {
685
+ const id = peer.peerId || peer
686
+ if (this.#connections[id]) {
687
+ if (this.#connections[id].connected) this.#connections[id].close()
688
+ delete this.#connections[id]
689
+ }
690
+ // RTCPeerConnection
691
+ this.#connections[id] = await new Peer({initiator: true, channelName: `${this.id}:${id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id})
692
+ debug(`peer ${id} joined`)
693
+ }
694
+
695
+ removePeer(peer) {
696
+ const id = peer.peerId || peer
697
+ if (this.#connections[id]) {
698
+ this.#connections[id].connected && this.#connections[id].close()
699
+ delete this.#connections[id]
700
+ }
701
+ debug(`peer ${id} removed`)
702
+ }
703
+
704
+
705
+ }
706
+
707
+
708
+ /***/ }),
709
+
710
+ /***/ 284:
711
+ /***/ (function(module) {
712
+
713
+ var naiveFallback = function () {
714
+ if (typeof self === "object" && self) return self;
715
+ if (typeof window === "object" && window) return window;
716
+ throw new Error("Unable to resolve global `this`");
717
+ };
718
+
719
+ module.exports = (function () {
720
+ if (this) return this;
721
+
722
+ // Unexpected strict mode (may happen if e.g. bundled into ESM module)
723
+
724
+ // Fallback to standard globalThis if available
725
+ if (typeof globalThis === "object" && globalThis) return globalThis;
726
+
727
+ // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
728
+ // In all ES5+ engines global object inherits from Object.prototype
729
+ // (if you approached one that doesn't please report)
730
+ try {
731
+ Object.defineProperty(Object.prototype, "__global__", {
732
+ get: function () { return this; },
733
+ configurable: true
734
+ });
735
+ } catch (error) {
736
+ // Unfortunate case of updates to Object.prototype being restricted
737
+ // via preventExtensions, seal or freeze
738
+ return naiveFallback();
739
+ }
740
+ try {
741
+ // Safari case (window.__global__ works, but __global__ does not)
742
+ if (!__global__) return naiveFallback();
743
+ return __global__;
744
+ } finally {
745
+ delete Object.prototype.__global__;
746
+ }
747
+ })();
748
+
749
+
750
+ /***/ }),
751
+
752
+ /***/ 840:
753
+ /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
754
+
755
+ var _globalThis;
756
+ if (typeof globalThis === 'object') {
757
+ _globalThis = globalThis;
758
+ } else {
759
+ try {
760
+ _globalThis = __webpack_require__(284);
761
+ } catch (error) {
762
+ } finally {
763
+ if (!_globalThis && typeof window !== 'undefined') { _globalThis = window; }
764
+ if (!_globalThis) { throw new Error('Could not determine global this'); }
765
+ }
766
+ }
767
+
768
+ var NativeWebSocket = _globalThis.WebSocket || _globalThis.MozWebSocket;
769
+ var websocket_version = __webpack_require__(387);
770
+
771
+
772
+ /**
773
+ * Expose a W3C WebSocket class with just one or two arguments.
774
+ */
775
+ function W3CWebSocket(uri, protocols) {
776
+ var native_instance;
777
+
778
+ if (protocols) {
779
+ native_instance = new NativeWebSocket(uri, protocols);
780
+ }
781
+ else {
782
+ native_instance = new NativeWebSocket(uri);
783
+ }
784
+
785
+ /**
786
+ * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket
787
+ * class). Since it is an Object it will be returned as it is when creating an
788
+ * instance of W3CWebSocket via 'new W3CWebSocket()'.
789
+ *
790
+ * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2
791
+ */
792
+ return native_instance;
793
+ }
794
+ if (NativeWebSocket) {
795
+ ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) {
796
+ Object.defineProperty(W3CWebSocket, prop, {
797
+ get: function() { return NativeWebSocket[prop]; }
798
+ });
799
+ });
800
+ }
801
+
802
+ /**
803
+ * Module exports.
804
+ */
805
+ module.exports = {
806
+ 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null,
807
+ 'version' : websocket_version
808
+ };
809
+
810
+
811
+ /***/ }),
812
+
813
+ /***/ 387:
814
+ /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
815
+
816
+ module.exports = __webpack_require__(794).version;
817
+
818
+
819
+ /***/ }),
820
+
821
+ /***/ 794:
822
+ /***/ (function(module) {
823
+
824
+ "use strict";
825
+ module.exports = {"version":"1.0.34"};
826
+
827
+ /***/ })
828
+
829
+ }]);