@leofcoin/peernet 1.1.71 → 1.1.73

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.
@@ -1,4 +1,4 @@
1
- import { F as FormatInterface } from './peernet-509d1c89.js';
1
+ import { F as FormatInterface } from './peernet-0298b289.js';
2
2
  import './value-4e80eeeb.js';
3
3
 
4
4
  var proto$b = {
@@ -8,58 +8,62 @@ globalThis.debug = text => {
8
8
  if (globalThis.DEBUG) console.log('\x1b[34m\x1b[1m%s', text, '\x1b[0m'); // bright blue
9
9
  };
10
10
 
11
- class LittlePubSub {
12
- subscribers = {};
13
- verbose;
14
- constructor(verbose) {
15
- this.verbose = verbose;
16
- }
17
- _handleContext(handler, context) {
18
- if (typeof context === 'undefined') {
19
- context = handler;
20
- }
21
- return context;
22
- }
23
- hasSubscribers(event) {
24
- return this.subscribers[event] ? true : false;
25
- }
26
- subscribe(event, handler, context) {
27
- if (!this.hasSubscribers(event))
28
- this.subscribers[event] = { handlers: [], value: undefined };
29
- context = this._handleContext(handler, context);
30
- this.subscribers[event].handlers.push(handler.bind(context));
31
- }
32
- unsubscribe(event, handler, context) {
33
- if (!this.hasSubscribers(event))
34
- return;
35
- context = this._handleContext(handler, context);
36
- const index = this.subscribers[event].handlers.indexOf(handler.bind(context));
37
- this.subscribers[event].handlers.splice(index);
38
- if (this.subscribers[event].handlers.length === 0)
39
- delete this.subscribers[event];
40
- }
41
- publish(event, value) {
42
- // always set value even when having no subscribers
43
- if (!this.hasSubscribers(event))
44
- this.subscribers[event] = {
45
- handlers: []
46
- };
47
- const oldValue = this.subscribers[event]?.value;
48
- this.subscribers[event].value = value;
49
- if (this.verbose || oldValue !== value)
50
- for (const handler of this.subscribers[event].handlers) {
51
- handler(value, oldValue);
52
- }
53
- }
54
- once(event) {
55
- return new Promise((resolve) => {
56
- const cb = (value) => {
57
- this.unsubscribe(event, cb);
58
- resolve(value);
59
- };
60
- this.subscribe(event, cb);
61
- });
62
- }
11
+ class LittlePubSub {
12
+ subscribers = {};
13
+ verbose;
14
+ constructor(verbose) {
15
+ this.verbose = verbose;
16
+ }
17
+ _handleContext(handler, context) {
18
+ if (typeof context === 'undefined') {
19
+ context = handler;
20
+ }
21
+ return context;
22
+ }
23
+ hasSubscribers(event) {
24
+ return this.subscribers[event] ? true : false;
25
+ }
26
+ subscribe(event, handler, context) {
27
+ if (!this.hasSubscribers(event))
28
+ this.subscribers[event] = { handlers: [], value: undefined };
29
+ context = this._handleContext(handler, context);
30
+ this.subscribers[event].handlers.push(handler.bind(context));
31
+ }
32
+ unsubscribe(event, handler, context) {
33
+ if (!this.hasSubscribers(event))
34
+ return;
35
+ context = this._handleContext(handler, context);
36
+ const index = this.subscribers[event].handlers.indexOf(handler.bind(context));
37
+ this.subscribers[event].handlers.splice(index);
38
+ if (this.subscribers[event].handlers.length === 0)
39
+ delete this.subscribers[event];
40
+ }
41
+ publish(event, value, verbose) {
42
+ // always set value even when having no subscribers
43
+ if (!this.hasSubscribers(event))
44
+ this.subscribers[event] = {
45
+ handlers: []
46
+ };
47
+ const oldValue = this.subscribers[event]?.value;
48
+ if (this.verbose || verbose || oldValue !== value) {
49
+ this.subscribers[event].value = value;
50
+ for (const handler of this.subscribers[event].handlers) {
51
+ handler(value, oldValue);
52
+ }
53
+ }
54
+ }
55
+ publishVerbose(event, value) {
56
+ this.publish(event, value, true);
57
+ }
58
+ once(event) {
59
+ return new Promise((resolve) => {
60
+ const cb = (value) => {
61
+ resolve(value);
62
+ this.unsubscribe(event, cb);
63
+ };
64
+ this.subscribe(event, cb);
65
+ });
66
+ }
63
67
  }
64
68
 
65
69
  // base-x encoding / decoding
@@ -696,7 +700,7 @@ var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
696
700
  default: _nodeResolve_empty
697
701
  });
698
702
 
699
- var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1);
703
+ var require$$3 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1);
700
704
 
701
705
  bn$1.exports;
702
706
 
@@ -755,7 +759,7 @@ bn$1.exports;
755
759
  if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {
756
760
  Buffer = window.Buffer;
757
761
  } else {
758
- Buffer = require$$0$1.Buffer;
762
+ Buffer = require$$3.Buffer;
759
763
  }
760
764
  } catch (e) {
761
765
  }
@@ -13467,7 +13471,7 @@ bn.exports;
13467
13471
  if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {
13468
13472
  Buffer = window.Buffer;
13469
13473
  } else {
13470
- Buffer = require$$0$1.Buffer;
13474
+ Buffer = require$$3.Buffer;
13471
13475
  }
13472
13476
  } catch (e) {
13473
13477
  }
@@ -17111,7 +17115,7 @@ if (typeof self === 'object') {
17111
17115
  } else {
17112
17116
  // Node.js or Web worker with no crypto support
17113
17117
  try {
17114
- var crypto$1 = require$$0$1;
17118
+ var crypto$1 = require$$3;
17115
17119
  if (typeof crypto$1.randomBytes !== 'function')
17116
17120
  throw new Error('Not supported');
17117
17121
 
@@ -27088,7 +27092,7 @@ class Identity {
27088
27092
  this.selectedAccount = new TextDecoder().decode(selected);
27089
27093
  }
27090
27094
  else {
27091
- const importee = await import(/* webpackChunkName: "generate-account" */ './index-2836cc96.js');
27095
+ const importee = await import(/* webpackChunkName: "generate-account" */ './index-81687e93.js');
27092
27096
  const { identity, accounts } = await importee.default(password, this.network);
27093
27097
  await globalThis.accountStore.put('public', JSON.stringify({ walletId: identity.walletId }));
27094
27098
  await globalThis.walletStore.put('version', String(1));
@@ -27279,7 +27283,7 @@ class Peernet {
27279
27283
  this.root = options.root;
27280
27284
  const { RequestMessage, ResponseMessage, PeerMessage, PeerMessageResponse, PeernetMessage, DHTMessage, DHTMessageResponse, DataMessage, DataMessageResponse, PsMessage, ChatMessage, PeernetFile
27281
27285
  // FolderMessageResponse
27282
- } = await import(/* webpackChunkName: "messages" */ './messages-554d2a85.js');
27286
+ } = await import(/* webpackChunkName: "messages" */ './messages-cccb78db.js');
27283
27287
  /**
27284
27288
  * proto Object containing protos
27285
27289
  * @type {Object}
@@ -27373,238 +27377,7 @@ class Peernet {
27373
27377
  if (this.#starting || this.#started)
27374
27378
  return;
27375
27379
  this.#starting = true;
27376
- const importee = class Client {
27377
- #peerId;
27378
- #connections = {};
27379
- #stars = {};
27380
- #connectEvent = 'peer:connected';
27381
- id;
27382
- networkVersion;
27383
- starsConfig;
27384
- socketClient;
27385
- messageSize = 262144;
27386
- version;
27387
- #messagesToHandle = {};
27388
- get peerId() {
27389
- return this.#peerId;
27390
- }
27391
- get connections() {
27392
- return { ...this.#connections };
27393
- }
27394
- get peers() {
27395
- return Object.entries(this.#connections);
27396
- }
27397
- getPeer(peerId) {
27398
- return this.#connections[peerId];
27399
- }
27400
- /**
27401
- *
27402
- * @param options {object}
27403
- * @param options.peerId {string}
27404
- * @param options.networkVersion {string}
27405
- * @param options.version {string}
27406
- * @param options.stars {string[]}
27407
- * @param options.connectEvent {string} defaults to peer:connected, can be renamed to handle different protocols, like peer:discovered (setup peer props before fireing the connect event)
27408
- */
27409
- constructor(options) {
27410
- const { peerId, networkVersion, version, connectEvent, stars } = {
27411
- ...defaultOptions,
27412
- ...options
27413
- };
27414
- this.#peerId = peerId;
27415
- this.networkVersion = networkVersion;
27416
- this.version = version;
27417
- this.#connectEvent = connectEvent;
27418
- this.starsConfig = stars;
27419
- this._init();
27420
- }
27421
- async _init() {
27422
- // reconnectJob()
27423
- if (!globalThis.RTCPeerConnection)
27424
- globalThis.wrtc = (await import('./browser-2c73e2ef.js').then(function (n) { return n.b; })).default;
27425
- for (const star of this.starsConfig) {
27426
- try {
27427
- const client = new SocketRequestClient(star, this.networkVersion);
27428
- this.#stars[star] = await client.init();
27429
- this.setupStarListeners(this.#stars[star]);
27430
- this.#stars[star].send({
27431
- url: 'join',
27432
- params: { version: this.version, peerId: this.peerId }
27433
- });
27434
- }
27435
- catch (e) {
27436
- if (this.starsConfig.indexOf(star) === this.starsConfig.length - 1 &&
27437
- !this.socketClient)
27438
- throw new Error(`No star available to connect`);
27439
- }
27440
- }
27441
- if (globalThis.navigator) {
27442
- globalThis.addEventListener('beforeunload', async () => this.close());
27443
- }
27444
- else {
27445
- process.on('SIGINT', async () => {
27446
- process.stdin.resume();
27447
- await this.close();
27448
- process.exit();
27449
- });
27450
- }
27451
- }
27452
- setupStarListeners(star) {
27453
- star.pubsub.subscribe('peer:joined', (id) => this.#peerJoined(id, star));
27454
- star.pubsub.subscribe('peer:left', (id) => this.#peerLeft(id, star));
27455
- star.pubsub.subscribe('star:joined', this.#starJoined);
27456
- star.pubsub.subscribe('star:left', this.#starLeft);
27457
- star.pubsub.subscribe('signal', (message) => this.#inComingSignal(message, star));
27458
- }
27459
- #starJoined = (id) => {
27460
- if (this.#stars[id]) {
27461
- this.#stars[id].close(0);
27462
- delete this.#stars[id];
27463
- }
27464
- console.log(`star ${id} joined`);
27465
- };
27466
- #starLeft = async (id) => {
27467
- if (this.#stars[id]) {
27468
- this.#stars[id].close(0);
27469
- delete this.#stars[id];
27470
- }
27471
- if (Object.keys(this.#stars).length === 0) {
27472
- for (const star of this.starsConfig) {
27473
- try {
27474
- const socketClient = await new SocketRequestClient(star, this.networkVersion).init();
27475
- if (!socketClient?.client?.OPEN)
27476
- return;
27477
- this.#stars[star] = socketClient;
27478
- this.#stars[star].send({
27479
- url: 'join',
27480
- params: { peerId: this.peerId, version: this.version }
27481
- });
27482
- this.setupStarListeners(socketClient);
27483
- }
27484
- catch (e) {
27485
- if (this.starsConfig.indexOf(star) === this.starsConfig.length - 1)
27486
- throw new Error(`No star available to connect`);
27487
- }
27488
- }
27489
- }
27490
- globalThis.debug(`star ${id} left`);
27491
- };
27492
- #peerLeft(peer, star) {
27493
- const id = peer.peerId || peer;
27494
- if (this.#connections[id]) {
27495
- this.#connections[id].destroy();
27496
- delete this.#connections[id];
27497
- }
27498
- globalThis.debug(`peer ${id} left`);
27499
- }
27500
- #createRTCPeerConnection = (peerId, star, version, initiator = false) => {
27501
- const peer = new Peer({
27502
- initiator: initiator,
27503
- from: this.peerId,
27504
- to: peerId,
27505
- version
27506
- });
27507
- peer.on('signal', (signal) => this.#peerSignal(peer, signal, star, this.version));
27508
- peer.on('connect', () => this.#peerConnect(peer));
27509
- peer.on('close', () => this.#peerClose(peer));
27510
- peer.on('data', (data) => this.#peerData(peer, data));
27511
- peer.on('error', (error) => this.#peerError(peer, error));
27512
- this.#connections[peerId] = peer;
27513
- };
27514
- #peerJoined = async ({ peerId, version }, star) => {
27515
- // check if peer rejoined before the previous connection closed
27516
- if (this.#connections[peerId]) {
27517
- if (this.#connections[peerId].connected)
27518
- this.#connections[peerId].destroy();
27519
- delete this.#connections[peerId];
27520
- }
27521
- // RTCPeerConnection
27522
- this.#createRTCPeerConnection(peerId, star, version, true);
27523
- globalThis.debug(`peer ${peerId} joined`);
27524
- };
27525
- #inComingSignal = async ({ from, signal, channelName, version }, star) => {
27526
- if (version !== this.version) {
27527
- console.warn(`${from} joined using the wrong version.\nexpected: ${this.version} but got:${version}`);
27528
- return;
27529
- }
27530
- let peer = this.#connections[from];
27531
- if (!peer) {
27532
- this.#createRTCPeerConnection(from, star, version);
27533
- peer = this.#connections[from];
27534
- }
27535
- if (String(peer.channelName) !== String(channelName))
27536
- console.warn(`channelNames don't match: got ${peer.channelName}, expected: ${channelName}`);
27537
- peer.signal(signal);
27538
- };
27539
- #peerSignal = (peer, signal, star, version) => {
27540
- let client = this.#stars[star];
27541
- if (!client)
27542
- client = this.#stars[Object.keys(this.#stars)[0]];
27543
- client.send({
27544
- url: 'signal',
27545
- params: {
27546
- from: this.peerId,
27547
- to: peer.peerId,
27548
- channelName: peer.channelName,
27549
- version,
27550
- signal
27551
- }
27552
- });
27553
- };
27554
- #peerClose = (peer) => {
27555
- if (this.#connections[peer.peerId]) {
27556
- this.#connections[peer.peerId].destroy();
27557
- delete this.#connections[peer.peerId];
27558
- }
27559
- globalThis.debug(`closed ${peer.peerId}'s connection`);
27560
- };
27561
- #peerConnect = (peer) => {
27562
- globalThis.debug(`${peer.peerId} connected`);
27563
- globalThis.pubsub.publish(this.#connectEvent, peer.peerId);
27564
- };
27565
- #noticeMessage = (message, id) => {
27566
- if (globalThis.pubsub.subscribers[id]) {
27567
- globalThis.pubsub.publish(id, new Uint8Array(message));
27568
- }
27569
- else {
27570
- globalThis.pubsub.publish('peer:data', new Uint8Array(message));
27571
- }
27572
- };
27573
- #peerData = (peer, data) => {
27574
- const { id, size, chunk } = JSON.parse(new TextDecoder().decode(data));
27575
- peer.bw.down += size;
27576
- if (size <= MAX_MESSAGE_SIZE) {
27577
- this.#noticeMessage(chunk, id);
27578
- }
27579
- else {
27580
- if (!this.#messagesToHandle[id])
27581
- this.#messagesToHandle[id] = [];
27582
- this.#messagesToHandle[id] = [
27583
- ...this.#messagesToHandle[id],
27584
- ...Object.values(chunk)
27585
- ];
27586
- if (this.#messagesToHandle[id].length === Number(size)) {
27587
- this.#noticeMessage(this.#messagesToHandle[id], id);
27588
- delete this.#messagesToHandle[id];
27589
- }
27590
- }
27591
- };
27592
- #peerError = (peer, error) => {
27593
- console.warn(`Connection error: ${error.message}`);
27594
- peer.destroy();
27595
- };
27596
- async close() {
27597
- for (const star in this.#stars) {
27598
- if (this.#stars[star].connectionState() === 'open')
27599
- await this.#stars[star].send({ url: 'leave', params: this.peerId });
27600
- }
27601
- const promises = [
27602
- Object.values(this.#connections).map((connection) => connection.destroy()),
27603
- Object.values(this.#stars).map((connection) => connection.close(0))
27604
- ];
27605
- await Promise.allSettled(promises);
27606
- }
27607
- };
27380
+ const importee = await import('./client-f193279c.js');
27608
27381
  /**
27609
27382
  * @access public
27610
27383
  * @type {PeernetClient}
@@ -27635,9 +27408,23 @@ class Peernet {
27635
27408
  if (peer.connected) {
27636
27409
  await peer.send(data, id);
27637
27410
  this.bw.up += data.length;
27411
+ return id;
27412
+ }
27413
+ else {
27414
+ return new Promise((resolve, reject) => {
27415
+ const onError = (error) => {
27416
+ this.removePeer(peer);
27417
+ reject(error);
27418
+ };
27419
+ peer.once('error', onError);
27420
+ peer.once('connect', async () => {
27421
+ await peer.send(data, id);
27422
+ this.bw.up += data.length;
27423
+ peer.removeListener('error', onError);
27424
+ resolve(id);
27425
+ });
27426
+ });
27638
27427
  }
27639
- else
27640
- this.removePeer(peer);
27641
27428
  }
27642
27429
  async handleDHT(peer, id, proto) {
27643
27430
  let { hash, store } = proto.decoded;
@@ -28064,4 +27851,4 @@ class Peernet {
28064
27851
  }
28065
27852
  globalThis.Peernet = Peernet;
28066
27853
 
28067
- export { FormatInterface as F, MultiWallet as M, Peernet as P, base58$1 as b, encrypt as e };
27854
+ 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 };
@@ -106,7 +106,7 @@ export default class Peernet {
106
106
  }, password: string): Promise<Peernet>;
107
107
  start(): Promise<void>;
108
108
  addRequestHandler(name: any, method: any): void;
109
- sendMessage(peer: any, id: any, data: any): Promise<void>;
109
+ sendMessage(peer: any, id: any, data: any): Promise<any>;
110
110
  handleDHT(peer: any, id: any, proto: any): Promise<void>;
111
111
  handleData(peer: any, id: any, proto: any): Promise<void>;
112
112
  handleRequest(peer: any, id: any, proto: any): Promise<void>;
@@ -1,2 +1,2 @@
1
- export { P as default } from './peernet-509d1c89.js';
1
+ export { P as default } from './peernet-0298b289.js';
2
2
  import './value-4e80eeeb.js';
@@ -665,9 +665,23 @@ class Peernet {
665
665
  if (peer.connected) {
666
666
  await peer.send(data, id);
667
667
  this.bw.up += data.length;
668
+ return id;
669
+ }
670
+ else {
671
+ return new Promise((resolve, reject) => {
672
+ const onError = (error) => {
673
+ this.removePeer(peer);
674
+ reject(error);
675
+ };
676
+ peer.once('error', onError);
677
+ peer.once('connect', async () => {
678
+ await peer.send(data, id);
679
+ this.bw.up += data.length;
680
+ peer.removeListener('error', onError);
681
+ resolve(id);
682
+ });
683
+ });
668
684
  }
669
- else
670
- this.removePeer(peer);
671
685
  }
672
686
  async handleDHT(peer, id, proto) {
673
687
  let { hash, store } = proto.decoded;
@@ -106,7 +106,7 @@ export default class Peernet {
106
106
  }, password: string): Promise<Peernet>;
107
107
  start(): Promise<void>;
108
108
  addRequestHandler(name: any, method: any): void;
109
- sendMessage(peer: any, id: any, data: any): Promise<void>;
109
+ sendMessage(peer: any, id: any, data: any): Promise<any>;
110
110
  handleDHT(peer: any, id: any, proto: any): Promise<void>;
111
111
  handleData(peer: any, id: any, proto: any): Promise<void>;
112
112
  handleRequest(peer: any, id: any, proto: any): Promise<void>;
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@leofcoin/peernet",
3
- "version": "1.1.71",
3
+ "version": "1.1.73",
4
4
  "description": "",
5
- "main": "src/peernet.js",
5
+ "browser": "./exports/browser/peernet.js",
6
6
  "exports": {
7
7
  ".": {
8
8
  "import": "./exports/peernet.js",
@@ -66,7 +66,6 @@
66
66
  "eslint-plugin-unicorn": "^45.0.1",
67
67
  "node-stdlib-browser": "^1.2.0",
68
68
  "rollup": "^3.12.0",
69
- "rollup-plugin-modify": "^3.0.0",
70
69
  "webpack-cli": "^5.0.1"
71
70
  }
72
71
  }
package/rollup.config.js CHANGED
@@ -1,10 +1,9 @@
1
- import resolve, { nodeResolve } from '@rollup/plugin-node-resolve'
1
+ import resolve from '@rollup/plugin-node-resolve'
2
2
  import commonjs from '@rollup/plugin-commonjs'
3
3
  import json from '@rollup/plugin-json'
4
4
  import wasm from '@rollup/plugin-wasm'
5
5
  import rimraf from 'rimraf'
6
6
  import typescript from '@rollup/plugin-typescript'
7
- import modify from 'rollup-plugin-modify'
8
7
 
9
8
  rimraf.sync('./exports/**')
10
9
 
@@ -18,9 +17,6 @@ export default [
18
17
  plugins: [
19
18
  json(),
20
19
  wasm(),
21
- modify({
22
- "await import('@netpeer/swarm/client')": (await import('@netpeer/swarm/browser')).default.toString()
23
- }),
24
20
  resolve({
25
21
  browser: true,
26
22
  preferBuiltins: false,
@@ -41,9 +37,6 @@ export default [
41
37
  dir: './exports'
42
38
  },
43
39
  plugins: [
44
- modify({
45
- '@netpeer/swarm/client': '@netpeer/swarm/client'
46
- }),
47
40
  typescript({
48
41
  compilerOptions: {
49
42
  outDir: './exports',
package/src/peernet.ts CHANGED
@@ -348,7 +348,22 @@ export default class Peernet {
348
348
  if (peer.connected) {
349
349
  await peer.send(data, id)
350
350
  this.bw.up += data.length
351
- } else this.removePeer(peer)
351
+ return id
352
+ } else {
353
+ return new Promise((resolve, reject) => {
354
+ const onError = (error) => {
355
+ this.removePeer(peer)
356
+ reject(error)
357
+ }
358
+ peer.once('error', onError)
359
+ peer.once('connect', async () => {
360
+ await peer.send(data, id)
361
+ this.bw.up += data.length
362
+ peer.removeListener('error', onError)
363
+ resolve(id)
364
+ })
365
+ })
366
+ }
352
367
  }
353
368
 
354
369
  async handleDHT(peer, id, proto) {