peerpigeon 0.0.8 → 0.1.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.
@@ -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
  }
@@ -13,10 +13,12 @@ import { WebDHT } from './WebDHT.js';
13
13
  import { CryptoManager } from './CryptoManager.js';
14
14
  import { DistributedStorageManager } from './DistributedStorageManager.js';
15
15
  import { environmentDetector } from './EnvironmentDetector.js';
16
+ import DebugLogger from './DebugLogger.js';
16
17
 
17
18
  export class PeerPigeonMesh extends EventEmitter {
18
19
  constructor(options = {}) {
19
20
  super();
21
+ this.debug = DebugLogger.create('PeerPigeonMesh');
20
22
 
21
23
  // Validate environment capabilities
22
24
  this.environmentReport = this.validateEnvironment(options);
@@ -78,7 +80,7 @@ export class PeerPigeonMesh extends EventEmitter {
78
80
 
79
81
  // Handle peer disconnections and trigger keep-alive ping coordination
80
82
  this.addEventListener('peerDisconnected', (data) => {
81
- console.log(`Peer ${data.peerId.substring(0, 8)}... disconnected: ${data.reason}`);
83
+ this.debug.log(`Peer ${data.peerId.substring(0, 8)}... disconnected: ${data.reason}`);
82
84
  // Trigger immediate keep-alive ping check in case the disconnected peer was the designated sender
83
85
  if (this.signalingClient && this.signalingClient.connected) {
84
86
  setTimeout(() => {
@@ -87,18 +89,51 @@ export class PeerPigeonMesh extends EventEmitter {
87
89
  }
88
90
  });
89
91
 
90
- // Handle gossip messages
92
+ // Handle gossip messages and intercept mesh signaling
91
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
+
92
106
  this.emit('messageReceived', data);
93
107
  });
94
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
+
95
116
  // Forward media events
96
117
  this.mediaManager.addEventListener('localStreamStarted', (data) => {
97
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');
98
127
  });
99
128
 
100
129
  this.mediaManager.addEventListener('localStreamStopped', () => {
101
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');
102
137
  });
103
138
 
104
139
  this.mediaManager.addEventListener('error', (data) => {
@@ -136,7 +171,7 @@ export class PeerPigeonMesh extends EventEmitter {
136
171
  const errors = [];
137
172
 
138
173
  // Log environment info
139
- console.log('🔍 PeerPigeon Environment Detection:', {
174
+ this.debug.log('🔍 PeerPigeon Environment Detection:', {
140
175
  runtime: `${report.runtime.isBrowser ? 'Browser' : ''}${report.runtime.isNodeJS ? 'Node.js' : ''}${report.runtime.isWorker ? 'Worker' : ''}${report.runtime.isNativeScript ? 'NativeScript' : ''}`,
141
176
  webrtc: report.capabilities.webrtc,
142
177
  websocket: report.capabilities.webSocket,
@@ -199,7 +234,7 @@ export class PeerPigeonMesh extends EventEmitter {
199
234
  // NativeScript-specific checks
200
235
  const nativeScript = report.nativescript;
201
236
  if (nativeScript && nativeScript.platform) {
202
- console.log(`🔮 Running on NativeScript ${nativeScript.platform} platform`);
237
+ this.debug.log(`🔮 Running on NativeScript ${nativeScript.platform} platform`);
203
238
 
204
239
  // Platform-specific considerations
205
240
  if (nativeScript.platform === 'android') {
@@ -213,14 +248,14 @@ export class PeerPigeonMesh extends EventEmitter {
213
248
  // Handle errors and warnings
214
249
  if (errors.length > 0) {
215
250
  const errorMessage = 'PeerPigeon environment validation failed:\n' + errors.join('\n');
216
- console.error(errorMessage);
251
+ this.debug.error(errorMessage);
217
252
  if (!options.ignoreEnvironmentErrors) {
218
253
  throw new Error(errorMessage);
219
254
  }
220
255
  }
221
256
 
222
257
  if (warnings.length > 0) {
223
- console.warn('PeerPigeon environment warnings:\n' + warnings.join('\n'));
258
+ this.debug.warn('PeerPigeon environment warnings:\n' + warnings.join('\n'));
224
259
  }
225
260
 
226
261
  // Store capabilities for runtime checks
@@ -236,9 +271,9 @@ export class PeerPigeonMesh extends EventEmitter {
236
271
  if (this.providedPeerId) {
237
272
  if (this.storageManager.validatePeerId(this.providedPeerId)) {
238
273
  this.peerId = this.providedPeerId;
239
- console.log(`Using provided peer ID: ${this.peerId}`);
274
+ this.debug.log(`Using provided peer ID: ${this.peerId}`);
240
275
  } else {
241
- 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.`);
242
277
  this.peerId = await this.storageManager.generatePeerId();
243
278
  }
244
279
  } else {
@@ -248,19 +283,19 @@ export class PeerPigeonMesh extends EventEmitter {
248
283
  // Initialize WebDHT now that we have a peerId (if enabled)
249
284
  if (this.enableWebDHT) {
250
285
  this.webDHT = new WebDHT(this);
251
- console.log('WebDHT initialized and enabled');
286
+ this.debug.log('WebDHT initialized and enabled');
252
287
 
253
288
  // Setup WebDHT event handlers now that it's initialized
254
289
  this.setupWebDHTEventHandlers();
255
290
 
256
291
  // Initialize DistributedStorageManager if WebDHT is enabled
257
292
  this.distributedStorage = new DistributedStorageManager(this);
258
- console.log('DistributedStorageManager initialized');
293
+ this.debug.log('DistributedStorageManager initialized');
259
294
 
260
295
  // Setup DistributedStorageManager event handlers
261
296
  this.setupDistributedStorageEventHandlers();
262
297
  } else {
263
- console.log('WebDHT disabled by configuration');
298
+ this.debug.log('WebDHT disabled by configuration');
264
299
  }
265
300
 
266
301
  // Load signaling URL from query params or storage
@@ -284,11 +319,11 @@ export class PeerPigeonMesh extends EventEmitter {
284
319
  // Initialize crypto manager if enabled
285
320
  if (this.cryptoManager) {
286
321
  try {
287
- console.log('🔐 Initializing crypto manager...');
322
+ this.debug.log('🔐 Initializing crypto manager...');
288
323
  await this.cryptoManager.init({ generateKeypair: true });
289
- console.log('🔐 Crypto manager initialized successfully');
324
+ this.debug.log('🔐 Crypto manager initialized successfully');
290
325
  } catch (error) {
291
- console.error('Failed to initialize crypto manager:', error);
326
+ this.debug.error('Failed to initialize crypto manager:', error);
292
327
  // Continue without crypto - don't fail the entire init
293
328
  this.enableCrypto = false;
294
329
  this.cryptoManager = null;
@@ -297,7 +332,7 @@ export class PeerPigeonMesh extends EventEmitter {
297
332
 
298
333
  this.emit('statusChanged', { type: 'initialized', peerId: this.peerId });
299
334
  } catch (error) {
300
- console.error('Failed to initialize mesh:', error);
335
+ this.debug.error('Failed to initialize mesh:', error);
301
336
  this.emit('statusChanged', { type: 'error', message: `Initialization failed: ${error.message}` });
302
337
  throw error;
303
338
  }
@@ -339,7 +374,7 @@ export class PeerPigeonMesh extends EventEmitter {
339
374
  });
340
375
 
341
376
  this.peerDiscovery.addEventListener('connectToPeer', (data) => {
342
- console.log(`PeerDiscovery requested connection to: ${data.peerId.substring(0, 8)}...`);
377
+ this.debug.log(`PeerDiscovery requested connection to: ${data.peerId.substring(0, 8)}...`);
343
378
  this.connectionManager.connectToPeer(data.peerId);
344
379
  });
345
380
 
@@ -364,7 +399,7 @@ export class PeerPigeonMesh extends EventEmitter {
364
399
  this.peerDiscovery.addEventListener('checkCapacity', () => {
365
400
  const canAccept = this.connectionManager.canAcceptMorePeers();
366
401
  const currentConnectionCount = this.connectionManager.getConnectedPeerCount();
367
- console.log(`Capacity check: ${canAccept} (${currentConnectionCount}/${this.maxPeers} peers)`);
402
+ this.debug.log(`Capacity check: ${canAccept} (${currentConnectionCount}/${this.maxPeers} peers)`);
368
403
  this.peerDiscovery._canAcceptMorePeers = canAccept;
369
404
  this.peerDiscovery._currentConnectionCount = currentConnectionCount;
370
405
  });
@@ -372,7 +407,7 @@ export class PeerPigeonMesh extends EventEmitter {
372
407
  // Handle eviction checks
373
408
  this.peerDiscovery.addEventListener('checkEviction', (data) => {
374
409
  const evictPeerId = this.evictionManager.shouldEvictForPeer(data.newPeerId);
375
- 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'}`);
376
411
  this.peerDiscovery._shouldEvictForPeer = evictPeerId;
377
412
  });
378
413
  }
@@ -386,7 +421,7 @@ export class PeerPigeonMesh extends EventEmitter {
386
421
  try {
387
422
  await this.signalingClient.connect(signalingUrl);
388
423
  } catch (error) {
389
- console.error('Connection failed:', error);
424
+ this.debug.error('Connection failed:', error);
390
425
  this.polling = false;
391
426
  this.emit('statusChanged', { type: 'error', message: `Connection failed: ${error.message}` });
392
427
  throw error;
@@ -527,7 +562,7 @@ export class PeerPigeonMesh extends EventEmitter {
527
562
  */
528
563
  sendDirectMessage(targetPeerId, content) {
529
564
  if (!targetPeerId || typeof targetPeerId !== 'string') {
530
- console.error('Invalid targetPeerId for direct message');
565
+ this.debug.error('Invalid targetPeerId for direct message');
531
566
  return null;
532
567
  }
533
568
  return this.gossipManager.sendDirectMessage(targetPeerId, content);
@@ -581,12 +616,12 @@ export class PeerPigeonMesh extends EventEmitter {
581
616
 
582
617
  // Debugging and maintenance methods
583
618
  forceCleanupInvalidPeers() {
584
- console.log('Force cleaning up peers not in connected state...');
619
+ this.debug.log('Force cleaning up peers not in connected state...');
585
620
  return this.connectionManager.forceCleanupInvalidPeers();
586
621
  }
587
622
 
588
623
  cleanupStalePeers() {
589
- console.log('Manually cleaning up stale peers...');
624
+ this.debug.log('Manually cleaning up stale peers...');
590
625
  return this.connectionManager.cleanupStalePeers();
591
626
  }
592
627
 
@@ -609,13 +644,13 @@ export class PeerPigeonMesh extends EventEmitter {
609
644
  const intervalCallback = () => {
610
645
  if (this.signalingClient) {
611
646
  const stats = this.signalingClient.getConnectionStats();
612
- console.log('Connection monitoring:', stats);
647
+ this.debug.log('Connection monitoring:', stats);
613
648
 
614
649
  // Force health check if connection seems problematic
615
650
  if (stats.connected && stats.lastPingTime && stats.lastPongTime) {
616
651
  const timeSinceLastPong = Date.now() - stats.lastPongTime;
617
652
  if (timeSinceLastPong > 60000) { // 1 minute without pong
618
- console.warn('Connection may be unhealthy, forcing health check');
653
+ this.debug.warn('Connection may be unhealthy, forcing health check');
619
654
  this.signalingClient.forceHealthCheck();
620
655
  }
621
656
  }
@@ -631,14 +666,14 @@ export class PeerPigeonMesh extends EventEmitter {
631
666
  this.connectionMonitorInterval = setInterval(intervalCallback, 120000);
632
667
  }
633
668
 
634
- console.log('Started connection monitoring');
669
+ this.debug.log('Started connection monitoring');
635
670
  }
636
671
 
637
672
  stopConnectionMonitoring() {
638
673
  if (this.connectionMonitorInterval) {
639
674
  clearInterval(this.connectionMonitorInterval);
640
675
  this.connectionMonitorInterval = null;
641
- console.log('Stopped connection monitoring');
676
+ this.debug.log('Stopped connection monitoring');
642
677
  }
643
678
  }
644
679
 
@@ -655,13 +690,36 @@ export class PeerPigeonMesh extends EventEmitter {
655
690
 
656
691
  // Update all existing peer connections with the new stream
657
692
  const connections = this.connectionManager.getAllConnections();
693
+ this.debug.log(`📡 MEDIA START: Applying stream to ${connections.length} connections`);
694
+
658
695
  for (const connection of connections) {
696
+ this.debug.log(`📡 MEDIA START: Setting stream for peer ${connection.peerId.substring(0, 8)}...`);
659
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
660
718
  }
661
719
 
662
720
  return stream;
663
721
  } catch (error) {
664
- console.error('Failed to start media:', error);
722
+ this.debug.error('Failed to start media:', error);
665
723
  throw error;
666
724
  }
667
725
  }
@@ -1005,7 +1063,7 @@ export class PeerPigeonMesh extends EventEmitter {
1005
1063
  await this.cryptoManager.init(options);
1006
1064
  return true;
1007
1065
  } catch (error) {
1008
- console.error('Failed to initialize crypto:', error);
1066
+ this.debug.error('Failed to initialize crypto:', error);
1009
1067
  throw error;
1010
1068
  }
1011
1069
  }
@@ -1070,11 +1128,140 @@ export class PeerPigeonMesh extends EventEmitter {
1070
1128
  }
1071
1129
  }
1072
1130
  } catch (error) {
1073
- console.error('Failed to encrypt message:', error);
1131
+ this.debug.error('Failed to encrypt message:', error);
1074
1132
  throw error;
1075
1133
  }
1076
1134
  }
1077
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
+
1078
1265
  /**
1079
1266
  * Send an encrypted message to a specific peer
1080
1267
  * @param {string} peerId - Target peer ID
@@ -1091,7 +1278,7 @@ export class PeerPigeonMesh extends EventEmitter {
1091
1278
  const encryptedContent = await this.cryptoManager.encryptForPeer(content, peerId);
1092
1279
  return this.sendDirectMessage(peerId, encryptedContent);
1093
1280
  } catch (error) {
1094
- console.error('Failed to send encrypted message:', error);
1281
+ this.debug.error('Failed to send encrypted message:', error);
1095
1282
  throw error;
1096
1283
  }
1097
1284
  }
@@ -1125,7 +1312,7 @@ export class PeerPigeonMesh extends EventEmitter {
1125
1312
  // Use 'encrypted' message type instead of 'chat' for encrypted broadcasts
1126
1313
  return this.gossipManager.broadcastMessage(encryptedContent, 'encrypted');
1127
1314
  } catch (error) {
1128
- console.error('Failed to send encrypted broadcast:', error);
1315
+ this.debug.error('Failed to send encrypted broadcast:', error);
1129
1316
  throw error;
1130
1317
  }
1131
1318
  }
@@ -1147,7 +1334,7 @@ export class PeerPigeonMesh extends EventEmitter {
1147
1334
  return await this.cryptoManager.decryptFromPeer(encryptedData);
1148
1335
  }
1149
1336
  } catch (error) {
1150
- console.error('Failed to decrypt message:', error);
1337
+ this.debug.error('Failed to decrypt message:', error);
1151
1338
  throw error;
1152
1339
  }
1153
1340
  }
@@ -1287,7 +1474,7 @@ export class PeerPigeonMesh extends EventEmitter {
1287
1474
  _handleKeyExchange(data, from) {
1288
1475
  if ((data.type === 'key_exchange' || data.type === 'key_exchange_response') && data.publicKey && this.cryptoManager) {
1289
1476
  this.cryptoManager.addPeerKey(from, data.publicKey);
1290
- console.log(`🔐 Stored public key for peer ${from.substring(0, 8)}...`);
1477
+ this.debug.log(`🔐 Stored public key for peer ${from.substring(0, 8)}...`);
1291
1478
 
1292
1479
  // Send our public key back if this was an initial exchange (not a response)
1293
1480
  if (data.type === 'key_exchange') {
@@ -1305,4 +1492,25 @@ export class PeerPigeonMesh extends EventEmitter {
1305
1492
  }
1306
1493
  }
1307
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
+ }
1308
1516
  }