@leofcoin/peernet 1.1.3 → 1.1.4

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,612 @@
1
+ import { L as LittlePubSub } from './peernet-f349ddaf.js';
2
+ import './value-157ab062.js';
3
+
4
+ var clientApi = _pubsub => {
5
+
6
+ const subscribe = (topic, cb) => {
7
+ _pubsub.subscribe(topic, cb);
8
+ };
9
+
10
+ const unsubscribe = (topic, cb) => {
11
+ _pubsub.unsubscribe(topic, cb);
12
+ };
13
+
14
+ const publish = (topic, value) => {
15
+ _pubsub.publish(topic, value);
16
+ };
17
+
18
+ const connectionState = (state) => {
19
+ switch (state) {
20
+ case 0:
21
+ return 'connecting'
22
+ case 1:
23
+ return 'open'
24
+ case 2:
25
+ return 'closing'
26
+ case 3:
27
+ return 'closed'
28
+ }
29
+ };
30
+ /**
31
+ * @param {string} type
32
+ * @param {string} name
33
+ * @param {object} params
34
+ */
35
+ const request = (client, request) => {
36
+ return new Promise((resolve, reject) => {
37
+
38
+ const state = connectionState(client.readyState);
39
+ if (state !== 'open') return reject(`coudn't send request to ${client.id}, no open connection found.`)
40
+
41
+ request.id = Math.random().toString(36).slice(-12);
42
+ const handler = result => {
43
+ if (result && result.error) return reject(result.error)
44
+ resolve({result, id: request.id, handler});
45
+ unsubscribe(request.id, handler);
46
+ };
47
+ subscribe(request.id, handler);
48
+ send(client, request);
49
+ });
50
+ };
51
+
52
+ const send = async (client, request) => {
53
+ return client.send(JSON.stringify(request))
54
+ };
55
+
56
+ const pubsub = client => {
57
+ return {
58
+ publish: (topic = 'pubsub', value) => {
59
+ return send(client, {url: 'pubsub', params: { topic, value }})
60
+ },
61
+ subscribe: (topic = 'pubsub', cb) => {
62
+ subscribe(topic, cb);
63
+ return send(client, {url: 'pubsub', params: { topic, subscribe: true }})
64
+ },
65
+ unsubscribe: (topic = 'pubsub', cb) => {
66
+ unsubscribe(topic, cb);
67
+ return send(client, {url: 'pubsub', params: { topic, unsubscribe: true }})
68
+ },
69
+ subscribers: _pubsub.subscribers
70
+ }
71
+ };
72
+
73
+ const server = (client) => {
74
+ return {
75
+ uptime: async () => {
76
+ try {
77
+ const { result, id, handler } = await request(client, {url: 'uptime'});
78
+ unsubscribe(id, handler);
79
+ return result
80
+ } catch (e) {
81
+ throw e
82
+ }
83
+ },
84
+ ping: async () => {
85
+ try {
86
+ const now = new Date().getTime();
87
+ const { result, id, handler } = await request(client, {url: 'ping'});
88
+ unsubscribe(id, handler);
89
+ return (Number(result) - now)
90
+ } catch (e) {
91
+ throw e
92
+ }
93
+ }
94
+ }
95
+ };
96
+
97
+ const peernet = (client) => {
98
+ return {
99
+ join: async (params) => {
100
+ try {
101
+ params.join = true;
102
+ const requested = { url: 'peernet', params };
103
+ const { result, id, handler } = await request(client, requested);
104
+ unsubscribe(id, handler);
105
+ return result
106
+ } catch (e) {
107
+ throw e
108
+ }
109
+ },
110
+ leave: async (params) => {
111
+ try {
112
+ params.join = false;
113
+ const requested = { url: 'peernet', params };
114
+ const { result, id, handler } = await request(client, requested);
115
+ unsubscribe(id, handler);
116
+ return result
117
+ } catch (e) {
118
+ throw e
119
+ }
120
+ }
121
+ }
122
+ };
123
+
124
+ return { send, request, pubsub, server, subscribe, unsubscribe, publish, peernet, connectionState }
125
+ };
126
+
127
+ if (!globalThis.PubSub) globalThis.PubSub = LittlePubSub;
128
+ if (!globalThis.pubsub) globalThis.pubsub = new LittlePubSub({verbose: false});
129
+
130
+ const socketRequestClient = (url, protocols = 'echo-protocol', options = { retry: true, timeout: 10_000, times: 10 }) => {
131
+ let { retry, timeout, times } = options;
132
+ if (retry === undefined) retry = true;
133
+ if (timeout === undefined) timeout = 10_000;
134
+ if (times === undefined) times = 10;
135
+
136
+ const api = clientApi(pubsub);
137
+
138
+ let tries = 0;
139
+
140
+ const onerror = error => {
141
+ if (pubsub.subscribers['error']) {
142
+ pubsub.publish('error', error);
143
+ } else {
144
+ console.error(error);
145
+ }
146
+ };
147
+
148
+ const onmessage = message => {
149
+ const {value, url, status, id} = JSON.parse(message.data.toString());
150
+ const publisher = id ? id : url;
151
+ if (status === 200) {
152
+ pubsub.publish(publisher, value);
153
+ } else {
154
+ pubsub.publish(publisher, {error: value});
155
+ }
156
+ };
157
+
158
+ const clientConnection = client => {
159
+ const startTime = new Date().getTime();
160
+ return {
161
+ client,
162
+ request: async req => {
163
+ const { result, id, handler } = await api.request(client, req);
164
+ pubsub.unsubscribe(id, handler);
165
+ return result
166
+ },
167
+ send: req => api.send(client, req),
168
+ subscribe: api.subscribe,
169
+ unsubscribe: api.unsubscribe,
170
+ subscribers: api.subscribers,
171
+ publish: api.publish,
172
+ pubsub: api.pubsub(client),
173
+ uptime: () => {
174
+ const now = new Date().getTime();
175
+ return (now - startTime)
176
+ },
177
+ peernet: api.peernet(client),
178
+ server: api.server(client),
179
+ connectionState: () => api.connectionState(client.readyState),
180
+ close: exit => {
181
+ // client.onclose = message => {
182
+ // if (exit) process.exit()
183
+ // }
184
+ client.close();
185
+ }
186
+ }
187
+ };
188
+
189
+ return new Promise(async (resolve, reject) => {
190
+ const init = async () => {
191
+ let ws;
192
+ if (typeof process === 'object' && !globalThis.WebSocket) {
193
+ ws = (await import('./browser-e1cd4e67.js').then(function (n) { return n.b; })).default;
194
+ ws = ws.w3cwebsocket;
195
+ } else {
196
+ ws = WebSocket;
197
+ }
198
+ const client = new ws(url, protocols);
199
+
200
+ client.onmessage = onmessage;
201
+ client.onerror = onerror;
202
+
203
+ client.onopen = () => {
204
+ tries = 0;
205
+ resolve(clientConnection(client));
206
+ };
207
+ client.onclose = message => {
208
+ tries++;
209
+ if (!retry) return reject(options)
210
+ if (tries > times) {
211
+ console.log(`${protocols} Client Closed`);
212
+ console.error(`could not connect to - ${url}/`);
213
+ return resolve(clientConnection(client))
214
+ }
215
+ if (message.code === 1006) {
216
+ console.log(`Retrying in ${timeout} ms`);
217
+ setTimeout(() => {
218
+ return init();
219
+ }, timeout);
220
+ }
221
+ };
222
+ };
223
+ return init();
224
+ });
225
+ };
226
+
227
+ class Peer {
228
+ #connection;
229
+ #connected = false;
230
+ #messageQue = [];
231
+ #chunksQue = {};
232
+ #channel;
233
+ id;
234
+ #peerId;
235
+ #channelName;
236
+ #chunkSize = 16 * 1024; // 16384
237
+ #queRunning = false;
238
+ #MAX_BUFFERED_AMOUNT = 16 * 1024 * 1024;
239
+ initiator = false;
240
+ state;
241
+ #makingOffer = false;
242
+ get connection() {
243
+ return this.#connection;
244
+ }
245
+ get connected() {
246
+ return this.#connected;
247
+ }
248
+ get readyState() {
249
+ return this.#channel?.readyState;
250
+ }
251
+ get channelName() {
252
+ return this.#channelName;
253
+ }
254
+ /**
255
+ * @params {Object} options
256
+ * @params {string} options.channelName - this peerid : otherpeer id
257
+ */
258
+ constructor(options = {}) {
259
+ this._in = this._in.bind(this);
260
+ this.offerOptions = options.offerOptions;
261
+ this.initiator = options.initiator;
262
+ this.streams = options.streams;
263
+ this.socketClient = options.socketClient;
264
+ this.id = options.id;
265
+ this.to = options.to;
266
+ this.bw = {
267
+ up: 0,
268
+ down: 0
269
+ };
270
+ this.#channelName = options.channelName;
271
+ this.#peerId = options.peerId;
272
+ this.options = options;
273
+ return this.#init();
274
+ }
275
+ get peerId() {
276
+ return this.#peerId;
277
+ }
278
+ set socketClient(value) {
279
+ // this.socketClient?.pubsub.unsubscribe('signal', this._in)
280
+ this._socketClient = value;
281
+ this._socketClient.pubsub.subscribe('signal', this._in);
282
+ }
283
+ get socketClient() {
284
+ return this._socketClient;
285
+ }
286
+ splitMessage(message) {
287
+ const chunks = [];
288
+ message = pako.deflate(message);
289
+ const size = message.byteLength || message.length;
290
+ let offset = 0;
291
+ return new Promise((resolve, reject) => {
292
+ const splitMessage = () => {
293
+ const chunk = message.slice(offset, offset + this.#chunkSize > size ? size : offset + this.#chunkSize);
294
+ offset += this.#chunkSize;
295
+ chunks.push(chunk);
296
+ if (offset < size)
297
+ return splitMessage();
298
+ else
299
+ resolve({ chunks, size });
300
+ };
301
+ splitMessage();
302
+ });
303
+ }
304
+ async #runQue() {
305
+ this.#queRunning = true;
306
+ if (this.#messageQue.length > 0 && this.#channel?.bufferedAmount + this.#messageQue[0]?.length < this.#MAX_BUFFERED_AMOUNT) {
307
+ const message = this.#messageQue.shift();
308
+ await this.#connection.send(message);
309
+ if (this.#messageQue.length > 0)
310
+ return this.#runQue();
311
+ // switch (this.#channel?.readyState) {
312
+ // case 'open':
313
+ // await this.#channel.send(message);
314
+ // if (this.#messageQue.length > 0) return this.#runQue()
315
+ // else this.#queRunning = false
316
+ // break;
317
+ // case 'closed':
318
+ // case 'closing':
319
+ // this.#messageQue = []
320
+ // this.#queRunning = false
321
+ // debug('channel already closed, this usually means a bad implementation, try checking the readyState or check if the peer is connected before sending');
322
+ // break;
323
+ // case undefined:
324
+ // this.#messageQue = []
325
+ // this.#queRunning = false
326
+ // debug(`trying to send before a channel is created`);
327
+ // break;
328
+ // }
329
+ }
330
+ else {
331
+ return setTimeout(() => this.#runQue(), 50);
332
+ }
333
+ }
334
+ #trySend({ size, id, chunks }) {
335
+ let offset = 0;
336
+ for (const chunk of chunks) {
337
+ const start = offset;
338
+ const end = offset + chunk.length;
339
+ const message = new TextEncoder().encode(JSON.stringify({ size, id, chunk, start, end }));
340
+ this.#messageQue.push(message);
341
+ }
342
+ if (!this.queRunning)
343
+ return this.#runQue();
344
+ }
345
+ async send(message, id) {
346
+ const { chunks, size } = await this.splitMessage(message);
347
+ return this.#trySend({ size, id, chunks });
348
+ }
349
+ request(data) {
350
+ return new Promise((resolve, reject) => {
351
+ const id = Math.random().toString(36).slice(-12);
352
+ const _onData = message => {
353
+ if (message.id === id) {
354
+ resolve(message.data);
355
+ pubsub.unsubscribe(`peer:data`, _onData);
356
+ }
357
+ };
358
+ pubsub.subscribe(`peer:data`, _onData);
359
+ // cleanup subscriptions
360
+ // setTimeout(() => {
361
+ // pubsub.unsubscribe(`peer:data-request-${id}`, _onData)
362
+ // }, 5000);
363
+ this.send(data, id);
364
+ });
365
+ }
366
+ async #init() {
367
+ try {
368
+ if (!globalThis.pako) {
369
+ const importee = await import('./pako.esm-aa674ebf.js');
370
+ globalThis.pako = importee.default;
371
+ }
372
+ const iceServers = [{
373
+ urls: 'stun:stun.l.google.com:19302' // Google's public STUN server
374
+ }, {
375
+ urls: "stun:openrelay.metered.ca:80",
376
+ }, {
377
+ urls: "turn:openrelay.metered.ca:443",
378
+ username: "openrelayproject",
379
+ credential: "openrelayproject",
380
+ }, {
381
+ urls: "turn:openrelay.metered.ca:443?transport=tcp",
382
+ username: "openrelayproject",
383
+ credential: "openrelayproject",
384
+ }];
385
+ const importee = await import('./simple-peer-743c19fe.js');
386
+ const SimplePeer = importee.default;
387
+ this.#connection = new SimplePeer({
388
+ channelName: this.channelName,
389
+ initiator: this.initiator,
390
+ peerId: this.peerId,
391
+ wrtc: globalThis.wrtc,
392
+ config: {
393
+ iceServers
394
+ }
395
+ });
396
+ this.#connection.on('signal', signal => {
397
+ this._sendMessage({ signal });
398
+ });
399
+ this.#connection.on('connected', () => {
400
+ this.#connected = true;
401
+ pubsub.publish('peer:connected', this);
402
+ });
403
+ this.#connection.on('close', () => {
404
+ this.close();
405
+ });
406
+ this.#connection.on('data', data => {
407
+ this._handleMessage(data);
408
+ });
409
+ this.#connection.on('error', (e) => {
410
+ pubsub.publish('connection closed', this);
411
+ console.log(e);
412
+ this.close();
413
+ });
414
+ }
415
+ catch (e) {
416
+ console.log(e);
417
+ }
418
+ return this;
419
+ }
420
+ _handleMessage(message) {
421
+ console.log({ message });
422
+ message = JSON.parse(new TextDecoder().decode(message.data));
423
+ // allow sharding (multiple peers share data)
424
+ pubsub.publish('peernet:shard', message);
425
+ const { id } = message;
426
+ if (!this.#chunksQue[id])
427
+ this.#chunksQue[id] = [];
428
+ if (message.size > this.#chunksQue[id].length || message.size === this.#chunksQue[id].length) {
429
+ for (const value of Object.values(message.chunk)) {
430
+ this.#chunksQue[id].push(value);
431
+ }
432
+ }
433
+ if (message.size === this.#chunksQue[id].length) {
434
+ let data = new Uint8Array(Object.values(this.#chunksQue[id]));
435
+ delete this.#chunksQue[id];
436
+ data = pako.inflate(data);
437
+ pubsub.publish('peer:data', { id, data, from: this.peerId });
438
+ }
439
+ this.bw.down += message.byteLength || message.length;
440
+ }
441
+ _sendMessage(message) {
442
+ this.socketClient.send({ url: 'signal', params: {
443
+ to: this.to,
444
+ from: this.id,
445
+ channelName: this.channelName,
446
+ ...message
447
+ } });
448
+ }
449
+ async _in(message, data) {
450
+ if (message.signal)
451
+ return this.#connection.signal(message.signal);
452
+ }
453
+ close() {
454
+ // debug(`closing ${this.peerId}`)
455
+ this.#connected = false;
456
+ // this.#channel?.close()
457
+ // this.#connection?.exit()
458
+ this.socketClient.pubsub.unsubscribe('signal', this._in);
459
+ }
460
+ }
461
+
462
+ class Client {
463
+ #peerConnection;
464
+ #connections = {};
465
+ #stars = {};
466
+ id;
467
+ networkVersion;
468
+ starsConfig;
469
+ socketClient;
470
+ get connections() {
471
+ return { ...this.#connections };
472
+ }
473
+ get peers() {
474
+ return Object.entries(this.#connections);
475
+ }
476
+ constructor(id, networkVersion = 'peach', stars = ['wss://peach.leofcoin.org']) {
477
+ this.id = id || Math.random().toString(36).slice(-12);
478
+ this.peerJoined = this.peerJoined.bind(this);
479
+ this.peerLeft = this.peerLeft.bind(this);
480
+ this.starLeft = this.starLeft.bind(this);
481
+ this.starJoined = this.starJoined.bind(this);
482
+ this.networkVersion = networkVersion;
483
+ this._init(stars);
484
+ }
485
+ async _init(stars = []) {
486
+ this.starsConfig = stars;
487
+ // reconnectJob()
488
+ if (!globalThis.RTCPeerConnection)
489
+ globalThis.wrtc = (await import('./browser-10ffabe1.js').then(function (n) { return n.b; })).default;
490
+ else
491
+ globalThis.wrtc = {
492
+ RTCPeerConnection,
493
+ RTCSessionDescription,
494
+ RTCIceCandidate
495
+ };
496
+ for (const star of stars) {
497
+ try {
498
+ this.socketClient = await socketRequestClient(star, this.networkVersion);
499
+ const id = await this.socketClient.request({ url: 'id', params: { from: this.id } });
500
+ this.socketClient.peerId = id;
501
+ this.#stars[id] = this.socketClient;
502
+ }
503
+ catch (e) {
504
+ if (stars.indexOf(star) === stars.length - 1 && !this.socketClient)
505
+ throw new Error(`No star available to connect`);
506
+ }
507
+ }
508
+ this.setupListeners();
509
+ const peers = await this.socketClient.peernet.join({ id: this.id });
510
+ for (const id of peers) {
511
+ if (id !== this.id && !this.#connections[id])
512
+ this.#connections[id] = await new Peer({ channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id });
513
+ }
514
+ pubsub.subscribe('connection closed', (peer) => {
515
+ this.removePeer(peer.peerId);
516
+ setTimeout(() => {
517
+ this.peerJoined(peer.peerId);
518
+ }, 1000);
519
+ });
520
+ }
521
+ setupListeners() {
522
+ this.socketClient.subscribe('peer:joined', this.peerJoined);
523
+ this.socketClient.subscribe('peer:left', this.peerLeft);
524
+ this.socketClient.subscribe('star:left', this.starLeft);
525
+ }
526
+ starJoined(id) {
527
+ if (this.#stars[id]) {
528
+ this.#stars[id].close();
529
+ delete this.#stars[id];
530
+ }
531
+ console.log(`star ${id} joined`);
532
+ }
533
+ async starLeft(id) {
534
+ if (this.#stars[id]) {
535
+ this.#stars[id].close();
536
+ delete this.#stars[id];
537
+ }
538
+ if (this.socketClient?.peerId === id) {
539
+ this.socketClient.unsubscribe('peer:joined', this.peerJoined);
540
+ this.socketClient.unsubscribe('peer:left', this.peerLeft);
541
+ this.socketClient.unsubscribe('star:left', this.starLeft);
542
+ this.socketClient.close();
543
+ this.socketClient = undefined;
544
+ for (const star of this.starsConfig) {
545
+ try {
546
+ this.socketClient = await socketRequestClient(star, this.networkVersion);
547
+ if (!this.socketClient?.client?._connection.connected)
548
+ return;
549
+ const id = await this.socketClient.request({ url: 'id', params: { from: this.id } });
550
+ this.#stars[id] = this.socketClient;
551
+ this.socketClient.peerId = id;
552
+ const peers = await this.socketClient.peernet.join({ id: this.id });
553
+ this.setupListeners();
554
+ for (const id of peers) {
555
+ if (id !== this.id) {
556
+ if (!this.#connections[id]) {
557
+ if (id !== this.id)
558
+ this.#connections[id] = await new Peer({ channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id });
559
+ }
560
+ }
561
+ }
562
+ }
563
+ catch (e) {
564
+ console.log(e);
565
+ if (this.starsConfig.indexOf(star) === this.starsConfig.length - 1 && !this.socketClient)
566
+ throw new Error(`No star available to connect`);
567
+ }
568
+ }
569
+ }
570
+ globalThis.debug(`star ${id} left`);
571
+ }
572
+ peerLeft(peer) {
573
+ const id = peer.peerId || peer;
574
+ if (this.#connections[id]) {
575
+ this.#connections[id].close();
576
+ delete this.#connections[id];
577
+ }
578
+ globalThis.debug(`peer ${id} left`);
579
+ }
580
+ async peerJoined(peer, signal) {
581
+ const id = peer.peerId || peer;
582
+ if (this.#connections[id]) {
583
+ if (this.#connections[id].connected)
584
+ this.#connections[id].close();
585
+ delete this.#connections[id];
586
+ }
587
+ // RTCPeerConnection
588
+ this.#connections[id] = await new Peer({ initiator: true, channelName: `${this.id}:${id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id });
589
+ globalThis.debug(`peer ${id} joined`);
590
+ }
591
+ removePeer(peer) {
592
+ const id = peer.peerId || peer;
593
+ if (this.#connections[id]) {
594
+ this.#connections[id].connected && this.#connections[id].close();
595
+ delete this.#connections[id];
596
+ }
597
+ globalThis.debug(`peer ${id} removed`);
598
+ }
599
+ async close() {
600
+ this.socketClient.unsubscribe('peer:joined', this.peerJoined);
601
+ this.socketClient.unsubscribe('peer:left', this.peerLeft);
602
+ this.socketClient.unsubscribe('star:left', this.starLeft);
603
+ const promises = [
604
+ Object.values(this.#connections).map(connection => connection.close()),
605
+ Object.values(this.#stars).map(connection => connection.close()),
606
+ this.socketClient.close()
607
+ ];
608
+ return Promise.allSettled(promises);
609
+ }
610
+ }
611
+
612
+ export { Client as default };
@@ -1,4 +1,4 @@
1
- import { M as MultiWallet, e as encrypt, b as base58$1 } from './peernet-7b231fd6.js';
1
+ import { M as MultiWallet, e as encrypt, b as base58$1 } from './peernet-f349ddaf.js';
2
2
  import './value-157ab062.js';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { F as FormatInterface } from './peernet-7b231fd6.js';
1
+ import { F as FormatInterface } from './peernet-f349ddaf.js';
2
2
  import './value-157ab062.js';
3
3
 
4
4
  var proto$b = {
@@ -2600,6 +2600,10 @@ var index = {
2600
2600
 
2601
2601
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2602
2602
 
2603
+ function getDefaultExportFromCjs (x) {
2604
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2605
+ }
2606
+
2603
2607
  function getAugmentedNamespace(n) {
2604
2608
  if (n.__esModule) return n;
2605
2609
  var f = n.default;
@@ -16082,7 +16086,7 @@ class Identity {
16082
16086
  globalThis.peernet.selectedAccount = new TextDecoder().decode(selected);
16083
16087
  }
16084
16088
  else {
16085
- const importee = await import(/* webpackChunkName: "generate-account" */ './index-4d744cf5.js');
16089
+ const importee = await import(/* webpackChunkName: "generate-account" */ './index-3d3f56ca.js');
16086
16090
  const { identity, accounts } = await importee.default(password, this.network);
16087
16091
  await globalThis.accountStore.put('public', JSON.stringify({ walletId: identity.walletId }));
16088
16092
  await globalThis.walletStore.put('version', String(1));
@@ -16252,7 +16256,7 @@ class Peernet {
16252
16256
  this.root = options.root;
16253
16257
  const { RequestMessage, ResponseMessage, PeerMessage, PeerMessageResponse, PeernetMessage, DHTMessage, DHTMessageResponse, DataMessage, DataMessageResponse, PsMessage, ChatMessage, PeernetFile
16254
16258
  // FolderMessageResponse
16255
- } = await import(/* webpackChunkName: "messages" */ './messages-4a94eee0.js');
16259
+ } = await import(/* webpackChunkName: "messages" */ './messages-af41e873.js');
16256
16260
  /**
16257
16261
  * proto Object containing protos
16258
16262
  * @type {Object}
@@ -16319,7 +16323,7 @@ class Peernet {
16319
16323
  if (this.#starting || this.#started)
16320
16324
  return;
16321
16325
  this.#starting = true;
16322
- const importee = await import('./client-238e0eb2.js');
16326
+ const importee = await import('./client-111c93a3.js');
16323
16327
  /**
16324
16328
  * @access public
16325
16329
  * @type {PeernetClient}
@@ -16754,4 +16758,4 @@ class Peernet {
16754
16758
  }
16755
16759
  globalThis.Peernet = Peernet;
16756
16760
 
16757
- export { FormatInterface as F, LittlePubSub as L, MultiWallet as M, Peernet as P, base58$1 as b, commonjsGlobal as c, encrypt as e, inherits_browserExports as i, require$$3 as r };
16761
+ export { FormatInterface as F, LittlePubSub as L, MultiWallet as M, Peernet as P, base58$1 as b, commonjsGlobal as c, encrypt as e, getDefaultExportFromCjs as g, inherits_browserExports as i, require$$3 as r };
@@ -1,2 +1,2 @@
1
- export { P as default } from './peernet-7b231fd6.js';
1
+ export { P as default } from './peernet-f349ddaf.js';
2
2
  import './value-157ab062.js';
@@ -1,229 +1,6 @@
1
- import { L as LittlePubSub, c as commonjsGlobal, r as require$$3, i as inherits_browserExports } from './peernet-7b231fd6.js';
1
+ import { c as commonjsGlobal, r as require$$3$1, i as inherits_browserExports, g as getDefaultExportFromCjs } from './peernet-f349ddaf.js';
2
2
  import './value-157ab062.js';
3
3
 
4
- var clientApi = _pubsub => {
5
-
6
- const subscribe = (topic, cb) => {
7
- _pubsub.subscribe(topic, cb);
8
- };
9
-
10
- const unsubscribe = (topic, cb) => {
11
- _pubsub.unsubscribe(topic, cb);
12
- };
13
-
14
- const publish = (topic, value) => {
15
- _pubsub.publish(topic, value);
16
- };
17
-
18
- const connectionState = (state) => {
19
- switch (state) {
20
- case 0:
21
- return 'connecting'
22
- case 1:
23
- return 'open'
24
- case 2:
25
- return 'closing'
26
- case 3:
27
- return 'closed'
28
- }
29
- };
30
- /**
31
- * @param {string} type
32
- * @param {string} name
33
- * @param {object} params
34
- */
35
- const request = (client, request) => {
36
- return new Promise((resolve, reject) => {
37
-
38
- const state = connectionState(client.readyState);
39
- if (state !== 'open') return reject(`coudn't send request to ${client.id}, no open connection found.`)
40
-
41
- request.id = Math.random().toString(36).slice(-12);
42
- const handler = result => {
43
- if (result && result.error) return reject(result.error)
44
- resolve({result, id: request.id, handler});
45
- unsubscribe(request.id, handler);
46
- };
47
- subscribe(request.id, handler);
48
- send(client, request);
49
- });
50
- };
51
-
52
- const send = async (client, request) => {
53
- return client.send(JSON.stringify(request))
54
- };
55
-
56
- const pubsub = client => {
57
- return {
58
- publish: (topic = 'pubsub', value) => {
59
- return send(client, {url: 'pubsub', params: { topic, value }})
60
- },
61
- subscribe: (topic = 'pubsub', cb) => {
62
- subscribe(topic, cb);
63
- return send(client, {url: 'pubsub', params: { topic, subscribe: true }})
64
- },
65
- unsubscribe: (topic = 'pubsub', cb) => {
66
- unsubscribe(topic, cb);
67
- return send(client, {url: 'pubsub', params: { topic, unsubscribe: true }})
68
- },
69
- subscribers: _pubsub.subscribers
70
- }
71
- };
72
-
73
- const server = (client) => {
74
- return {
75
- uptime: async () => {
76
- try {
77
- const { result, id, handler } = await request(client, {url: 'uptime'});
78
- unsubscribe(id, handler);
79
- return result
80
- } catch (e) {
81
- throw e
82
- }
83
- },
84
- ping: async () => {
85
- try {
86
- const now = new Date().getTime();
87
- const { result, id, handler } = await request(client, {url: 'ping'});
88
- unsubscribe(id, handler);
89
- return (Number(result) - now)
90
- } catch (e) {
91
- throw e
92
- }
93
- }
94
- }
95
- };
96
-
97
- const peernet = (client) => {
98
- return {
99
- join: async (params) => {
100
- try {
101
- params.join = true;
102
- const requested = { url: 'peernet', params };
103
- const { result, id, handler } = await request(client, requested);
104
- unsubscribe(id, handler);
105
- return result
106
- } catch (e) {
107
- throw e
108
- }
109
- },
110
- leave: async (params) => {
111
- try {
112
- params.join = false;
113
- const requested = { url: 'peernet', params };
114
- const { result, id, handler } = await request(client, requested);
115
- unsubscribe(id, handler);
116
- return result
117
- } catch (e) {
118
- throw e
119
- }
120
- }
121
- }
122
- };
123
-
124
- return { send, request, pubsub, server, subscribe, unsubscribe, publish, peernet, connectionState }
125
- };
126
-
127
- if (!globalThis.PubSub) globalThis.PubSub = LittlePubSub;
128
- if (!globalThis.pubsub) globalThis.pubsub = new LittlePubSub({verbose: false});
129
-
130
- const socketRequestClient = (url, protocols = 'echo-protocol', options = { retry: true, timeout: 10_000, times: 10 }) => {
131
- let { retry, timeout, times } = options;
132
- if (retry === undefined) retry = true;
133
- if (timeout === undefined) timeout = 10_000;
134
- if (times === undefined) times = 10;
135
-
136
- const api = clientApi(pubsub);
137
-
138
- let tries = 0;
139
-
140
- const onerror = error => {
141
- if (pubsub.subscribers['error']) {
142
- pubsub.publish('error', error);
143
- } else {
144
- console.error(error);
145
- }
146
- };
147
-
148
- const onmessage = message => {
149
- const {value, url, status, id} = JSON.parse(message.data.toString());
150
- const publisher = id ? id : url;
151
- if (status === 200) {
152
- pubsub.publish(publisher, value);
153
- } else {
154
- pubsub.publish(publisher, {error: value});
155
- }
156
- };
157
-
158
- const clientConnection = client => {
159
- const startTime = new Date().getTime();
160
- return {
161
- client,
162
- request: async req => {
163
- const { result, id, handler } = await api.request(client, req);
164
- pubsub.unsubscribe(id, handler);
165
- return result
166
- },
167
- send: req => api.send(client, req),
168
- subscribe: api.subscribe,
169
- unsubscribe: api.unsubscribe,
170
- subscribers: api.subscribers,
171
- publish: api.publish,
172
- pubsub: api.pubsub(client),
173
- uptime: () => {
174
- const now = new Date().getTime();
175
- return (now - startTime)
176
- },
177
- peernet: api.peernet(client),
178
- server: api.server(client),
179
- connectionState: () => api.connectionState(client.readyState),
180
- close: exit => {
181
- // client.onclose = message => {
182
- // if (exit) process.exit()
183
- // }
184
- client.close();
185
- }
186
- }
187
- };
188
-
189
- return new Promise(async (resolve, reject) => {
190
- const init = async () => {
191
- let ws;
192
- if (typeof process === 'object' && !globalThis.WebSocket) {
193
- ws = (await import('./browser-e1cd4e67.js').then(function (n) { return n.b; })).default;
194
- ws = ws.w3cwebsocket;
195
- } else {
196
- ws = WebSocket;
197
- }
198
- const client = new ws(url, protocols);
199
-
200
- client.onmessage = onmessage;
201
- client.onerror = onerror;
202
-
203
- client.onopen = () => {
204
- tries = 0;
205
- resolve(clientConnection(client));
206
- };
207
- client.onclose = message => {
208
- tries++;
209
- if (!retry) return reject(options)
210
- if (tries > times) {
211
- console.log(`${protocols} Client Closed`);
212
- console.error(`could not connect to - ${url}/`);
213
- return resolve(clientConnection(client))
214
- }
215
- if (message.code === 1006) {
216
- console.log(`Retrying in ${timeout} ms`);
217
- setTimeout(() => {
218
- return init();
219
- }, timeout);
220
- }
221
- };
222
- };
223
- return init();
224
- });
225
- };
226
-
227
4
  var browserExports$1 = {};
228
5
  var browser$2 = {
229
6
  get exports(){ return browserExports$1; },
@@ -947,6 +724,8 @@ var common = setup;
947
724
  };
948
725
  } (browser$2, browserExports$1));
949
726
 
727
+ var require$$0 = browserExports$1;
728
+
950
729
  // originally pulled out of simple-peer
951
730
 
952
731
  var getBrowserRtc = function getBrowserRTC () {
@@ -3944,7 +3723,7 @@ function requireBuffer_list () {
3944
3723
  function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
3945
3724
  const _require = buffer,
3946
3725
  Buffer = _require.Buffer;
3947
- const _require2 = require$$3,
3726
+ const _require2 = require$$3$1,
3948
3727
  inspect = _require2.inspect;
3949
3728
  const custom = inspect && inspect.custom || 'inspect';
3950
3729
  function copyBuffer(src, target, offset) {
@@ -5732,7 +5511,7 @@ function require_stream_readable () {
5732
5511
  }
5733
5512
 
5734
5513
  /*<replacement>*/
5735
- const debugUtil = require$$3;
5514
+ const debugUtil = require$$3$1;
5736
5515
  let debug;
5737
5516
  if (debugUtil && debugUtil.debuglog) {
5738
5517
  debug = debugUtil.debuglog('stream');
@@ -6939,6 +6718,8 @@ var pipeline_1 = pipeline;
6939
6718
  exports.pipeline = pipeline_1;
6940
6719
  } (readableBrowser, readableBrowserExports));
6941
6720
 
6721
+ var require$$3 = /*@__PURE__*/getDefaultExportFromCjs(readableBrowserExports);
6722
+
6942
6723
  /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
6943
6724
 
6944
6725
  let promise;
@@ -7020,10 +6801,10 @@ var errCode$1 = createError;
7020
6801
 
7021
6802
  /*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
7022
6803
 
7023
- const debug = browserExports$1('simple-peer');
6804
+ const debug = require$$0('simple-peer');
7024
6805
  const getBrowserRTC = getBrowserRtc;
7025
6806
  const randombytes = browserExports;
7026
- const stream = readableBrowserExports;
6807
+ const stream = require$$3;
7027
6808
  const queueMicrotask$1 = queueMicrotask_1; // TODO: remove when Node 10 is not supported
7028
6809
  const errCode = errCode$1;
7029
6810
  const { Buffer } = buffer;
@@ -7046,7 +6827,7 @@ function warn (message) {
7046
6827
  * Duplex stream.
7047
6828
  * @param {Object} opts
7048
6829
  */
7049
- let Peer$1 = class Peer extends stream.Duplex {
6830
+ class Peer extends stream.Duplex {
7050
6831
  constructor (opts) {
7051
6832
  opts = Object.assign({
7052
6833
  allowHalfOpen: false
@@ -8047,16 +7828,16 @@ let Peer$1 = class Peer extends stream.Duplex {
8047
7828
  args[0] = '[' + this._id + '] ' + args[0];
8048
7829
  debug.apply(null, args);
8049
7830
  }
8050
- };
7831
+ }
8051
7832
 
8052
- Peer$1.WEBRTC_SUPPORT = !!getBrowserRTC();
7833
+ Peer.WEBRTC_SUPPORT = !!getBrowserRTC();
8053
7834
 
8054
7835
  /**
8055
7836
  * Expose peer and data channel config for overriding all Peer
8056
7837
  * instances. Otherwise, just set opts.config or opts.channelConfig
8057
7838
  * when constructing a Peer.
8058
7839
  */
8059
- Peer$1.config = {
7840
+ Peer.config = {
8060
7841
  iceServers: [
8061
7842
  {
8062
7843
  urls: [
@@ -8068,391 +7849,8 @@ Peer$1.config = {
8068
7849
  sdpSemantics: 'unified-plan'
8069
7850
  };
8070
7851
 
8071
- Peer$1.channelConfig = {};
8072
-
8073
- var simplePeer = Peer$1;
8074
-
8075
- class Peer {
8076
- #connection;
8077
- #connected = false;
8078
- #messageQue = [];
8079
- #chunksQue = {};
8080
- #channel;
8081
- id;
8082
- #peerId;
8083
- #channelName;
8084
- #chunkSize = 16 * 1024; // 16384
8085
- #queRunning = false;
8086
- #MAX_BUFFERED_AMOUNT = 16 * 1024 * 1024;
8087
- initiator = false;
8088
- state;
8089
- #makingOffer = false;
8090
- get connection() {
8091
- return this.#connection;
8092
- }
8093
- get connected() {
8094
- return this.#connected;
8095
- }
8096
- get readyState() {
8097
- return this.#channel?.readyState;
8098
- }
8099
- get channelName() {
8100
- return this.#channelName;
8101
- }
8102
- /**
8103
- * @params {Object} options
8104
- * @params {string} options.channelName - this peerid : otherpeer id
8105
- */
8106
- constructor(options = {}) {
8107
- this._in = this._in.bind(this);
8108
- this.offerOptions = options.offerOptions;
8109
- this.initiator = options.initiator;
8110
- this.streams = options.streams;
8111
- this.socketClient = options.socketClient;
8112
- this.id = options.id;
8113
- this.to = options.to;
8114
- this.bw = {
8115
- up: 0,
8116
- down: 0
8117
- };
8118
- this.#channelName = options.channelName;
8119
- this.#peerId = options.peerId;
8120
- this.options = options;
8121
- return this.#init();
8122
- }
8123
- get peerId() {
8124
- return this.#peerId;
8125
- }
8126
- set socketClient(value) {
8127
- // this.socketClient?.pubsub.unsubscribe('signal', this._in)
8128
- this._socketClient = value;
8129
- this._socketClient.pubsub.subscribe('signal', this._in);
8130
- }
8131
- get socketClient() {
8132
- return this._socketClient;
8133
- }
8134
- splitMessage(message) {
8135
- const chunks = [];
8136
- message = pako.deflate(message);
8137
- const size = message.byteLength || message.length;
8138
- let offset = 0;
8139
- return new Promise((resolve, reject) => {
8140
- const splitMessage = () => {
8141
- const chunk = message.slice(offset, offset + this.#chunkSize > size ? size : offset + this.#chunkSize);
8142
- offset += this.#chunkSize;
8143
- chunks.push(chunk);
8144
- if (offset < size)
8145
- return splitMessage();
8146
- else
8147
- resolve({ chunks, size });
8148
- };
8149
- splitMessage();
8150
- });
8151
- }
8152
- async #runQue() {
8153
- this.#queRunning = true;
8154
- if (this.#messageQue.length > 0 && this.#channel?.bufferedAmount + this.#messageQue[0]?.length < this.#MAX_BUFFERED_AMOUNT) {
8155
- const message = this.#messageQue.shift();
8156
- await this.#connection.send(message);
8157
- if (this.#messageQue.length > 0)
8158
- return this.#runQue();
8159
- // switch (this.#channel?.readyState) {
8160
- // case 'open':
8161
- // await this.#channel.send(message);
8162
- // if (this.#messageQue.length > 0) return this.#runQue()
8163
- // else this.#queRunning = false
8164
- // break;
8165
- // case 'closed':
8166
- // case 'closing':
8167
- // this.#messageQue = []
8168
- // this.#queRunning = false
8169
- // debug('channel already closed, this usually means a bad implementation, try checking the readyState or check if the peer is connected before sending');
8170
- // break;
8171
- // case undefined:
8172
- // this.#messageQue = []
8173
- // this.#queRunning = false
8174
- // debug(`trying to send before a channel is created`);
8175
- // break;
8176
- // }
8177
- }
8178
- else {
8179
- return setTimeout(() => this.#runQue(), 50);
8180
- }
8181
- }
8182
- #trySend({ size, id, chunks }) {
8183
- let offset = 0;
8184
- for (const chunk of chunks) {
8185
- const start = offset;
8186
- const end = offset + chunk.length;
8187
- const message = new TextEncoder().encode(JSON.stringify({ size, id, chunk, start, end }));
8188
- this.#messageQue.push(message);
8189
- }
8190
- if (!this.queRunning)
8191
- return this.#runQue();
8192
- }
8193
- async send(message, id) {
8194
- const { chunks, size } = await this.splitMessage(message);
8195
- return this.#trySend({ size, id, chunks });
8196
- }
8197
- request(data) {
8198
- return new Promise((resolve, reject) => {
8199
- const id = Math.random().toString(36).slice(-12);
8200
- const _onData = message => {
8201
- if (message.id === id) {
8202
- resolve(message.data);
8203
- pubsub.unsubscribe(`peer:data`, _onData);
8204
- }
8205
- };
8206
- pubsub.subscribe(`peer:data`, _onData);
8207
- // cleanup subscriptions
8208
- // setTimeout(() => {
8209
- // pubsub.unsubscribe(`peer:data-request-${id}`, _onData)
8210
- // }, 5000);
8211
- this.send(data, id);
8212
- });
8213
- }
8214
- async #init() {
8215
- try {
8216
- if (!globalThis.pako) {
8217
- const importee = await import('./pako.esm-aa674ebf.js');
8218
- globalThis.pako = importee.default;
8219
- }
8220
- const iceServers = [{
8221
- urls: 'stun:stun.l.google.com:19302' // Google's public STUN server
8222
- }, {
8223
- urls: "stun:openrelay.metered.ca:80",
8224
- }, {
8225
- urls: "turn:openrelay.metered.ca:443",
8226
- username: "openrelayproject",
8227
- credential: "openrelayproject",
8228
- }, {
8229
- urls: "turn:openrelay.metered.ca:443?transport=tcp",
8230
- username: "openrelayproject",
8231
- credential: "openrelayproject",
8232
- }];
8233
- this.#connection = new simplePeer({
8234
- channelName: this.channelName,
8235
- initiator: this.initiator,
8236
- peerId: this.peerId,
8237
- wrtc: globalThis.wrtc,
8238
- config: {
8239
- iceServers
8240
- }
8241
- });
8242
- this.#connection.on('signal', signal => {
8243
- this._sendMessage({ signal });
8244
- });
8245
- this.#connection.on('connected', () => {
8246
- this.#connected = true;
8247
- pubsub.publish('peer:connected', this);
8248
- });
8249
- this.#connection.on('close', () => {
8250
- this.close();
8251
- });
8252
- this.#connection.on('data', data => {
8253
- this._handleMessage(data);
8254
- });
8255
- this.#connection.on('error', (e) => {
8256
- pubsub.publish('connection closed', this);
8257
- console.log(e);
8258
- this.close();
8259
- });
8260
- }
8261
- catch (e) {
8262
- console.log(e);
8263
- }
8264
- return this;
8265
- }
8266
- _handleMessage(message) {
8267
- console.log({ message });
8268
- message = JSON.parse(new TextDecoder().decode(message.data));
8269
- // allow sharding (multiple peers share data)
8270
- pubsub.publish('peernet:shard', message);
8271
- const { id } = message;
8272
- if (!this.#chunksQue[id])
8273
- this.#chunksQue[id] = [];
8274
- if (message.size > this.#chunksQue[id].length || message.size === this.#chunksQue[id].length) {
8275
- for (const value of Object.values(message.chunk)) {
8276
- this.#chunksQue[id].push(value);
8277
- }
8278
- }
8279
- if (message.size === this.#chunksQue[id].length) {
8280
- let data = new Uint8Array(Object.values(this.#chunksQue[id]));
8281
- delete this.#chunksQue[id];
8282
- data = pako.inflate(data);
8283
- pubsub.publish('peer:data', { id, data, from: this.peerId });
8284
- }
8285
- this.bw.down += message.byteLength || message.length;
8286
- }
8287
- _sendMessage(message) {
8288
- this.socketClient.send({ url: 'signal', params: {
8289
- to: this.to,
8290
- from: this.id,
8291
- channelName: this.channelName,
8292
- ...message
8293
- } });
8294
- }
8295
- async _in(message, data) {
8296
- if (message.signal)
8297
- return this.#connection.signal(message.signal);
8298
- }
8299
- close() {
8300
- // debug(`closing ${this.peerId}`)
8301
- this.#connected = false;
8302
- // this.#channel?.close()
8303
- // this.#connection?.exit()
8304
- this.socketClient.pubsub.unsubscribe('signal', this._in);
8305
- }
8306
- }
7852
+ Peer.channelConfig = {};
8307
7853
 
8308
- class Client {
8309
- #peerConnection;
8310
- #connections = {};
8311
- #stars = {};
8312
- id;
8313
- networkVersion;
8314
- starsConfig;
8315
- socketClient;
8316
- get connections() {
8317
- return { ...this.#connections };
8318
- }
8319
- get peers() {
8320
- return Object.entries(this.#connections);
8321
- }
8322
- constructor(id, networkVersion = 'peach', stars = ['wss://peach.leofcoin.org']) {
8323
- this.id = id || Math.random().toString(36).slice(-12);
8324
- this.peerJoined = this.peerJoined.bind(this);
8325
- this.peerLeft = this.peerLeft.bind(this);
8326
- this.starLeft = this.starLeft.bind(this);
8327
- this.starJoined = this.starJoined.bind(this);
8328
- this.networkVersion = networkVersion;
8329
- this._init(stars);
8330
- }
8331
- async _init(stars = []) {
8332
- this.starsConfig = stars;
8333
- // reconnectJob()
8334
- if (!globalThis.RTCPeerConnection)
8335
- globalThis.wrtc = (await import('./browser-10ffabe1.js').then(function (n) { return n.b; })).default;
8336
- else
8337
- globalThis.wrtc = {
8338
- RTCPeerConnection,
8339
- RTCSessionDescription,
8340
- RTCIceCandidate
8341
- };
8342
- for (const star of stars) {
8343
- try {
8344
- this.socketClient = await socketRequestClient(star, this.networkVersion);
8345
- const id = await this.socketClient.request({ url: 'id', params: { from: this.id } });
8346
- this.socketClient.peerId = id;
8347
- this.#stars[id] = this.socketClient;
8348
- }
8349
- catch (e) {
8350
- if (stars.indexOf(star) === stars.length - 1 && !this.socketClient)
8351
- throw new Error(`No star available to connect`);
8352
- }
8353
- }
8354
- this.setupListeners();
8355
- const peers = await this.socketClient.peernet.join({ id: this.id });
8356
- for (const id of peers) {
8357
- if (id !== this.id && !this.#connections[id])
8358
- this.#connections[id] = await new Peer({ channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id });
8359
- }
8360
- pubsub.subscribe('connection closed', (peer) => {
8361
- this.removePeer(peer.peerId);
8362
- setTimeout(() => {
8363
- this.peerJoined(peer.peerId);
8364
- }, 1000);
8365
- });
8366
- }
8367
- setupListeners() {
8368
- this.socketClient.subscribe('peer:joined', this.peerJoined);
8369
- this.socketClient.subscribe('peer:left', this.peerLeft);
8370
- this.socketClient.subscribe('star:left', this.starLeft);
8371
- }
8372
- starJoined(id) {
8373
- if (this.#stars[id]) {
8374
- this.#stars[id].close();
8375
- delete this.#stars[id];
8376
- }
8377
- console.log(`star ${id} joined`);
8378
- }
8379
- async starLeft(id) {
8380
- if (this.#stars[id]) {
8381
- this.#stars[id].close();
8382
- delete this.#stars[id];
8383
- }
8384
- if (this.socketClient?.peerId === id) {
8385
- this.socketClient.unsubscribe('peer:joined', this.peerJoined);
8386
- this.socketClient.unsubscribe('peer:left', this.peerLeft);
8387
- this.socketClient.unsubscribe('star:left', this.starLeft);
8388
- this.socketClient.close();
8389
- this.socketClient = undefined;
8390
- for (const star of this.starsConfig) {
8391
- try {
8392
- this.socketClient = await socketRequestClient(star, this.networkVersion);
8393
- if (!this.socketClient?.client?._connection.connected)
8394
- return;
8395
- const id = await this.socketClient.request({ url: 'id', params: { from: this.id } });
8396
- this.#stars[id] = this.socketClient;
8397
- this.socketClient.peerId = id;
8398
- const peers = await this.socketClient.peernet.join({ id: this.id });
8399
- this.setupListeners();
8400
- for (const id of peers) {
8401
- if (id !== this.id) {
8402
- if (!this.#connections[id]) {
8403
- if (id !== this.id)
8404
- this.#connections[id] = await new Peer({ channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id });
8405
- }
8406
- }
8407
- }
8408
- }
8409
- catch (e) {
8410
- console.log(e);
8411
- if (this.starsConfig.indexOf(star) === this.starsConfig.length - 1 && !this.socketClient)
8412
- throw new Error(`No star available to connect`);
8413
- }
8414
- }
8415
- }
8416
- globalThis.debug(`star ${id} left`);
8417
- }
8418
- peerLeft(peer) {
8419
- const id = peer.peerId || peer;
8420
- if (this.#connections[id]) {
8421
- this.#connections[id].close();
8422
- delete this.#connections[id];
8423
- }
8424
- globalThis.debug(`peer ${id} left`);
8425
- }
8426
- async peerJoined(peer, signal) {
8427
- const id = peer.peerId || peer;
8428
- if (this.#connections[id]) {
8429
- if (this.#connections[id].connected)
8430
- this.#connections[id].close();
8431
- delete this.#connections[id];
8432
- }
8433
- // RTCPeerConnection
8434
- this.#connections[id] = await new Peer({ initiator: true, channelName: `${this.id}:${id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id });
8435
- globalThis.debug(`peer ${id} joined`);
8436
- }
8437
- removePeer(peer) {
8438
- const id = peer.peerId || peer;
8439
- if (this.#connections[id]) {
8440
- this.#connections[id].connected && this.#connections[id].close();
8441
- delete this.#connections[id];
8442
- }
8443
- globalThis.debug(`peer ${id} removed`);
8444
- }
8445
- async close() {
8446
- this.socketClient.unsubscribe('peer:joined', this.peerJoined);
8447
- this.socketClient.unsubscribe('peer:left', this.peerLeft);
8448
- this.socketClient.unsubscribe('star:left', this.starLeft);
8449
- const promises = [
8450
- Object.values(this.#connections).map(connection => connection.close()),
8451
- Object.values(this.#stars).map(connection => connection.close()),
8452
- this.socketClient.close()
8453
- ];
8454
- return Promise.allSettled(promises);
8455
- }
8456
- }
7854
+ var simplePeer = Peer;
8457
7855
 
8458
- export { Client as default };
7856
+ export { simplePeer as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leofcoin/peernet",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "",
5
5
  "main": "src/peernet.js",
6
6
  "exports": {