peerpigeon 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +141 -1365
  2. package/cli.js +1382 -0
  3. package/dist/peerpigeon-browser.js +12290 -0
  4. package/dist/peerpigeon-browser.js.map +7 -0
  5. package/docs/API_DOCUMENTATION.md +1945 -0
  6. package/docs/BOOTSTRAP_HUBS.md +319 -0
  7. package/docs/CLI_README.md +371 -0
  8. package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
  9. package/docs/HUB_QUICK_REF.md +107 -0
  10. package/docs/HUB_SCRIPTS.md +331 -0
  11. package/docs/HUB_SYSTEM.md +552 -0
  12. package/docs/MIGRATION_COMPLETE.md +93 -0
  13. package/docs/NETWORK_NAMESPACES.md +212 -0
  14. package/docs/README.md +107 -0
  15. package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
  16. package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
  17. package/examples/bootstrap-hub-example.js +292 -0
  18. package/examples/browser/README.md +278 -0
  19. package/examples/browser/app.js +2426 -49
  20. package/examples/browser/index.html +482 -543
  21. package/examples/browser/minimal/README.md +55 -0
  22. package/examples/browser/minimal/index.html +75 -0
  23. package/examples/browser/minimal/minimal.js +234 -0
  24. package/examples/browser/styles.css +687 -1425
  25. package/examples/browser/test-bundle.html +35 -0
  26. package/examples/browser-2/index.html +30 -0
  27. package/examples/browser-2/package.json +21 -0
  28. package/examples/browser-2/src/App-simple.vue +21 -0
  29. package/examples/browser-2/src/App.vue +420 -0
  30. package/examples/browser-2/src/components/CryptoView.vue +1661 -0
  31. package/examples/browser-2/src/components/DHTView.vue +1281 -0
  32. package/examples/browser-2/src/components/DebugView.vue +1773 -0
  33. package/examples/browser-2/src/components/MediaView.vue +1048 -0
  34. package/examples/browser-2/src/components/MessagingView.vue +775 -0
  35. package/examples/browser-2/src/components/NetworkView.vue +930 -0
  36. package/examples/browser-2/src/components/StorageView.vue +1376 -0
  37. package/examples/browser-2/src/main.js +5 -0
  38. package/examples/browser-2/src/stores/peerpigeon.js +895 -0
  39. package/examples/browser-2/vite.config.js +6 -0
  40. package/examples/hub-example.js +186 -0
  41. package/examples/multi-hub-test.js +186 -0
  42. package/examples/node/README.md +2 -2
  43. package/examples/node/storage-test.js +141 -6
  44. package/examples/selective-streaming-demo.html +698 -0
  45. package/examples/standard-events-demo.js +126 -0
  46. package/package.json +33 -16
  47. package/server/index.js +1032 -98
  48. package/server/start.js +49 -0
  49. package/src/ConnectionManager.js +239 -225
  50. package/src/CryptoManager.js +147 -18
  51. package/src/DebugLogger.js +0 -7
  52. package/src/DistributedStorageManager.js +245 -205
  53. package/src/EnvironmentDetector.js +109 -2
  54. package/src/EventEmitter.js +79 -1
  55. package/src/EvictionManager.js +10 -9
  56. package/src/GossipManager.js +163 -11
  57. package/src/LexicalStorageInterface.js +332 -0
  58. package/src/PeerConnection.js +333 -310
  59. package/src/PeerPigeonMesh.js +577 -135
  60. package/src/SignalingClient.js +14 -243
  61. package/src/SignalingHandler.js +31 -10
  62. package/src/StorageManager.js +0 -39
  63. package/src/WebDHT-Simple.js +389 -0
  64. package/src/WebDHT.js +363 -1165
  65. package/src/browser-entry.js +40 -0
  66. package/examples/browser/assets/images/favicon.png +0 -0
  67. package/examples/browser/assets/images/pigeon.png +0 -0
  68. package/examples/browser/crypto-test.html +0 -427
  69. package/examples/browser/ui-old.js +0 -1926
  70. package/examples/browser/ui.js +0 -3010
  71. package/websocket-server/README.md +0 -247
  72. package/websocket-server/server.js +0 -391
package/cli.js ADDED
@@ -0,0 +1,1382 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * PeerPigeon CLI - Complete with fixed peer connection logic
5
+ */
6
+
7
+ import { createInterface } from 'readline';
8
+ import { PeerPigeonMesh, PeerPigeonServer } from './index.js';
9
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
10
+ import { join } from 'path';
11
+ import { homedir } from 'os';
12
+ import { request } from 'http';
13
+ import { createServer } from 'net';
14
+ import DebugLogger from './src/DebugLogger.js';
15
+
16
+ // Global flag to track WebRTC initialization
17
+ let webrtcInitialized = false;
18
+
19
+ // Disable debug logging by default for cleaner CLI experience
20
+ DebugLogger.disableAll();
21
+
22
+ // Temporarily suppress noisy debug console.log messages
23
+ const originalConsoleLog = console.log;
24
+ console.log = (...args) => {
25
+ const message = args.join(' ');
26
+ // Suppress specific debug messages that clutter the CLI
27
+ if (message.includes('🚨 SIGNALING CRITICAL') ||
28
+ message.includes('🚨 SWITCH') ||
29
+ message.includes('✅ Loaded unsea')) {
30
+ return;
31
+ }
32
+ originalConsoleLog.apply(console, args);
33
+ };
34
+
35
+ // Debug levels
36
+ const DEBUG_LEVELS = {
37
+ OFF: 0,
38
+ ERROR: 1,
39
+ WARN: 2,
40
+ INFO: 3,
41
+ DEBUG: 4,
42
+ TRACE: 5
43
+ };
44
+
45
+ // Setup global error handlers to prevent CLI freezing
46
+ process.on('uncaughtException', (error) => {
47
+ console.error('❌ Uncaught Exception:', error.message);
48
+ console.error('Stack:', error.stack);
49
+ // Don't exit immediately, try to recover
50
+ });
51
+
52
+ process.on('unhandledRejection', (reason, _promise) => {
53
+ console.error('❌ Unhandled Promise Rejection:', reason);
54
+ // Don't exit immediately, try to recover
55
+ });
56
+
57
+ // Handle termination signals gracefully
58
+ process.on('SIGINT', () => {
59
+ console.log('\n👋 Received SIGINT, shutting down gracefully...');
60
+ if (cli) {
61
+ cli.shutdown();
62
+ }
63
+ process.exit(0);
64
+ });
65
+
66
+ process.on('SIGTERM', () => {
67
+ console.log('\n👋 Received SIGTERM, shutting down gracefully...');
68
+ if (cli) {
69
+ cli.shutdown();
70
+ }
71
+ process.exit(0);
72
+ });
73
+
74
+ // Setup WebRTC polyfill for Node.js
75
+ async function initializeWebRTC() {
76
+ if (webrtcInitialized) {
77
+ return true;
78
+ }
79
+
80
+ try {
81
+ // Add timeout to prevent hanging on import
82
+ const importPromise = Promise.all([
83
+ import('ws'),
84
+ import('@koush/wrtc')
85
+ ]);
86
+
87
+ const timeoutPromise = new Promise((resolve, reject) => {
88
+ setTimeout(() => reject(new Error('WebRTC import timeout')), 10000);
89
+ });
90
+
91
+ const [WebSocket, wrtc] = await Promise.race([importPromise, timeoutPromise]);
92
+
93
+ // Make WebRTC available globally for Node.js
94
+ global.RTCPeerConnection = wrtc.default.RTCPeerConnection;
95
+ global.RTCSessionDescription = wrtc.default.RTCSessionDescription;
96
+ global.RTCIceCandidate = wrtc.default.RTCIceCandidate;
97
+ global.WebSocket = WebSocket.default;
98
+
99
+ webrtcInitialized = true;
100
+ return true;
101
+ } catch (error) {
102
+ console.error('❌ Failed to load WebRTC dependencies:', error.message);
103
+ console.error('Please ensure ws and @koush/wrtc are installed: npm install ws @koush/wrtc');
104
+ console.error('Stack trace:', error.stack);
105
+ return false;
106
+ }
107
+ }
108
+
109
+ const CONFIG_DIR = join(homedir(), '.peerpigeon');
110
+ const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
111
+
112
+ // Simple prompt function with timeout to prevent hanging
113
+ function prompt(question, defaultValue = '', timeoutMs = 30000) {
114
+ return new Promise((resolve, reject) => {
115
+ const rl = createInterface({
116
+ input: process.stdin,
117
+ output: process.stdout
118
+ });
119
+
120
+ const timeout = setTimeout(() => {
121
+ rl.close();
122
+ reject(new Error('Prompt timeout - using default value'));
123
+ }, timeoutMs);
124
+
125
+ const displayDefault = defaultValue ? ` (${defaultValue})` : '';
126
+ rl.question(`${question}${displayDefault}: `, (answer) => {
127
+ clearTimeout(timeout);
128
+ rl.close();
129
+ resolve(answer.trim() || defaultValue);
130
+ });
131
+
132
+ // Handle errors to prevent hanging
133
+ rl.on('error', (error) => {
134
+ clearTimeout(timeout);
135
+ rl.close();
136
+ console.warn('Prompt error, using default:', error.message);
137
+ resolve(defaultValue);
138
+ });
139
+ });
140
+ }
141
+
142
+ // Check if any server is already running on the port
143
+ async function checkPortInUse(host = 'localhost', port = 3000) {
144
+ return new Promise((resolve) => {
145
+ const server = createServer();
146
+
147
+ server.listen(port, host, () => {
148
+ server.once('close', () => {
149
+ resolve({ inUse: false });
150
+ });
151
+ server.close();
152
+ });
153
+
154
+ server.on('error', (err) => {
155
+ if (err.code === 'EADDRINUSE') {
156
+ resolve({ inUse: true, error: `Port ${port} is already in use` });
157
+ } else {
158
+ resolve({ inUse: false, error: err.message });
159
+ }
160
+ });
161
+ });
162
+ }
163
+
164
+ // Check if PeerPigeon signaling server is running (optional detailed check)
165
+ async function checkServerStatus(host = 'localhost', port = 3000) {
166
+ return new Promise((resolve) => {
167
+ const req = request({
168
+ hostname: host,
169
+ port,
170
+ path: '/health',
171
+ method: 'GET',
172
+ timeout: 1000 // Shorter timeout
173
+ }, (res) => {
174
+ let data = '';
175
+ res.on('data', (chunk) => {
176
+ data += chunk;
177
+ });
178
+ res.on('end', () => {
179
+ try {
180
+ const status = JSON.parse(data);
181
+ resolve({
182
+ running: true,
183
+ isPeerPigeon: true,
184
+ status
185
+ });
186
+ } catch (error) {
187
+ resolve({
188
+ running: true,
189
+ isPeerPigeon: false,
190
+ error: 'Non-PeerPigeon server detected'
191
+ });
192
+ }
193
+ });
194
+ });
195
+
196
+ req.on('error', (error) => {
197
+ resolve({ running: false, error: error.message });
198
+ });
199
+
200
+ req.on('timeout', () => {
201
+ req.destroy();
202
+ resolve({ running: false, error: 'Request timeout' });
203
+ });
204
+
205
+ req.end();
206
+ });
207
+ }
208
+
209
+ class PeerPigeonCLI {
210
+ constructor() {
211
+ this.mesh = null;
212
+ this.ready = false;
213
+ this.config = this.loadConfig();
214
+ this.interactiveRL = null; // Store readline interface for prompt management
215
+ this.debugLevel = DEBUG_LEVELS.OFF; // Default debug level
216
+ this.promptRestoreDebounce = null; // Debounce rapid prompt restore calls
217
+ }
218
+
219
+ // Safely restore the prompt to prevent terminal freezing
220
+ safeRestorePrompt() {
221
+ // Don't attempt prompt restoration if not in interactive mode
222
+ if (!this.interactiveRL) {
223
+ return;
224
+ }
225
+
226
+ // Debounce rapid calls to prevent issues
227
+ if (this.promptRestoreDebounce) {
228
+ clearTimeout(this.promptRestoreDebounce);
229
+ }
230
+
231
+ this.promptRestoreDebounce = setTimeout(() => {
232
+ try {
233
+ // Multiple safety checks to prevent hanging
234
+ if (this.interactiveRL &&
235
+ !this.interactiveRL.closed &&
236
+ !this.interactiveRL.paused &&
237
+ this.interactiveRL.line !== undefined) {
238
+
239
+ // Check if stdin is readable
240
+ if (process.stdin.readable) {
241
+ this.interactiveRL.prompt();
242
+ } else {
243
+ // Fallback: write prompt directly to stdout
244
+ process.stdout.write('pigeon> ');
245
+ }
246
+ }
247
+ } catch (error) {
248
+ console.error('❌ Error restoring prompt:', error.message);
249
+ // Fallback: write prompt directly to stdout
250
+ try {
251
+ process.stdout.write('pigeon> ');
252
+ } catch (fallbackError) {
253
+ // If even this fails, log the error and continue
254
+ console.error('❌ Critical prompt error:', fallbackError.message);
255
+ }
256
+ }
257
+ this.promptRestoreDebounce = null;
258
+ }, 100); // Increased delay for better stability
259
+ }
260
+
261
+ // Clean shutdown method
262
+ shutdown() {
263
+ try {
264
+ if (this.promptRestoreDebounce) {
265
+ clearTimeout(this.promptRestoreDebounce);
266
+ this.promptRestoreDebounce = null;
267
+ }
268
+
269
+ if (this.interactiveRL && !this.interactiveRL.closed) {
270
+ this.interactiveRL.close();
271
+ this.interactiveRL = null;
272
+ }
273
+
274
+ if (this.mesh) {
275
+ try {
276
+ this.mesh.disconnect();
277
+ } catch (meshError) {
278
+ console.error('❌ Error disconnecting mesh:', meshError.message);
279
+ }
280
+ this.mesh = null;
281
+ }
282
+ } catch (error) {
283
+ console.error('❌ Error during shutdown:', error.message);
284
+ }
285
+ }
286
+
287
+ loadConfig() {
288
+ try {
289
+ if (existsSync(CONFIG_FILE)) {
290
+ const savedConfig = JSON.parse(readFileSync(CONFIG_FILE, 'utf8'));
291
+ // Merge with defaults to ensure new properties are added
292
+ return {
293
+ signalingUrl: savedConfig.signalingUrl || null,
294
+ peerId: null, // Don't persist peer ID to avoid duplicate connection issues
295
+ maxPeers: savedConfig.maxPeers || 5, // Same as browser default
296
+ minPeers: savedConfig.minPeers || 0,
297
+ autoDiscovery: savedConfig.autoDiscovery !== undefined ? savedConfig.autoDiscovery : true, // Enable auto discovery like browser
298
+ enableWebDHT: savedConfig.enableWebDHT !== undefined ? savedConfig.enableWebDHT : true, // Enable WebDHT like browser
299
+ enableCrypto: true // Force crypto to be enabled by default (ignore old config)
300
+ };
301
+ }
302
+ } catch (error) {
303
+ console.warn('Warning: Could not load config file');
304
+ }
305
+ return {
306
+ signalingUrl: null,
307
+ peerId: null, // Don't persist peer ID to avoid duplicate connection issues
308
+ maxPeers: 5, // Same as browser default
309
+ minPeers: 0,
310
+ autoDiscovery: true, // Enable auto discovery like browser
311
+ enableWebDHT: true, // Enable WebDHT like browser
312
+ enableCrypto: true // Enable crypto like browser
313
+ };
314
+ }
315
+
316
+ saveConfig() {
317
+ try {
318
+ if (!existsSync(CONFIG_DIR)) {
319
+ mkdirSync(CONFIG_DIR, { recursive: true });
320
+ }
321
+ writeFileSync(CONFIG_FILE, JSON.stringify(this.config, null, 2));
322
+ } catch (error) {
323
+ console.warn('Warning: Could not save config file');
324
+ }
325
+ }
326
+
327
+ log(message, type = 'info') {
328
+ const timestamp = new Date().toLocaleTimeString();
329
+ const symbols = {
330
+ success: '✅',
331
+ error: '❌',
332
+ warning: '⚠️',
333
+ info: 'ℹ️'
334
+ };
335
+ console.log(`[${timestamp}] ${symbols[type] || symbols.info} ${message}`);
336
+ }
337
+
338
+ setDebugLevel(level) {
339
+ if (typeof level === 'string') {
340
+ level = level.toUpperCase();
341
+ this.debugLevel = DEBUG_LEVELS[level] || DEBUG_LEVELS.OFF;
342
+ } else if (typeof level === 'number') {
343
+ this.debugLevel = Math.max(0, Math.min(5, level));
344
+ }
345
+ }
346
+
347
+ debug(message, level = DEBUG_LEVELS.DEBUG) {
348
+ if (this.debugLevel >= level) {
349
+ const timestamp = new Date().toLocaleTimeString();
350
+ const levelNames = ['OFF', 'ERROR', 'WARN', 'INFO', 'DEBUG', 'TRACE'];
351
+ const levelName = levelNames[level] || 'DEBUG';
352
+ const symbols = {
353
+ [DEBUG_LEVELS.ERROR]: '🔴',
354
+ [DEBUG_LEVELS.WARN]: '🟡',
355
+ [DEBUG_LEVELS.INFO]: '🔵',
356
+ [DEBUG_LEVELS.DEBUG]: '🟢',
357
+ [DEBUG_LEVELS.TRACE]: '🟣'
358
+ };
359
+ console.log(`[${timestamp}] ${symbols[level]} [${levelName}] ${message}`);
360
+ }
361
+ }
362
+
363
+ async initMesh(options) {
364
+ try {
365
+ // Initialize WebRTC first if not already done
366
+ if (!global.RTCPeerConnection) {
367
+ this.log('Initializing WebRTC for Node.js...', 'info');
368
+ const success = await initializeWebRTC();
369
+ if (!success) {
370
+ throw new Error('Failed to initialize WebRTC dependencies');
371
+ }
372
+ }
373
+
374
+ // Handle debug level if provided
375
+ if (options.debug !== undefined) {
376
+ this.setDebugLevel(options.debug);
377
+ this.debug('Debug mode enabled', DEBUG_LEVELS.INFO);
378
+ }
379
+
380
+ this.log('Creating PeerPigeon mesh...', 'info');
381
+ this.debug('Received options:', DEBUG_LEVELS.DEBUG);
382
+ this.debug(` peerId: ${options.peerId}`, DEBUG_LEVELS.DEBUG);
383
+ this.debug(` maxPeers: ${options.maxPeers}`, DEBUG_LEVELS.DEBUG);
384
+ this.debug(` minPeers: ${options.minPeers}`, DEBUG_LEVELS.DEBUG);
385
+ this.debug(` autoDiscovery: ${options.autoDiscovery}`, DEBUG_LEVELS.DEBUG);
386
+ this.debug(` enableWebdht: ${options.enableWebdht}`, DEBUG_LEVELS.DEBUG);
387
+ this.debug(` enableCrypto: ${options.enableCrypto}`, DEBUG_LEVELS.DEBUG);
388
+ this.debug(` debug: ${options.debug}`, DEBUG_LEVELS.DEBUG);
389
+
390
+ // Generate a cryptographically secure peer ID using PeerPigeonMesh's method
391
+ let freshPeerId = options.peerId;
392
+ if (!freshPeerId) {
393
+ freshPeerId = await PeerPigeonMesh.generatePeerId();
394
+ }
395
+ this.debug(`Generated peer ID: ${freshPeerId}`, DEBUG_LEVELS.TRACE);
396
+
397
+ const enableWebDHT = options.enableWebdht !== undefined ? options.enableWebdht : this.config.enableWebDHT;
398
+ const enableCrypto = options.enableCrypto !== undefined ? options.enableCrypto : this.config.enableCrypto;
399
+ const autoDiscovery = options.autoDiscovery !== undefined ? options.autoDiscovery : this.config.autoDiscovery;
400
+
401
+ this.debug(`Config values: enableWebDHT=${this.config.enableWebDHT}, enableCrypto=${this.config.enableCrypto}`, DEBUG_LEVELS.DEBUG);
402
+ this.debug(`Final values: enableWebDHT=${enableWebDHT}, enableCrypto=${enableCrypto}, autoDiscovery=${autoDiscovery}`, DEBUG_LEVELS.DEBUG);
403
+
404
+ const meshOptions = {
405
+ peerId: freshPeerId, // Use generated unique ID
406
+ maxPeers: options.maxPeers || this.config.maxPeers,
407
+ minPeers: options.minPeers || this.config.minPeers,
408
+ autoDiscovery,
409
+ enableWebDHT,
410
+ enableCrypto,
411
+ ignoreEnvironmentErrors: true // Allow Node.js environment
412
+ };
413
+ this.debug(`Mesh options: ${JSON.stringify(meshOptions, null, 2)}`, DEBUG_LEVELS.TRACE);
414
+
415
+ this.mesh = new PeerPigeonMesh(meshOptions);
416
+
417
+ if (!this.mesh) {
418
+ throw new Error('Failed to create PeerPigeonMesh instance');
419
+ }
420
+
421
+ this.debug('PeerPigeonMesh instance created successfully', DEBUG_LEVELS.TRACE);
422
+ this.log('Setting up event handlers...', 'info');
423
+ this.setupEventHandlers();
424
+
425
+ this.log('Initializing mesh network...', 'info');
426
+
427
+ // Add timeout to mesh initialization to prevent hanging
428
+ const initPromise = this.mesh.init();
429
+ const timeoutPromise = new Promise((resolve, reject) => {
430
+ setTimeout(() => reject(new Error('Mesh initialization timeout')), 30000);
431
+ });
432
+
433
+ await Promise.race([initPromise, timeoutPromise]);
434
+ this.ready = true;
435
+ this.log('Mesh network initialized', 'success');
436
+ this.log(`Using peer ID: ${this.mesh.peerId.substring(0, 8)}...`, 'info');
437
+
438
+ // Don't save peer ID to config to ensure fresh ID each session
439
+ if (options.maxPeers) this.config.maxPeers = options.maxPeers;
440
+ if (options.minPeers) this.config.minPeers = options.minPeers;
441
+ this.saveConfig();
442
+ } catch (error) {
443
+ this.log(`Error: ${error.message}`, 'error');
444
+ this.log(`Stack: ${error.stack}`, 'error');
445
+ throw error;
446
+ }
447
+ }
448
+
449
+ async connectToSignaling(url) {
450
+ try {
451
+ // Use provided URL, saved config, or default to ws://localhost:3000
452
+ const originalUrl = url;
453
+ url = url || this.config.signalingUrl || 'ws://localhost:3000';
454
+
455
+ this.debug(`connectToSignaling called with: ${originalUrl}`, DEBUG_LEVELS.DEBUG);
456
+ this.debug(`Using URL: ${url} (from: ${originalUrl ? 'parameter' : this.config.signalingUrl ? 'config' : 'default'})`, DEBUG_LEVELS.DEBUG);
457
+
458
+ this.log(`Connecting to signaling server at ${url}...`, 'info');
459
+
460
+ // Connect once like browser peers - no aggressive reconnection
461
+ this.debug('Calling mesh.connect()...', DEBUG_LEVELS.TRACE);
462
+
463
+ // Add timeout to connection to prevent hanging
464
+ const connectPromise = this.mesh.connect(url);
465
+ const timeoutPromise = new Promise((resolve, reject) => {
466
+ setTimeout(() => reject(new Error('Connection timeout')), 15000);
467
+ });
468
+
469
+ await Promise.race([connectPromise, timeoutPromise]);
470
+ this.config.signalingUrl = url;
471
+ this.saveConfig();
472
+ this.debug('Connection successful, config saved', DEBUG_LEVELS.TRACE);
473
+ this.log(`Connected to ${url}`, 'success');
474
+ } catch (error) {
475
+ this.debug(`Connection failed: ${error.message}`, DEBUG_LEVELS.ERROR);
476
+ this.log(`Failed to connect: ${error.message}`, 'error');
477
+
478
+ // Only prompt for input if automatic connection failed and no saved URL
479
+ if ((url === 'ws://localhost:3000' || !this.config.signalingUrl) && !this.config.signalingUrl) {
480
+ this.log('Automatic connection failed, please provide a signaling server URL', 'info');
481
+ try {
482
+ const newUrl = await prompt('Enter signaling server URL', 'ws://localhost:3000', 15000);
483
+ await this.mesh.connect(newUrl);
484
+ this.config.signalingUrl = newUrl;
485
+ this.saveConfig();
486
+ this.log(`Connected to ${newUrl}`, 'success');
487
+ } catch (promptError) {
488
+ if (promptError.message.includes('timeout')) {
489
+ this.log('Prompt timeout - using default URL ws://localhost:3000', 'warning');
490
+ try {
491
+ await this.mesh.connect('ws://localhost:3000');
492
+ this.config.signalingUrl = 'ws://localhost:3000';
493
+ this.saveConfig();
494
+ this.log('Connected to ws://localhost:3000', 'success');
495
+ } catch (retryError) {
496
+ this.log(`Failed to connect to default URL: ${retryError.message}`, 'error');
497
+ throw retryError;
498
+ }
499
+ } else {
500
+ this.log(`Failed to connect: ${promptError.message}`, 'error');
501
+ throw promptError;
502
+ }
503
+ }
504
+ } else {
505
+ throw error;
506
+ }
507
+ }
508
+ }
509
+
510
+ setupEventHandlers() {
511
+ try {
512
+ if (!this.mesh || typeof this.mesh.addEventListener !== 'function') {
513
+ this.log('Warning: Mesh does not support event handling', 'warning');
514
+ return;
515
+ }
516
+
517
+ this.debug('Setting up event handlers', DEBUG_LEVELS.TRACE);
518
+
519
+ this.mesh.addEventListener('peerConnected', (data) => {
520
+ try {
521
+ this.debug(`Peer connected event: ${data.peerId}`, DEBUG_LEVELS.DEBUG);
522
+ // Clear current line and move cursor to beginning
523
+ process.stdout.write('\r\x1b[K');
524
+ this.log(`🔗 Peer connected: ${data.peerId.substring(0, 8)}...`, 'success');
525
+ // Safely restore the prompt if we're in interactive mode
526
+ this.safeRestorePrompt();
527
+ } catch (error) {
528
+ console.error('❌ Error handling peerConnected event:', error.message);
529
+ }
530
+ });
531
+
532
+ this.mesh.addEventListener('peerDisconnected', (data) => {
533
+ try {
534
+ this.debug(`Peer disconnected event: ${data.peerId}, reason: ${data.reason}`, DEBUG_LEVELS.DEBUG);
535
+ // Clear current line and move cursor to beginning
536
+ process.stdout.write('\r\x1b[K');
537
+ this.log(`💔 Peer disconnected: ${data.peerId.substring(0, 8)}... (${data.reason})`, 'warning');
538
+ // Safely restore the prompt if we're in interactive mode
539
+ this.safeRestorePrompt();
540
+ } catch (error) {
541
+ console.error('❌ Error handling peerDisconnected event:', error.message);
542
+ }
543
+ });
544
+
545
+ this.mesh.addEventListener('messageReceived', (data) => {
546
+ try {
547
+ this.debug(`Message received from ${data.from}: "${data.content}"`, DEBUG_LEVELS.DEBUG);
548
+ const fromShort = data.from?.substring(0, 8) || 'unknown';
549
+ // Clear current line and move cursor to beginning
550
+ process.stdout.write('\r\x1b[K');
551
+ this.log(`💬 Message from ${fromShort}...: ${data.content}`, 'success');
552
+ // Safely restore the prompt if we're in interactive mode
553
+ this.safeRestorePrompt();
554
+ } catch (error) {
555
+ console.error('❌ Error handling messageReceived event:', error.message);
556
+ }
557
+ });
558
+
559
+ this.debug('Event handlers set up successfully', DEBUG_LEVELS.TRACE);
560
+ } catch (error) {
561
+ console.error('❌ Critical error setting up event handlers:', error.message);
562
+ console.error('Stack trace:', error.stack);
563
+ }
564
+ }
565
+
566
+ async send(content, target = null) {
567
+ if (!this.mesh) {
568
+ this.log('Mesh not initialized', 'error');
569
+ return;
570
+ }
571
+
572
+ this.debug(`Sending message: "${content}" ${target ? `to target ${target}` : 'as broadcast'}`, DEBUG_LEVELS.DEBUG);
573
+
574
+ try {
575
+ if (target) {
576
+ this.debug(`Attempting direct message to ${target}`, DEBUG_LEVELS.TRACE);
577
+ const success = this.mesh.sendDirectMessage(target, content);
578
+ if (success) {
579
+ this.debug('Direct message sent successfully', DEBUG_LEVELS.TRACE);
580
+ this.log(`📤 Direct message sent to ${target.substring(0, 8)}...: ${content}`, 'success');
581
+ } else {
582
+ this.debug('Direct message failed to send', DEBUG_LEVELS.WARN);
583
+ this.log(`Failed to send direct message to ${target.substring(0, 8)}...`, 'error');
584
+ }
585
+ } else {
586
+ this.debug('Attempting broadcast message', DEBUG_LEVELS.TRACE);
587
+ const messageId = this.mesh.sendMessage(content);
588
+ this.debug(`Broadcast returned messageId: ${messageId}`, DEBUG_LEVELS.TRACE);
589
+ if (messageId) {
590
+ // Clear current line and show success message
591
+ if (this.interactiveRL) {
592
+ process.stdout.write('\r\x1b[K');
593
+ }
594
+ this.log(`📢 Broadcast message sent: ${content}`, 'success');
595
+ // Safely restore prompt
596
+ this.safeRestorePrompt();
597
+ } else {
598
+ this.debug('Broadcast message failed - no messageId returned', DEBUG_LEVELS.WARN);
599
+ this.log('Failed to send broadcast message', 'error');
600
+ }
601
+ }
602
+ } catch (error) {
603
+ this.debug(`Send error: ${error.message}`, DEBUG_LEVELS.ERROR);
604
+ this.log(`Failed to send message: ${error.message}`, 'error');
605
+ }
606
+ }
607
+
608
+ showStatus() {
609
+ try {
610
+ if (!this.mesh) {
611
+ console.log('Mesh not initialized');
612
+ return;
613
+ }
614
+
615
+ this.debug('Getting mesh status', DEBUG_LEVELS.DEBUG);
616
+ const status = this.mesh.getStatus();
617
+ this.debug(`Status object: ${JSON.stringify(status, null, 2)}`, DEBUG_LEVELS.TRACE);
618
+
619
+ console.log('\n📊 Mesh Network Status\n');
620
+ console.log(`Peer ID: ${status.peerId}`);
621
+ console.log(`Connected: ${status.connected ? 'Yes' : 'No'}`);
622
+ console.log(`Signaling: ${status.signalingUrl || 'Not set'}`);
623
+ console.log(`Peers: ${status.connectedCount}/${status.maxPeers} connected, ${status.discoveredCount} discovered`);
624
+ console.log(`Auto Discovery: ${status.autoDiscovery ? 'Enabled' : 'Disabled'}`);
625
+ console.log(`WebDHT: ${this.mesh.webDHT ? 'Enabled' : 'Disabled'}`);
626
+ console.log(`Crypto: ${this.mesh.enableCrypto ? 'Enabled' : 'Disabled'}`);
627
+
628
+ if (status.startTime) {
629
+ const uptimeSeconds = Math.floor((Date.now() - status.startTime) / 1000);
630
+ console.log(`Uptime: ${uptimeSeconds}s`);
631
+ }
632
+
633
+ this.debug('Status display complete', DEBUG_LEVELS.DEBUG);
634
+ } catch (error) {
635
+ console.error('❌ Error displaying status:', error.message);
636
+ console.error('Stack trace:', error.stack);
637
+ console.log('Unable to retrieve mesh status - mesh may be in an invalid state');
638
+ }
639
+ }
640
+
641
+ showPeers() {
642
+ try {
643
+ if (!this.mesh) {
644
+ console.log('Mesh not initialized');
645
+ return;
646
+ }
647
+
648
+ this.debug('Getting peer lists from mesh methods', DEBUG_LEVELS.DEBUG);
649
+
650
+ const connectedPeers = this.mesh.getPeers();
651
+ const discoveredPeers = this.mesh.getDiscoveredPeers();
652
+
653
+ // Safe JSON stringify that handles BigInt values
654
+ const safeStringify = (obj) => {
655
+ try {
656
+ return JSON.stringify(obj, (key, value) =>
657
+ typeof value === 'bigint' ? value.toString() : value, 2);
658
+ } catch (error) {
659
+ return `[Stringify error: ${error.message}]`;
660
+ }
661
+ };
662
+
663
+ this.debug(`Connected peers: ${safeStringify(connectedPeers)}`, DEBUG_LEVELS.TRACE);
664
+ this.debug(`Discovered peers: ${safeStringify(discoveredPeers)}`, DEBUG_LEVELS.TRACE);
665
+
666
+ console.log('\n👥 Connected Peers\n');
667
+
668
+ if (!connectedPeers || connectedPeers.length === 0) {
669
+ console.log('No connected peers');
670
+ } else {
671
+ connectedPeers.forEach(peer => {
672
+ try {
673
+ const shortId = peer.peerId.substring(0, 8);
674
+ console.log(`${shortId}... Connected`);
675
+ } catch (peerError) {
676
+ console.log(`[Error displaying peer: ${peerError.message}]`);
677
+ }
678
+ });
679
+ }
680
+
681
+ console.log('\n🔍 Discovered Peers\n');
682
+ if (!discoveredPeers || discoveredPeers.length === 0) {
683
+ console.log('No discovered peers');
684
+ } else {
685
+ discoveredPeers.forEach(peer => {
686
+ try {
687
+ const shortId = peer.peerId.substring(0, 8);
688
+ console.log(`${shortId}... ${peer.isConnected ? '(connected)' : '(discovered)'}`);
689
+ } catch (peerError) {
690
+ console.log(`[Error displaying peer: ${peerError.message}]`);
691
+ }
692
+ });
693
+ }
694
+ } catch (error) {
695
+ console.error('❌ Error displaying peers:', error.message);
696
+ console.error('Stack trace:', error.stack);
697
+ console.log('Unable to retrieve peer information - mesh may be in an invalid state');
698
+ }
699
+ }
700
+
701
+ disconnect() {
702
+ try {
703
+ if (this.mesh) {
704
+ this.mesh.disconnect();
705
+ this.log('Disconnected from mesh', 'info');
706
+ } else {
707
+ this.log('Mesh not initialized - nothing to disconnect', 'warning');
708
+ }
709
+ } catch (error) {
710
+ console.error('❌ Error during disconnect:', error.message);
711
+ console.error('Stack trace:', error.stack);
712
+ this.log('Disconnect completed with errors', 'warning');
713
+ }
714
+ }
715
+ }
716
+
717
+ // Simple argument parser
718
+ function parseArgs() {
719
+ const args = process.argv.slice(2);
720
+ const command = args[0];
721
+ const options = {};
722
+
723
+ for (let i = 1; i < args.length; i++) {
724
+ const arg = args[i];
725
+ if (arg.startsWith('--')) {
726
+ const key = arg.slice(2);
727
+ const nextArg = args[i + 1];
728
+ if (nextArg && !nextArg.startsWith('--')) {
729
+ // Handle boolean values explicitly
730
+ if (nextArg === 'true') {
731
+ options[key] = true;
732
+ i++;
733
+ } else if (nextArg === 'false') {
734
+ options[key] = false;
735
+ i++;
736
+ } else {
737
+ const numValue = parseInt(nextArg);
738
+ options[key] = isNaN(numValue) ? nextArg : numValue;
739
+ i++; // Skip next arg since we used it as value
740
+ }
741
+ } else {
742
+ options[key] = true; // Boolean flag
743
+ }
744
+ } else if (arg.startsWith('-') && arg.length === 2) {
745
+ const key = arg.slice(1);
746
+ const nextArg = args[i + 1];
747
+ if (nextArg && !nextArg.startsWith('-')) {
748
+ // Handle boolean values explicitly
749
+ if (nextArg === 'true') {
750
+ options[key] = true;
751
+ i++;
752
+ } else if (nextArg === 'false') {
753
+ options[key] = false;
754
+ i++;
755
+ } else {
756
+ const numValue = parseInt(nextArg);
757
+ options[key] = isNaN(numValue) ? nextArg : numValue;
758
+ i++;
759
+ }
760
+ } else {
761
+ options[key] = true;
762
+ }
763
+ } else if (!command) {
764
+ // This is the command if we haven't set one yet
765
+ args.unshift(arg);
766
+ i--;
767
+ } else {
768
+ // This is a positional argument
769
+ if (!options._positional) options._positional = [];
770
+ options._positional.push(arg);
771
+ }
772
+ }
773
+
774
+ return { command, options };
775
+ }
776
+
777
+ function showHelp() {
778
+ console.log(`
779
+ PeerPigeon CLI - Mesh networking CLI
780
+
781
+ Usage:
782
+ node cli.js <command> [options] # Single command mode
783
+ node cli.js # Interactive mode
784
+
785
+ Commands:
786
+ init [options] Initialize and connect to mesh network
787
+ send <message> Send broadcast message to all peers
788
+ status Show mesh network status
789
+ peers List connected and discovered peers
790
+ server-status [options] Check if signaling server is running
791
+ server [options] Start signaling server
792
+ help Show this help message
793
+
794
+ Interactive Mode:
795
+ Run "node cli.js" without arguments to enter interactive mode.
796
+ In interactive mode, you can run multiple commands sequentially.
797
+ Type "exit" or "quit" to leave interactive mode.
798
+
799
+ Options:
800
+ Server command:
801
+ --port, -p <port> Server port (default: 3000)
802
+ --host, -h <host> Server host (default: localhost)
803
+ --max-connections <n> Maximum connections (default: 3)
804
+ --force, -f Force start even if server already running
805
+
806
+ Init command:
807
+ --url, -u <url> Signaling server URL
808
+ --peer-id <id> Custom peer ID
809
+ --max-peers <n> Maximum peers
810
+ --min-peers <n> Minimum peers
811
+ --auto-discovery <bool> Auto discovery (true|false)
812
+ --webdht <bool> WebDHT (true|false)
813
+ --crypto <bool> Encryption (true|false)
814
+ --debug, -d <level> Debug level (off, error, warn, info, debug, trace)
815
+
816
+ Server-status command:
817
+ --port, -p <port> Server port (default: 3000)
818
+ --host, -h <host> Server host (default: localhost)
819
+
820
+ Examples:
821
+ node cli.js server --port 3000 --max-connections 3
822
+ node cli.js init --url ws://localhost:3000 --max-peers 5
823
+ node cli.js init --peer-id abc123... --webdht true
824
+ node cli.js init --auto-discovery false --crypto true
825
+ node cli.js init --debug info # Enable info-level debugging
826
+ node cli.js init --debug trace # Enable verbose trace debugging
827
+ node cli.js send "Hello mesh!"
828
+ node cli.js server-status --port 3000
829
+ node cli.js # Start interactive mode
830
+ `);
831
+ }
832
+
833
+ // Create CLI instance
834
+ const cli = new PeerPigeonCLI();
835
+ const { command, options } = parseArgs();
836
+
837
+ // Handle commands
838
+ async function handleCommand() {
839
+ try {
840
+ switch (command) {
841
+ case 'init': {
842
+ try {
843
+ await cli.initMesh({
844
+ peerId: options['peer-id'],
845
+ maxPeers: options['max-peers'],
846
+ minPeers: options['min-peers'],
847
+ autoDiscovery: options['auto-discovery'],
848
+ enableWebdht: options.webdht,
849
+ enableCrypto: options.crypto,
850
+ debug: options.debug || options.d
851
+ });
852
+ await cli.connectToSignaling(options.url || options.u);
853
+ } catch (initError) {
854
+ console.error('❌ Initialization failed:', initError.message);
855
+ console.error('Stack trace:', initError.stack);
856
+ process.exit(1);
857
+ }
858
+ break;
859
+ }
860
+
861
+ case 'send': {
862
+ try {
863
+ const messageWords = options._positional || [];
864
+ if (messageWords.length === 0) {
865
+ console.error('Error: Message required for send command');
866
+ process.exit(1);
867
+ }
868
+ // Join all words to reconstruct the full message
869
+ const message = messageWords.join(' ').replace(/^"|"$/g, ''); // Remove surrounding quotes if present
870
+ if (!cli.mesh) {
871
+ await cli.initMesh({});
872
+ await cli.connectToSignaling();
873
+ }
874
+ await cli.send(message);
875
+ } catch (sendError) {
876
+ console.error('❌ Send command failed:', sendError.message);
877
+ console.error('Stack trace:', sendError.stack);
878
+ process.exit(1);
879
+ }
880
+ break;
881
+ }
882
+
883
+ case 'status':
884
+ cli.showStatus();
885
+ break;
886
+
887
+ case 'peers':
888
+ cli.showPeers();
889
+ break;
890
+
891
+ case 'server-status': {
892
+ try {
893
+ const host = options.host || options.h || 'localhost';
894
+ const port = options.port || options.p || 3000;
895
+
896
+ cli.log(`🔍 Checking server at ${host}:${port}...`, 'info');
897
+ const serverStatus = await checkServerStatus(host, port);
898
+
899
+ if (serverStatus.running) {
900
+ cli.log(`🟢 Server is running on ${host}:${port}`, 'success');
901
+ console.log('\nServer Details:');
902
+ console.log(` Status: ${serverStatus.status?.status || 'unknown'}`);
903
+ console.log(` Uptime: ${serverStatus.status ? Math.floor(serverStatus.status.uptime) : 'n/a'}s`);
904
+ console.log(` Connections: ${serverStatus.status?.connections || 'n/a'}`);
905
+ console.log(` Peers: ${serverStatus.status?.peers || 'n/a'}`);
906
+ console.log(` Memory: ${serverStatus.status ? Math.round(serverStatus.status.memory.heapUsed / 1024 / 1024) : 'n/a'}MB`);
907
+ } else {
908
+ cli.log(`🔴 No server running on ${host}:${port}`, 'warning');
909
+ if (serverStatus.error) {
910
+ console.log(`Error: ${serverStatus.error}`);
911
+ }
912
+ }
913
+ } catch (statusError) {
914
+ console.error('❌ Server status check failed:', statusError.message);
915
+ console.error('Stack trace:', statusError.stack);
916
+ process.exit(1);
917
+ }
918
+ break;
919
+ }
920
+
921
+ case 'server': {
922
+ try {
923
+ const serverHost = options.host || options.h || 'localhost';
924
+ const serverPort = options.port || options.p || 3000;
925
+ const maxConnections = options['max-connections'] || 3;
926
+
927
+ if (!options.force && !options.f) {
928
+ cli.log('Checking for existing server...', 'info');
929
+ const portCheck = await checkPortInUse(serverHost, serverPort);
930
+
931
+ if (portCheck.inUse) {
932
+ cli.log(`Port ${serverPort} is already in use on ${serverHost}`, 'warning');
933
+
934
+ const serverStatus = await checkServerStatus(serverHost, serverPort);
935
+ if (serverStatus.running && serverStatus.isPeerPigeon) {
936
+ console.log('\nPeerPigeon Server Details:');
937
+ console.log(` Uptime: ${Math.floor(serverStatus.status.uptime)}s`);
938
+ console.log(` Connections: ${serverStatus.status.connections}`);
939
+ console.log(` Peers: ${serverStatus.status.peers}`);
940
+ } else {
941
+ console.log('\nAnother service is using this port.');
942
+ }
943
+
944
+ console.log('\nUse --force to start anyway, or use a different port.');
945
+ return;
946
+ }
947
+ }
948
+
949
+ cli.log('Starting signaling server...', 'info');
950
+ const server = new PeerPigeonServer({
951
+ port: serverPort,
952
+ host: serverHost,
953
+ maxConnections
954
+ });
955
+ await server.start();
956
+ cli.log(`Signaling server running on ${serverHost}:${serverPort}`, 'success');
957
+
958
+ process.on('SIGINT', () => {
959
+ console.log('\nShutting down server...');
960
+ try {
961
+ server.stop();
962
+ } catch (stopError) {
963
+ console.error('❌ Error stopping server:', stopError.message);
964
+ }
965
+ process.exit(0);
966
+ });
967
+ } catch (serverError) {
968
+ console.error('❌ Server command failed:', serverError.message);
969
+ console.error('Stack trace:', serverError.stack);
970
+ process.exit(1);
971
+ }
972
+ break;
973
+ }
974
+
975
+ case 'help':
976
+ case '--help':
977
+ case '-h':
978
+ try {
979
+ showHelp();
980
+ } catch (helpError) {
981
+ console.error('❌ Error displaying help:', helpError.message);
982
+ console.log('PeerPigeon CLI - Help system unavailable');
983
+ }
984
+ break;
985
+
986
+ default:
987
+ try {
988
+ if (!command) {
989
+ showHelp();
990
+ } else {
991
+ console.error(`Error: Unknown command '${command}'`);
992
+ console.error('Use "node cli.js help" for usage information');
993
+ process.exit(1);
994
+ }
995
+ } catch (defaultError) {
996
+ console.error('❌ Error in default command handler:', defaultError.message);
997
+ process.exit(1);
998
+ }
999
+ }
1000
+ } catch (error) {
1001
+ console.error('❌ Critical command handler error:', error.message);
1002
+ console.error('Stack trace:', error.stack);
1003
+ cli.log(`Command execution failed: ${error.message}`, 'error');
1004
+ process.exit(1);
1005
+ }
1006
+ }
1007
+
1008
+ // Handle graceful shutdown
1009
+ process.on('SIGINT', () => {
1010
+ console.log('\nShutting down...');
1011
+ cli.disconnect();
1012
+ process.exit(0);
1013
+ });
1014
+
1015
+ // Execute the command or start interactive mode
1016
+ if (command) {
1017
+ // Single command mode
1018
+ handleCommand();
1019
+ } else {
1020
+ // Interactive mode
1021
+ startInteractiveMode();
1022
+ }
1023
+
1024
+ // Interactive mode function
1025
+ async function startInteractiveMode() {
1026
+ console.log('🐦 PeerPigeon CLI - Interactive Mode');
1027
+ console.log('Type "help" for available commands or "exit" to quit');
1028
+
1029
+ const rl = createInterface({
1030
+ input: process.stdin,
1031
+ output: process.stdout,
1032
+ prompt: 'pigeon> ',
1033
+ history: [], // Enable command history
1034
+ historySize: 100 // Keep last 100 commands
1035
+ });
1036
+
1037
+ // Store readline interface reference for message handling
1038
+ cli.interactiveRL = rl;
1039
+
1040
+ rl.prompt();
1041
+
1042
+ rl.on('line', async (line) => {
1043
+ try {
1044
+ const input = line.trim();
1045
+
1046
+ if (input === 'exit' || input === 'quit') {
1047
+ console.log('Goodbye! 🐦');
1048
+ try {
1049
+ rl.close();
1050
+ } catch (closeError) {
1051
+ console.error('❌ Error closing readline:', closeError.message);
1052
+ }
1053
+ process.exit(0);
1054
+ return;
1055
+ }
1056
+
1057
+ if (input === 'clear') {
1058
+ console.clear();
1059
+ rl.prompt();
1060
+ return;
1061
+ }
1062
+
1063
+ if (input === '') {
1064
+ rl.prompt();
1065
+ return;
1066
+ }
1067
+
1068
+ try {
1069
+ // Parse the interactive command
1070
+ const args = input.split(' ');
1071
+ const interactiveCommand = args[0];
1072
+ const interactiveOptions = {};
1073
+ const positionalArgs = [];
1074
+
1075
+ // Simple parsing for interactive mode
1076
+ for (let i = 1; i < args.length; i++) {
1077
+ const arg = args[i];
1078
+ if (arg.startsWith('--')) {
1079
+ const key = arg.slice(2);
1080
+ const nextArg = args[i + 1];
1081
+ if (nextArg && !nextArg.startsWith('--') && !nextArg.startsWith('-')) {
1082
+ // Handle boolean values explicitly
1083
+ if (nextArg === 'true') {
1084
+ interactiveOptions[key] = true;
1085
+ i++;
1086
+ } else if (nextArg === 'false') {
1087
+ interactiveOptions[key] = false;
1088
+ i++;
1089
+ } else {
1090
+ const numValue = parseInt(nextArg);
1091
+ interactiveOptions[key] = isNaN(numValue) ? nextArg : numValue;
1092
+ i++; // Skip next arg since we used it as value
1093
+ }
1094
+ } else {
1095
+ interactiveOptions[key] = true; // Boolean flag
1096
+ }
1097
+ } else if (arg.startsWith('-') && arg.length === 2) {
1098
+ const key = arg.slice(1);
1099
+ const nextArg = args[i + 1];
1100
+ if (nextArg && !nextArg.startsWith('-')) {
1101
+ // Handle boolean values explicitly
1102
+ if (nextArg === 'true') {
1103
+ interactiveOptions[key] = true;
1104
+ i++;
1105
+ } else if (nextArg === 'false') {
1106
+ interactiveOptions[key] = false;
1107
+ i++;
1108
+ } else {
1109
+ const numValue = parseInt(nextArg);
1110
+ interactiveOptions[key] = isNaN(numValue) ? nextArg : numValue;
1111
+ i++;
1112
+ }
1113
+ } else {
1114
+ interactiveOptions[key] = true;
1115
+ }
1116
+ } else {
1117
+ positionalArgs.push(arg);
1118
+ }
1119
+ }
1120
+
1121
+ if (positionalArgs.length > 0) {
1122
+ interactiveOptions._positional = positionalArgs;
1123
+ }
1124
+
1125
+ // Execute the interactive command
1126
+ await executeInteractiveCommand(interactiveCommand, interactiveOptions);
1127
+ } catch (parseError) {
1128
+ console.error(`❌ Command parsing error: ${parseError.message}`);
1129
+ console.error('Stack trace:', parseError.stack);
1130
+ }
1131
+
1132
+ } catch (lineError) {
1133
+ console.error(`❌ Critical line handler error: ${lineError.message}`);
1134
+ console.error('Stack trace:', lineError.stack);
1135
+ }
1136
+
1137
+ // Safely restore prompt
1138
+ try {
1139
+ if (!rl.closed) {
1140
+ rl.prompt();
1141
+ }
1142
+ } catch (promptError) {
1143
+ console.error('❌ Error restoring prompt:', promptError.message);
1144
+ // Try to create a new prompt
1145
+ try {
1146
+ process.stdout.write('pigeon> ');
1147
+ } catch (fallbackError) {
1148
+ console.error('❌ Critical prompt fallback error:', fallbackError.message);
1149
+ }
1150
+ }
1151
+ });
1152
+
1153
+ rl.on('close', () => {
1154
+ try {
1155
+ console.log('\n👋 Goodbye!');
1156
+ cli.shutdown();
1157
+ process.exit(0);
1158
+ } catch (closeError) {
1159
+ console.error('❌ Error during close:', closeError.message);
1160
+ process.exit(1);
1161
+ }
1162
+ });
1163
+
1164
+ // Add error handler for the readline interface
1165
+ rl.on('error', (error) => {
1166
+ console.error('❌ Readline error:', error.message);
1167
+ console.error('The CLI may become unresponsive. Please restart if needed.');
1168
+ });
1169
+ }
1170
+
1171
+ // Execute commands in interactive mode
1172
+ async function executeInteractiveCommand(cmd, opts) {
1173
+ try {
1174
+ switch (cmd) {
1175
+ case 'init': {
1176
+ try {
1177
+ await cli.initMesh({
1178
+ peerId: opts['peer-id'],
1179
+ maxPeers: opts['max-peers'],
1180
+ minPeers: opts['min-peers'],
1181
+ autoDiscovery: opts['auto-discovery'],
1182
+ enableWebdht: opts.webdht,
1183
+ enableCrypto: opts.crypto,
1184
+ debug: opts.debug || opts.d
1185
+ });
1186
+ await cli.connectToSignaling(opts.url || opts.u);
1187
+ } catch (initError) {
1188
+ console.error('❌ Interactive init failed:', initError.message);
1189
+ console.error('Stack trace:', initError.stack);
1190
+ }
1191
+ break;
1192
+ }
1193
+
1194
+ case 'send': {
1195
+ try {
1196
+ const messageWords = opts._positional || [];
1197
+ if (messageWords.length === 0) {
1198
+ console.error('Error: Message required for send command');
1199
+ return;
1200
+ }
1201
+ // Join all words to reconstruct the full message
1202
+ const message = messageWords.join(' ').replace(/^"|"$/g, ''); // Remove surrounding quotes if present
1203
+ if (!cli.mesh) {
1204
+ console.log('Mesh not initialized. Initializing...');
1205
+ await cli.initMesh({});
1206
+ await cli.connectToSignaling();
1207
+ }
1208
+ await cli.send(message);
1209
+ } catch (sendError) {
1210
+ console.error('❌ Interactive send failed:', sendError.message);
1211
+ console.error('Stack trace:', sendError.stack);
1212
+ }
1213
+ break;
1214
+ }
1215
+
1216
+ case 'status':
1217
+ cli.showStatus();
1218
+ break;
1219
+
1220
+ case 'peers':
1221
+ cli.showPeers();
1222
+ break;
1223
+
1224
+ case 'server-status': {
1225
+ try {
1226
+ const host = opts.host || opts.h || 'localhost';
1227
+ const port = opts.port || opts.p || 3000;
1228
+
1229
+ cli.log(`🔍 Checking server at ${host}:${port}...`, 'info');
1230
+ const serverStatus = await checkServerStatus(host, port);
1231
+
1232
+ if (serverStatus.running) {
1233
+ cli.log(`🟢 Server is running on ${host}:${port}`, 'success');
1234
+ console.log('\nServer Details:');
1235
+ console.log(` Status: ${serverStatus.status?.status || 'unknown'}`);
1236
+ console.log(` Uptime: ${serverStatus.status ? Math.floor(serverStatus.status.uptime) : 'n/a'}s`);
1237
+ console.log(` Connections: ${serverStatus.status?.connections || 'n/a'}`);
1238
+ console.log(` Peers: ${serverStatus.status?.peers || 'n/a'}`);
1239
+ console.log(` Memory: ${serverStatus.status ? Math.round(serverStatus.status.memory.heapUsed / 1024 / 1024) : 'n/a'}MB`);
1240
+ } else {
1241
+ cli.log(`🔴 No server running on ${host}:${port}`, 'warning');
1242
+ if (serverStatus.error) {
1243
+ console.log(`Error: ${serverStatus.error}`);
1244
+ }
1245
+ }
1246
+ } catch (statusError) {
1247
+ console.error('❌ Interactive server-status failed:', statusError.message);
1248
+ console.error('Stack trace:', statusError.stack);
1249
+ }
1250
+ break;
1251
+ }
1252
+
1253
+ case 'connect': {
1254
+ try {
1255
+ const url = opts._positional?.[0] || opts.url || opts.u;
1256
+ if (!url) {
1257
+ console.error('Error: URL required for connect command');
1258
+ return;
1259
+ }
1260
+ if (!cli.mesh) {
1261
+ console.log('Mesh not initialized. Initializing...');
1262
+ await cli.initMesh({});
1263
+ }
1264
+ await cli.connectToSignaling(url);
1265
+ } catch (connectError) {
1266
+ console.error('❌ Interactive connect failed:', connectError.message);
1267
+ console.error('Stack trace:', connectError.stack);
1268
+ }
1269
+ break;
1270
+ }
1271
+
1272
+ case 'disconnect':
1273
+ cli.disconnect();
1274
+ break;
1275
+
1276
+ case 'help':
1277
+ try {
1278
+ showInteractiveHelp();
1279
+ } catch (helpError) {
1280
+ console.error('❌ Error displaying interactive help:', helpError.message);
1281
+ console.log('Interactive help system unavailable');
1282
+ }
1283
+ break;
1284
+
1285
+ case 'server': {
1286
+ try {
1287
+ console.log('Note: Server command starts a background process. Use Ctrl+C to stop it.');
1288
+ const serverHost = opts.host || opts.h || 'localhost';
1289
+ const serverPort = opts.port || opts.p || 3000;
1290
+ const maxConnections = opts['max-connections'] || 3;
1291
+
1292
+ if (!opts.force && !opts.f) {
1293
+ cli.log('Checking for existing server...', 'info');
1294
+ const portCheck = await checkPortInUse(serverHost, serverPort);
1295
+
1296
+ if (portCheck.inUse) {
1297
+ cli.log(`Port ${serverPort} is already in use on ${serverHost}`, 'warning');
1298
+
1299
+ const serverStatus = await checkServerStatus(serverHost, serverPort);
1300
+ if (serverStatus.running && serverStatus.isPeerPigeon) {
1301
+ console.log('\nPeerPigeon Server Details:');
1302
+ console.log(` Uptime: ${Math.floor(serverStatus.status.uptime)}s`);
1303
+ console.log(` Connections: ${serverStatus.status.connections}`);
1304
+ console.log(` Peers: ${serverStatus.status.peers}`);
1305
+ } else {
1306
+ console.log('\nAnother service is using this port.');
1307
+ }
1308
+
1309
+ console.log('\nUse --force to start anyway, or use a different port.');
1310
+ return;
1311
+ }
1312
+ }
1313
+
1314
+ cli.log('Starting signaling server...', 'info');
1315
+ const server = new PeerPigeonServer({
1316
+ port: serverPort,
1317
+ host: serverHost,
1318
+ maxConnections
1319
+ });
1320
+ await server.start();
1321
+ cli.log(`Signaling server running on ${serverHost}:${serverPort}`, 'success');
1322
+ console.log('Server is running in background. Use Ctrl+C to stop or type "exit" to quit CLI.');
1323
+ } catch (serverError) {
1324
+ console.error('❌ Interactive server failed:', serverError.message);
1325
+ console.error('Stack trace:', serverError.stack);
1326
+ }
1327
+ break;
1328
+ }
1329
+
1330
+ default:
1331
+ console.error(`Unknown command: ${cmd}`);
1332
+ console.error('Type "help" for available commands');
1333
+ }
1334
+ } catch (error) {
1335
+ console.error('❌ Critical interactive command error:', error.message);
1336
+ console.error('Stack trace:', error.stack);
1337
+ }
1338
+ }
1339
+
1340
+ function showInteractiveHelp() {
1341
+ console.log(`
1342
+ 🐦 PeerPigeon CLI - Interactive Commands
1343
+
1344
+ Available commands:
1345
+ init [options] Initialize and connect to mesh network
1346
+ connect <url> Connect to signaling server
1347
+ send <message> Send broadcast message to all peers
1348
+ status Show mesh network status
1349
+ peers List connected and discovered peers
1350
+ server-status [options] Check if signaling server is running
1351
+ server [options] Start signaling server (background)
1352
+ disconnect Disconnect from mesh network
1353
+ clear Clear the screen
1354
+ help Show this help message
1355
+ exit, quit Exit the CLI
1356
+
1357
+ Options (same as command-line mode):
1358
+ --port, -p <port> Server port (default: 3000)
1359
+ --host, -h <host> Server host (default: localhost)
1360
+ --max-connections <n> Maximum connections (default: 3)
1361
+ --force, -f Force start even if server already running
1362
+ --url, -u <url> Signaling server URL
1363
+ --peer-id <id> Custom peer ID
1364
+ --max-peers <n> Maximum peers
1365
+ --min-peers <n> Minimum peers
1366
+ --auto-discovery <bool> Auto discovery (true|false)
1367
+ --webdht <bool> WebDHT (true|false)
1368
+ --crypto <bool> Encryption (true|false)
1369
+ --debug, -d <level> Debug level (off, error, warn, info, debug, trace)
1370
+
1371
+ Examples:
1372
+ init --max-peers 5
1373
+ init --webdht true --crypto false
1374
+ init --auto-discovery false
1375
+ init --debug info # Enable info-level debugging
1376
+ init --debug trace # Enable verbose trace debugging
1377
+ connect ws://localhost:3000
1378
+ send "Hello from interactive mode!"
1379
+ server --port 3001 --max-connections 50
1380
+ server-status --port 3000
1381
+ `);
1382
+ }