peerpigeon 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1187 -0
- package/examples/browser/app-dht-disabled.js +42 -0
- package/examples/browser/app.js +51 -0
- package/examples/browser/assets/images/favicon.png +0 -0
- package/examples/browser/assets/images/pigeon.png +0 -0
- package/examples/browser/index-dht-disabled.html +123 -0
- package/examples/browser/index.html +340 -0
- package/examples/browser/styles.css +1288 -0
- package/examples/browser/ui-clean.js +0 -0
- package/examples/browser/ui.js +1930 -0
- package/index.js +8 -0
- package/package.json +70 -0
- package/server/index.js +515 -0
- package/src/CleanupManager.js +181 -0
- package/src/ConnectionManager.js +841 -0
- package/src/EventEmitter.js +27 -0
- package/src/EvictionManager.js +257 -0
- package/src/GossipManager.js +416 -0
- package/src/MediaManager.js +225 -0
- package/src/MeshOptimizer.js +181 -0
- package/src/PeerConnection.js +831 -0
- package/src/PeerDiscovery.js +297 -0
- package/src/PeerPigeonMesh.js +703 -0
- package/src/SignalingClient.js +536 -0
- package/src/SignalingHandler.js +325 -0
- package/src/StorageManager.js +88 -0
- package/src/TimerUtils.js +46 -0
- package/src/WebDHT.js +1099 -0
- package/websocket-server/README.md +257 -0
- package/websocket-server/memory-leak-test.js +193 -0
- package/websocket-server/node_modules/.package-lock.json +29 -0
- package/websocket-server/node_modules/ws/LICENSE +20 -0
- package/websocket-server/node_modules/ws/README.md +548 -0
- package/websocket-server/node_modules/ws/browser.js +8 -0
- package/websocket-server/node_modules/ws/index.js +13 -0
- package/websocket-server/node_modules/ws/lib/buffer-util.js +131 -0
- package/websocket-server/node_modules/ws/lib/constants.js +18 -0
- package/websocket-server/node_modules/ws/lib/event-target.js +292 -0
- package/websocket-server/node_modules/ws/lib/extension.js +203 -0
- package/websocket-server/node_modules/ws/lib/limiter.js +55 -0
- package/websocket-server/node_modules/ws/lib/permessage-deflate.js +528 -0
- package/websocket-server/node_modules/ws/lib/receiver.js +706 -0
- package/websocket-server/node_modules/ws/lib/sender.js +602 -0
- package/websocket-server/node_modules/ws/lib/stream.js +161 -0
- package/websocket-server/node_modules/ws/lib/subprotocol.js +62 -0
- package/websocket-server/node_modules/ws/lib/validation.js +152 -0
- package/websocket-server/node_modules/ws/lib/websocket-server.js +550 -0
- package/websocket-server/node_modules/ws/lib/websocket.js +1388 -0
- package/websocket-server/node_modules/ws/package.json +69 -0
- package/websocket-server/node_modules/ws/wrapper.mjs +8 -0
- package/websocket-server/package-lock.json +39 -0
- package/websocket-server/server.js +298 -0
- package/websocket-server/test.js +133 -0
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
import { PeerConnection } from './PeerConnection.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Handles WebRTC signaling messages (offers, answers, ICE candidates)
|
|
6
|
+
*/
|
|
7
|
+
export class SignalingHandler extends EventEmitter {
|
|
8
|
+
constructor(mesh, connectionManager) {
|
|
9
|
+
super();
|
|
10
|
+
this.mesh = mesh;
|
|
11
|
+
this.connectionManager = connectionManager;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async handleSignalingMessage(message) {
|
|
15
|
+
const { type, data, fromPeerId, targetPeerId } = message;
|
|
16
|
+
|
|
17
|
+
if (fromPeerId === this.mesh.peerId) return;
|
|
18
|
+
if (targetPeerId && targetPeerId !== this.mesh.peerId) return;
|
|
19
|
+
|
|
20
|
+
// Ignore cleanup messages - they are handled by the server, not as peer signaling
|
|
21
|
+
if (type === 'cleanup' || type === 'cleanup-all') {
|
|
22
|
+
console.log('Ignoring cleanup message:', { type, fromPeerId });
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Ignore ping messages - they are for keepalive, not peer signaling
|
|
27
|
+
if (type === 'ping' || type === 'pong') {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
console.log('Processing signaling message:', { type, fromPeerId, targetPeerId });
|
|
32
|
+
|
|
33
|
+
switch (type) {
|
|
34
|
+
case 'announce':
|
|
35
|
+
this.handlePeerAnnouncement(fromPeerId);
|
|
36
|
+
break;
|
|
37
|
+
case 'peer-discovered':
|
|
38
|
+
// Handle peer discovery messages from the signaling server
|
|
39
|
+
if (data && data.peerId) {
|
|
40
|
+
this.handlePeerAnnouncement(data.peerId);
|
|
41
|
+
}
|
|
42
|
+
break;
|
|
43
|
+
case 'goodbye':
|
|
44
|
+
this.handlePeerGoodbye(fromPeerId);
|
|
45
|
+
break;
|
|
46
|
+
case 'offer':
|
|
47
|
+
await this.handleOffer(data, fromPeerId);
|
|
48
|
+
break;
|
|
49
|
+
case 'answer':
|
|
50
|
+
await this.handleAnswer(data, fromPeerId);
|
|
51
|
+
break;
|
|
52
|
+
case 'ice-candidate':
|
|
53
|
+
await this.connectionManager.handleIceCandidate(data, fromPeerId);
|
|
54
|
+
break;
|
|
55
|
+
case 'connection-rejected':
|
|
56
|
+
this.handleConnectionRejected(data, fromPeerId);
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
handlePeerAnnouncement(fromPeerId) {
|
|
62
|
+
// Prevent duplicate announcements - only announce if we haven't seen this peer before
|
|
63
|
+
if (this.mesh.peerDiscovery.hasPeer(fromPeerId)) {
|
|
64
|
+
console.log(`Peer ${fromPeerId.substring(0, 8)}... already known, skipping announcement`);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Peer ${fromPeerId.substring(0, 8)}... announced` });
|
|
69
|
+
console.log(`Adding discovered peer: ${fromPeerId.substring(0, 8)}... to PeerDiscovery`);
|
|
70
|
+
console.log(`Current peer count: ${this.connectionManager.getConnectedPeerCount()}/${this.mesh.maxPeers}`);
|
|
71
|
+
console.log(`All discovered peers: ${Array.from(this.mesh.peerDiscovery.discoveredPeers.keys()).map(p => p.substring(0, 8)).join(', ')}`);
|
|
72
|
+
this.mesh.peerDiscovery.addDiscoveredPeer(fromPeerId);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
handlePeerGoodbye(fromPeerId) {
|
|
76
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Peer ${fromPeerId.substring(0, 8)}... left the network` });
|
|
77
|
+
this.mesh.peerDiscovery.removeDiscoveredPeer(fromPeerId);
|
|
78
|
+
this.connectionManager.disconnectPeer(fromPeerId, 'left network');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async handleOffer(offer, fromPeerId) {
|
|
82
|
+
console.log('Handling offer from', fromPeerId);
|
|
83
|
+
|
|
84
|
+
// If we already have a connection or are connecting, handle gracefully
|
|
85
|
+
if (this.connectionManager.hasPeer(fromPeerId)) {
|
|
86
|
+
const existingPeer = this.connectionManager.getPeer(fromPeerId);
|
|
87
|
+
const existingStatus = existingPeer.getStatus();
|
|
88
|
+
|
|
89
|
+
// If connection is already established and working, don't interfere
|
|
90
|
+
if (existingStatus === 'connected') {
|
|
91
|
+
console.log(`Connection already established with ${fromPeerId}, ignoring duplicate offer`);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ABSOLUTE RULE: Lexicographically larger peer ID always initiates
|
|
96
|
+
// If we're receiving an offer but we should be the initiator, there's a race condition
|
|
97
|
+
const weShouldInitiate = this.mesh.peerId > fromPeerId;
|
|
98
|
+
|
|
99
|
+
if (weShouldInitiate && existingPeer.isInitiator) {
|
|
100
|
+
console.log(`Race condition detected! We should initiate (${this.mesh.peerId.substring(0, 8)}... > ${fromPeerId.substring(0, 8)}...) but received offer. Ignoring.`);
|
|
101
|
+
return;
|
|
102
|
+
} else if (!weShouldInitiate && existingPeer.isInitiator) {
|
|
103
|
+
console.log(`We're incorrectly initiating to ${fromPeerId.substring(0, 8)}..., backing down for their offer`);
|
|
104
|
+
// Cleanup our outgoing attempt and accept the incoming offer
|
|
105
|
+
if (existingStatus === 'connecting' || existingStatus === 'new') {
|
|
106
|
+
console.log(`Cleaning up our outgoing connection attempt to ${fromPeerId.substring(0, 8)}...`);
|
|
107
|
+
this.connectionManager.cleanupRaceCondition(fromPeerId);
|
|
108
|
+
} else {
|
|
109
|
+
console.log('Connection in progress, not cleaning up');
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
} else {
|
|
113
|
+
console.log('Already processing incoming connection from', fromPeerId);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Check if we're already attempting to connect to this peer
|
|
119
|
+
if (this.connectionManager.connectionAttempts.has(fromPeerId)) {
|
|
120
|
+
console.log('Already attempting connection to', fromPeerId, 'accepting incoming offer');
|
|
121
|
+
this.connectionManager.connectionAttempts.delete(fromPeerId);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// CRITICAL: Check capacity again right before accepting to prevent race conditions
|
|
125
|
+
const currentCount = this.connectionManager.getConnectedPeerCount();
|
|
126
|
+
const totalPeerCount = this.connectionManager.peers.size;
|
|
127
|
+
let canAccept = this.mesh.canAcceptMorePeers();
|
|
128
|
+
let evictPeerId = null;
|
|
129
|
+
|
|
130
|
+
console.log(`Capacity check for ${fromPeerId.substring(0, 8)}...: ${currentCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers, canAccept: ${canAccept}`);
|
|
131
|
+
|
|
132
|
+
if (!canAccept) {
|
|
133
|
+
console.log(`At capacity (${currentCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total) - checking eviction and cleanup options`);
|
|
134
|
+
|
|
135
|
+
// First try: Check if we should evict a peer for this new connection
|
|
136
|
+
if (this.mesh.evictionStrategy) {
|
|
137
|
+
evictPeerId = this.mesh.evictionManager.shouldEvictForPeer(fromPeerId);
|
|
138
|
+
if (evictPeerId) {
|
|
139
|
+
console.log(`Will evict ${evictPeerId.substring(0, 8)}... for incoming connection from ${fromPeerId.substring(0, 8)}...`);
|
|
140
|
+
canAccept = true; // We can accept because we'll evict
|
|
141
|
+
} else {
|
|
142
|
+
console.log(`No suitable peer found for eviction for ${fromPeerId.substring(0, 8)}...`);
|
|
143
|
+
}
|
|
144
|
+
} else {
|
|
145
|
+
console.log(`Eviction strategy disabled - cannot evict for ${fromPeerId.substring(0, 8)}...`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Second try: Clean up stale peers to make room
|
|
149
|
+
if (!canAccept) {
|
|
150
|
+
const stalePeerCount = this.connectionManager.getStalePeerCount();
|
|
151
|
+
if (stalePeerCount > 0) {
|
|
152
|
+
console.log(`No eviction candidate, attempting to clean up ${stalePeerCount} stale peer(s) to make room for ${fromPeerId.substring(0, 8)}...`);
|
|
153
|
+
this.connectionManager.cleanupStalePeers();
|
|
154
|
+
canAccept = this.mesh.canAcceptMorePeers();
|
|
155
|
+
if (canAccept) {
|
|
156
|
+
console.log(`Successfully made room after cleanup for ${fromPeerId.substring(0, 8)}...`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Final rejection if no options worked
|
|
162
|
+
if (!canAccept) {
|
|
163
|
+
const reason = `max_peers_reached (${currentCount}/${this.mesh.maxPeers} connected, ${this.connectionManager.peers.size} total, no eviction candidate)`;
|
|
164
|
+
console.log(`Rejecting offer from ${fromPeerId.substring(0, 8)}...: ${reason}`);
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
await this.mesh.signalingClient.sendSignalingMessage({
|
|
168
|
+
type: 'connection-rejected',
|
|
169
|
+
data: {
|
|
170
|
+
reason: 'max_peers_reached',
|
|
171
|
+
details: reason,
|
|
172
|
+
currentCount: currentCount,
|
|
173
|
+
maxPeers: this.mesh.maxPeers
|
|
174
|
+
},
|
|
175
|
+
targetPeerId: fromPeerId
|
|
176
|
+
});
|
|
177
|
+
console.log(`Sent connection rejection to ${fromPeerId.substring(0, 8)}...`);
|
|
178
|
+
} catch (error) {
|
|
179
|
+
console.error('Failed to send connection rejection:', error);
|
|
180
|
+
}
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Perform eviction if we determined one was needed
|
|
186
|
+
if (evictPeerId) {
|
|
187
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Evicting ${evictPeerId.substring(0, 8)}... for incoming connection from ${fromPeerId.substring(0, 8)}...` });
|
|
188
|
+
await this.mesh.evictionManager.evictPeer(evictPeerId, 'incoming closer peer');
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
// Get current media stream if available
|
|
192
|
+
const localStream = this.mesh.mediaManager.localStream;
|
|
193
|
+
const hasMedia = localStream !== null;
|
|
194
|
+
const options = { localStream };
|
|
195
|
+
|
|
196
|
+
console.log(`Creating answer connection for ${fromPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
|
|
197
|
+
|
|
198
|
+
const peerConnection = new PeerConnection(fromPeerId, false, options);
|
|
199
|
+
|
|
200
|
+
// Set up event handlers BEFORE creating connection to catch all events
|
|
201
|
+
this.connectionManager.setupPeerConnectionHandlers(peerConnection);
|
|
202
|
+
this.connectionManager.peers.set(fromPeerId, peerConnection);
|
|
203
|
+
|
|
204
|
+
await peerConnection.createConnection();
|
|
205
|
+
|
|
206
|
+
console.log(`Processing offer from ${fromPeerId.substring(0, 8)}...`, {
|
|
207
|
+
type: offer.type,
|
|
208
|
+
sdpLength: offer.sdp?.length || 0,
|
|
209
|
+
hasAudio: offer.sdp?.includes('m=audio') || false,
|
|
210
|
+
hasVideo: offer.sdp?.includes('m=video') || false
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
// Handle the offer using PeerConnection's method
|
|
214
|
+
const answer = await peerConnection.handleOffer(offer);
|
|
215
|
+
|
|
216
|
+
console.log(`Answer created for ${fromPeerId.substring(0, 8)}...`, {
|
|
217
|
+
type: answer.type,
|
|
218
|
+
sdpLength: answer.sdp?.length || 0,
|
|
219
|
+
hasAudio: answer.sdp?.includes('m=audio') || false,
|
|
220
|
+
hasVideo: answer.sdp?.includes('m=video') || false
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
console.log('Sending answer to', fromPeerId);
|
|
224
|
+
|
|
225
|
+
// Send answer via signaling
|
|
226
|
+
await this.mesh.signalingClient.sendSignalingMessage({
|
|
227
|
+
type: 'answer',
|
|
228
|
+
data: answer,
|
|
229
|
+
targetPeerId: fromPeerId
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Answer sent to ${fromPeerId.substring(0, 8)}...` });
|
|
233
|
+
// Clear connection attempt since we're now processing the connection
|
|
234
|
+
this.mesh.peerDiscovery.clearConnectionAttempt(fromPeerId);
|
|
235
|
+
} catch (error) {
|
|
236
|
+
console.error('Failed to handle offer from', fromPeerId, ':', error);
|
|
237
|
+
|
|
238
|
+
// If it's a state error, handle gracefully
|
|
239
|
+
if (error.message.includes('state:')) {
|
|
240
|
+
console.log(`Offer ignored for ${fromPeerId.substring(0, 8)}... - connection state issue (likely race condition)`);
|
|
241
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Offer skipped for ${fromPeerId.substring(0, 8)}... (connection state conflict)` });
|
|
242
|
+
} else {
|
|
243
|
+
this.mesh.emit('statusChanged', { type: 'error', message: `Failed to handle offer from ${fromPeerId.substring(0, 8)}...: ${error.message}` });
|
|
244
|
+
this.connectionManager.cleanupFailedConnection(fromPeerId);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async handleAnswer(answer, fromPeerId) {
|
|
250
|
+
console.log('Handling answer from', fromPeerId);
|
|
251
|
+
|
|
252
|
+
const peerConnection = this.connectionManager.getPeer(fromPeerId);
|
|
253
|
+
if (peerConnection) {
|
|
254
|
+
try {
|
|
255
|
+
await peerConnection.handleAnswer(answer);
|
|
256
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Answer processed from ${fromPeerId.substring(0, 8)}...` });
|
|
257
|
+
} catch (error) {
|
|
258
|
+
console.error('Failed to handle answer:', error);
|
|
259
|
+
|
|
260
|
+
// If it's a state error (connection already stable), don't treat as failure
|
|
261
|
+
if (error.message.includes('state:') || error.message.includes('stable')) {
|
|
262
|
+
console.log(`Answer ignored for ${fromPeerId.substring(0, 8)}... - connection state issue (likely race condition resolved)`);
|
|
263
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Answer skipped for ${fromPeerId.substring(0, 8)}... (connection already stable)` });
|
|
264
|
+
} else {
|
|
265
|
+
this.mesh.emit('statusChanged', { type: 'error', message: `Failed to handle answer from ${fromPeerId.substring(0, 8)}...: ${error.message}` });
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
} else {
|
|
269
|
+
console.log('No peer connection found for answer from', fromPeerId);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
handleConnectionRejected(data, fromPeerId) {
|
|
274
|
+
console.log(`Connection rejected by ${fromPeerId.substring(0, 8)}...: ${data.reason} (${data.details})`);
|
|
275
|
+
this.mesh.emit('statusChanged', {
|
|
276
|
+
type: 'info',
|
|
277
|
+
message: `Connection rejected by ${fromPeerId.substring(0, 8)}... (${data.reason})`
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
// Clean up any pending connection attempt
|
|
281
|
+
this.connectionManager.connectionAttempts.delete(fromPeerId);
|
|
282
|
+
|
|
283
|
+
// Remove the peer connection if it exists and is not connected
|
|
284
|
+
const peerConnection = this.connectionManager.getPeer(fromPeerId);
|
|
285
|
+
if (peerConnection && peerConnection.getStatus() !== 'connected') {
|
|
286
|
+
peerConnection.close();
|
|
287
|
+
this.connectionManager.peers.delete(fromPeerId);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Clear any discovery connection attempt tracking
|
|
291
|
+
this.mesh.peerDiscovery.clearConnectionAttempt(fromPeerId);
|
|
292
|
+
|
|
293
|
+
// If we have no connections, immediately try other peers more aggressively
|
|
294
|
+
const connectedCount = this.connectionManager.getConnectedPeerCount();
|
|
295
|
+
if (connectedCount === 0) {
|
|
296
|
+
console.log(`Connection rejected and peer is isolated (${connectedCount} connections) - trying alternative peers immediately`);
|
|
297
|
+
|
|
298
|
+
// Immediately try to connect to other discovered peers
|
|
299
|
+
const discoveredPeers = Array.from(this.mesh.peerDiscovery.getDiscoveredPeers());
|
|
300
|
+
const availablePeers = discoveredPeers.filter(peer =>
|
|
301
|
+
peer.peerId !== fromPeerId &&
|
|
302
|
+
!this.connectionManager.hasPeer(peer.peerId) &&
|
|
303
|
+
!this.mesh.peerDiscovery.isAttemptingConnection(peer.peerId)
|
|
304
|
+
);
|
|
305
|
+
|
|
306
|
+
if (availablePeers.length > 0) {
|
|
307
|
+
// Sort by XOR distance and try the closest available peer
|
|
308
|
+
const sortedByDistance = availablePeers.sort((a, b) => {
|
|
309
|
+
const distA = this.mesh.peerDiscovery.calculateXorDistance(this.mesh.peerId, a.peerId);
|
|
310
|
+
const distB = this.mesh.peerDiscovery.calculateXorDistance(this.mesh.peerId, b.peerId);
|
|
311
|
+
return distA < distB ? -1 : 1;
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
const nextPeer = sortedByDistance[0];
|
|
315
|
+
console.log(`Immediately attempting connection to next closest peer: ${nextPeer.peerId.substring(0, 8)}...`);
|
|
316
|
+
this.connectionManager.connectToPeer(nextPeer.peerId);
|
|
317
|
+
}
|
|
318
|
+
} else {
|
|
319
|
+
// Regular mesh optimization for non-isolated peers
|
|
320
|
+
setTimeout(() => {
|
|
321
|
+
this.mesh.peerDiscovery.optimizeMeshConnections(this.connectionManager.peers);
|
|
322
|
+
}, 1000);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Manages storage operations, URL handling, and configuration persistence
|
|
5
|
+
*/
|
|
6
|
+
export class StorageManager extends EventEmitter {
|
|
7
|
+
constructor(mesh) {
|
|
8
|
+
super();
|
|
9
|
+
this.mesh = mesh;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
loadSignalingUrlFromStorage() {
|
|
13
|
+
if (typeof localStorage !== 'undefined') {
|
|
14
|
+
const savedUrl = localStorage.getItem('pigon-signaling-url');
|
|
15
|
+
if (savedUrl) {
|
|
16
|
+
this.mesh.signalingUrl = savedUrl;
|
|
17
|
+
this.mesh.emit('statusChanged', { type: 'urlLoaded', signalingUrl: savedUrl });
|
|
18
|
+
return savedUrl;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
saveSignalingUrlToStorage(url) {
|
|
25
|
+
if (typeof localStorage !== 'undefined' && url) {
|
|
26
|
+
localStorage.setItem('pigon-signaling-url', url);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
loadSignalingUrlFromQuery() {
|
|
31
|
+
if (typeof window === 'undefined') return null;
|
|
32
|
+
|
|
33
|
+
const urlParams = new URLSearchParams(window.location.search);
|
|
34
|
+
const signalingUrl = urlParams.get('api') || urlParams.get('url') || urlParams.get('signaling');
|
|
35
|
+
|
|
36
|
+
if (signalingUrl) {
|
|
37
|
+
// Only emit event if URL is different from current one
|
|
38
|
+
const currentUrl = this.mesh.signalingUrl;
|
|
39
|
+
this.mesh.signalingUrl = signalingUrl;
|
|
40
|
+
this.saveSignalingUrlToStorage(signalingUrl);
|
|
41
|
+
|
|
42
|
+
if (currentUrl !== signalingUrl) {
|
|
43
|
+
this.mesh.emit('statusChanged', { type: 'urlLoaded', signalingUrl });
|
|
44
|
+
}
|
|
45
|
+
return signalingUrl;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Fallback to localStorage if no URL in query params
|
|
49
|
+
return this.loadSignalingUrlFromStorage();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async generatePeerId() {
|
|
53
|
+
const array = new Uint8Array(20);
|
|
54
|
+
crypto.getRandomValues(array);
|
|
55
|
+
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
validatePeerId(peerId) {
|
|
59
|
+
return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
saveSettings(settings) {
|
|
63
|
+
if (typeof localStorage !== 'undefined') {
|
|
64
|
+
localStorage.setItem('pigon-settings', JSON.stringify(settings));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
loadSettings() {
|
|
69
|
+
if (typeof localStorage !== 'undefined') {
|
|
70
|
+
const saved = localStorage.getItem('pigon-settings');
|
|
71
|
+
if (saved) {
|
|
72
|
+
try {
|
|
73
|
+
return JSON.parse(saved);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
console.error('Failed to parse saved settings:', error);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return {};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
clearStorage() {
|
|
83
|
+
if (typeof localStorage !== 'undefined') {
|
|
84
|
+
localStorage.removeItem('pigon-signaling-url');
|
|
85
|
+
localStorage.removeItem('pigon-settings');
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Timer utilities to handle cases where global setInterval/setTimeout might be wrapped
|
|
3
|
+
* by debugging tools, preventing "Illegal invocation" errors.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// Store original timer functions to avoid issues with wrapped functions
|
|
7
|
+
const originalSetInterval = window.setInterval;
|
|
8
|
+
const originalSetTimeout = window.setTimeout;
|
|
9
|
+
const originalClearInterval = window.clearInterval;
|
|
10
|
+
const originalClearTimeout = window.clearTimeout;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Safe setInterval that uses the original function to avoid context issues
|
|
14
|
+
* @param {Function} callback - Function to execute
|
|
15
|
+
* @param {number} delay - Delay in milliseconds
|
|
16
|
+
* @returns {number} - Interval ID
|
|
17
|
+
*/
|
|
18
|
+
export function safeSetInterval(callback, delay) {
|
|
19
|
+
return originalSetInterval.call(window, callback, delay);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Safe setTimeout that uses the original function to avoid context issues
|
|
24
|
+
* @param {Function} callback - Function to execute
|
|
25
|
+
* @param {number} delay - Delay in milliseconds
|
|
26
|
+
* @returns {number} - Timeout ID
|
|
27
|
+
*/
|
|
28
|
+
export function safeSetTimeout(callback, delay) {
|
|
29
|
+
return originalSetTimeout.call(window, callback, delay);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Safe clearInterval that uses the original function
|
|
34
|
+
* @param {number} id - Interval ID to clear
|
|
35
|
+
*/
|
|
36
|
+
export function safeClearInterval(id) {
|
|
37
|
+
return originalClearInterval.call(window, id);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Safe clearTimeout that uses the original function
|
|
42
|
+
* @param {number} id - Timeout ID to clear
|
|
43
|
+
*/
|
|
44
|
+
export function safeClearTimeout(id) {
|
|
45
|
+
return originalClearTimeout.call(window, id);
|
|
46
|
+
}
|