peerpigeon 0.0.1

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 (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1187 -0
  3. package/examples/browser/app-dht-disabled.js +42 -0
  4. package/examples/browser/app.js +51 -0
  5. package/examples/browser/assets/images/favicon.png +0 -0
  6. package/examples/browser/assets/images/pigeon.png +0 -0
  7. package/examples/browser/index-dht-disabled.html +123 -0
  8. package/examples/browser/index.html +340 -0
  9. package/examples/browser/styles.css +1288 -0
  10. package/examples/browser/ui-clean.js +0 -0
  11. package/examples/browser/ui.js +1930 -0
  12. package/index.js +8 -0
  13. package/package.json +70 -0
  14. package/server/index.js +515 -0
  15. package/src/CleanupManager.js +181 -0
  16. package/src/ConnectionManager.js +841 -0
  17. package/src/EventEmitter.js +27 -0
  18. package/src/EvictionManager.js +257 -0
  19. package/src/GossipManager.js +416 -0
  20. package/src/MediaManager.js +225 -0
  21. package/src/MeshOptimizer.js +181 -0
  22. package/src/PeerConnection.js +831 -0
  23. package/src/PeerDiscovery.js +297 -0
  24. package/src/PeerPigeonMesh.js +703 -0
  25. package/src/SignalingClient.js +536 -0
  26. package/src/SignalingHandler.js +325 -0
  27. package/src/StorageManager.js +88 -0
  28. package/src/TimerUtils.js +46 -0
  29. package/src/WebDHT.js +1099 -0
  30. package/websocket-server/README.md +257 -0
  31. package/websocket-server/memory-leak-test.js +193 -0
  32. package/websocket-server/node_modules/.package-lock.json +29 -0
  33. package/websocket-server/node_modules/ws/LICENSE +20 -0
  34. package/websocket-server/node_modules/ws/README.md +548 -0
  35. package/websocket-server/node_modules/ws/browser.js +8 -0
  36. package/websocket-server/node_modules/ws/index.js +13 -0
  37. package/websocket-server/node_modules/ws/lib/buffer-util.js +131 -0
  38. package/websocket-server/node_modules/ws/lib/constants.js +18 -0
  39. package/websocket-server/node_modules/ws/lib/event-target.js +292 -0
  40. package/websocket-server/node_modules/ws/lib/extension.js +203 -0
  41. package/websocket-server/node_modules/ws/lib/limiter.js +55 -0
  42. package/websocket-server/node_modules/ws/lib/permessage-deflate.js +528 -0
  43. package/websocket-server/node_modules/ws/lib/receiver.js +706 -0
  44. package/websocket-server/node_modules/ws/lib/sender.js +602 -0
  45. package/websocket-server/node_modules/ws/lib/stream.js +161 -0
  46. package/websocket-server/node_modules/ws/lib/subprotocol.js +62 -0
  47. package/websocket-server/node_modules/ws/lib/validation.js +152 -0
  48. package/websocket-server/node_modules/ws/lib/websocket-server.js +550 -0
  49. package/websocket-server/node_modules/ws/lib/websocket.js +1388 -0
  50. package/websocket-server/node_modules/ws/package.json +69 -0
  51. package/websocket-server/node_modules/ws/wrapper.mjs +8 -0
  52. package/websocket-server/package-lock.json +39 -0
  53. package/websocket-server/server.js +298 -0
  54. package/websocket-server/test.js +133 -0
@@ -0,0 +1,703 @@
1
+ import { EventEmitter } from './EventEmitter.js';
2
+ import { SignalingClient } from './SignalingClient.js';
3
+ import { PeerDiscovery } from './PeerDiscovery.js';
4
+ import { ConnectionManager } from './ConnectionManager.js';
5
+ import { SignalingHandler } from './SignalingHandler.js';
6
+ import { EvictionManager } from './EvictionManager.js';
7
+ import { MeshOptimizer } from './MeshOptimizer.js';
8
+ import { CleanupManager } from './CleanupManager.js';
9
+ import { StorageManager } from './StorageManager.js';
10
+ import { GossipManager } from './GossipManager.js';
11
+ import { MediaManager } from './MediaManager.js';
12
+ import { WebDHT } from './WebDHT.js';
13
+
14
+ export class PeerPigeonMesh extends EventEmitter {
15
+ constructor(options = {}) {
16
+ super();
17
+ this.peerId = null;
18
+ this.providedPeerId = options.peerId || null;
19
+ this.signalingClient = null;
20
+ this.peerDiscovery = null;
21
+
22
+ // Configuration
23
+ this.maxPeers = 3;
24
+ this.minPeers = 2;
25
+ this.autoDiscovery = true;
26
+ this.evictionStrategy = true;
27
+ this.xorRouting = true;
28
+ this.enableWebDHT = options.enableWebDHT !== false; // Default to true, can be disabled by setting to false
29
+
30
+ // State
31
+ this.connected = false;
32
+ this.polling = false; // Only WebSocket is supported
33
+ this.signalingUrl = null;
34
+ this.discoveredPeers = new Map();
35
+ this.connectionMonitorInterval = null;
36
+
37
+ // Initialize managers
38
+ this.storageManager = new StorageManager(this);
39
+ this.mediaManager = new MediaManager();
40
+ this.connectionManager = new ConnectionManager(this);
41
+ this.evictionManager = new EvictionManager(this, this.connectionManager);
42
+ this.meshOptimizer = new MeshOptimizer(this, this.connectionManager, this.evictionManager);
43
+ this.cleanupManager = new CleanupManager(this);
44
+ this.signalingHandler = new SignalingHandler(this, this.connectionManager);
45
+ this.gossipManager = new GossipManager(this, this.connectionManager);
46
+ this.webDHT = null; // Will be initialized after peerId is set
47
+
48
+ // Set up inter-module event forwarding
49
+ this.setupManagerEventHandlers();
50
+
51
+ // Set up unload handlers
52
+ this.cleanupManager.setupUnloadHandlers();
53
+
54
+ // Load saved signaling URL immediately
55
+ this.storageManager.loadSignalingUrlFromStorage();
56
+ }
57
+
58
+ setupManagerEventHandlers() {
59
+ // Forward events from managers to main mesh
60
+ this.connectionManager.addEventListener('peersUpdated', () => {
61
+ this.emit('peersUpdated');
62
+ });
63
+
64
+ // Track successful connections to reset isolation timer
65
+ this.connectionManager.addEventListener('peerConnected', (data) => {
66
+ if (this.peerDiscovery) {
67
+ this.peerDiscovery.onConnectionEstablished();
68
+ }
69
+ this.emit('peerConnected', data);
70
+ });
71
+
72
+ // Handle peer disconnections and trigger keep-alive ping coordination
73
+ this.addEventListener('peerDisconnected', (data) => {
74
+ console.log(`Peer ${data.peerId.substring(0, 8)}... disconnected: ${data.reason}`);
75
+ // Trigger immediate keep-alive ping check in case the disconnected peer was the designated sender
76
+ if (this.signalingClient && this.signalingClient.connected) {
77
+ setTimeout(() => {
78
+ this.signalingClient.triggerKeepAlivePingCheck();
79
+ }, 1000); // Small delay to let peer lists update
80
+ }
81
+ });
82
+
83
+ // Handle gossip messages
84
+ this.gossipManager.addEventListener('messageReceived', (data) => {
85
+ this.emit('messageReceived', data);
86
+ });
87
+
88
+ // Forward media events
89
+ this.mediaManager.addEventListener('localStreamStarted', (data) => {
90
+ this.emit('localStreamStarted', data);
91
+ });
92
+
93
+ this.mediaManager.addEventListener('localStreamStopped', () => {
94
+ this.emit('localStreamStopped');
95
+ });
96
+
97
+ this.mediaManager.addEventListener('error', (data) => {
98
+ this.emit('mediaError', data);
99
+ });
100
+
101
+ // Forward remote stream events from ConnectionManager
102
+ this.connectionManager.addEventListener('remoteStream', (data) => {
103
+ this.emit('remoteStream', data);
104
+ });
105
+ }
106
+
107
+ async init() {
108
+ try {
109
+ // Use provided peer ID if valid, otherwise generate one
110
+ if (this.providedPeerId) {
111
+ if (this.storageManager.validatePeerId(this.providedPeerId)) {
112
+ this.peerId = this.providedPeerId;
113
+ console.log(`Using provided peer ID: ${this.peerId}`);
114
+ } else {
115
+ console.warn(`Invalid peer ID provided: ${this.providedPeerId}. Must be 40-character SHA-1 hex string. Generating new one.`);
116
+ this.peerId = await this.storageManager.generatePeerId();
117
+ }
118
+ } else {
119
+ this.peerId = await this.storageManager.generatePeerId();
120
+ }
121
+
122
+ // Initialize WebDHT now that we have a peerId (if enabled)
123
+ if (this.enableWebDHT) {
124
+ this.webDHT = new WebDHT(this);
125
+ console.log('WebDHT initialized and enabled');
126
+
127
+ // Setup WebDHT event handlers now that it's initialized
128
+ this.setupWebDHTEventHandlers();
129
+ } else {
130
+ console.log('WebDHT disabled by configuration');
131
+ }
132
+
133
+ // Load signaling URL from query params or storage
134
+ const savedUrl = this.storageManager.loadSignalingUrlFromQuery();
135
+ if (savedUrl) {
136
+ this.signalingUrl = savedUrl;
137
+ }
138
+
139
+ this.signalingClient = new SignalingClient(this.peerId, this.maxPeers, this);
140
+ this.setupSignalingHandlers();
141
+
142
+ this.peerDiscovery = new PeerDiscovery(this.peerId, {
143
+ autoDiscovery: this.autoDiscovery,
144
+ evictionStrategy: this.evictionStrategy,
145
+ xorRouting: this.xorRouting,
146
+ minPeers: this.minPeers,
147
+ maxPeers: this.maxPeers
148
+ });
149
+ this.setupDiscoveryHandlers();
150
+
151
+ this.emit('statusChanged', { type: 'initialized', peerId: this.peerId });
152
+ } catch (error) {
153
+ console.error('Failed to initialize mesh:', error);
154
+ this.emit('statusChanged', { type: 'error', message: `Initialization failed: ${error.message}` });
155
+ throw error;
156
+ }
157
+ }
158
+
159
+ setupSignalingHandlers() {
160
+ this.signalingClient.addEventListener('connected', () => {
161
+ this.connected = true;
162
+ this.polling = false;
163
+ this.peerDiscovery.start();
164
+
165
+ // Start periodic health monitoring
166
+ this.startConnectionMonitoring();
167
+
168
+ this.emit('statusChanged', { type: 'connected' });
169
+ });
170
+
171
+ this.signalingClient.addEventListener('disconnected', () => {
172
+ this.connected = false;
173
+ this.polling = false;
174
+ this.peerDiscovery.stop();
175
+ this.connectionManager.disconnectAllPeers();
176
+ this.stopConnectionMonitoring();
177
+ this.emit('statusChanged', { type: 'disconnected' });
178
+ });
179
+
180
+ this.signalingClient.addEventListener('signalingMessage', (message) => {
181
+ this.signalingHandler.handleSignalingMessage(message);
182
+ });
183
+
184
+ this.signalingClient.addEventListener('statusChanged', (data) => {
185
+ this.emit('statusChanged', data);
186
+ });
187
+ }
188
+
189
+ setupDiscoveryHandlers() {
190
+ this.peerDiscovery.addEventListener('peerDiscovered', (data) => {
191
+ this.emit('peerDiscovered', data);
192
+ });
193
+
194
+ this.peerDiscovery.addEventListener('connectToPeer', (data) => {
195
+ console.log(`PeerDiscovery requested connection to: ${data.peerId.substring(0, 8)}...`);
196
+ this.connectionManager.connectToPeer(data.peerId);
197
+ });
198
+
199
+ this.peerDiscovery.addEventListener('evictPeer', (data) => {
200
+ this.evictionManager.evictPeer(data.peerId, data.reason);
201
+ });
202
+
203
+ this.peerDiscovery.addEventListener('optimizeMesh', () => {
204
+ this.peerDiscovery.optimizeMeshConnections(this.connectionManager.peers);
205
+ });
206
+
207
+ this.peerDiscovery.addEventListener('optimizeConnections', (data) => {
208
+ this.meshOptimizer.handleOptimizeConnections(data.unconnectedPeers);
209
+ });
210
+
211
+ this.peerDiscovery.addEventListener('peersUpdated', (data) => {
212
+ this.emit('statusChanged', { type: 'info', message: `Cleaned up ${data.removedCount} stale peer(s)` });
213
+ this.emit('peersUpdated');
214
+ });
215
+
216
+ // Handle capacity checks
217
+ this.peerDiscovery.addEventListener('checkCapacity', () => {
218
+ const canAccept = this.connectionManager.canAcceptMorePeers();
219
+ const currentConnectionCount = this.connectionManager.getConnectedPeerCount();
220
+ console.log(`Capacity check: ${canAccept} (${currentConnectionCount}/${this.maxPeers} peers)`);
221
+ this.peerDiscovery._canAcceptMorePeers = canAccept;
222
+ this.peerDiscovery._currentConnectionCount = currentConnectionCount;
223
+ });
224
+
225
+ // Handle eviction checks
226
+ this.peerDiscovery.addEventListener('checkEviction', (data) => {
227
+ const evictPeerId = this.evictionManager.shouldEvictForPeer(data.newPeerId);
228
+ console.log(`Eviction check for ${data.newPeerId.substring(0, 8)}...: ${evictPeerId ? evictPeerId.substring(0, 8) + '...' : 'none'}`);
229
+ this.peerDiscovery._shouldEvictForPeer = evictPeerId;
230
+ });
231
+ }
232
+
233
+ async connect(signalingUrl) {
234
+ this.signalingUrl = signalingUrl;
235
+ this.storageManager.saveSignalingUrlToStorage(signalingUrl);
236
+ this.polling = false; // Only WebSocket is supported
237
+ // Don't emit connecting here - SignalingClient will handle it with more detail
238
+
239
+ try {
240
+ await this.signalingClient.connect(signalingUrl);
241
+ } catch (error) {
242
+ console.error('Connection failed:', error);
243
+ this.polling = false;
244
+ this.emit('statusChanged', { type: 'error', message: `Connection failed: ${error.message}` });
245
+ throw error;
246
+ }
247
+ }
248
+
249
+ disconnect() {
250
+ if (this.connected) {
251
+ this.cleanupManager.sendGoodbyeMessage();
252
+ }
253
+
254
+ this.connected = false;
255
+ this.polling = false;
256
+
257
+ // Stop connection monitoring
258
+ this.stopConnectionMonitoring();
259
+
260
+ if (this.signalingClient) {
261
+ this.signalingClient.disconnect();
262
+ }
263
+
264
+ if (this.peerDiscovery) {
265
+ this.peerDiscovery.stop();
266
+ }
267
+
268
+ this.connectionManager.disconnectAllPeers();
269
+ this.connectionManager.cleanup();
270
+
271
+ // Cleanup WebDHT
272
+ if (this.webDHT) {
273
+ this.webDHT.cleanup();
274
+ }
275
+ this.evictionManager.cleanup();
276
+ this.cleanupManager.cleanup();
277
+ this.gossipManager.cleanup();
278
+
279
+ this.emit('statusChanged', { type: 'disconnected' });
280
+ }
281
+
282
+ // Configuration methods
283
+ setMaxPeers(maxPeers) {
284
+ this.maxPeers = Math.max(1, Math.min(50, maxPeers));
285
+
286
+ if (this.connectionManager.peers.size > this.maxPeers) {
287
+ this.evictionManager.disconnectExcessPeers();
288
+ }
289
+
290
+ return this.maxPeers;
291
+ }
292
+
293
+ setMinPeers(minPeers) {
294
+ this.minPeers = Math.max(0, Math.min(49, minPeers));
295
+
296
+ // If we're below minimum and auto-discovery is enabled, trigger optimization
297
+ if (this.connectionManager.getConnectedPeerCount() < this.minPeers && this.autoDiscovery && this.connected) {
298
+ this.peerDiscovery.optimizeMeshConnections(this.connectionManager.peers);
299
+ }
300
+
301
+ return this.minPeers;
302
+ }
303
+
304
+ setXorRouting(enabled) {
305
+ this.xorRouting = enabled;
306
+ this.emit('statusChanged', { type: 'setting', setting: 'xorRouting', value: enabled });
307
+
308
+ // If XOR routing is disabled, we might need to adjust our connection strategy
309
+ if (!enabled && this.evictionStrategy) {
310
+ this.emit('statusChanged', { type: 'warning', message: 'XOR routing disabled - eviction strategy effectiveness reduced' });
311
+ }
312
+ }
313
+
314
+ setAutoDiscovery(enabled) {
315
+ this.autoDiscovery = enabled;
316
+ this.emit('statusChanged', { type: 'setting', setting: 'autoDiscovery', value: enabled });
317
+ }
318
+
319
+ setEvictionStrategy(enabled) {
320
+ this.evictionStrategy = enabled;
321
+ this.emit('statusChanged', { type: 'setting', setting: 'evictionStrategy', value: enabled });
322
+ }
323
+
324
+ // Status and information methods
325
+ getStatus() {
326
+ const connectedCount = this.connectionManager.getConnectedPeerCount();
327
+ const totalCount = this.connectionManager.peers.size;
328
+ return {
329
+ peerId: this.peerId,
330
+ connected: this.connected,
331
+ polling: false, // Only WebSocket is supported
332
+ connectedCount: connectedCount,
333
+ totalPeerCount: totalCount, // Include total count for debugging
334
+ minPeers: this.minPeers,
335
+ maxPeers: this.maxPeers,
336
+ discoveredCount: this.discoveredPeers.size,
337
+ autoDiscovery: this.autoDiscovery,
338
+ evictionStrategy: this.evictionStrategy,
339
+ xorRouting: this.xorRouting
340
+ };
341
+ }
342
+
343
+ getPeers() {
344
+ return this.connectionManager.getPeers();
345
+ }
346
+
347
+ getPeerStatus(peerConnection) {
348
+ return peerConnection.getStatus();
349
+ }
350
+
351
+ getDiscoveredPeers() {
352
+ if (!this.peerDiscovery) {
353
+ return [];
354
+ }
355
+ const discoveredPeers = this.peerDiscovery.getDiscoveredPeers();
356
+
357
+ // Enrich with connection state from the actual peer connections
358
+ return discoveredPeers.map(peer => {
359
+ const peerConnection = this.connectionManager.getPeer(peer.peerId);
360
+ let isConnected = false;
361
+
362
+ if (peerConnection) {
363
+ const status = peerConnection.getStatus();
364
+ // Consider peer connected if WebRTC connection is established
365
+ isConnected = status === 'connected' || status === 'channel-connecting';
366
+ }
367
+
368
+ return {
369
+ ...peer,
370
+ isConnected
371
+ };
372
+ });
373
+ }
374
+
375
+ /**
376
+ * Send a direct message to a specific peer via gossip routing
377
+ * @param {string} targetPeerId - The destination peer's ID
378
+ * @param {string|object} content - The message content
379
+ * @returns {string|null} The message ID if sent, or null on error
380
+ */
381
+ sendDirectMessage(targetPeerId, content) {
382
+ if (!targetPeerId || typeof targetPeerId !== 'string') {
383
+ console.error('Invalid targetPeerId for direct message');
384
+ return null;
385
+ }
386
+ return this.gossipManager.sendDirectMessage(targetPeerId, content);
387
+ }
388
+
389
+ /**
390
+ * Send a broadcast (gossip) message to all peers
391
+ * @param {string|object} content - The message content
392
+ * @returns {string|null} The message ID if sent, or null on error
393
+ */
394
+ sendMessage(content) {
395
+ // For clarity, this is a broadcast/gossip message
396
+ return this.gossipManager.broadcastMessage(content, 'chat');
397
+ }
398
+
399
+ // Helper methods for backward compatibility
400
+ canAcceptMorePeers() {
401
+ return this.connectionManager.canAcceptMorePeers();
402
+ }
403
+
404
+ getConnectedPeerCount() {
405
+ return this.connectionManager.getConnectedPeerCount();
406
+ }
407
+
408
+ // Expose peers Map for backward compatibility
409
+ get peers() {
410
+ return this.connectionManager.peers;
411
+ }
412
+
413
+ // Get peer status method for UI compatibility
414
+ getPeerStatus(peer) {
415
+ if (!peer) return 'unknown';
416
+ return peer.getStatus ? peer.getStatus() : 'unknown';
417
+ }
418
+
419
+ // Get connected peer IDs as array for UI compatibility
420
+ getConnectedPeerIds() {
421
+ return this.connectionManager.getPeers()
422
+ .filter(peer => peer.status === 'connected')
423
+ .map(peer => peer.peerId);
424
+ }
425
+
426
+ // Advanced methods
427
+ async cleanupStaleSignalingData() {
428
+ return this.cleanupManager.cleanupStaleSignalingData();
429
+ }
430
+
431
+ forceConnectToAllPeers() {
432
+ return this.meshOptimizer.forceConnectToAllPeers();
433
+ }
434
+
435
+ // Debugging and maintenance methods
436
+ forceCleanupInvalidPeers() {
437
+ console.log('Force cleaning up peers not in connected state...');
438
+ return this.connectionManager.forceCleanupInvalidPeers();
439
+ }
440
+
441
+ cleanupStalePeers() {
442
+ console.log('Manually cleaning up stale peers...');
443
+ return this.connectionManager.cleanupStalePeers();
444
+ }
445
+
446
+ getPeerStateSummary() {
447
+ return this.connectionManager.getPeerStateSummary();
448
+ }
449
+
450
+ debugConnectivity() {
451
+ return this.meshOptimizer.debugConnectivity();
452
+ }
453
+
454
+ // Connection monitoring methods
455
+ startConnectionMonitoring() {
456
+ // Monitor connection health every 2 minutes
457
+ if (this.connectionMonitorInterval) {
458
+ clearInterval(this.connectionMonitorInterval);
459
+ }
460
+
461
+ this.connectionMonitorInterval = window.setInterval.call(window, () => {
462
+ if (this.signalingClient) {
463
+ const stats = this.signalingClient.getConnectionStats();
464
+ console.log('Connection monitoring:', stats);
465
+
466
+ // Force health check if connection seems problematic
467
+ if (stats.connected && stats.lastPingTime && stats.lastPongTime) {
468
+ const timeSinceLastPong = Date.now() - stats.lastPongTime;
469
+ if (timeSinceLastPong > 60000) { // 1 minute without pong
470
+ console.warn('Connection may be unhealthy, forcing health check');
471
+ this.signalingClient.forceHealthCheck();
472
+ }
473
+ }
474
+
475
+ // Emit connection status for UI
476
+ this.emit('connectionStats', stats);
477
+ }
478
+ }, 120000); // Every 2 minutes
479
+
480
+ console.log('Started connection monitoring');
481
+ }
482
+
483
+ stopConnectionMonitoring() {
484
+ if (this.connectionMonitorInterval) {
485
+ clearInterval(this.connectionMonitorInterval);
486
+ this.connectionMonitorInterval = null;
487
+ console.log('Stopped connection monitoring');
488
+ }
489
+ }
490
+
491
+ // Media management methods
492
+ async initializeMedia() {
493
+ return await this.mediaManager.init();
494
+ }
495
+
496
+ async startMedia(options = {}) {
497
+ const { video = false, audio = false, deviceIds = {} } = options;
498
+
499
+ try {
500
+ const stream = await this.mediaManager.startLocalStream({ video, audio, deviceIds });
501
+
502
+ // Update all existing peer connections with the new stream
503
+ const connections = this.connectionManager.getAllConnections();
504
+ for (const connection of connections) {
505
+ await connection.setLocalStream(stream);
506
+ }
507
+
508
+ return stream;
509
+ } catch (error) {
510
+ console.error('Failed to start media:', error);
511
+ throw error;
512
+ }
513
+ }
514
+
515
+ async stopMedia() {
516
+ this.mediaManager.stopLocalStream();
517
+
518
+ // Update all existing peer connections to remove the stream
519
+ const connections = this.connectionManager.getAllConnections();
520
+ for (const connection of connections) {
521
+ await connection.setLocalStream(null);
522
+ }
523
+ }
524
+
525
+ toggleVideo() {
526
+ return this.mediaManager.toggleVideo();
527
+ }
528
+
529
+ toggleAudio() {
530
+ return this.mediaManager.toggleAudio();
531
+ }
532
+
533
+ getMediaState() {
534
+ return this.mediaManager.getMediaState();
535
+ }
536
+
537
+ getMediaDevices() {
538
+ return this.mediaManager.devices;
539
+ }
540
+
541
+ async enumerateMediaDevices() {
542
+ return await this.mediaManager.enumerateDevices();
543
+ }
544
+
545
+ getLocalStream() {
546
+ return this.mediaManager.localStream;
547
+ }
548
+
549
+ // Get remote streams from all connected peers
550
+ getRemoteStreams() {
551
+ const streams = new Map();
552
+ const connections = this.connectionManager.getAllConnections();
553
+
554
+ for (const connection of connections) {
555
+ const remoteStream = connection.getRemoteStream();
556
+ if (remoteStream) {
557
+ streams.set(connection.peerId, remoteStream);
558
+ }
559
+ }
560
+
561
+ return streams;
562
+ }
563
+
564
+ // Static utility methods
565
+ static validatePeerId(peerId) {
566
+ return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
567
+ }
568
+
569
+ static async generatePeerId() {
570
+ const array = new Uint8Array(20);
571
+ crypto.getRandomValues(array);
572
+ return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
573
+ }
574
+
575
+ // WebDHT methods - Distributed Hash Table
576
+ /**
577
+ * Store a key-value pair in the distributed hash table
578
+ * @param {string} key - The key to store
579
+ * @param {any} value - The value to store
580
+ * @param {object} options - Storage options (ttl, etc.)
581
+ * @returns {Promise<boolean>} True if stored successfully
582
+ */
583
+ async dhtPut(key, value, options = {}) {
584
+ if (!this.enableWebDHT) {
585
+ throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
586
+ }
587
+ if (!this.webDHT) {
588
+ throw new Error('WebDHT not initialized');
589
+ }
590
+ return this.webDHT.put(key, value, options);
591
+ }
592
+
593
+ /**
594
+ * Retrieve a value from the distributed hash table
595
+ * @param {string} key - The key to retrieve
596
+ * @param {object} options - Retrieval options (subscribe, etc.)
597
+ * @returns {Promise<any>} The stored value or null if not found
598
+ */
599
+ async dhtGet(key, options = {}) {
600
+ if (!this.enableWebDHT) {
601
+ throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
602
+ }
603
+ if (!this.webDHT) {
604
+ throw new Error('WebDHT not initialized');
605
+ }
606
+ return this.webDHT.get(key, options);
607
+ }
608
+
609
+ /**
610
+ * Subscribe to changes for a key in the DHT
611
+ * @param {string} key - The key to subscribe to
612
+ * @returns {Promise<any>} The current value
613
+ */
614
+ async dhtSubscribe(key) {
615
+ if (!this.enableWebDHT) {
616
+ throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
617
+ }
618
+ if (!this.webDHT) {
619
+ throw new Error('WebDHT not initialized');
620
+ }
621
+ return this.webDHT.subscribe(key);
622
+ }
623
+
624
+ /**
625
+ * Unsubscribe from changes for a key in the DHT
626
+ * @param {string} key - The key to unsubscribe from
627
+ */
628
+ async dhtUnsubscribe(key) {
629
+ if (!this.enableWebDHT) {
630
+ throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
631
+ }
632
+ if (!this.webDHT) {
633
+ throw new Error('WebDHT not initialized');
634
+ }
635
+ return this.webDHT.unsubscribe(key);
636
+ }
637
+
638
+ /**
639
+ * Update a key's value and notify subscribers
640
+ * @param {string} key - The key to update
641
+ * @param {any} newValue - The new value
642
+ * @param {object} options - Update options
643
+ * @returns {Promise<boolean>} True if updated successfully
644
+ */
645
+ async dhtUpdate(key, newValue, options = {}) {
646
+ if (!this.enableWebDHT) {
647
+ throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
648
+ }
649
+ if (!this.webDHT) {
650
+ throw new Error('WebDHT not initialized');
651
+ }
652
+ return this.webDHT.update(key, newValue, options);
653
+ }
654
+
655
+ /**
656
+ * Get DHT statistics
657
+ * @returns {object} DHT statistics
658
+ */
659
+ getDHTStats() {
660
+ if (!this.enableWebDHT) {
661
+ return { error: 'WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.' };
662
+ }
663
+ if (!this.webDHT) {
664
+ return { error: 'WebDHT not initialized' };
665
+ }
666
+ return this.webDHT.getStats();
667
+ }
668
+
669
+ /**
670
+ * Check if WebDHT is enabled
671
+ * @returns {boolean} True if WebDHT is enabled
672
+ */
673
+ isDHTEnabled() {
674
+ return this.enableWebDHT;
675
+ }
676
+
677
+ /**
678
+ * Setup WebDHT event handlers
679
+ */
680
+ setupWebDHTEventHandlers() {
681
+ // Only set up if webDHT exists
682
+ if (this.webDHT) {
683
+ this.webDHT.addEventListener('valueChanged', (data) => {
684
+ this.emit('dhtValueChanged', data);
685
+ });
686
+ }
687
+ }
688
+
689
+ /**
690
+ * Connect to a specific peer by ID
691
+ */
692
+ connectToPeer(peerId) {
693
+ if (!peerId || typeof peerId !== 'string') {
694
+ throw new Error('Valid peer ID is required');
695
+ }
696
+
697
+ if (peerId === this.peerId) {
698
+ throw new Error('Cannot connect to yourself');
699
+ }
700
+
701
+ return this.connectionManager.connectToPeer(peerId);
702
+ }
703
+ }