peerpigeon 0.0.7 โ†’ 0.0.8

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.
@@ -0,0 +1,520 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * PeerPigeon Distributed Storage Test
5
+ *
6
+ * This example demonstrates all storage operations including:
7
+ * - Basic store/retrieve/update/delete operations
8
+ * - Encryption and access control
9
+ * - Public vs private data
10
+ * - Immutable data with CRDT support
11
+ * - Bulk operations
12
+ * - Search functionality
13
+ * - Backup and restore
14
+ * - Key management and statistics
15
+ */
16
+
17
+ import { PeerPigeonMesh } from '../../src/PeerPigeonMesh.js';
18
+
19
+ class StorageTest {
20
+ constructor() {
21
+ this.mesh = null;
22
+ this.storage = null;
23
+ this.testResults = [];
24
+ }
25
+
26
+ async init() {
27
+ console.log('๐Ÿš€ Initializing PeerPigeon Mesh with Storage...');
28
+
29
+ // Initialize mesh with all features enabled
30
+ this.mesh = new PeerPigeonMesh({
31
+ enableWebDHT: true,
32
+ enableCrypto: true,
33
+ enableDistributedStorage: true
34
+ });
35
+
36
+ await this.mesh.init();
37
+ this.storage = this.mesh.distributedStorage;
38
+
39
+ console.log(`โœ… Mesh initialized with peer ID: ${this.mesh.peerId.substring(0, 16)}...`);
40
+ console.log(`๐Ÿ“ฆ Storage enabled: ${this.storage.isEnabled()}`);
41
+ console.log('');
42
+ }
43
+
44
+ async runTest(testName, testFn) {
45
+ console.log(`๐Ÿงช Running test: ${testName}`);
46
+ try {
47
+ await testFn();
48
+ console.log(`โœ… Test passed: ${testName}`);
49
+ this.testResults.push({ name: testName, status: 'PASS' });
50
+ } catch (error) {
51
+ console.error(`โŒ Test failed: ${testName} - ${error.message}`);
52
+ this.testResults.push({ name: testName, status: 'FAIL', error: error.message });
53
+ }
54
+ console.log('');
55
+ }
56
+
57
+ async testBasicOperations() {
58
+ // Test basic store and retrieve
59
+ await this.runTest('Basic Store and Retrieve', async () => {
60
+ const key = 'test-basic';
61
+ const value = { message: 'Hello, World!', timestamp: Date.now() };
62
+
63
+ const stored = await this.storage.store(key, value);
64
+ if (!stored) throw new Error('Store operation failed');
65
+
66
+ const retrieved = await this.storage.retrieve(key);
67
+ if (!retrieved) throw new Error('Retrieve operation failed');
68
+
69
+ if (JSON.stringify(retrieved) !== JSON.stringify(value)) {
70
+ throw new Error('Retrieved value does not match stored value');
71
+ }
72
+
73
+ console.log(` Stored and retrieved: ${JSON.stringify(value)}`);
74
+ });
75
+
76
+ // Test update operation
77
+ await this.runTest('Update Operation', async () => {
78
+ const key = 'test-update';
79
+ const originalValue = { counter: 1, name: 'original' };
80
+ const updatedValue = { counter: 2, name: 'updated' };
81
+
82
+ await this.storage.store(key, originalValue);
83
+ const updateResult = await this.storage.update(key, updatedValue);
84
+ if (!updateResult) throw new Error('Update operation failed');
85
+
86
+ const retrieved = await this.storage.retrieve(key);
87
+ if (JSON.stringify(retrieved) !== JSON.stringify(updatedValue)) {
88
+ throw new Error('Updated value does not match expected value');
89
+ }
90
+
91
+ console.log(` Updated: ${JSON.stringify(originalValue)} โ†’ ${JSON.stringify(updatedValue)}`);
92
+ });
93
+
94
+ // Test delete operation
95
+ await this.runTest('Delete Operation', async () => {
96
+ const key = 'test-delete';
97
+ const value = { temporary: true };
98
+
99
+ await this.storage.store(key, value);
100
+ const deleteResult = await this.storage.delete(key);
101
+ if (!deleteResult) throw new Error('Delete operation failed');
102
+
103
+ const retrieved = await this.storage.retrieve(key);
104
+ if (retrieved !== null) throw new Error('Key should not exist after deletion');
105
+
106
+ console.log(` Successfully deleted key: ${key}`);
107
+ });
108
+ }
109
+
110
+ async testEncryptionAndAccessControl() {
111
+ // Test private (encrypted) data
112
+ await this.runTest('Private Encrypted Data', async () => {
113
+ const key = 'test-private';
114
+ const value = { secret: 'classified information', level: 'confidential' };
115
+
116
+ // Store as private (encrypted by default)
117
+ await this.storage.store(key, value, { isPublic: false });
118
+
119
+ const retrieved = await this.storage.retrieve(key);
120
+ if (JSON.stringify(retrieved) !== JSON.stringify(value)) {
121
+ throw new Error('Encrypted data not properly decrypted');
122
+ }
123
+
124
+ console.log(' Private data encrypted and decrypted successfully');
125
+ });
126
+
127
+ // Test public data
128
+ await this.runTest('Public Data', async () => {
129
+ const key = 'test-public';
130
+ const value = { announcement: 'public information', visibility: 'everyone' };
131
+
132
+ await this.storage.store(key, value, { isPublic: true });
133
+
134
+ const retrieved = await this.storage.retrieve(key);
135
+ if (JSON.stringify(retrieved) !== JSON.stringify(value)) {
136
+ throw new Error('Public data not properly stored/retrieved');
137
+ }
138
+
139
+ console.log(' Public data stored and retrieved successfully');
140
+ });
141
+
142
+ // Test access control (simulated - would need multiple peers for full test)
143
+ await this.runTest('Access Control Metadata', async () => {
144
+ const key = 'test-access-control';
145
+ const value = { restricted: true };
146
+ const allowedPeers = ['peer1', 'peer2'];
147
+
148
+ await this.storage.store(key, value, {
149
+ isPublic: false,
150
+ allowedPeers
151
+ });
152
+
153
+ const keyInfo = await this.storage.getKeyInfo(key);
154
+ if (!keyInfo) throw new Error('Key info not available');
155
+ if (keyInfo.allowedPeers.length !== allowedPeers.length) {
156
+ throw new Error('Allowed peers not properly set');
157
+ }
158
+
159
+ console.log(` Access control set for peers: ${allowedPeers.join(', ')}`);
160
+ });
161
+ }
162
+
163
+ async testImmutableAndCRDT() {
164
+ // Test immutable data
165
+ await this.runTest('Immutable Data', async () => {
166
+ const key = 'test-immutable';
167
+ const value = { constant: 'unchangeable', version: 1 };
168
+
169
+ await this.storage.store(key, value, { isImmutable: true });
170
+
171
+ try {
172
+ // This should succeed because we're the owner
173
+ await this.storage.update(key, { constant: 'changed', version: 2 });
174
+ console.log(' Owner can update immutable data');
175
+ } catch (error) {
176
+ throw new Error('Owner should be able to update their own immutable data');
177
+ }
178
+ });
179
+
180
+ // Test CRDT-enabled data
181
+ await this.runTest('CRDT-Enabled Data', async () => {
182
+ const key = 'test-crdt';
183
+ const value = { collaborative: true, edits: 1 };
184
+
185
+ await this.storage.store(key, value, { enableCRDT: true });
186
+
187
+ const keyInfo = await this.storage.getKeyInfo(key);
188
+ if (!keyInfo.enableCRDT) throw new Error('CRDT not enabled');
189
+ if (!keyInfo.crdtEnabled) throw new Error('CRDT state not initialized');
190
+
191
+ console.log(' CRDT enabled for collaborative editing');
192
+ });
193
+ }
194
+
195
+ async testTTLAndExpiration() {
196
+ await this.runTest('TTL (Time To Live)', async () => {
197
+ const key = 'test-ttl';
198
+ const value = { temporary: true, expires: 'soon' };
199
+ const ttl = 2000; // 2 seconds
200
+
201
+ await this.storage.store(key, value, { ttl });
202
+
203
+ // Should be available immediately
204
+ const retrieved = await this.storage.retrieve(key);
205
+ if (!retrieved) throw new Error('TTL data not available immediately');
206
+
207
+ const keyInfo = await this.storage.getKeyInfo(key);
208
+ if (keyInfo.ttl !== ttl) throw new Error('TTL not properly set');
209
+
210
+ console.log(` TTL set to ${ttl}ms for key: ${key}`);
211
+
212
+ // Note: In a real scenario, we'd wait for expiration and test cleanup
213
+ // For this demo, we'll just verify the TTL was set correctly
214
+ });
215
+ }
216
+
217
+ async testBulkOperations() {
218
+ // Test bulk store
219
+ await this.runTest('Bulk Store Operations', async () => {
220
+ const items = [
221
+ { key: 'bulk-1', value: { data: 'first bulk item' } },
222
+ { key: 'bulk-2', value: { data: 'second bulk item' } },
223
+ { key: 'bulk-3', value: { data: 'third bulk item' } }
224
+ ];
225
+
226
+ const results = await this.storage.bulkStore(items);
227
+ if (results.stored !== 3 || results.failed !== 0) {
228
+ throw new Error(`Bulk store failed: ${results.stored} stored, ${results.failed} failed`);
229
+ }
230
+
231
+ console.log(` Bulk stored ${results.stored} items successfully`);
232
+ });
233
+
234
+ // Test bulk retrieve
235
+ await this.runTest('Bulk Retrieve Operations', async () => {
236
+ const keys = ['bulk-1', 'bulk-2', 'bulk-3'];
237
+
238
+ const results = await this.storage.bulkRetrieve(keys);
239
+ const retrievedKeys = Object.keys(results).filter(key => results[key] !== null);
240
+
241
+ if (retrievedKeys.length !== 3) {
242
+ throw new Error(`Bulk retrieve failed: only ${retrievedKeys.length} out of 3 items retrieved`);
243
+ }
244
+
245
+ console.log(` Bulk retrieved ${retrievedKeys.length} items successfully`);
246
+ });
247
+
248
+ // Test bulk delete
249
+ await this.runTest('Bulk Delete Operations', async () => {
250
+ const prefix = 'bulk-';
251
+
252
+ const deletedCount = await this.storage.bulkDelete(prefix);
253
+ if (deletedCount !== 3) {
254
+ throw new Error(`Bulk delete failed: only ${deletedCount} out of 3 items deleted`);
255
+ }
256
+
257
+ console.log(` Bulk deleted ${deletedCount} items with prefix: ${prefix}`);
258
+ });
259
+ }
260
+
261
+ async testSearchOperations() {
262
+ // Prepare test data for search
263
+ await this.storage.store('search-test-1', { category: 'fruits', name: 'apple', color: 'red' });
264
+ await this.storage.store('search-test-2', { category: 'fruits', name: 'banana', color: 'yellow' });
265
+ await this.storage.store('search-different', { category: 'vegetables', name: 'carrot', color: 'orange' });
266
+
267
+ // Test key search
268
+ await this.runTest('Search by Key Pattern', async () => {
269
+ const results = this.storage.searchKeys({ keyPattern: 'search-test.*' });
270
+ if (results.length !== 2) {
271
+ throw new Error(`Key search failed: expected 2 results, got ${results.length}`);
272
+ }
273
+
274
+ console.log(` Found ${results.length} keys matching pattern 'search-test.*'`);
275
+ });
276
+
277
+ // Test value search
278
+ await this.runTest('Search by Value Content', async () => {
279
+ const results = await this.storage.search('apple', 'value');
280
+ if (results.length !== 1) {
281
+ throw new Error(`Value search failed: expected 1 result, got ${results.length}`);
282
+ }
283
+
284
+ console.log(` Found ${results.length} items containing 'apple' in value`);
285
+ });
286
+
287
+ // Test metadata search
288
+ await this.runTest('Search by Metadata', async () => {
289
+ const results = await this.storage.search('fruits', 'value');
290
+ if (results.length !== 2) {
291
+ throw new Error(`Metadata search failed: expected 2 results, got ${results.length}`);
292
+ }
293
+
294
+ console.log(` Found ${results.length} items with 'fruits' in metadata`);
295
+ });
296
+ }
297
+
298
+ async testKeyManagement() {
299
+ // Test list owned keys
300
+ await this.runTest('List Owned Keys', async () => {
301
+ const ownedKeys = this.storage.getOwnedKeys();
302
+ if (ownedKeys.length === 0) {
303
+ throw new Error('No owned keys found - expected some from previous tests');
304
+ }
305
+
306
+ console.log(` Found ${ownedKeys.length} owned keys`);
307
+ ownedKeys.slice(0, 3).forEach(key => {
308
+ console.log(` - ${key.key} (${key.isPublic ? 'public' : 'private'})`);
309
+ });
310
+ });
311
+
312
+ // Test list keys with prefix
313
+ await this.runTest('List Keys with Prefix', async () => {
314
+ const keys = await this.storage.listKeys('search-');
315
+ if (keys.length === 0) {
316
+ throw new Error('No keys found with prefix - expected some from search tests');
317
+ }
318
+
319
+ console.log(` Found ${keys.length} keys with prefix 'search-'`);
320
+ });
321
+
322
+ // Test accessible keys
323
+ await this.runTest('List Accessible Keys', async () => {
324
+ const accessibleKeys = await this.storage.listAccessibleKeys();
325
+ if (accessibleKeys.length === 0) {
326
+ throw new Error('No accessible keys found');
327
+ }
328
+
329
+ console.log(` Found ${accessibleKeys.length} accessible keys`);
330
+ });
331
+ }
332
+
333
+ async testBackupAndRestore() {
334
+ // Test backup
335
+ await this.runTest('Create Backup', async () => {
336
+ const backup = await this.storage.backup();
337
+ if (!backup || !backup.keys || backup.keys.length === 0) {
338
+ throw new Error('Backup failed or contains no keys');
339
+ }
340
+
341
+ console.log(` Created backup with ${backup.keys.length} keys`);
342
+ console.log(` Backup version: ${backup.version}, timestamp: ${new Date(backup.timestamp).toISOString()}`);
343
+
344
+ // Store backup for restore test
345
+ this.testBackup = backup;
346
+ });
347
+
348
+ // Test restore (we'll clear some data and restore it)
349
+ await this.runTest('Restore from Backup', async () => {
350
+ if (!this.testBackup) throw new Error('No backup available for restore test');
351
+
352
+ // First, let's store a key that should be skipped during restore
353
+ await this.storage.store('restore-test', { existing: true });
354
+
355
+ // Restore with overwrite disabled (default)
356
+ const results = await this.storage.restore(this.testBackup, { overwrite: false });
357
+
358
+ if (results.failed > 0) {
359
+ console.log(` Some items failed to restore: ${results.errors.length} errors`);
360
+ results.errors.slice(0, 3).forEach(error => {
361
+ console.log(` - ${error.key}: ${error.error}`);
362
+ });
363
+ }
364
+
365
+ console.log(` Restore completed: ${results.restored} restored, ${results.skipped} skipped, ${results.failed} failed`);
366
+ });
367
+ }
368
+
369
+ async testStatistics() {
370
+ await this.runTest('Storage Statistics', async () => {
371
+ const stats = await this.storage.getStats();
372
+
373
+ console.log(' Storage Statistics:');
374
+ console.log(` - Enabled: ${stats.enabled}`);
375
+ console.log(` - Items: ${stats.itemCount}`);
376
+ console.log(` - Total Size: ${stats.totalSize} bytes`);
377
+ console.log(` - Owned Keys: ${stats.ownedKeys}`);
378
+ console.log(` - Total Keys: ${stats.totalKeys}`);
379
+ console.log(` - CRDT Keys: ${stats.crdtKeys}`);
380
+ console.log(` - Encryption Enabled: ${stats.encryptionEnabled}`);
381
+ console.log(` - Max Value Size: ${stats.maxValueSize} bytes`);
382
+
383
+ if (stats.itemCount === 0) {
384
+ throw new Error('Expected some items in storage statistics');
385
+ }
386
+ });
387
+ }
388
+
389
+ async testStorageToggle() {
390
+ await this.runTest('Storage Enable/Disable', async () => {
391
+ // Test disable
392
+ await this.storage.disable();
393
+ if (this.storage.isEnabled()) {
394
+ throw new Error('Storage should be disabled');
395
+ }
396
+
397
+ // Test enable
398
+ await this.storage.enable();
399
+ if (!this.storage.isEnabled()) {
400
+ throw new Error('Storage should be enabled');
401
+ }
402
+
403
+ console.log(' Storage successfully toggled enabled/disabled');
404
+ });
405
+ }
406
+
407
+ async testCleanup() {
408
+ await this.runTest('Storage Cleanup', async () => {
409
+ // Test cleanup function (won't see immediate effects but should not error)
410
+ this.storage.cleanup();
411
+ console.log(' Cleanup operation completed successfully');
412
+ });
413
+ }
414
+
415
+ async runAllTests() {
416
+ console.log('๐Ÿงช Starting Distributed Storage Test Suite');
417
+ console.log('='.repeat(60));
418
+ console.log('');
419
+
420
+ await this.testBasicOperations();
421
+ await this.testEncryptionAndAccessControl();
422
+ await this.testImmutableAndCRDT();
423
+ await this.testTTLAndExpiration();
424
+ await this.testBulkOperations();
425
+ await this.testSearchOperations();
426
+ await this.testKeyManagement();
427
+ await this.testBackupAndRestore();
428
+ await this.testStatistics();
429
+ await this.testStorageToggle();
430
+ await this.testCleanup();
431
+
432
+ this.printSummary();
433
+ }
434
+
435
+ printSummary() {
436
+ console.log('='.repeat(60));
437
+ console.log('๐Ÿ TEST SUMMARY');
438
+ console.log('='.repeat(60));
439
+
440
+ const passed = this.testResults.filter(r => r.status === 'PASS').length;
441
+ const failed = this.testResults.filter(r => r.status === 'FAIL').length;
442
+ const total = this.testResults.length;
443
+
444
+ console.log(`Total Tests: ${total}`);
445
+ console.log(`โœ… Passed: ${passed}`);
446
+ console.log(`โŒ Failed: ${failed}`);
447
+ console.log(`Success Rate: ${((passed / total) * 100).toFixed(1)}%`);
448
+ console.log('');
449
+
450
+ if (failed > 0) {
451
+ console.log('Failed Tests:');
452
+ this.testResults.filter(r => r.status === 'FAIL').forEach(result => {
453
+ console.log(` โŒ ${result.name}: ${result.error}`);
454
+ });
455
+ console.log('');
456
+ }
457
+
458
+ if (passed === total) {
459
+ console.log('๐ŸŽ‰ All tests passed! The Distributed Storage system is working perfectly.');
460
+ } else {
461
+ console.log('โš ๏ธ Some tests failed. Please review the errors above.');
462
+ }
463
+
464
+ console.log('');
465
+ console.log('๐Ÿ“Š Storage Operations Tested:');
466
+ console.log(' โ€ข Basic CRUD operations (store, retrieve, update, delete)');
467
+ console.log(' โ€ข Encryption and access control');
468
+ console.log(' โ€ข Public vs private data handling');
469
+ console.log(' โ€ข Immutable data and CRDT support');
470
+ console.log(' โ€ข TTL (Time To Live) functionality');
471
+ console.log(' โ€ข Bulk operations (store, retrieve, delete)');
472
+ console.log(' โ€ข Search operations (by key, value, metadata)');
473
+ console.log(' โ€ข Key management and statistics');
474
+ console.log(' โ€ข Backup and restore functionality');
475
+ console.log(' โ€ข Storage enable/disable toggle');
476
+ console.log(' โ€ข Cleanup operations');
477
+ }
478
+
479
+ async cleanup() {
480
+ if (this.mesh) {
481
+ console.log('๐Ÿงน Cleaning up test environment...');
482
+ // Clear all test data
483
+ try {
484
+ await this.storage.clear();
485
+ console.log('โœ… Test data cleared');
486
+ } catch (error) {
487
+ console.warn('โš ๏ธ Failed to clear test data:', error.message);
488
+ }
489
+ }
490
+ }
491
+ }
492
+
493
+ // Main execution
494
+ async function main() {
495
+ const test = new StorageTest();
496
+
497
+ try {
498
+ await test.init();
499
+ await test.runAllTests();
500
+ } catch (error) {
501
+ console.error('๐Ÿ’ฅ Test suite failed to run:', error);
502
+ } finally {
503
+ await test.cleanup();
504
+ process.exit(0);
505
+ }
506
+ }
507
+
508
+ // Handle graceful shutdown
509
+ process.on('SIGINT', async () => {
510
+ console.log('\n๐Ÿ›‘ Received SIGINT, shutting down gracefully...');
511
+ process.exit(0);
512
+ });
513
+
514
+ process.on('SIGTERM', async () => {
515
+ console.log('\n๐Ÿ›‘ Received SIGTERM, shutting down gracefully...');
516
+ process.exit(0);
517
+ });
518
+
519
+ // Run the test suite
520
+ main().catch(console.error);
package/index.js CHANGED
@@ -3,17 +3,18 @@ export { PeerPigeonMesh } from './src/PeerPigeonMesh.js';
3
3
  export { PeerConnection } from './src/PeerConnection.js';
4
4
  export { SignalingClient } from './src/SignalingClient.js';
5
5
  export { WebDHT } from './src/WebDHT.js';
6
+ export { DistributedStorageManager } from './src/DistributedStorageManager.js';
6
7
 
7
8
  // Export environment detection utilities
8
- export {
9
- EnvironmentDetector,
10
- environmentDetector,
11
- isBrowser,
12
- isNodeJS,
13
- isWorker,
14
- hasWebRTC,
15
- hasWebSocket,
16
- getEnvironmentReport
9
+ export {
10
+ EnvironmentDetector,
11
+ environmentDetector,
12
+ isBrowser,
13
+ isNodeJS,
14
+ isWorker,
15
+ hasWebRTC,
16
+ hasWebSocket,
17
+ getEnvironmentReport
17
18
  } from './src/EnvironmentDetector.js';
18
19
 
19
20
  // Export the WebSocket server class for programmatic use
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peerpigeon",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "description": "WebRTC-based peer-to-peer mesh networking library with intelligent routing and signaling server",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -15,7 +15,9 @@
15
15
  "server": "node websocket-server/server.js",
16
16
  "lint": "eslint src/ examples/ websocket-server/ --ext .js",
17
17
  "lint:fix": "eslint src/ examples/ websocket-server/ --ext .js --fix",
18
- "ci": "npm run lint",
18
+ "test": "node examples/node/storage-test.js",
19
+ "test:storage": "node examples/distributed-storage-test.js",
20
+ "ci": "npm run lint && npm run test",
19
21
  "prepublishOnly": "npm run ci"
20
22
  },
21
23
  "files": [