peerpigeon 0.0.7 → 0.1.0

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,9 +1,11 @@
1
1
  import { EventEmitter } from './EventEmitter.js';
2
2
  import { environmentDetector } from './EnvironmentDetector.js';
3
+ import DebugLogger from './DebugLogger.js';
3
4
 
4
5
  export class PeerDiscovery extends EventEmitter {
5
6
  constructor(peerId, options = {}) {
6
7
  super();
8
+ this.debug = DebugLogger.create('PeerDiscovery');
7
9
  this.peerId = peerId;
8
10
  this.discoveredPeers = new Map();
9
11
  this.connectionAttempts = new Map();
@@ -46,15 +48,15 @@ export class PeerDiscovery extends EventEmitter {
46
48
  this.discoveredPeers.set(peerId, Date.now());
47
49
  this.emit('peerDiscovered', { peerId });
48
50
 
49
- console.log(`Discovered peer ${peerId.substring(0, 8)}...`);
51
+ this.debug.log(`Discovered peer ${peerId.substring(0, 8)}...`);
50
52
 
51
53
  // Only auto-connect if we should initiate to this peer and we're not already trying
52
54
  if (this.autoDiscovery && this.shouldInitiateConnection(peerId) && !this.connectionAttempts.has(peerId)) {
53
- console.log(`Considering connection to ${peerId.substring(0, 8)}...`);
55
+ this.debug.log(`Considering connection to ${peerId.substring(0, 8)}...`);
54
56
 
55
57
  const canAccept = this.canAcceptMorePeers();
56
58
  if (canAccept) {
57
- console.log(`Connecting to ${peerId.substring(0, 8)}...`);
59
+ this.debug.log(`Connecting to ${peerId.substring(0, 8)}...`);
58
60
  this.emit('connectToPeer', { peerId });
59
61
  }
60
62
  }
@@ -64,7 +66,7 @@ export class PeerDiscovery extends EventEmitter {
64
66
 
65
67
  // Update connection attempts tracking (no complex isolation logic needed)
66
68
  onConnectionEstablished() {
67
- console.log('Connection established');
69
+ this.debug.log('Connection established');
68
70
  }
69
71
 
70
72
  removeDiscoveredPeer(peerId) {
@@ -111,7 +113,7 @@ export class PeerDiscovery extends EventEmitter {
111
113
 
112
114
  // First priority: peers where we'd naturally be the initiator
113
115
  if (naturalInitiators.length > 0 && naturalInitiators.includes(targetPeerId)) {
114
- console.log(`shouldInitiateConnection: Isolation override (natural) - ${this.peerId.substring(0, 8)}... will initiate to ${targetPeerId.substring(0, 8)}...`);
116
+ this.debug.log(`shouldInitiateConnection: Isolation override (natural) - ${this.peerId.substring(0, 8)}... will initiate to ${targetPeerId.substring(0, 8)}...`);
115
117
  return true;
116
118
  }
117
119
 
@@ -127,7 +129,7 @@ export class PeerDiscovery extends EventEmitter {
127
129
  const closestPeers = sortedByDistance.slice(0, Math.min(3, sortedByDistance.length));
128
130
  if (closestPeers.includes(targetPeerId)) {
129
131
  const index = closestPeers.indexOf(targetPeerId);
130
- console.log(`shouldInitiateConnection: Isolation override (closest ${index + 1}) - ${this.peerId.substring(0, 8)}... will initiate to ${targetPeerId.substring(0, 8)}...`);
132
+ this.debug.log(`shouldInitiateConnection: Isolation override (closest ${index + 1}) - ${this.peerId.substring(0, 8)}... will initiate to ${targetPeerId.substring(0, 8)}...`);
131
133
  return true;
132
134
  }
133
135
  }
@@ -136,12 +138,12 @@ export class PeerDiscovery extends EventEmitter {
136
138
  // be even more aggressive and try ANY peer to break isolation
137
139
  const attemptedConnections = this.connectionAttempts.size;
138
140
  if (attemptedConnections >= 2 && discoveredPeers.includes(targetPeerId)) {
139
- console.log(`shouldInitiateConnection: Isolation override (desperate) - ${this.peerId.substring(0, 8)}... will initiate to ${targetPeerId.substring(0, 8)}... (${attemptedConnections} attempts failed)`);
141
+ this.debug.log(`shouldInitiateConnection: Isolation override (desperate) - ${this.peerId.substring(0, 8)}... will initiate to ${targetPeerId.substring(0, 8)}... (${attemptedConnections} attempts failed)`);
140
142
  return true;
141
143
  }
142
144
  }
143
145
 
144
- console.log(`shouldInitiateConnection: ${this.peerId.substring(0, 8)}... > ${targetPeerId.substring(0, 8)}... = ${lexicographicShouldInitiate}`);
146
+ this.debug.log(`shouldInitiateConnection: ${this.peerId.substring(0, 8)}... > ${targetPeerId.substring(0, 8)}... = ${lexicographicShouldInitiate}`);
145
147
  return lexicographicShouldInitiate;
146
148
  }
147
149
 
@@ -168,7 +170,7 @@ export class PeerDiscovery extends EventEmitter {
168
170
  optimizeMeshConnections(currentPeers) {
169
171
  if (!this.autoDiscovery) return;
170
172
 
171
- console.log('Optimizing mesh connections...');
173
+ this.debug.log('Optimizing mesh connections...');
172
174
 
173
175
  // Find unconnected peers that we should initiate connections to
174
176
  const unconnectedPeers = Array.from(this.discoveredPeers.keys())
@@ -181,7 +183,7 @@ export class PeerDiscovery extends EventEmitter {
181
183
  });
182
184
 
183
185
  if (unconnectedPeers.length === 0) {
184
- console.log('No unconnected peers to optimize');
186
+ this.debug.log('No unconnected peers to optimize');
185
187
  return;
186
188
  }
187
189
 
@@ -232,7 +234,7 @@ export class PeerDiscovery extends EventEmitter {
232
234
  this.discoveredPeers.delete(peerId);
233
235
  this.connectionAttempts.delete(peerId);
234
236
  removedCount++;
235
- console.log('Removed stale peer:', peerId.substring(0, 8));
237
+ this.debug.log('Removed stale peer:', peerId.substring(0, 8));
236
238
  }
237
239
  });
238
240
 
@@ -283,18 +285,18 @@ export class PeerDiscovery extends EventEmitter {
283
285
  const discoveredPeerIds = Array.from(this.discoveredPeers.keys()).map(p => p.substring(0, 8));
284
286
  const connectionAttempts = Array.from(this.connectionAttempts.keys()).map(p => p.substring(0, 8));
285
287
 
286
- console.log('=== PEER DISCOVERY DEBUG ===');
287
- console.log(`Our peer ID: ${this.peerId.substring(0, 8)}...`);
288
- console.log(`Discovered peers (${discoveredPeerIds.length}): ${discoveredPeerIds.join(', ')}`);
289
- console.log(`Connection attempts (${connectionAttempts.length}): ${connectionAttempts.join(', ')}`);
288
+ this.debug.log('=== PEER DISCOVERY DEBUG ===');
289
+ this.debug.log(`Our peer ID: ${this.peerId.substring(0, 8)}...`);
290
+ this.debug.log(`Discovered peers (${discoveredPeerIds.length}): ${discoveredPeerIds.join(', ')}`);
291
+ this.debug.log(`Connection attempts (${connectionAttempts.length}): ${connectionAttempts.join(', ')}`);
290
292
 
291
293
  // Show which peers we should/shouldn't initiate to
292
294
  discoveredPeerIds.forEach(peerId => {
293
295
  const fullPeerId = Array.from(this.discoveredPeers.keys()).find(p => p.startsWith(peerId));
294
296
  const shouldInitiate = this.shouldInitiateConnection(fullPeerId);
295
297
  const comparison = this.peerId > fullPeerId;
296
- console.log(` ${peerId}...: should initiate = ${shouldInitiate} (${this.peerId.substring(0, 8)}... > ${peerId}... = ${comparison})`);
298
+ this.debug.log(` ${peerId}...: should initiate = ${shouldInitiate} (${this.peerId.substring(0, 8)}... > ${peerId}... = ${comparison})`);
297
299
  });
298
- console.log('=== END DEBUG ===');
300
+ this.debug.log('=== END DEBUG ===');
299
301
  }
300
302
  }
@@ -11,11 +11,14 @@ import { GossipManager } from './GossipManager.js';
11
11
  import { MediaManager } from './MediaManager.js';
12
12
  import { WebDHT } from './WebDHT.js';
13
13
  import { CryptoManager } from './CryptoManager.js';
14
+ import { DistributedStorageManager } from './DistributedStorageManager.js';
14
15
  import { environmentDetector } from './EnvironmentDetector.js';
16
+ import DebugLogger from './DebugLogger.js';
15
17
 
16
18
  export class PeerPigeonMesh extends EventEmitter {
17
19
  constructor(options = {}) {
18
20
  super();
21
+ this.debug = DebugLogger.create('PeerPigeonMesh');
19
22
 
20
23
  // Validate environment capabilities
21
24
  this.environmentReport = this.validateEnvironment(options);
@@ -51,6 +54,7 @@ export class PeerPigeonMesh extends EventEmitter {
51
54
  this.signalingHandler = new SignalingHandler(this, this.connectionManager);
52
55
  this.gossipManager = new GossipManager(this, this.connectionManager);
53
56
  this.webDHT = null; // Will be initialized after peerId is set
57
+ this.distributedStorage = null; // Will be initialized after WebDHT is set
54
58
 
55
59
  // Initialize crypto manager if enabled
56
60
  this.cryptoManager = null;
@@ -76,7 +80,7 @@ export class PeerPigeonMesh extends EventEmitter {
76
80
 
77
81
  // Handle peer disconnections and trigger keep-alive ping coordination
78
82
  this.addEventListener('peerDisconnected', (data) => {
79
- console.log(`Peer ${data.peerId.substring(0, 8)}... disconnected: ${data.reason}`);
83
+ this.debug.log(`Peer ${data.peerId.substring(0, 8)}... disconnected: ${data.reason}`);
80
84
  // Trigger immediate keep-alive ping check in case the disconnected peer was the designated sender
81
85
  if (this.signalingClient && this.signalingClient.connected) {
82
86
  setTimeout(() => {
@@ -85,18 +89,51 @@ export class PeerPigeonMesh extends EventEmitter {
85
89
  }
86
90
  });
87
91
 
88
- // Handle gossip messages
92
+ // Handle gossip messages and intercept mesh signaling
89
93
  this.gossipManager.addEventListener('messageReceived', (data) => {
94
+ // Check if this is a mesh signaling message
95
+ if (data.message && data.message.type === 'mesh_signaling') {
96
+ this._handleMeshSignalingMessage(data.message, data.from);
97
+ return; // Don't emit as regular message
98
+ }
99
+
100
+ // Handle crypto key exchange messages
101
+ if (data.message && (data.message.type === 'key_exchange' || data.message.type === 'key_exchange_response')) {
102
+ this._handleKeyExchange(data.message, data.from);
103
+ return; // Don't emit as regular message
104
+ }
105
+
90
106
  this.emit('messageReceived', data);
91
107
  });
92
108
 
109
+ // CRITICAL: Handle remote stream announcements from gossip
110
+ // When we hear about a stream from an indirectly connected peer,
111
+ // establish a direct connection to receive the media
112
+ this.addEventListener('remoteStreamAnnouncement', (data) => {
113
+ this._handleRemoteStreamAnnouncement(data);
114
+ });
115
+
93
116
  // Forward media events
94
117
  this.mediaManager.addEventListener('localStreamStarted', (data) => {
95
118
  this.emit('localStreamStarted', data);
119
+ // Gossip stream start announcement to all peers in the mesh
120
+ this.gossipManager.broadcastMessage({
121
+ event: 'streamStarted',
122
+ peerId: this.peerId,
123
+ hasVideo: data.hasVideo,
124
+ hasAudio: data.hasAudio,
125
+ timestamp: Date.now()
126
+ }, 'mediaEvent');
96
127
  });
97
128
 
98
129
  this.mediaManager.addEventListener('localStreamStopped', () => {
99
130
  this.emit('localStreamStopped');
131
+ // Gossip stream stop announcement to all peers in the mesh
132
+ this.gossipManager.broadcastMessage({
133
+ event: 'streamStopped',
134
+ peerId: this.peerId,
135
+ timestamp: Date.now()
136
+ }, 'mediaEvent');
100
137
  });
101
138
 
102
139
  this.mediaManager.addEventListener('error', (data) => {
@@ -134,7 +171,7 @@ export class PeerPigeonMesh extends EventEmitter {
134
171
  const errors = [];
135
172
 
136
173
  // Log environment info
137
- console.log('🔍 PeerPigeon Environment Detection:', {
174
+ this.debug.log('🔍 PeerPigeon Environment Detection:', {
138
175
  runtime: `${report.runtime.isBrowser ? 'Browser' : ''}${report.runtime.isNodeJS ? 'Node.js' : ''}${report.runtime.isWorker ? 'Worker' : ''}${report.runtime.isNativeScript ? 'NativeScript' : ''}`,
139
176
  webrtc: report.capabilities.webrtc,
140
177
  websocket: report.capabilities.webSocket,
@@ -197,7 +234,7 @@ export class PeerPigeonMesh extends EventEmitter {
197
234
  // NativeScript-specific checks
198
235
  const nativeScript = report.nativescript;
199
236
  if (nativeScript && nativeScript.platform) {
200
- console.log(`🔮 Running on NativeScript ${nativeScript.platform} platform`);
237
+ this.debug.log(`🔮 Running on NativeScript ${nativeScript.platform} platform`);
201
238
 
202
239
  // Platform-specific considerations
203
240
  if (nativeScript.platform === 'android') {
@@ -211,14 +248,14 @@ export class PeerPigeonMesh extends EventEmitter {
211
248
  // Handle errors and warnings
212
249
  if (errors.length > 0) {
213
250
  const errorMessage = 'PeerPigeon environment validation failed:\n' + errors.join('\n');
214
- console.error(errorMessage);
251
+ this.debug.error(errorMessage);
215
252
  if (!options.ignoreEnvironmentErrors) {
216
253
  throw new Error(errorMessage);
217
254
  }
218
255
  }
219
256
 
220
257
  if (warnings.length > 0) {
221
- console.warn('PeerPigeon environment warnings:\n' + warnings.join('\n'));
258
+ this.debug.warn('PeerPigeon environment warnings:\n' + warnings.join('\n'));
222
259
  }
223
260
 
224
261
  // Store capabilities for runtime checks
@@ -234,9 +271,9 @@ export class PeerPigeonMesh extends EventEmitter {
234
271
  if (this.providedPeerId) {
235
272
  if (this.storageManager.validatePeerId(this.providedPeerId)) {
236
273
  this.peerId = this.providedPeerId;
237
- console.log(`Using provided peer ID: ${this.peerId}`);
274
+ this.debug.log(`Using provided peer ID: ${this.peerId}`);
238
275
  } else {
239
- console.warn(`Invalid peer ID provided: ${this.providedPeerId}. Must be 40-character SHA-1 hex string. Generating new one.`);
276
+ this.debug.warn(`Invalid peer ID provided: ${this.providedPeerId}. Must be 40-character SHA-1 hex string. Generating new one.`);
240
277
  this.peerId = await this.storageManager.generatePeerId();
241
278
  }
242
279
  } else {
@@ -246,12 +283,19 @@ export class PeerPigeonMesh extends EventEmitter {
246
283
  // Initialize WebDHT now that we have a peerId (if enabled)
247
284
  if (this.enableWebDHT) {
248
285
  this.webDHT = new WebDHT(this);
249
- console.log('WebDHT initialized and enabled');
286
+ this.debug.log('WebDHT initialized and enabled');
250
287
 
251
288
  // Setup WebDHT event handlers now that it's initialized
252
289
  this.setupWebDHTEventHandlers();
290
+
291
+ // Initialize DistributedStorageManager if WebDHT is enabled
292
+ this.distributedStorage = new DistributedStorageManager(this);
293
+ this.debug.log('DistributedStorageManager initialized');
294
+
295
+ // Setup DistributedStorageManager event handlers
296
+ this.setupDistributedStorageEventHandlers();
253
297
  } else {
254
- console.log('WebDHT disabled by configuration');
298
+ this.debug.log('WebDHT disabled by configuration');
255
299
  }
256
300
 
257
301
  // Load signaling URL from query params or storage
@@ -275,11 +319,11 @@ export class PeerPigeonMesh extends EventEmitter {
275
319
  // Initialize crypto manager if enabled
276
320
  if (this.cryptoManager) {
277
321
  try {
278
- console.log('🔐 Initializing crypto manager...');
322
+ this.debug.log('🔐 Initializing crypto manager...');
279
323
  await this.cryptoManager.init({ generateKeypair: true });
280
- console.log('🔐 Crypto manager initialized successfully');
324
+ this.debug.log('🔐 Crypto manager initialized successfully');
281
325
  } catch (error) {
282
- console.error('Failed to initialize crypto manager:', error);
326
+ this.debug.error('Failed to initialize crypto manager:', error);
283
327
  // Continue without crypto - don't fail the entire init
284
328
  this.enableCrypto = false;
285
329
  this.cryptoManager = null;
@@ -288,7 +332,7 @@ export class PeerPigeonMesh extends EventEmitter {
288
332
 
289
333
  this.emit('statusChanged', { type: 'initialized', peerId: this.peerId });
290
334
  } catch (error) {
291
- console.error('Failed to initialize mesh:', error);
335
+ this.debug.error('Failed to initialize mesh:', error);
292
336
  this.emit('statusChanged', { type: 'error', message: `Initialization failed: ${error.message}` });
293
337
  throw error;
294
338
  }
@@ -330,7 +374,7 @@ export class PeerPigeonMesh extends EventEmitter {
330
374
  });
331
375
 
332
376
  this.peerDiscovery.addEventListener('connectToPeer', (data) => {
333
- console.log(`PeerDiscovery requested connection to: ${data.peerId.substring(0, 8)}...`);
377
+ this.debug.log(`PeerDiscovery requested connection to: ${data.peerId.substring(0, 8)}...`);
334
378
  this.connectionManager.connectToPeer(data.peerId);
335
379
  });
336
380
 
@@ -355,7 +399,7 @@ export class PeerPigeonMesh extends EventEmitter {
355
399
  this.peerDiscovery.addEventListener('checkCapacity', () => {
356
400
  const canAccept = this.connectionManager.canAcceptMorePeers();
357
401
  const currentConnectionCount = this.connectionManager.getConnectedPeerCount();
358
- console.log(`Capacity check: ${canAccept} (${currentConnectionCount}/${this.maxPeers} peers)`);
402
+ this.debug.log(`Capacity check: ${canAccept} (${currentConnectionCount}/${this.maxPeers} peers)`);
359
403
  this.peerDiscovery._canAcceptMorePeers = canAccept;
360
404
  this.peerDiscovery._currentConnectionCount = currentConnectionCount;
361
405
  });
@@ -363,7 +407,7 @@ export class PeerPigeonMesh extends EventEmitter {
363
407
  // Handle eviction checks
364
408
  this.peerDiscovery.addEventListener('checkEviction', (data) => {
365
409
  const evictPeerId = this.evictionManager.shouldEvictForPeer(data.newPeerId);
366
- console.log(`Eviction check for ${data.newPeerId.substring(0, 8)}...: ${evictPeerId ? evictPeerId.substring(0, 8) + '...' : 'none'}`);
410
+ this.debug.log(`Eviction check for ${data.newPeerId.substring(0, 8)}...: ${evictPeerId ? evictPeerId.substring(0, 8) + '...' : 'none'}`);
367
411
  this.peerDiscovery._shouldEvictForPeer = evictPeerId;
368
412
  });
369
413
  }
@@ -377,7 +421,7 @@ export class PeerPigeonMesh extends EventEmitter {
377
421
  try {
378
422
  await this.signalingClient.connect(signalingUrl);
379
423
  } catch (error) {
380
- console.error('Connection failed:', error);
424
+ this.debug.error('Connection failed:', error);
381
425
  this.polling = false;
382
426
  this.emit('statusChanged', { type: 'error', message: `Connection failed: ${error.message}` });
383
427
  throw error;
@@ -518,7 +562,7 @@ export class PeerPigeonMesh extends EventEmitter {
518
562
  */
519
563
  sendDirectMessage(targetPeerId, content) {
520
564
  if (!targetPeerId || typeof targetPeerId !== 'string') {
521
- console.error('Invalid targetPeerId for direct message');
565
+ this.debug.error('Invalid targetPeerId for direct message');
522
566
  return null;
523
567
  }
524
568
  return this.gossipManager.sendDirectMessage(targetPeerId, content);
@@ -572,12 +616,12 @@ export class PeerPigeonMesh extends EventEmitter {
572
616
 
573
617
  // Debugging and maintenance methods
574
618
  forceCleanupInvalidPeers() {
575
- console.log('Force cleaning up peers not in connected state...');
619
+ this.debug.log('Force cleaning up peers not in connected state...');
576
620
  return this.connectionManager.forceCleanupInvalidPeers();
577
621
  }
578
622
 
579
623
  cleanupStalePeers() {
580
- console.log('Manually cleaning up stale peers...');
624
+ this.debug.log('Manually cleaning up stale peers...');
581
625
  return this.connectionManager.cleanupStalePeers();
582
626
  }
583
627
 
@@ -600,13 +644,13 @@ export class PeerPigeonMesh extends EventEmitter {
600
644
  const intervalCallback = () => {
601
645
  if (this.signalingClient) {
602
646
  const stats = this.signalingClient.getConnectionStats();
603
- console.log('Connection monitoring:', stats);
647
+ this.debug.log('Connection monitoring:', stats);
604
648
 
605
649
  // Force health check if connection seems problematic
606
650
  if (stats.connected && stats.lastPingTime && stats.lastPongTime) {
607
651
  const timeSinceLastPong = Date.now() - stats.lastPongTime;
608
652
  if (timeSinceLastPong > 60000) { // 1 minute without pong
609
- console.warn('Connection may be unhealthy, forcing health check');
653
+ this.debug.warn('Connection may be unhealthy, forcing health check');
610
654
  this.signalingClient.forceHealthCheck();
611
655
  }
612
656
  }
@@ -622,14 +666,14 @@ export class PeerPigeonMesh extends EventEmitter {
622
666
  this.connectionMonitorInterval = setInterval(intervalCallback, 120000);
623
667
  }
624
668
 
625
- console.log('Started connection monitoring');
669
+ this.debug.log('Started connection monitoring');
626
670
  }
627
671
 
628
672
  stopConnectionMonitoring() {
629
673
  if (this.connectionMonitorInterval) {
630
674
  clearInterval(this.connectionMonitorInterval);
631
675
  this.connectionMonitorInterval = null;
632
- console.log('Stopped connection monitoring');
676
+ this.debug.log('Stopped connection monitoring');
633
677
  }
634
678
  }
635
679
 
@@ -646,13 +690,36 @@ export class PeerPigeonMesh extends EventEmitter {
646
690
 
647
691
  // Update all existing peer connections with the new stream
648
692
  const connections = this.connectionManager.getAllConnections();
693
+ this.debug.log(`📡 MEDIA START: Applying stream to ${connections.length} connections`);
694
+
649
695
  for (const connection of connections) {
696
+ this.debug.log(`📡 MEDIA START: Setting stream for peer ${connection.peerId.substring(0, 8)}...`);
650
697
  await connection.setLocalStream(stream);
698
+
699
+ // FORCE IMMEDIATE RENEGOTIATION: Don't wait for the automatic trigger
700
+ this.debug.log(`📡 MEDIA START: Forcing immediate renegotiation for peer ${connection.peerId.substring(0, 8)}...`);
701
+ setTimeout(async () => {
702
+ try {
703
+ if (connection.connection && connection.connection.signalingState === 'stable') {
704
+ // Create and send a renegotiation offer immediately
705
+ const offer = await connection.createOffer();
706
+ await this.sendSignalingMessage({
707
+ type: 'renegotiation-offer',
708
+ data: offer,
709
+ timestamp: Date.now(),
710
+ forced: true // Mark as forced renegotiation
711
+ }, connection.peerId);
712
+ this.debug.log(`✅ MEDIA START: Forced renegotiation offer sent to ${connection.peerId.substring(0, 8)}...`);
713
+ }
714
+ } catch (error) {
715
+ this.debug.error(`❌ MEDIA START: Failed to force renegotiation for ${connection.peerId.substring(0, 8)}...`, error);
716
+ }
717
+ }, 500); // Small delay to ensure setLocalStream completes
651
718
  }
652
719
 
653
720
  return stream;
654
721
  } catch (error) {
655
- console.error('Failed to start media:', error);
722
+ this.debug.error('Failed to start media:', error);
656
723
  throw error;
657
724
  }
658
725
  }
@@ -831,6 +898,38 @@ export class PeerPigeonMesh extends EventEmitter {
831
898
  }
832
899
  }
833
900
 
901
+ /**
902
+ * Setup event handlers for DistributedStorageManager
903
+ */
904
+ setupDistributedStorageEventHandlers() {
905
+ // Only set up if distributedStorage exists
906
+ if (this.distributedStorage) {
907
+ this.distributedStorage.addEventListener('dataStored', (data) => {
908
+ this.emit('storageDataStored', data);
909
+ });
910
+
911
+ this.distributedStorage.addEventListener('dataRetrieved', (data) => {
912
+ this.emit('storageDataRetrieved', data);
913
+ });
914
+
915
+ this.distributedStorage.addEventListener('dataUpdated', (data) => {
916
+ this.emit('storageDataUpdated', data);
917
+ });
918
+
919
+ this.distributedStorage.addEventListener('dataDeleted', (data) => {
920
+ this.emit('storageDataDeleted', data);
921
+ });
922
+
923
+ this.distributedStorage.addEventListener('accessGranted', (data) => {
924
+ this.emit('storageAccessGranted', data);
925
+ });
926
+
927
+ this.distributedStorage.addEventListener('accessRevoked', (data) => {
928
+ this.emit('storageAccessRevoked', data);
929
+ });
930
+ }
931
+ }
932
+
834
933
  /**
835
934
  * Connect to a specific peer by ID
836
935
  */
@@ -964,7 +1063,7 @@ export class PeerPigeonMesh extends EventEmitter {
964
1063
  await this.cryptoManager.init(options);
965
1064
  return true;
966
1065
  } catch (error) {
967
- console.error('Failed to initialize crypto:', error);
1066
+ this.debug.error('Failed to initialize crypto:', error);
968
1067
  throw error;
969
1068
  }
970
1069
  }
@@ -1029,11 +1128,140 @@ export class PeerPigeonMesh extends EventEmitter {
1029
1128
  }
1030
1129
  }
1031
1130
  } catch (error) {
1032
- console.error('Failed to encrypt message:', error);
1131
+ this.debug.error('Failed to encrypt message:', error);
1033
1132
  throw error;
1034
1133
  }
1035
1134
  }
1036
1135
 
1136
+ /**
1137
+ * Send a signaling message over the mesh (peer-to-peer) instead of the signaling server
1138
+ * This allows peers to coordinate without the signaling server after initial connection
1139
+ * @param {Object} message - The signaling message
1140
+ * @param {string} targetPeerId - Target peer ID (optional, for direct signaling)
1141
+ * @returns {Promise<boolean>} Success status
1142
+ */
1143
+ async sendMeshSignalingMessage(message, targetPeerId = null) {
1144
+ if (!this.connected) {
1145
+ this.debug.warn('Cannot send mesh signaling message - mesh not connected');
1146
+ return false;
1147
+ }
1148
+
1149
+ const signalingMessage = {
1150
+ type: 'mesh_signaling',
1151
+ meshSignalingType: message.type,
1152
+ data: message.data,
1153
+ fromPeerId: this.peerId,
1154
+ targetPeerId,
1155
+ timestamp: Date.now(),
1156
+ messageId: this.generateMessageId()
1157
+ };
1158
+
1159
+ this.debug.log(`📡 Sending mesh signaling message: ${message.type} ${targetPeerId ? `to ${targetPeerId.substring(0, 8)}...` : '(broadcast)'}`);
1160
+
1161
+ try {
1162
+ if (targetPeerId) {
1163
+ // Send directly to target peer
1164
+ return this.sendDirectMessage(targetPeerId, signalingMessage);
1165
+ } else {
1166
+ // Broadcast to all connected peers
1167
+ return this.broadcast(signalingMessage);
1168
+ }
1169
+ } catch (error) {
1170
+ this.debug.error('Failed to send mesh signaling message:', error);
1171
+ return false;
1172
+ }
1173
+ }
1174
+
1175
+ /**
1176
+ * Handle incoming mesh signaling messages
1177
+ * @param {Object} message - The mesh signaling message
1178
+ * @param {string} from - Sender peer ID
1179
+ * @private
1180
+ */
1181
+ _handleMeshSignalingMessage(message, from) {
1182
+ if (!message.meshSignalingType || !message.data) {
1183
+ this.debug.warn('Invalid mesh signaling message format');
1184
+ return;
1185
+ }
1186
+
1187
+ // Only process messages intended for us or broadcasts
1188
+ if (message.targetPeerId && message.targetPeerId !== this.peerId) {
1189
+ this.debug.log(`Ignoring mesh signaling message not intended for us (target: ${message.targetPeerId?.substring(0, 8)}...)`);
1190
+ return;
1191
+ }
1192
+
1193
+ this.debug.log(`📡 Received mesh signaling message: ${message.meshSignalingType} from ${from.substring(0, 8)}...`);
1194
+
1195
+ // Create a signaling message format that our existing handler can process
1196
+ const reconstitutedMessage = {
1197
+ type: message.meshSignalingType,
1198
+ data: message.data,
1199
+ fromPeerId: from,
1200
+ targetPeerId: message.targetPeerId,
1201
+ timestamp: message.timestamp,
1202
+ messageId: message.messageId,
1203
+ viaWebSocket: false, // Mark as coming from mesh, not WebSocket
1204
+ viaMesh: true
1205
+ };
1206
+
1207
+ // Forward to our existing signaling handler
1208
+ this.signalingHandler.handleSignalingMessage(reconstitutedMessage);
1209
+ }
1210
+
1211
+ /**
1212
+ * Send a signaling message, using mesh connections for renegotiation
1213
+ * @param {Object} message - The signaling message
1214
+ * @param {string} targetPeerId - Target peer ID (optional)
1215
+ * @returns {Promise<boolean>} Success status
1216
+ */
1217
+ async sendSignalingMessage(message, targetPeerId = null) {
1218
+ // CRITICAL FIX: Use mesh for renegotiation, WebSocket only for initial handshake
1219
+ const isRenegotiation = message.type === 'renegotiation-offer' || message.type === 'renegotiation-answer';
1220
+
1221
+ if (isRenegotiation && targetPeerId) {
1222
+ // Use existing mesh connection for renegotiation
1223
+ this.debug.log(`🔄 MESH RENEGOTIATION: Sending ${message.type} via mesh to ${targetPeerId.substring(0, 8)}...`);
1224
+
1225
+ const peerConnection = this.connectionManager.getPeer(targetPeerId);
1226
+ if (peerConnection && peerConnection.sendMessage) {
1227
+ const success = peerConnection.sendMessage({
1228
+ type: 'signaling',
1229
+ data: message,
1230
+ fromPeerId: this.peerId,
1231
+ timestamp: Date.now()
1232
+ });
1233
+
1234
+ if (success) {
1235
+ this.debug.log(`✅ MESH RENEGOTIATION: ${message.type} sent via mesh to ${targetPeerId.substring(0, 8)}...`);
1236
+ return true;
1237
+ } else {
1238
+ this.debug.error(`❌ MESH RENEGOTIATION: Failed to send ${message.type} via mesh to ${targetPeerId.substring(0, 8)}...`);
1239
+ }
1240
+ } else {
1241
+ this.debug.error(`❌ MESH RENEGOTIATION: No mesh connection to ${targetPeerId.substring(0, 8)}... for ${message.type}`);
1242
+ }
1243
+
1244
+ // Fall back to WebSocket if mesh fails
1245
+ this.debug.log(`🔄 FALLBACK: Using WebSocket for ${message.type} to ${targetPeerId.substring(0, 8)}...`);
1246
+ }
1247
+
1248
+ // Use WebSocket for initial offers/answers and fallback
1249
+ if (this.signalingClient && this.signalingClient.isConnected()) {
1250
+ this.debug.log(`📡 Using WebSocket signaling for ${message.type} to ${targetPeerId?.substring(0, 8) || 'broadcast'}`);
1251
+
1252
+ // Include targetPeerId in the message if provided
1253
+ const messageWithTarget = { ...message };
1254
+ if (targetPeerId) {
1255
+ messageWithTarget.targetPeerId = targetPeerId;
1256
+ }
1257
+
1258
+ return await this.signalingClient.sendSignalingMessage(messageWithTarget);
1259
+ }
1260
+
1261
+ this.debug.warn(`📡 Cannot send signaling message ${message.type} - WebSocket not connected and mesh failed`);
1262
+ return false;
1263
+ }
1264
+
1037
1265
  /**
1038
1266
  * Send an encrypted message to a specific peer
1039
1267
  * @param {string} peerId - Target peer ID
@@ -1050,7 +1278,7 @@ export class PeerPigeonMesh extends EventEmitter {
1050
1278
  const encryptedContent = await this.cryptoManager.encryptForPeer(content, peerId);
1051
1279
  return this.sendDirectMessage(peerId, encryptedContent);
1052
1280
  } catch (error) {
1053
- console.error('Failed to send encrypted message:', error);
1281
+ this.debug.error('Failed to send encrypted message:', error);
1054
1282
  throw error;
1055
1283
  }
1056
1284
  }
@@ -1084,7 +1312,7 @@ export class PeerPigeonMesh extends EventEmitter {
1084
1312
  // Use 'encrypted' message type instead of 'chat' for encrypted broadcasts
1085
1313
  return this.gossipManager.broadcastMessage(encryptedContent, 'encrypted');
1086
1314
  } catch (error) {
1087
- console.error('Failed to send encrypted broadcast:', error);
1315
+ this.debug.error('Failed to send encrypted broadcast:', error);
1088
1316
  throw error;
1089
1317
  }
1090
1318
  }
@@ -1106,7 +1334,7 @@ export class PeerPigeonMesh extends EventEmitter {
1106
1334
  return await this.cryptoManager.decryptFromPeer(encryptedData);
1107
1335
  }
1108
1336
  } catch (error) {
1109
- console.error('Failed to decrypt message:', error);
1337
+ this.debug.error('Failed to decrypt message:', error);
1110
1338
  throw error;
1111
1339
  }
1112
1340
  }
@@ -1246,7 +1474,7 @@ export class PeerPigeonMesh extends EventEmitter {
1246
1474
  _handleKeyExchange(data, from) {
1247
1475
  if ((data.type === 'key_exchange' || data.type === 'key_exchange_response') && data.publicKey && this.cryptoManager) {
1248
1476
  this.cryptoManager.addPeerKey(from, data.publicKey);
1249
- console.log(`🔐 Stored public key for peer ${from.substring(0, 8)}...`);
1477
+ this.debug.log(`🔐 Stored public key for peer ${from.substring(0, 8)}...`);
1250
1478
 
1251
1479
  // Send our public key back if this was an initial exchange (not a response)
1252
1480
  if (data.type === 'key_exchange') {
@@ -1264,4 +1492,25 @@ export class PeerPigeonMesh extends EventEmitter {
1264
1492
  }
1265
1493
  }
1266
1494
  }
1495
+
1496
+ /**
1497
+ * Handle remote stream announcements from gossip protocol
1498
+ * The actual stream forwarding is handled by ConnectionManager
1499
+ * @param {Object} data - Stream announcement data
1500
+ * @private
1501
+ */
1502
+ async _handleRemoteStreamAnnouncement(data) {
1503
+ const { peerId, event } = data;
1504
+
1505
+ // Don't process our own announcements
1506
+ if (peerId === this.peerId) {
1507
+ return;
1508
+ }
1509
+
1510
+ this.debug.log(`🎵 GOSSIP STREAM: Received stream announcement - ${event} from ${peerId.substring(0, 8)}...`);
1511
+
1512
+ // Stream forwarding is now handled automatically by ConnectionManager
1513
+ // when remoteStream events are received, so we just emit for UI handling
1514
+ this.emit('remoteStreamAnnouncement', data);
1515
+ }
1267
1516
  }