peerpigeon 0.0.4 → 0.0.6

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.
@@ -2,588 +2,587 @@ import { EventEmitter } from './EventEmitter.js';
2
2
  import { environmentDetector } from './EnvironmentDetector.js';
3
3
 
4
4
  export class SignalingClient extends EventEmitter {
5
- constructor(peerId, maxPeers = 10, mesh = null) {
6
- super();
7
- this.peerId = peerId;
8
- this.maxPeers = maxPeers;
9
- this.mesh = mesh; // Reference to the mesh for peer coordination
10
- this.signalingUrl = null;
11
- this.connected = false;
12
- this.websocket = null;
13
- this.reconnectDelay = 1000;
14
- this.maxReconnectDelay = 30000;
15
- this.reconnectAttempts = 0;
16
- this.maxReconnectAttempts = 10; // Increased for better persistence
17
- this.connectionPromise = null;
18
- this.reconnectTimeout = null;
19
- this.isReconnecting = false;
20
-
21
- // Add keep-alive ping to prevent WebSocket timeout
22
- this.keepAliveInterval = null;
23
- this.keepAliveIntervalMs = 9 * 60 * 1000; // Ping every 9 minutes for large safety margin
24
-
25
- // Health monitoring
26
- this.lastPingTime = null;
27
- this.lastPongTime = null;
28
- this.pingTimeout = null;
29
- this.healthCheckInterval = null;
30
- this.connectionQualityTimeout = 10000; // 10 seconds to consider connection unhealthy
31
- }
32
-
33
- setConnectionType(type) {
34
- // WebSocket-only implementation, ignore connection type setting
35
- console.log(`WebSocket-only implementation - connection type setting ignored: ${type}`);
36
- }
37
-
38
- createWebSocket(url) {
39
- // Environment-aware WebSocket creation
40
- if (environmentDetector.isNodeJS) {
41
- // Check for globally injected WebSocket first (set by user)
42
- if (typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined') {
43
- return new global.WebSocket(url);
44
- }
45
- if (typeof WebSocket !== 'undefined') {
46
- return new WebSocket(url);
47
- }
48
-
49
- // Try to use the 'ws' package if available
50
- try {
51
- if (typeof require !== 'undefined') {
52
- const WebSocket = require('ws');
53
- return new WebSocket(url);
54
- } else {
55
- // In ES modules, dynamic import would be needed
56
- console.warn('WebSocket package detection not available in ES modules. Ensure "ws" is installed.');
57
- throw new Error('WebSocket not available in Node.js ES modules. Install the "ws" package and import it manually.');
58
- }
59
- } catch (error) {
60
- console.warn('ws package not found in Node.js environment. Install with: npm install ws');
61
- throw new Error('WebSocket not available in Node.js. Install the "ws" package.');
62
- }
63
- } else if (environmentDetector.isBrowser || environmentDetector.isWorker) {
64
- // In browser or worker environments, use the native WebSocket
65
- return new WebSocket(url);
5
+ constructor(peerId, maxPeers = 10, mesh = null) {
6
+ super();
7
+ this.peerId = peerId;
8
+ this.maxPeers = maxPeers;
9
+ this.mesh = mesh; // Reference to the mesh for peer coordination
10
+ this.signalingUrl = null;
11
+ this.connected = false;
12
+ this.websocket = null;
13
+ this.reconnectDelay = 1000;
14
+ this.maxReconnectDelay = 30000;
15
+ this.reconnectAttempts = 0;
16
+ this.maxReconnectAttempts = 10; // Increased for better persistence
17
+ this.connectionPromise = null;
18
+ this.reconnectTimeout = null;
19
+ this.isReconnecting = false;
20
+
21
+ // Add keep-alive ping to prevent WebSocket timeout
22
+ this.keepAliveInterval = null;
23
+ this.keepAliveIntervalMs = 9 * 60 * 1000; // Ping every 9 minutes for large safety margin
24
+
25
+ // Health monitoring
26
+ this.lastPingTime = null;
27
+ this.lastPongTime = null;
28
+ this.pingTimeout = null;
29
+ this.healthCheckInterval = null;
30
+ this.connectionQualityTimeout = 10000; // 10 seconds to consider connection unhealthy
31
+ }
32
+
33
+ setConnectionType(type) {
34
+ // WebSocket-only implementation, ignore connection type setting
35
+ console.log(`WebSocket-only implementation - connection type setting ignored: ${type}`);
36
+ }
37
+
38
+ createWebSocket(url) {
39
+ // Environment-aware WebSocket creation
40
+ if (environmentDetector.isNodeJS) {
41
+ // Check for globally injected WebSocket first (set by user)
42
+ if (typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined') {
43
+ return new global.WebSocket(url);
44
+ }
45
+ if (typeof WebSocket !== 'undefined') {
46
+ return new WebSocket(url);
47
+ }
48
+
49
+ // Try to use the 'ws' package if available
50
+ try {
51
+ if (typeof require !== 'undefined') {
52
+ const WebSocket = require('ws');
53
+ return new WebSocket(url);
66
54
  } else {
67
- throw new Error('WebSocket not supported in this environment');
55
+ // In ES modules, dynamic import would be needed
56
+ console.warn('WebSocket package detection not available in ES modules. Ensure "ws" is installed.');
57
+ throw new Error('WebSocket not available in Node.js ES modules. Install the "ws" package and import it manually.');
68
58
  }
59
+ } catch (error) {
60
+ console.warn('ws package not found in Node.js environment. Install with: npm install ws');
61
+ throw new Error('WebSocket not available in Node.js. Install the "ws" package.');
62
+ }
63
+ } else if (environmentDetector.isBrowser || environmentDetector.isWorker) {
64
+ // In browser or worker environments, use the native WebSocket
65
+ return new WebSocket(url);
66
+ } else {
67
+ throw new Error('WebSocket not supported in this environment');
68
+ }
69
+ }
70
+
71
+ async sendSignalingMessage(message) {
72
+ // Check connection health before sending
73
+ if (!this.isConnected()) {
74
+ console.log('WebSocket not connected, attempting to reconnect...');
75
+ if (!this.isReconnecting) {
76
+ this.attemptReconnect();
77
+ }
78
+ throw new Error('WebSocket not connected');
69
79
  }
70
80
 
71
- async sendSignalingMessage(message) {
72
- // Check connection health before sending
73
- if (!this.isConnected()) {
74
- console.log('WebSocket not connected, attempting to reconnect...');
75
- if (!this.isReconnecting) {
76
- this.attemptReconnect();
77
- }
78
- throw new Error('WebSocket not connected');
79
- }
80
-
81
- const payload = {
82
- type: message.type,
83
- data: message.data,
84
- maxPeers: this.maxPeers,
85
- ...(message.targetPeerId && { targetPeerId: message.targetPeerId })
86
- };
87
-
88
- try {
89
- this.websocket.send(JSON.stringify(payload));
90
- console.log('Sent WebSocket message:', payload.type);
91
- return { success: true };
92
- } catch (error) {
93
- console.error('Failed to send WebSocket message:', error);
94
- // Trigger reconnection on send failure
95
- if (!this.isReconnecting) {
96
- this.attemptReconnect();
97
- }
98
- throw error;
99
- }
81
+ const payload = {
82
+ type: message.type,
83
+ data: message.data,
84
+ maxPeers: this.maxPeers,
85
+ ...(message.targetPeerId && { targetPeerId: message.targetPeerId })
86
+ };
87
+
88
+ try {
89
+ this.websocket.send(JSON.stringify(payload));
90
+ console.log('Sent WebSocket message:', payload.type);
91
+ return { success: true };
92
+ } catch (error) {
93
+ console.error('Failed to send WebSocket message:', error);
94
+ // Trigger reconnection on send failure
95
+ if (!this.isReconnecting) {
96
+ this.attemptReconnect();
97
+ }
98
+ throw error;
100
99
  }
100
+ }
101
101
 
102
- isConnected() {
103
- return this.websocket &&
104
- this.websocket.readyState === WebSocket.OPEN &&
102
+ isConnected() {
103
+ return this.websocket &&
104
+ this.websocket.readyState === WebSocket.OPEN &&
105
105
  this.connected;
106
+ }
107
+
108
+ async connect(websocketUrl) {
109
+ // Validate WebSocket support before attempting connection
110
+ if (!environmentDetector.hasWebSocket) {
111
+ const error = new Error('WebSocket not supported in this environment');
112
+ this.emit('statusChanged', { type: 'error', message: error.message });
113
+ throw error;
106
114
  }
107
115
 
108
- async connect(websocketUrl) {
109
- // Validate WebSocket support before attempting connection
110
- if (!environmentDetector.hasWebSocket) {
111
- const error = new Error('WebSocket not supported in this environment');
112
- this.emit('statusChanged', { type: 'error', message: error.message });
113
- throw error;
114
- }
115
-
116
- // Prevent multiple simultaneous connection attempts
117
- if (this.connectionPromise) {
118
- console.log('Connection already in progress, waiting for completion...');
119
- return this.connectionPromise;
120
- }
121
-
122
- // Convert HTTP/HTTPS URL to WebSocket URL if needed
123
- if (websocketUrl.startsWith('http://')) {
124
- websocketUrl = websocketUrl.replace('http://', 'ws://');
125
- } else if (websocketUrl.startsWith('https://')) {
126
- websocketUrl = websocketUrl.replace('https://', 'wss://');
127
- }
128
-
129
- // Ensure WebSocket URL format
130
- if (!websocketUrl.startsWith('ws://') && !websocketUrl.startsWith('wss://')) {
131
- throw new Error('Invalid WebSocket URL format');
132
- }
133
-
134
- this.signalingUrl = websocketUrl;
135
-
136
- // Add peerId as query parameter
137
- const url = new URL(websocketUrl);
138
- url.searchParams.set('peerId', this.peerId);
139
-
140
- this.emit('statusChanged', { type: 'connecting', message: 'Connecting to WebSocket...' });
141
-
142
- this.connectionPromise = new Promise((resolve, reject) => {
143
- try {
144
- // Create WebSocket with environment-specific handling
145
- this.websocket = this.createWebSocket(url.toString());
146
-
147
- const connectTimeout = setTimeout(() => {
148
- if (this.websocket.readyState === WebSocket.CONNECTING) {
149
- this.websocket.close();
150
- reject(new Error('WebSocket connection timeout'));
151
- }
152
- }, 10000);
153
-
154
- this.websocket.onopen = () => {
155
- clearTimeout(connectTimeout);
156
- this.connected = true;
157
- this.reconnectAttempts = 0;
158
- this.reconnectDelay = 1000;
159
- this.isReconnecting = false;
160
- this.connectionPromise = null;
161
-
162
- console.log('WebSocket connected');
163
- this.emit('statusChanged', { type: 'info', message: 'WebSocket connected' });
164
-
165
- // Send announce message
166
- this.sendSignalingMessage({
167
- type: 'announce',
168
- data: { peerId: this.peerId }
169
- }).then(() => {
170
- this.startKeepAlive();
171
- // Removed health monitoring - keep-alive pings are sufficient
172
- this.emit('connected');
173
- resolve();
174
- }).catch(error => {
175
- console.error('Failed to send announce message:', error);
176
- this.startKeepAlive();
177
- // Removed health monitoring - keep-alive pings are sufficient
178
- this.emit('connected'); // Still emit connected even if announce fails
179
- resolve();
180
- });
181
- };
182
-
183
- this.websocket.onmessage = (event) => {
184
- try {
185
- const message = JSON.parse(event.data);
186
- console.log('Received WebSocket message:', message.type);
187
-
188
- if (message.type === 'connected') {
189
- // Connection confirmation from server
190
- console.log('WebSocket connection confirmed by server');
191
- } else if (message.type === 'pong') {
192
- // Handle pong response for health monitoring
193
- this.handlePong();
194
- } else {
195
- // Forward signaling message to mesh
196
- this.emit('signalingMessage', message);
197
- }
198
- } catch (error) {
199
- console.error('Failed to parse WebSocket message:', error);
200
- }
201
- };
202
-
203
- this.websocket.onclose = (event) => {
204
- clearTimeout(connectTimeout);
205
- this.connected = false;
206
- this.connectionPromise = null;
207
- this.stopKeepAlive();
208
- // Removed health monitoring stop - not using health monitoring
209
-
210
- console.log('WebSocket closed:', event.code, event.reason);
211
-
212
- if (event.code === 1000) {
213
- // Normal closure
214
- this.emit('disconnected');
215
- } else {
216
- // Abnormal closure - attempt reconnection
217
- this.emit('statusChanged', { type: 'warning', message: 'WebSocket connection lost - reconnecting...' });
218
- if (!this.isReconnecting) {
219
- this.attemptReconnect();
220
- }
221
- }
222
- };
223
-
224
- this.websocket.onerror = (error) => {
225
- clearTimeout(connectTimeout);
226
- console.error('WebSocket error:', error);
227
-
228
- if (this.websocket.readyState === WebSocket.CONNECTING) {
229
- this.connectionPromise = null;
230
- reject(new Error('WebSocket connection failed'));
231
- } else {
232
- this.emit('statusChanged', { type: 'error', message: 'WebSocket error occurred' });
233
- // Trigger reconnection on error if not already reconnecting
234
- if (!this.isReconnecting) {
235
- this.attemptReconnect();
236
- }
237
- }
238
- };
239
-
240
- } catch (error) {
241
- this.connectionPromise = null;
242
- reject(error);
243
- }
244
- });
245
-
246
- return this.connectionPromise;
116
+ // Prevent multiple simultaneous connection attempts
117
+ if (this.connectionPromise) {
118
+ console.log('Connection already in progress, waiting for completion...');
119
+ return this.connectionPromise;
247
120
  }
248
121
 
249
- attemptReconnect() {
250
- if (this.isReconnecting) {
251
- console.log('Reconnection already in progress');
252
- return;
253
- }
122
+ // Convert HTTP/HTTPS URL to WebSocket URL if needed
123
+ if (websocketUrl.startsWith('http://')) {
124
+ websocketUrl = websocketUrl.replace('http://', 'ws://');
125
+ } else if (websocketUrl.startsWith('https://')) {
126
+ websocketUrl = websocketUrl.replace('https://', 'wss://');
127
+ }
254
128
 
255
- // Clear any existing reconnect timeout
256
- if (this.reconnectTimeout) {
257
- clearTimeout(this.reconnectTimeout);
258
- this.reconnectTimeout = null;
259
- }
129
+ // Ensure WebSocket URL format
130
+ if (!websocketUrl.startsWith('ws://') && !websocketUrl.startsWith('wss://')) {
131
+ throw new Error('Invalid WebSocket URL format');
132
+ }
260
133
 
261
- if (this.reconnectAttempts >= this.maxReconnectAttempts) {
262
- console.log('Max reconnection attempts reached, using exponential backoff');
263
- // Don't give up completely, but use longer delays
264
- const extendedDelay = Math.min(this.maxReconnectDelay * 2, 300000); // Max 5 minutes
265
- this.reconnectTimeout = setTimeout(() => {
266
- this.reconnectAttempts = Math.floor(this.maxReconnectAttempts / 2); // Reset to half max
267
- this.attemptReconnect();
268
- }, extendedDelay);
269
- return;
270
- }
134
+ this.signalingUrl = websocketUrl;
135
+
136
+ // Add peerId as query parameter
137
+ const url = new URL(websocketUrl);
138
+ url.searchParams.set('peerId', this.peerId);
139
+
140
+ this.emit('statusChanged', { type: 'connecting', message: 'Connecting to WebSocket...' });
141
+
142
+ this.connectionPromise = new Promise((resolve, reject) => {
143
+ try {
144
+ // Create WebSocket with environment-specific handling
145
+ this.websocket = this.createWebSocket(url.toString());
146
+
147
+ const connectTimeout = setTimeout(() => {
148
+ if (this.websocket.readyState === WebSocket.CONNECTING) {
149
+ this.websocket.close();
150
+ reject(new Error('WebSocket connection timeout'));
151
+ }
152
+ }, 10000);
153
+
154
+ this.websocket.onopen = () => {
155
+ clearTimeout(connectTimeout);
156
+ this.connected = true;
157
+ this.reconnectAttempts = 0;
158
+ this.reconnectDelay = 1000;
159
+ this.isReconnecting = false;
160
+ this.connectionPromise = null;
161
+
162
+ console.log('WebSocket connected');
163
+ this.emit('statusChanged', { type: 'info', message: 'WebSocket connected' });
164
+
165
+ // Send announce message
166
+ this.sendSignalingMessage({
167
+ type: 'announce',
168
+ data: { peerId: this.peerId }
169
+ }).then(() => {
170
+ this.startKeepAlive();
171
+ // Removed health monitoring - keep-alive pings are sufficient
172
+ this.emit('connected');
173
+ resolve();
174
+ }).catch(error => {
175
+ console.error('Failed to send announce message:', error);
176
+ this.startKeepAlive();
177
+ // Removed health monitoring - keep-alive pings are sufficient
178
+ this.emit('connected'); // Still emit connected even if announce fails
179
+ resolve();
180
+ });
181
+ };
271
182
 
272
- this.isReconnecting = true;
273
- this.reconnectAttempts++;
274
- const delay = Math.min(this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1), this.maxReconnectDelay);
275
-
276
- console.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
277
-
278
- this.reconnectTimeout = setTimeout(async () => {
279
- if (!this.connected && this.signalingUrl) {
280
- try {
281
- await this.connect(this.signalingUrl);
282
- this.emit('statusChanged', { type: 'info', message: 'WebSocket reconnected successfully' });
283
- } catch (error) {
284
- console.error('Reconnection failed:', error);
285
- this.isReconnecting = false;
286
- this.attemptReconnect();
287
- }
183
+ this.websocket.onmessage = (event) => {
184
+ try {
185
+ const message = JSON.parse(event.data);
186
+ console.log('Received WebSocket message:', message.type);
187
+
188
+ if (message.type === 'connected') {
189
+ // Connection confirmation from server
190
+ console.log('WebSocket connection confirmed by server');
191
+ } else if (message.type === 'pong') {
192
+ // Handle pong response for health monitoring
193
+ this.handlePong();
288
194
  } else {
289
- this.isReconnecting = false;
195
+ // Forward signaling message to mesh
196
+ this.emit('signalingMessage', message);
290
197
  }
291
- }, delay);
292
- }
198
+ } catch (error) {
199
+ console.error('Failed to parse WebSocket message:', error);
200
+ }
201
+ };
293
202
 
294
- disconnect() {
295
- // Clear reconnection state
296
- this.isReconnecting = false;
297
- if (this.reconnectTimeout) {
298
- clearTimeout(this.reconnectTimeout);
299
- this.reconnectTimeout = null;
300
- }
203
+ this.websocket.onclose = (event) => {
204
+ clearTimeout(connectTimeout);
205
+ this.connected = false;
206
+ this.connectionPromise = null;
207
+ this.stopKeepAlive();
208
+ // Removed health monitoring stop - not using health monitoring
209
+
210
+ console.log('WebSocket closed:', event.code, event.reason);
211
+
212
+ if (event.code === 1000) {
213
+ // Normal closure
214
+ this.emit('disconnected');
215
+ } else {
216
+ // Abnormal closure - attempt reconnection
217
+ this.emit('statusChanged', { type: 'warning', message: 'WebSocket connection lost - reconnecting...' });
218
+ if (!this.isReconnecting) {
219
+ this.attemptReconnect();
220
+ }
221
+ }
222
+ };
301
223
 
302
- // The sendGoodbyeMessage is often called from an unload handler,
303
- // so we don't want to make it part of the standard disconnect flow here.
304
- // The CleanupManager handles sending goodbye on unload.
305
- this.stopKeepAlive();
306
- this.stopHealthMonitoring(); // FIX: Stop health monitoring to prevent memory leaks
307
-
308
- this.connected = false;
224
+ this.websocket.onerror = (error) => {
225
+ clearTimeout(connectTimeout);
226
+ console.error('WebSocket error:', error);
227
+
228
+ if (this.websocket.readyState === WebSocket.CONNECTING) {
229
+ this.connectionPromise = null;
230
+ reject(new Error('WebSocket connection failed'));
231
+ } else {
232
+ this.emit('statusChanged', { type: 'error', message: 'WebSocket error occurred' });
233
+ // Trigger reconnection on error if not already reconnecting
234
+ if (!this.isReconnecting) {
235
+ this.attemptReconnect();
236
+ }
237
+ }
238
+ };
239
+ } catch (error) {
309
240
  this.connectionPromise = null;
241
+ reject(error);
242
+ }
243
+ });
310
244
 
311
- if (this.websocket) {
312
- // Clear event handlers to prevent memory leaks
313
- this.websocket.onopen = null;
314
- this.websocket.onmessage = null;
315
- this.websocket.onclose = null;
316
- this.websocket.onerror = null;
317
-
318
- this.websocket.close(1000, 'Client disconnect');
319
- this.websocket = null;
320
- }
245
+ return this.connectionPromise;
246
+ }
321
247
 
322
- this.emit('disconnected');
248
+ attemptReconnect() {
249
+ if (this.isReconnecting) {
250
+ console.log('Reconnection already in progress');
251
+ return;
323
252
  }
324
253
 
325
- sendGoodbyeMessage() {
326
- if (!this.connected) return;
254
+ // Clear any existing reconnect timeout
255
+ if (this.reconnectTimeout) {
256
+ clearTimeout(this.reconnectTimeout);
257
+ this.reconnectTimeout = null;
258
+ }
327
259
 
328
- try {
329
- console.log('Sending goodbye message');
330
-
331
- if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
332
- this.websocket.send(JSON.stringify({
333
- type: 'goodbye',
334
- data: {
335
- peerId: this.peerId,
336
- timestamp: Date.now(),
337
- reason: 'peer_disconnect'
338
- }
339
- }));
340
- }
341
- } catch (error) {
342
- console.error('Failed to send goodbye message:', error);
343
- }
260
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
261
+ console.log('Max reconnection attempts reached, using exponential backoff');
262
+ // Don't give up completely, but use longer delays
263
+ const extendedDelay = Math.min(this.maxReconnectDelay * 2, 300000); // Max 5 minutes
264
+ this.reconnectTimeout = setTimeout(() => {
265
+ this.reconnectAttempts = Math.floor(this.maxReconnectAttempts / 2); // Reset to half max
266
+ this.attemptReconnect();
267
+ }, extendedDelay);
268
+ return;
344
269
  }
345
270
 
346
- async sendCleanupMessage(targetPeerId) {
347
- if (!this.connected) return;
348
-
271
+ this.isReconnecting = true;
272
+ this.reconnectAttempts++;
273
+ const delay = Math.min(this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1), this.maxReconnectDelay);
274
+
275
+ console.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
276
+
277
+ this.reconnectTimeout = setTimeout(async () => {
278
+ if (!this.connected && this.signalingUrl) {
349
279
  try {
350
- await this.sendSignalingMessage({
351
- type: 'cleanup',
352
- data: {
353
- peerId: this.peerId,
354
- targetPeerId: targetPeerId,
355
- timestamp: Date.now(),
356
- reason: 'peer_disconnect'
357
- },
358
- targetPeerId: targetPeerId
359
- });
280
+ await this.connect(this.signalingUrl);
281
+ this.emit('statusChanged', { type: 'info', message: 'WebSocket reconnected successfully' });
360
282
  } catch (error) {
361
- console.log(`Cleanup message failed for ${targetPeerId}:`, error.message);
283
+ console.error('Reconnection failed:', error);
284
+ this.isReconnecting = false;
285
+ this.attemptReconnect();
362
286
  }
287
+ } else {
288
+ this.isReconnecting = false;
289
+ }
290
+ }, delay);
291
+ }
292
+
293
+ disconnect() {
294
+ // Clear reconnection state
295
+ this.isReconnecting = false;
296
+ if (this.reconnectTimeout) {
297
+ clearTimeout(this.reconnectTimeout);
298
+ this.reconnectTimeout = null;
363
299
  }
364
300
 
365
- startKeepAlive() {
366
- if (this.keepAliveInterval) return;
367
-
368
- console.log('Starting keep-alive pings every', this.keepAliveIntervalMs / 1000, 'seconds');
369
-
370
- const keepAliveCallback = () => {
371
- if (this.connected) {
372
- // Check if this peer should send the ping
373
- if (this.shouldSendKeepAlivePing()) {
374
- console.log('Sending keep-alive ping (designated peer)');
375
- this.sendSignalingMessage({
376
- type: 'ping',
377
- data: { peerId: this.peerId }
378
- }).catch(error => {
379
- console.error('Keep-alive ping failed:', error);
380
- });
381
- } else {
382
- console.log('Skipping keep-alive ping (not designated peer)');
383
- }
384
- }
385
- };
301
+ // The sendGoodbyeMessage is often called from an unload handler,
302
+ // so we don't want to make it part of the standard disconnect flow here.
303
+ // The CleanupManager handles sending goodbye on unload.
304
+ this.stopKeepAlive();
305
+ this.stopHealthMonitoring(); // FIX: Stop health monitoring to prevent memory leaks
306
+
307
+ this.connected = false;
308
+ this.connectionPromise = null;
309
+
310
+ if (this.websocket) {
311
+ // Clear event handlers to prevent memory leaks
312
+ this.websocket.onopen = null;
313
+ this.websocket.onmessage = null;
314
+ this.websocket.onclose = null;
315
+ this.websocket.onerror = null;
386
316
 
387
- if (environmentDetector.isBrowser) {
388
- this.keepAliveInterval = window.setInterval(keepAliveCallback, this.keepAliveIntervalMs);
317
+ this.websocket.close(1000, 'Client disconnect');
318
+ this.websocket = null;
319
+ }
320
+
321
+ this.emit('disconnected');
322
+ }
323
+
324
+ sendGoodbyeMessage() {
325
+ if (!this.connected) return;
326
+
327
+ try {
328
+ console.log('Sending goodbye message');
329
+
330
+ if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
331
+ this.websocket.send(JSON.stringify({
332
+ type: 'goodbye',
333
+ data: {
334
+ peerId: this.peerId,
335
+ timestamp: Date.now(),
336
+ reason: 'peer_disconnect'
337
+ }
338
+ }));
339
+ }
340
+ } catch (error) {
341
+ console.error('Failed to send goodbye message:', error);
342
+ }
343
+ }
344
+
345
+ async sendCleanupMessage(targetPeerId) {
346
+ if (!this.connected) return;
347
+
348
+ try {
349
+ await this.sendSignalingMessage({
350
+ type: 'cleanup',
351
+ data: {
352
+ peerId: this.peerId,
353
+ targetPeerId,
354
+ timestamp: Date.now(),
355
+ reason: 'peer_disconnect'
356
+ },
357
+ targetPeerId
358
+ });
359
+ } catch (error) {
360
+ console.log(`Cleanup message failed for ${targetPeerId}:`, error.message);
361
+ }
362
+ }
363
+
364
+ startKeepAlive() {
365
+ if (this.keepAliveInterval) return;
366
+
367
+ console.log('Starting keep-alive pings every', this.keepAliveIntervalMs / 1000, 'seconds');
368
+
369
+ const keepAliveCallback = () => {
370
+ if (this.connected) {
371
+ // Check if this peer should send the ping
372
+ if (this.shouldSendKeepAlivePing()) {
373
+ console.log('Sending keep-alive ping (designated peer)');
374
+ this.sendSignalingMessage({
375
+ type: 'ping',
376
+ data: { peerId: this.peerId }
377
+ }).catch(error => {
378
+ console.error('Keep-alive ping failed:', error);
379
+ });
389
380
  } else {
390
- this.keepAliveInterval = setInterval(keepAliveCallback, this.keepAliveIntervalMs);
381
+ console.log('Skipping keep-alive ping (not designated peer)');
391
382
  }
383
+ }
384
+ };
385
+
386
+ if (environmentDetector.isBrowser) {
387
+ this.keepAliveInterval = window.setInterval(keepAliveCallback, this.keepAliveIntervalMs);
388
+ } else {
389
+ this.keepAliveInterval = setInterval(keepAliveCallback, this.keepAliveIntervalMs);
392
390
  }
391
+ }
393
392
 
394
- /**
393
+ /**
395
394
  * Determine if this peer should send the keep-alive ping.
396
395
  * Only one peer should send it when there are multiple peers connected.
397
396
  * The peer with the lexicographically smallest ID becomes the designated sender.
398
397
  */
399
- shouldSendKeepAlivePing() {
400
- // If no mesh reference available, always send (fallback)
401
- if (!this.mesh) {
402
- return true;
403
- }
398
+ shouldSendKeepAlivePing() {
399
+ // If no mesh reference available, always send (fallback)
400
+ if (!this.mesh) {
401
+ return true;
402
+ }
404
403
 
405
- // Get all connected peers
406
- const connectedPeers = this.mesh.connectionManager.getConnectedPeers();
407
-
408
- // If no peers connected, always send
409
- if (connectedPeers.length === 0) {
410
- return true;
411
- }
404
+ // Get all connected peers
405
+ const connectedPeers = this.mesh.connectionManager.getConnectedPeers();
412
406
 
413
- // Get all peer IDs including this one
414
- const allPeerIds = [this.peerId, ...connectedPeers.map(peer => peer.peerId)];
415
-
416
- // Sort lexicographically and check if this peer is the smallest
417
- allPeerIds.sort();
418
- const designatedPeer = allPeerIds[0];
419
-
420
- const isDesignated = designatedPeer === this.peerId;
421
- console.log(`Keep-alive ping decision: ${isDesignated ? 'SEND' : 'SKIP'} (this: ${this.peerId.substring(0, 8)}, designated: ${designatedPeer.substring(0, 8)}, total peers: ${allPeerIds.length})`);
422
-
423
- return isDesignated;
407
+ // If no peers connected, always send
408
+ if (connectedPeers.length === 0) {
409
+ return true;
424
410
  }
425
411
 
426
- stopKeepAlive() {
427
- if (this.keepAliveInterval) {
428
- clearInterval(this.keepAliveInterval);
429
- this.keepAliveInterval = null;
430
- console.log('Stopped keep-alive pings');
431
- }
432
- }
412
+ // Get all peer IDs including this one
413
+ const allPeerIds = [this.peerId, ...connectedPeers.map(peer => peer.peerId)];
433
414
 
434
- startHealthMonitoring() {
435
- if (this.healthCheckInterval) return;
436
-
437
- console.log('Starting connection health monitoring');
438
-
439
- const healthCheckCallback = () => {
440
- // Check WebSocket state first
441
- if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
442
- console.warn('WebSocket is not in OPEN state:', this.websocket?.readyState);
443
- this.handleUnhealthyConnection();
444
- return;
445
- }
415
+ // Sort lexicographically and check if this peer is the smallest
416
+ allPeerIds.sort();
417
+ const designatedPeer = allPeerIds[0];
446
418
 
447
- if (this.connected) {
448
- const now = Date.now();
449
-
450
- // Only check for pong timeout if we have a pending ping
451
- if (this.pingTimeout) {
452
- // There's already a ping waiting for pong, don't send another
453
- console.log('Ping already pending, waiting for pong...');
454
- return;
455
- }
456
-
457
- // Check if we have an old pong that indicates connection issues
458
- if (this.lastPingTime && this.lastPongTime &&
459
- (this.lastPingTime > this.lastPongTime) &&
460
- (now - this.lastPingTime > this.connectionQualityTimeout)) {
461
- console.warn('Connection unhealthy - ping/pong timeout');
462
- this.handleUnhealthyConnection();
463
- return;
464
- }
465
-
466
- // Send health ping
467
- this.sendHealthPing();
468
- }
469
- };
419
+ const isDesignated = designatedPeer === this.peerId;
420
+ console.log(`Keep-alive ping decision: ${isDesignated ? 'SEND' : 'SKIP'} (this: ${this.peerId.substring(0, 8)}, designated: ${designatedPeer.substring(0, 8)}, total peers: ${allPeerIds.length})`);
470
421
 
471
- if (environmentDetector.isBrowser) {
472
- this.healthCheckInterval = window.setInterval(healthCheckCallback, 30000);
473
- } else {
474
- this.healthCheckInterval = setInterval(healthCheckCallback, 30000);
475
- }
422
+ return isDesignated;
423
+ }
424
+
425
+ stopKeepAlive() {
426
+ if (this.keepAliveInterval) {
427
+ clearInterval(this.keepAliveInterval);
428
+ this.keepAliveInterval = null;
429
+ console.log('Stopped keep-alive pings');
476
430
  }
431
+ }
477
432
 
478
- stopHealthMonitoring() {
479
- if (this.healthCheckInterval) {
480
- clearInterval(this.healthCheckInterval);
481
- this.healthCheckInterval = null;
482
- console.log('Stopped connection health monitoring');
483
- }
484
-
433
+ startHealthMonitoring() {
434
+ if (this.healthCheckInterval) return;
435
+
436
+ console.log('Starting connection health monitoring');
437
+
438
+ const healthCheckCallback = () => {
439
+ // Check WebSocket state first
440
+ if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
441
+ console.warn('WebSocket is not in OPEN state:', this.websocket?.readyState);
442
+ this.handleUnhealthyConnection();
443
+ return;
444
+ }
445
+
446
+ if (this.connected) {
447
+ const now = Date.now();
448
+
449
+ // Only check for pong timeout if we have a pending ping
485
450
  if (this.pingTimeout) {
486
- clearTimeout(this.pingTimeout);
487
- this.pingTimeout = null;
451
+ // There's already a ping waiting for pong, don't send another
452
+ console.log('Ping already pending, waiting for pong...');
453
+ return;
454
+ }
455
+
456
+ // Check if we have an old pong that indicates connection issues
457
+ if (this.lastPingTime && this.lastPongTime &&
458
+ (this.lastPingTime > this.lastPongTime) &&
459
+ (now - this.lastPingTime > this.connectionQualityTimeout)) {
460
+ console.warn('Connection unhealthy - ping/pong timeout');
461
+ this.handleUnhealthyConnection();
462
+ return;
488
463
  }
464
+
465
+ // Send health ping
466
+ this.sendHealthPing();
467
+ }
468
+ };
469
+
470
+ if (environmentDetector.isBrowser) {
471
+ this.healthCheckInterval = window.setInterval(healthCheckCallback, 30000);
472
+ } else {
473
+ this.healthCheckInterval = setInterval(healthCheckCallback, 30000);
489
474
  }
475
+ }
490
476
 
491
- sendHealthPing() {
492
- if (!this.isConnected()) return;
477
+ stopHealthMonitoring() {
478
+ if (this.healthCheckInterval) {
479
+ clearInterval(this.healthCheckInterval);
480
+ this.healthCheckInterval = null;
481
+ console.log('Stopped connection health monitoring');
482
+ }
493
483
 
494
- try {
495
- this.lastPingTime = Date.now();
496
-
497
- // Set timeout for pong response
498
- if (this.pingTimeout) {
499
- clearTimeout(this.pingTimeout);
500
- }
501
-
502
- this.pingTimeout = setTimeout(() => {
503
- console.warn('Health ping timeout - connection may be unhealthy');
504
- this.handleUnhealthyConnection();
505
- }, this.connectionQualityTimeout);
506
-
507
- // Send ping as a regular message (server will handle it)
508
- this.websocket.send(JSON.stringify({
509
- type: 'ping',
510
- data: { peerId: this.peerId, timestamp: this.lastPingTime }
511
- }));
512
-
513
- console.log('Sent health ping');
514
- } catch (error) {
515
- console.error('Failed to send health ping:', error);
516
- this.handleUnhealthyConnection();
517
- }
484
+ if (this.pingTimeout) {
485
+ clearTimeout(this.pingTimeout);
486
+ this.pingTimeout = null;
487
+ }
488
+ }
489
+
490
+ sendHealthPing() {
491
+ if (!this.isConnected()) return;
492
+
493
+ try {
494
+ this.lastPingTime = Date.now();
495
+
496
+ // Set timeout for pong response
497
+ if (this.pingTimeout) {
498
+ clearTimeout(this.pingTimeout);
499
+ }
500
+
501
+ this.pingTimeout = setTimeout(() => {
502
+ console.warn('Health ping timeout - connection may be unhealthy');
503
+ this.handleUnhealthyConnection();
504
+ }, this.connectionQualityTimeout);
505
+
506
+ // Send ping as a regular message (server will handle it)
507
+ this.websocket.send(JSON.stringify({
508
+ type: 'ping',
509
+ data: { peerId: this.peerId, timestamp: this.lastPingTime }
510
+ }));
511
+
512
+ console.log('Sent health ping');
513
+ } catch (error) {
514
+ console.error('Failed to send health ping:', error);
515
+ this.handleUnhealthyConnection();
518
516
  }
517
+ }
519
518
 
520
- handlePong() {
521
- this.lastPongTime = Date.now();
522
-
523
- if (this.pingTimeout) {
524
- clearTimeout(this.pingTimeout);
525
- this.pingTimeout = null;
526
- }
527
-
528
- console.log('Received pong - connection healthy');
519
+ handlePong() {
520
+ this.lastPongTime = Date.now();
521
+
522
+ if (this.pingTimeout) {
523
+ clearTimeout(this.pingTimeout);
524
+ this.pingTimeout = null;
529
525
  }
530
526
 
531
- handleUnhealthyConnection() {
532
- console.warn('Detected unhealthy WebSocket connection, forcing reconnection');
533
- this.emit('statusChanged', { type: 'warning', message: 'Connection health degraded - reconnecting...' });
534
-
535
- // Force close and reconnect
536
- this.connected = false;
537
- if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
538
- this.websocket.close(3000, 'Health check failed'); // Use valid close code 3000-4999
539
- }
540
-
541
- if (!this.isReconnecting) {
542
- this.attemptReconnect();
543
- }
527
+ console.log('Received pong - connection healthy');
528
+ }
529
+
530
+ handleUnhealthyConnection() {
531
+ console.warn('Detected unhealthy WebSocket connection, forcing reconnection');
532
+ this.emit('statusChanged', { type: 'warning', message: 'Connection health degraded - reconnecting...' });
533
+
534
+ // Force close and reconnect
535
+ this.connected = false;
536
+ if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
537
+ this.websocket.close(3000, 'Health check failed'); // Use valid close code 3000-4999
544
538
  }
545
539
 
546
- forceHealthCheck() {
547
- if (!this.isConnected()) {
548
- console.log('Connection not healthy, triggering reconnection');
549
- if (!this.isReconnecting) {
550
- this.attemptReconnect();
551
- }
552
- return false;
553
- }
554
-
555
- this.sendHealthPing();
556
- return true;
540
+ if (!this.isReconnecting) {
541
+ this.attemptReconnect();
542
+ }
543
+ }
544
+
545
+ forceHealthCheck() {
546
+ if (!this.isConnected()) {
547
+ console.log('Connection not healthy, triggering reconnection');
548
+ if (!this.isReconnecting) {
549
+ this.attemptReconnect();
550
+ }
551
+ return false;
557
552
  }
558
553
 
559
- /**
554
+ this.sendHealthPing();
555
+ return true;
556
+ }
557
+
558
+ /**
560
559
  * Force an immediate keep-alive ping check when peer topology changes.
561
560
  * This ensures quick takeover when the designated ping sender disconnects.
562
561
  */
563
- triggerKeepAlivePingCheck() {
564
- if (!this.connected) return;
565
-
566
- if (this.shouldSendKeepAlivePing()) {
567
- console.log('Topology changed - sending immediate keep-alive ping as new designated peer');
568
- this.sendSignalingMessage({
569
- type: 'ping',
570
- data: { peerId: this.peerId }
571
- }).catch(error => {
572
- console.error('Immediate keep-alive ping failed:', error);
573
- });
574
- } else {
575
- console.log('Topology changed - not designated for keep-alive pings');
576
- }
577
- }
578
-
579
- getConnectionStats() {
580
- return {
581
- connected: this.connected,
582
- isReconnecting: this.isReconnecting,
583
- reconnectAttempts: this.reconnectAttempts,
584
- lastPingTime: this.lastPingTime,
585
- lastPongTime: this.lastPongTime,
586
- websocketState: this.websocket ? this.websocket.readyState : 'not created'
587
- };
562
+ triggerKeepAlivePingCheck() {
563
+ if (!this.connected) return;
564
+
565
+ if (this.shouldSendKeepAlivePing()) {
566
+ console.log('Topology changed - sending immediate keep-alive ping as new designated peer');
567
+ this.sendSignalingMessage({
568
+ type: 'ping',
569
+ data: { peerId: this.peerId }
570
+ }).catch(error => {
571
+ console.error('Immediate keep-alive ping failed:', error);
572
+ });
573
+ } else {
574
+ console.log('Topology changed - not designated for keep-alive pings');
588
575
  }
576
+ }
577
+
578
+ getConnectionStats() {
579
+ return {
580
+ connected: this.connected,
581
+ isReconnecting: this.isReconnecting,
582
+ reconnectAttempts: this.reconnectAttempts,
583
+ lastPingTime: this.lastPingTime,
584
+ lastPongTime: this.lastPongTime,
585
+ websocketState: this.websocket ? this.websocket.readyState : 'not created'
586
+ };
587
+ }
589
588
  }