peerpigeon 0.0.1 โ†’ 0.0.3

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.
Files changed (43) hide show
  1. package/README.md +4 -4
  2. package/examples/browser/index.html +2 -2
  3. package/examples/node/test-node.js +153 -0
  4. package/index.js +12 -0
  5. package/package.json +3 -3
  6. package/src/ConnectionManager.js +11 -4
  7. package/src/EnvironmentDetector.js +441 -0
  8. package/src/GossipManager.js +11 -3
  9. package/src/MediaManager.js +14 -0
  10. package/src/PeerConnection.js +30 -13
  11. package/src/PeerDiscovery.js +10 -3
  12. package/src/PeerPigeonMesh.js +187 -2
  13. package/src/SignalingClient.js +67 -14
  14. package/src/StorageManager.js +48 -6
  15. package/src/TimerUtils.js +36 -8
  16. package/websocket-server/README.md +0 -10
  17. package/websocket-server/server.js +1 -1
  18. package/examples/browser/app-dht-disabled.js +0 -42
  19. package/examples/browser/index-dht-disabled.html +0 -123
  20. package/examples/browser/ui-clean.js +0 -0
  21. package/websocket-server/memory-leak-test.js +0 -193
  22. package/websocket-server/node_modules/.package-lock.json +0 -29
  23. package/websocket-server/node_modules/ws/LICENSE +0 -20
  24. package/websocket-server/node_modules/ws/README.md +0 -548
  25. package/websocket-server/node_modules/ws/browser.js +0 -8
  26. package/websocket-server/node_modules/ws/index.js +0 -13
  27. package/websocket-server/node_modules/ws/lib/buffer-util.js +0 -131
  28. package/websocket-server/node_modules/ws/lib/constants.js +0 -18
  29. package/websocket-server/node_modules/ws/lib/event-target.js +0 -292
  30. package/websocket-server/node_modules/ws/lib/extension.js +0 -203
  31. package/websocket-server/node_modules/ws/lib/limiter.js +0 -55
  32. package/websocket-server/node_modules/ws/lib/permessage-deflate.js +0 -528
  33. package/websocket-server/node_modules/ws/lib/receiver.js +0 -706
  34. package/websocket-server/node_modules/ws/lib/sender.js +0 -602
  35. package/websocket-server/node_modules/ws/lib/stream.js +0 -161
  36. package/websocket-server/node_modules/ws/lib/subprotocol.js +0 -62
  37. package/websocket-server/node_modules/ws/lib/validation.js +0 -152
  38. package/websocket-server/node_modules/ws/lib/websocket-server.js +0 -550
  39. package/websocket-server/node_modules/ws/lib/websocket.js +0 -1388
  40. package/websocket-server/node_modules/ws/package.json +0 -69
  41. package/websocket-server/node_modules/ws/wrapper.mjs +0 -8
  42. package/websocket-server/package-lock.json +0 -39
  43. package/websocket-server/test.js +0 -133
package/src/TimerUtils.js CHANGED
@@ -3,11 +3,23 @@
3
3
  * by debugging tools, preventing "Illegal invocation" errors.
4
4
  */
5
5
 
6
+ import { environmentDetector } from './EnvironmentDetector.js';
7
+
6
8
  // Store original timer functions to avoid issues with wrapped functions
7
- const originalSetInterval = window.setInterval;
8
- const originalSetTimeout = window.setTimeout;
9
- const originalClearInterval = window.clearInterval;
10
- const originalClearTimeout = window.clearTimeout;
9
+ let originalSetInterval, originalSetTimeout, originalClearInterval, originalClearTimeout;
10
+
11
+ if (environmentDetector.isBrowser) {
12
+ originalSetInterval = window.setInterval;
13
+ originalSetTimeout = window.setTimeout;
14
+ originalClearInterval = window.clearInterval;
15
+ originalClearTimeout = window.clearTimeout;
16
+ } else {
17
+ // In Node.js or other environments, use global functions
18
+ originalSetInterval = setInterval;
19
+ originalSetTimeout = setTimeout;
20
+ originalClearInterval = clearInterval;
21
+ originalClearTimeout = clearTimeout;
22
+ }
11
23
 
12
24
  /**
13
25
  * Safe setInterval that uses the original function to avoid context issues
@@ -16,7 +28,11 @@ const originalClearTimeout = window.clearTimeout;
16
28
  * @returns {number} - Interval ID
17
29
  */
18
30
  export function safeSetInterval(callback, delay) {
19
- return originalSetInterval.call(window, callback, delay);
31
+ if (environmentDetector.isBrowser) {
32
+ return originalSetInterval.call(window, callback, delay);
33
+ } else {
34
+ return originalSetInterval(callback, delay);
35
+ }
20
36
  }
21
37
 
22
38
  /**
@@ -26,7 +42,11 @@ export function safeSetInterval(callback, delay) {
26
42
  * @returns {number} - Timeout ID
27
43
  */
28
44
  export function safeSetTimeout(callback, delay) {
29
- return originalSetTimeout.call(window, callback, delay);
45
+ if (environmentDetector.isBrowser) {
46
+ return originalSetTimeout.call(window, callback, delay);
47
+ } else {
48
+ return originalSetTimeout(callback, delay);
49
+ }
30
50
  }
31
51
 
32
52
  /**
@@ -34,7 +54,11 @@ export function safeSetTimeout(callback, delay) {
34
54
  * @param {number} id - Interval ID to clear
35
55
  */
36
56
  export function safeClearInterval(id) {
37
- return originalClearInterval.call(window, id);
57
+ if (environmentDetector.isBrowser) {
58
+ return originalClearInterval.call(window, id);
59
+ } else {
60
+ return originalClearInterval(id);
61
+ }
38
62
  }
39
63
 
40
64
  /**
@@ -42,5 +66,9 @@ export function safeClearInterval(id) {
42
66
  * @param {number} id - Timeout ID to clear
43
67
  */
44
68
  export function safeClearTimeout(id) {
45
- return originalClearTimeout.call(window, id);
69
+ if (environmentDetector.isBrowser) {
70
+ return originalClearTimeout.call(window, id);
71
+ } else {
72
+ return originalClearTimeout(id);
73
+ }
46
74
  }
@@ -220,16 +220,6 @@ Browser Client 1 Browser Client 2 Browser Client N
220
220
  (peers, connections)
221
221
  ```
222
222
 
223
- ## Comparison with AWS
224
-
225
- | Feature | Local Server | AWS WebSocket |
226
- |---------|-------------|---------------|
227
- | Cost | Free | Pay per message |
228
- | Scalability | Single machine | Auto-scaling |
229
- | Persistence | In-memory | DynamoDB |
230
- | Deployment | Local only | Global |
231
- | Development | Instant | Deploy cycle |
232
-
233
223
  ## Troubleshooting
234
224
 
235
225
  ### Common Issues
@@ -5,7 +5,7 @@ import { URL } from 'url';
5
5
  /**
6
6
  * Local WebSocket Server for PeerPigeon Development
7
7
  *
8
- * This server mimics the AWS WebSocket API Gateway functionality
8
+ * This server provides WebSocket signaling functionality
9
9
  * for local development and testing of the PeerPigeon mesh network.
10
10
  */
11
11
 
@@ -1,42 +0,0 @@
1
- import { PeerPigeonMesh } from '../../src/PeerPigeonMesh.js';
2
- import { PeerPigeonUI } from './ui.js';
3
-
4
- class PeerPigeonApp {
5
- constructor() {
6
- // Test: Initialize mesh with WebDHT disabled to demonstrate the UI setting
7
- this.mesh = new PeerPigeonMesh({ enableWebDHT: false });
8
-
9
- // To enable WebDHT (default), use:
10
- // this.mesh = new PeerPigeonMesh();
11
- // this.mesh = new PeerPigeonMesh({ enableWebDHT: true });
12
-
13
- this.ui = new PeerPigeonUI(this.mesh);
14
- this.init();
15
- }
16
-
17
- async init() {
18
- try {
19
- await this.mesh.init();
20
- this.ui.updateUI();
21
- this.setupUnloadHandler();
22
- } catch (error) {
23
- console.error('Failed to initialize app:', error);
24
- }
25
- }
26
-
27
- setupUnloadHandler() {
28
- const handleUnload = () => {
29
- if (this.mesh.connected) {
30
- this.mesh.sendGoodbyeMessage();
31
- }
32
- };
33
-
34
- window.addEventListener('beforeunload', handleUnload);
35
- window.addEventListener('unload', handleUnload);
36
- }
37
- }
38
-
39
- // Initialize the app when the page loads
40
- document.addEventListener('DOMContentLoaded', () => {
41
- new PeerPigeonApp();
42
- });
@@ -1,123 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>PeerPigeon - DHT Disabled Demo</title>
7
- <link rel="icon" type="image/png" href="assets/images/favicon.png">
8
- <link rel="stylesheet" href="styles.css">
9
- <style>
10
- .demo-notice {
11
- background: #fff3cd;
12
- border: 1px solid #ffeaa7;
13
- border-radius: 6px;
14
- padding: 12px;
15
- margin: 20px auto;
16
- max-width: 600px;
17
- text-align: center;
18
- color: #856404;
19
- font-weight: 500;
20
- }
21
- </style>
22
- </head>
23
- <body>
24
- <div class="container">
25
- <header>
26
- <h1>
27
- <img src="assets/images/pigeon.png" alt="PeerPigeon Logo">
28
- PeerPigeon Demo - DHT Disabled
29
- </h1>
30
- <p>WebRTC-based peer-to-peer mesh networking with intelligent routing</p>
31
- <div class="demo-notice">
32
- ๐Ÿ”ง <strong>Demo Mode:</strong> This demo shows PeerPigeon with WebDHT disabled.
33
- Check the Settings section to see the DHT status indicator.
34
- </div>
35
- <div class="usage-hint">
36
- <strong>Quick Start:</strong>
37
- 1. Open multiple browser tabs/windows with this page<br>
38
- 2. Enter a signaling server URL (or use <code>?api=your-api-gateway-url</code> in URL)<br>
39
- 3. Click Connect - all tabs will automatically discover and connect to each other<br>
40
- 4. Notice that DHT operations will show error messages since DHT is disabled
41
- </div>
42
- </header>
43
-
44
- <main>
45
- <!-- Include the same content as index.html but referencing the modified app.js -->
46
- <!-- Copy the entire main content from index.html -->
47
- <div class="peer-info">
48
- <div class="section-header">
49
- <h2>
50
- <button id="peer-info-toggle" class="toggle-btn" aria-expanded="true">
51
- โ–ผ Peer Info
52
- </button>
53
- </h2>
54
- </div>
55
- <div id="peer-info-content" class="collapsible-content">
56
- <div class="info-group">
57
- <label>Peer ID:</label>
58
- <span id="peer-id">Not initialized</span>
59
- </div>
60
- <div class="info-group">
61
- <label>Status:</label>
62
- <span id="status" class="status disconnected">Disconnected</span>
63
- </div>
64
- <div class="info-group">
65
- <label>Connected Peers:</label>
66
- <span id="peer-count">0</span>
67
- </div>
68
- <div class="input-group">
69
- <label for="signaling-url-main">Signaling Server URL:</label>
70
- <div class="input-group horizontal">
71
- <input type="url" id="signaling-url-main"
72
- placeholder="https://your-api-gateway.execute-api.region.amazonaws.com/dev">
73
- <div class="button-group">
74
- <button id="connect-btn" class="btn primary">Connect</button>
75
- <button id="disconnect-btn" class="btn secondary" disabled>Disconnect</button>
76
- </div>
77
- </div>
78
- <small class="input-help">
79
- Auto-populated from ?api, ?url, or ?signaling query parameters
80
- </small>
81
- </div>
82
- </div>
83
- </div>
84
-
85
- <!-- Rest of the UI components would go here... -->
86
- <!-- For brevity, showing just the key Settings section -->
87
-
88
- <div class="settings" aria-expanded="false">
89
- <div class="section-header">
90
- <h2>
91
- <button id="settings-toggle" class="toggle-btn" aria-expanded="false">
92
- โ–ถ Settings
93
- </button>
94
- </h2>
95
- </div>
96
- <div id="settings-content" class="collapsible-content" style="display: none;">
97
- <div class="input-group">
98
- <label for="signaling-url">Signaling Server URL:</label>
99
- <input type="url" id="signaling-url"
100
- placeholder="https://your-api-gateway.execute-api.region.amazonaws.com/dev">
101
- <small class="input-help">
102
- Auto-populated from ?api, ?url, or ?signaling query parameters. Enter base API Gateway URL (without /signaling path).
103
- </small>
104
- </div>
105
-
106
- <div class="auto-discovery-control">
107
- <label class="checkbox-label">
108
- <input type="checkbox" id="webdht-toggle" checked disabled>
109
- <span class="checkmark"></span>
110
- Enable WebDHT (Distributed Hash Table)
111
- </label>
112
- <small class="input-help">
113
- WebDHT status (configured at startup, restart required to change)
114
- </small>
115
- </div>
116
- </div>
117
- </div>
118
- </main>
119
- </div>
120
-
121
- <script type="module" src="app-dht-disabled.js"></script>
122
- </body>
123
- </html>
File without changes
@@ -1,193 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Memory Leak Test Script
5
- *
6
- * This script helps identify memory leaks by repeatedly connecting and disconnecting
7
- * multiple peers, monitoring memory usage.
8
- */
9
-
10
- import { WebSocket } from 'ws';
11
-
12
- // Configuration
13
- const SERVER_URL = 'ws://localhost:3000';
14
- const NUM_PEERS = 5;
15
- const CYCLES = 10;
16
- const CYCLE_DURATION = 5000; // 5 seconds per cycle
17
-
18
- // Track memory usage
19
- let initialMemory = 0;
20
- let cycleCount = 0;
21
-
22
- // Generate a random 40-character hex peer ID
23
- function generatePeerId() {
24
- return Array.from({ length: 40 }, () => Math.floor(Math.random() * 16).toString(16)).join('');
25
- }
26
-
27
- // Get memory usage
28
- function getMemoryUsage() {
29
- if (typeof process !== 'undefined' && process.memoryUsage) {
30
- return process.memoryUsage().heapUsed / 1024 / 1024; // MB
31
- }
32
- return 0;
33
- }
34
-
35
- // Create a test peer that will be disconnected
36
- function createTestPeer(peerId) {
37
- return new Promise((resolve, reject) => {
38
- const ws = new WebSocket(`${SERVER_URL}?peerId=${peerId}`);
39
- let pingInterval;
40
-
41
- ws.on('open', () => {
42
- console.log(`โœ… Peer ${peerId.substring(0, 8)}... connected`);
43
-
44
- // Send announcement
45
- ws.send(JSON.stringify({
46
- type: 'announce',
47
- data: { peerId }
48
- }));
49
-
50
- // Send periodic pings
51
- pingInterval = setInterval(() => {
52
- if (ws.readyState === WebSocket.OPEN) {
53
- ws.send(JSON.stringify({
54
- type: 'ping',
55
- data: { timestamp: Date.now() }
56
- }));
57
- }
58
- }, 2000);
59
-
60
- resolve({ ws, peerId, pingInterval });
61
- });
62
-
63
- ws.on('message', (data) => {
64
- try {
65
- const message = JSON.parse(data);
66
- if (message.type === 'peer-discovered') {
67
- console.log(`๐Ÿ” Peer ${peerId.substring(0, 8)}... discovered: ${message.data.peerId.substring(0, 8)}...`);
68
- }
69
- } catch (error) {
70
- console.error(`โŒ Parse error for ${peerId.substring(0, 8)}...:`, error);
71
- }
72
- });
73
-
74
- ws.on('close', () => {
75
- if (pingInterval) {
76
- clearInterval(pingInterval);
77
- }
78
- console.log(`๐Ÿ”Œ Peer ${peerId.substring(0, 8)}... disconnected`);
79
- });
80
-
81
- ws.on('error', (error) => {
82
- if (pingInterval) {
83
- clearInterval(pingInterval);
84
- }
85
- console.error(`โŒ Peer ${peerId.substring(0, 8)}... error:`, error.message);
86
- reject(error);
87
- });
88
- });
89
- }
90
-
91
- // Run a single cycle
92
- async function runCycle() {
93
- cycleCount++;
94
- console.log(`\n๐Ÿ”„ Starting cycle ${cycleCount}/${CYCLES}`);
95
-
96
- // Create peers
97
- const peers = [];
98
- for (let i = 0; i < NUM_PEERS; i++) {
99
- const peerId = generatePeerId();
100
- try {
101
- const peer = await createTestPeer(peerId);
102
- peers.push(peer);
103
- } catch (error) {
104
- console.error(`โŒ Failed to create peer ${peerId.substring(0, 8)}...:`, error);
105
- }
106
- }
107
-
108
- console.log(`๐Ÿ“Š Created ${peers.length} peers`);
109
-
110
- // Wait for cycle duration
111
- await new Promise(resolve => setTimeout(resolve, CYCLE_DURATION));
112
-
113
- // Disconnect all peers
114
- console.log('๐Ÿงน Disconnecting all peers...');
115
- peers.forEach(({ ws, peerId, pingInterval }) => {
116
- if (pingInterval) {
117
- clearInterval(pingInterval);
118
- }
119
- if (ws.readyState === WebSocket.OPEN) {
120
- ws.send(JSON.stringify({
121
- type: 'goodbye',
122
- data: { peerId }
123
- }));
124
- ws.close();
125
- }
126
- });
127
-
128
- // Wait for cleanup
129
- await new Promise(resolve => setTimeout(resolve, 1000));
130
-
131
- // Check memory usage
132
- const currentMemory = getMemoryUsage();
133
- const memoryDelta = currentMemory - initialMemory;
134
-
135
- console.log(`๐Ÿ“ˆ Memory usage: ${currentMemory.toFixed(2)} MB (delta: ${memoryDelta > 0 ? '+' : ''}${memoryDelta.toFixed(2)} MB)`);
136
-
137
- if (memoryDelta > 50) { // Alert if memory increased by more than 50MB
138
- console.warn(`โš ๏ธ Potential memory leak detected! Memory increased by ${memoryDelta.toFixed(2)} MB`);
139
- }
140
- }
141
-
142
- // Main test function
143
- async function runMemoryTest() {
144
- console.log(`๐Ÿš€ Starting memory leak test`);
145
- console.log(`๐Ÿ“ก Server URL: ${SERVER_URL}`);
146
- console.log(`๐Ÿ‘ฅ Peers per cycle: ${NUM_PEERS}`);
147
- console.log(`๐Ÿ”„ Cycles: ${CYCLES}`);
148
- console.log(`โฑ๏ธ Cycle duration: ${CYCLE_DURATION / 1000} seconds`);
149
-
150
- // Record initial memory
151
- initialMemory = getMemoryUsage();
152
- console.log(`๐Ÿ“Š Initial memory usage: ${initialMemory.toFixed(2)} MB`);
153
-
154
- // Run cycles
155
- for (let i = 0; i < CYCLES; i++) {
156
- try {
157
- await runCycle();
158
- } catch (error) {
159
- console.error(`โŒ Cycle ${i + 1} failed:`, error);
160
- }
161
- }
162
-
163
- // Final memory check
164
- const finalMemory = getMemoryUsage();
165
- const totalDelta = finalMemory - initialMemory;
166
-
167
- console.log(`\n๐Ÿ“Š Final Results:`);
168
- console.log(`Initial memory: ${initialMemory.toFixed(2)} MB`);
169
- console.log(`Final memory: ${finalMemory.toFixed(2)} MB`);
170
- console.log(`Total delta: ${totalDelta > 0 ? '+' : ''}${totalDelta.toFixed(2)} MB`);
171
-
172
- if (totalDelta > 100) {
173
- console.error(`โŒ Memory leak detected! Total increase: ${totalDelta.toFixed(2)} MB`);
174
- process.exit(1);
175
- } else {
176
- console.log(`โœ… Memory usage appears stable (increase: ${totalDelta.toFixed(2)} MB)`);
177
- process.exit(0);
178
- }
179
- }
180
-
181
- // Handle errors
182
- process.on('uncaughtException', (error) => {
183
- console.error('โŒ Uncaught Exception:', error);
184
- process.exit(1);
185
- });
186
-
187
- process.on('unhandledRejection', (reason, promise) => {
188
- console.error('โŒ Unhandled Rejection at:', promise, 'reason:', reason);
189
- process.exit(1);
190
- });
191
-
192
- // Run the test
193
- runMemoryTest().catch(console.error);
@@ -1,29 +0,0 @@
1
- {
2
- "name": "local-websocket-server",
3
- "version": "1.0.0",
4
- "lockfileVersion": 3,
5
- "requires": true,
6
- "packages": {
7
- "node_modules/ws": {
8
- "version": "8.18.3",
9
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
10
- "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
11
- "license": "MIT",
12
- "engines": {
13
- "node": ">=10.0.0"
14
- },
15
- "peerDependencies": {
16
- "bufferutil": "^4.0.1",
17
- "utf-8-validate": ">=5.0.2"
18
- },
19
- "peerDependenciesMeta": {
20
- "bufferutil": {
21
- "optional": true
22
- },
23
- "utf-8-validate": {
24
- "optional": true
25
- }
26
- }
27
- }
28
- }
29
- }
@@ -1,20 +0,0 @@
1
- Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
2
- Copyright (c) 2013 Arnout Kazemier and contributors
3
- Copyright (c) 2016 Luigi Pinca and contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of
6
- this software and associated documentation files (the "Software"), to deal in
7
- the Software without restriction, including without limitation the rights to
8
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
- the Software, and to permit persons to whom the Software is furnished to do so,
10
- subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
- IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.