peerpigeon 0.0.6 → 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,73 @@
1
+ # NativeScript Example
2
+
3
+ This example demonstrates how to use PeerPigeon in a NativeScript application.
4
+
5
+ ## Prerequisites
6
+
7
+ - NativeScript CLI installed (`npm install -g @nativescript/cli`)
8
+ - NativeScript development environment set up for your target platform (iOS/Android)
9
+ - WebRTC plugin for NativeScript (if using media features)
10
+
11
+ ## Setup
12
+
13
+ 1. Create a new NativeScript project:
14
+ ```bash
15
+ ns create MyPeerPigeonApp --js
16
+ cd MyPeerPigeonApp
17
+ ```
18
+
19
+ 2. Install PeerPigeon:
20
+ ```bash
21
+ npm install peerpigeon
22
+ ```
23
+
24
+ 3. For WebRTC support, install a WebRTC plugin:
25
+ ```bash
26
+ # Example plugin (check for latest NativeScript WebRTC plugins)
27
+ ns plugin add @nativescript/webrtc
28
+ ```
29
+
30
+ 4. Copy the example code from `app.js` to your project's main file.
31
+
32
+ ## Features Supported
33
+
34
+ - ✅ Environment detection
35
+ - ✅ WebSocket signaling (with appropriate plugin)
36
+ - ✅ Basic mesh networking
37
+ - ✅ Storage management (using NativeScript's application-settings)
38
+ - ⚠️ WebRTC (requires additional plugin)
39
+ - ⚠️ Media features (requires camera/microphone permissions)
40
+
41
+ ## Platform Considerations
42
+
43
+ ### Android
44
+ - Requires network permissions in `app/App_Resources/Android/src/main/AndroidManifest.xml`:
45
+ ```xml
46
+ <uses-permission android:name="android.permission.INTERNET" />
47
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
48
+ ```
49
+
50
+ ### iOS
51
+ - May require camera/microphone permissions if using media features
52
+ - Add appropriate usage descriptions in `app/App_Resources/iOS/Info.plist`
53
+
54
+ ## Running the Example
55
+
56
+ ```bash
57
+ # Run on iOS simulator
58
+ ns run ios
59
+
60
+ # Run on Android emulator
61
+ ns run android
62
+
63
+ # Run on physical device
64
+ ns run ios --device
65
+ ns run android --device
66
+ ```
67
+
68
+ ## Notes
69
+
70
+ - This example uses basic mesh networking without WebRTC
71
+ - For full WebRTC support, additional native plugins are required
72
+ - Storage uses NativeScript's application-settings module
73
+ - Network connectivity is automatically detected
@@ -0,0 +1,152 @@
1
+ import { Application } from '@nativescript/core';
2
+ import { PeerPigeonMesh } from 'peerpigeon';
3
+
4
+ // NativeScript PeerPigeon Example
5
+ console.log('🔮 Starting NativeScript PeerPigeon Example');
6
+
7
+ let mesh;
8
+ let peerId;
9
+
10
+ // Initialize PeerPigeon when app launches
11
+ Application.on(Application.launchEvent, (_args) => {
12
+ console.log('📱 NativeScript app launched');
13
+ initializePeerPigeon();
14
+ });
15
+
16
+ // Cleanup when app exits
17
+ Application.on(Application.exitEvent, () => {
18
+ console.log('📱 NativeScript app exiting');
19
+ if (mesh) {
20
+ mesh.disconnect();
21
+ }
22
+ });
23
+
24
+ async function initializePeerPigeon() {
25
+ try {
26
+ console.log('🚀 Initializing PeerPigeon...');
27
+
28
+ // Create mesh instance with basic configuration
29
+ mesh = new PeerPigeonMesh({
30
+ enableWebDHT: true,
31
+ enableCrypto: false // Disable crypto for simplicity in this example
32
+ });
33
+
34
+ // Set up event listeners
35
+ setupEventListeners();
36
+
37
+ // Initialize the mesh
38
+ await mesh.init();
39
+ peerId = mesh.peerId;
40
+ console.log(`✅ PeerPigeon initialized with ID: ${peerId.substring(0, 8)}...`);
41
+
42
+ // Connect to signaling server
43
+ // Replace with your signaling server URL
44
+ const signalingUrl = 'wss://your-signaling-server.com';
45
+ await mesh.connect(signalingUrl);
46
+
47
+ console.log('🌐 Connected to signaling server');
48
+ } catch (error) {
49
+ console.error('❌ Failed to initialize PeerPigeon:', error);
50
+
51
+ // Log environment info for debugging
52
+ const report = mesh?.environmentReport;
53
+ if (report) {
54
+ console.log('🔍 Environment Report:', JSON.stringify(report, null, 2));
55
+ }
56
+ }
57
+ }
58
+
59
+ function setupEventListeners() {
60
+ // Connection events
61
+ mesh.addEventListener('connected', () => {
62
+ console.log('🔗 Connected to mesh network');
63
+ });
64
+
65
+ mesh.addEventListener('disconnected', (data) => {
66
+ console.log('🔌 Disconnected from mesh network:', data.reason);
67
+ });
68
+
69
+ // Peer events
70
+ mesh.addEventListener('peerConnected', (data) => {
71
+ console.log(`👋 Peer connected: ${data.peerId.substring(0, 8)}...`);
72
+ console.log(`📊 Total peers: ${mesh.getConnectedPeers().length}`);
73
+ });
74
+
75
+ mesh.addEventListener('peerDisconnected', (data) => {
76
+ console.log(`👋 Peer disconnected: ${data.peerId.substring(0, 8)}...`);
77
+ console.log(`📊 Total peers: ${mesh.getConnectedPeers().length}`);
78
+ });
79
+
80
+ // Message events
81
+ mesh.addEventListener('messageReceived', (data) => {
82
+ console.log(`📨 Message from ${data.fromPeerId.substring(0, 8)}...:`, data.message);
83
+
84
+ // Echo the message back
85
+ if (data.message.type === 'ping') {
86
+ sendMessage(data.fromPeerId, { type: 'pong', timestamp: Date.now() });
87
+ }
88
+ });
89
+
90
+ // Error events
91
+ mesh.addEventListener('error', (data) => {
92
+ console.error('❌ Mesh error:', data.error);
93
+ });
94
+
95
+ // Status events
96
+ mesh.addEventListener('statusChanged', (data) => {
97
+ console.log('📈 Status changed:', data);
98
+ });
99
+ }
100
+
101
+ // Send a message to a specific peer or broadcast
102
+ async function sendMessage(targetPeerId, message) {
103
+ try {
104
+ if (targetPeerId) {
105
+ await mesh.sendMessage(targetPeerId, message);
106
+ console.log(`📤 Message sent to ${targetPeerId.substring(0, 8)}...`);
107
+ } else {
108
+ // Broadcast to all peers
109
+ const peers = mesh.getConnectedPeers();
110
+ for (const peer of peers) {
111
+ await mesh.sendMessage(peer.peerId, message);
112
+ }
113
+ console.log(`📡 Message broadcast to ${peers.length} peers`);
114
+ }
115
+ } catch (error) {
116
+ console.error('❌ Failed to send message:', error);
117
+ }
118
+ }
119
+
120
+ // Example: Send a ping message every 30 seconds
121
+ setInterval(() => {
122
+ if (mesh && mesh.connected) {
123
+ const peers = mesh.getConnectedPeers();
124
+ if (peers.length > 0) {
125
+ const randomPeer = peers[Math.floor(Math.random() * peers.length)];
126
+ sendMessage(randomPeer.peerId, {
127
+ type: 'ping',
128
+ timestamp: Date.now(),
129
+ from: 'NativeScript'
130
+ });
131
+ }
132
+ }
133
+ }, 30000);
134
+
135
+ // Example: Log mesh status every 60 seconds
136
+ setInterval(() => {
137
+ if (mesh) {
138
+ const peers = mesh.getConnectedPeers();
139
+ console.log(`📊 Mesh Status - Connected: ${mesh.connected}, Peers: ${peers.length}`);
140
+
141
+ if (peers.length > 0) {
142
+ console.log(`👥 Connected to: ${peers.map(p => p.peerId.substring(0, 8)).join(', ')}...`);
143
+ }
144
+ }
145
+ }, 60000);
146
+
147
+ // Export functions for potential UI integration
148
+ export {
149
+ mesh,
150
+ sendMessage,
151
+ initializePeerPigeon
152
+ };
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "peerpigeon-nativescript-example",
3
+ "version": "1.0.0",
4
+ "description": "NativeScript example for PeerPigeon mesh networking",
5
+ "main": "app.js",
6
+ "dependencies": {
7
+ "@nativescript/core": "^8.0.0",
8
+ "peerpigeon": "^0.0.7"
9
+ },
10
+ "devDependencies": {
11
+ "@nativescript/cli": "^8.0.0"
12
+ },
13
+ "scripts": {
14
+ "ios": "ns run ios",
15
+ "android": "ns run android",
16
+ "clean": "ns clean"
17
+ },
18
+ "keywords": [
19
+ "nativescript",
20
+ "peerpigeon",
21
+ "webrtc",
22
+ "p2p",
23
+ "mesh-networking"
24
+ ],
25
+ "author": "PeerPigeon",
26
+ "license": "MIT"
27
+ }
@@ -0,0 +1,110 @@
1
+ # Node.js Examples for PeerPigeon
2
+
3
+ This directory contains Node.js examples demonstrating various PeerPigeon features.
4
+
5
+ ## Examples
6
+
7
+ ### Basic Storage Example (`basic-storage-example.js`)
8
+
9
+ A simple demonstration of core storage operations perfect for getting started:
10
+
11
+ - Store, retrieve, update, and delete data
12
+ - List all stored keys
13
+ - View storage statistics
14
+ - Clean shutdown handling
15
+
16
+ #### Running the Basic Example
17
+
18
+ ```bash
19
+ cd examples/node
20
+ npm run basic-example
21
+ ```
22
+
23
+ ### Storage Test (`storage-test.js`)
24
+
25
+ A comprehensive test suite that demonstrates all distributed storage operations:
26
+
27
+ - **Basic Operations**: Store, retrieve, update, delete
28
+ - **Encryption & Access Control**: Private encrypted data, public data, peer access lists
29
+ - **Advanced Features**: Immutable data, CRDT support, TTL expiration
30
+ - **Bulk Operations**: Bulk store, retrieve, and delete
31
+ - **Search**: Search by key patterns, value content, and metadata
32
+ - **Management**: Key listing, statistics, backup/restore
33
+ - **Configuration**: Enable/disable storage, cleanup operations
34
+
35
+ #### Running the Storage Test
36
+
37
+ ```bash
38
+ cd examples/node
39
+ npm run storage-test
40
+ ```
41
+
42
+ Or directly:
43
+
44
+ ```bash
45
+ node storage-test.js
46
+ ```
47
+
48
+ #### Expected Output
49
+
50
+ The test will run through all storage operations and provide detailed output:
51
+
52
+ ```
53
+ 🚀 Initializing PeerPigeon Mesh with Storage...
54
+ ✅ Mesh initialized with peer ID: abcd1234...
55
+ 📦 Storage enabled: true
56
+
57
+ 🧪 Running test: Basic Store and Retrieve
58
+ Stored and retrieved: {"message":"Hello, World!","timestamp":1234567890}
59
+ ✅ Test passed: Basic Store and Retrieve
60
+
61
+ 🧪 Running test: Update Operation
62
+ Updated: {"counter":1,"name":"original"} → {"counter":2,"name":"updated"}
63
+ ✅ Test passed: Update Operation
64
+
65
+ ... (continues with all tests)
66
+
67
+ 🏁 TEST SUMMARY
68
+ ================================================
69
+ Total Tests: 18
70
+ ✅ Passed: 18
71
+ ❌ Failed: 0
72
+ Success Rate: 100.0%
73
+
74
+ 🎉 All tests passed! The Distributed Storage system is working perfectly.
75
+ ```
76
+
77
+ ### Basic Example (`basic-example.js`)
78
+
79
+ A simple example showing basic PeerPigeon mesh functionality (to be created).
80
+
81
+ ## Requirements
82
+
83
+ - Node.js 16.0.0 or higher
84
+ - ES Modules support (using `"type": "module"` in package.json)
85
+
86
+ ## Features Demonstrated
87
+
88
+ The examples show how to use PeerPigeon's distributed storage system with:
89
+
90
+ 1. **WebDHT Integration**: Distributed hash table for data persistence
91
+ 2. **Encryption**: Automatic encryption for private data using the crypto manager
92
+ 3. **Access Control**: Fine-grained permissions for data access
93
+ 4. **CRDT Support**: Conflict-free replicated data types for collaborative editing
94
+ 5. **Search Capabilities**: Flexible search across keys, values, and metadata
95
+ 6. **Bulk Operations**: Efficient batch processing of multiple items
96
+ 7. **Backup/Restore**: Data portability and recovery features
97
+
98
+ ## Architecture
99
+
100
+ Each example initializes a PeerPigeon mesh with the required features:
101
+
102
+ ```javascript
103
+ const mesh = new PeerPigeonMesh({
104
+ enableWebDHT: true, // Distributed hash table
105
+ enableCrypto: true, // Encryption/decryption
106
+ enableDistributedStorage: true // Optional storage layer
107
+ });
108
+ ```
109
+
110
+ The distributed storage manager provides a high-level API over the WebDHT with additional features like encryption, access control, and search capabilities.
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Basic Distributed Storage Example for PeerPigeon
4
+ *
5
+ * This example demonstrates simple usage of the distributed storage layer.
6
+ * For comprehensive testing, see storage-test.js
7
+ */
8
+
9
+ import { PeerPigeonMesh } from '../../src/PeerPigeonMesh.js';
10
+
11
+ async function basicStorageExample() {
12
+ console.log('🐦 PeerPigeon Basic Storage Example');
13
+ console.log('=====================================\n');
14
+
15
+ // Initialize the mesh network with storage enabled
16
+ const mesh = new PeerPigeonMesh({
17
+ enableStorage: true,
18
+ enableWebDHT: true,
19
+ enableCrypto: true,
20
+ nodeId: 'basic-example-node'
21
+ });
22
+
23
+ try {
24
+ // Wait a moment for initialization
25
+ await new Promise(resolve => setTimeout(resolve, 1000));
26
+
27
+ console.log('1. Storing some data...');
28
+ await mesh.storageManager.store('user:123', { name: 'Alice', age: 30 });
29
+ await mesh.storageManager.store('config:theme', 'dark');
30
+ await mesh.storageManager.store('counter', 42);
31
+ console.log(' ✅ Data stored successfully\n');
32
+
33
+ console.log('2. Retrieving data...');
34
+ const user = await mesh.storageManager.retrieve('user:123');
35
+ const theme = await mesh.storageManager.retrieve('config:theme');
36
+ const counter = await mesh.storageManager.retrieve('counter');
37
+
38
+ console.log(` User: ${JSON.stringify(user)}`);
39
+ console.log(` Theme: ${theme}`);
40
+ console.log(` Counter: ${counter}\n`);
41
+
42
+ console.log('3. Updating data...');
43
+ await mesh.storageManager.update('counter', 100);
44
+ const updatedCounter = await mesh.storageManager.retrieve('counter');
45
+ console.log(` Updated counter: ${updatedCounter}\n`);
46
+
47
+ console.log('4. Listing all keys...');
48
+ const keys = await mesh.storageManager.listKeys();
49
+ console.log(` Found keys: ${keys.join(', ')}\n`);
50
+
51
+ console.log('5. Getting storage statistics...');
52
+ const stats = await mesh.storageManager.getStats();
53
+ console.log(` Total items: ${stats.itemCount}`);
54
+ console.log(` Storage size: ${stats.totalSize} bytes\n`);
55
+
56
+ console.log('6. Cleaning up...');
57
+ await mesh.storageManager.delete('user:123');
58
+ await mesh.storageManager.delete('config:theme');
59
+ await mesh.storageManager.delete('counter');
60
+ console.log(' ✅ Cleanup complete\n');
61
+
62
+ console.log('🎉 Basic storage example completed successfully!');
63
+ } catch (error) {
64
+ console.error('❌ Error in basic storage example:', error.message);
65
+ console.error(error.stack);
66
+ } finally {
67
+ // Clean shutdown
68
+ if (mesh.cleanup) {
69
+ await mesh.cleanup();
70
+ }
71
+ process.exit(0);
72
+ }
73
+ }
74
+
75
+ // Handle process termination gracefully
76
+ process.on('SIGINT', () => {
77
+ console.log('\n👋 Shutting down gracefully...');
78
+ process.exit(0);
79
+ });
80
+
81
+ process.on('unhandledRejection', (reason, promise) => {
82
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
83
+ process.exit(1);
84
+ });
85
+
86
+ // Run the example
87
+ basicStorageExample().catch(error => {
88
+ console.error('Fatal error:', error);
89
+ process.exit(1);
90
+ });
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "peerpigeon-node-examples",
3
+ "version": "1.0.0",
4
+ "description": "Node.js examples for PeerPigeon distributed mesh networking",
5
+ "type": "module",
6
+ "scripts": {
7
+ "storage-test": "node storage-test.js",
8
+ "basic-example": "node basic-storage-example.js",
9
+ "test": "node storage-test.js"
10
+ },
11
+ "dependencies": {},
12
+ "engines": {
13
+ "node": ">=16.0.0"
14
+ },
15
+ "author": "PeerPigeon Contributors",
16
+ "license": "MIT"
17
+ }