peerpigeon 1.0.3 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -1
- package/dist/peerpigeon-browser.js +439 -6
- package/dist/peerpigeon-browser.js.map +3 -3
- package/docs/BINARY_IMPLEMENTATION_SUMMARY.md +304 -0
- package/docs/BINARY_MESSAGES.md +332 -0
- package/docs/STREAMING_API.md +542 -0
- package/docs/STREAMING_IMPLEMENTATION_SUMMARY.md +286 -0
- package/examples/binary-message-demo.html +496 -0
- package/examples/browser-2/EXPRESS_SOLUTION.md +183 -0
- package/examples/browser-2/ICE_DEBUG.md +171 -0
- package/examples/browser-2/IMPLEMENTATION.md +218 -0
- package/examples/browser-2/QUICK_START.md +149 -0
- package/examples/browser-2/README.md +303 -0
- package/examples/browser-2/dist/assets/index-Cck_6WJV.css +1 -0
- package/examples/browser-2/dist/assets/index-D8-cNlWQ.js +57 -0
- package/examples/browser-2/dist/index.html +32 -0
- package/examples/browser-2/dist/peerpigeon-browser.js +12483 -0
- package/examples/browser-2/index.html +2 -1
- package/examples/browser-2/package-lock.json +1276 -0
- package/examples/browser-2/package.json +5 -3
- package/examples/browser-2/public/peerpigeon-browser.js +12483 -0
- package/examples/browser-2/src/App.vue +7 -4
- package/examples/browser-2/src/components/CryptoView.vue +4 -4
- package/examples/browser-2/src/components/TestingView.vue +794 -0
- package/examples/browser-2/src/main.js +7 -1
- package/examples/browser-2/src/router.js +63 -0
- package/examples/browser-2/src/stores/peerpigeon.js +68 -7
- package/examples/browser-2/vite.config.js +15 -1
- package/examples/stream-file-transfer-demo.html +935 -0
- package/package.json +2 -2
- package/src/ConnectionManager.js +30 -0
- package/src/PeerConnection.js +409 -4
- package/src/PeerPigeonMesh.js +120 -1
- package/src/SignalingClient.js +12 -5
- package/src/browser-entry.js +5 -1
package/README.md
CHANGED
|
@@ -19,7 +19,9 @@ PeerPigeon is a production-ready library for building decentralized applications
|
|
|
19
19
|
- **🌐 Network Namespaces** - Isolated peer networks with automatic global fallback
|
|
20
20
|
- **🗄️ Distributed Storage** - Encrypted, CRDT-enabled storage across the mesh
|
|
21
21
|
- **🎥 Selective Streaming** - Efficient audio/video streaming with bandwidth management
|
|
22
|
-
-
|
|
22
|
+
- **📦 Binary Messages** - Native support for efficient binary data transfer (Uint8Array/ArrayBuffer)
|
|
23
|
+
- **� Stream API** - Transfer large files with ReadableStream/WritableStream (memory-efficient, backpressure handling)
|
|
24
|
+
- **�🏢 Hub System** - Connect multiple signaling servers for global peer discovery
|
|
23
25
|
- **🔐 End-to-End Encryption** - Built-in crypto for secure communication
|
|
24
26
|
- **💰 Cost Optimized** - Smart routing reduces server costs by ~95%
|
|
25
27
|
- **📱 Multi-Platform** - Browser, Node.js, NativeScript support
|
|
@@ -78,6 +80,59 @@ See [docs/LOCAL_TESTING.md](docs/LOCAL_TESTING.md) for full details.
|
|
|
78
80
|
|
|
79
81
|
## 📚 Examples
|
|
80
82
|
|
|
83
|
+
### Streaming File Transfer
|
|
84
|
+
|
|
85
|
+
```javascript
|
|
86
|
+
// Send a file using streams (memory-efficient for large files)
|
|
87
|
+
const file = fileInput.files[0];
|
|
88
|
+
await mesh.sendFile(targetPeerId, file);
|
|
89
|
+
|
|
90
|
+
// Receive files
|
|
91
|
+
mesh.on('streamReceived', async (event) => {
|
|
92
|
+
const { stream, metadata } = event;
|
|
93
|
+
console.log(`Receiving ${metadata.filename} (${metadata.totalSize} bytes)`);
|
|
94
|
+
|
|
95
|
+
// Read stream and create blob
|
|
96
|
+
const chunks = [];
|
|
97
|
+
const reader = stream.getReader();
|
|
98
|
+
while (true) {
|
|
99
|
+
const { done, value } = await reader.read();
|
|
100
|
+
if (done) break;
|
|
101
|
+
chunks.push(value);
|
|
102
|
+
}
|
|
103
|
+
const blob = new Blob(chunks, { type: metadata.mimeType });
|
|
104
|
+
|
|
105
|
+
// Download file
|
|
106
|
+
const url = URL.createObjectURL(blob);
|
|
107
|
+
const a = document.createElement('a');
|
|
108
|
+
a.href = url;
|
|
109
|
+
a.download = metadata.filename;
|
|
110
|
+
a.click();
|
|
111
|
+
});
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Binary Messages
|
|
115
|
+
|
|
116
|
+
```javascript
|
|
117
|
+
// Send binary data to specific peer
|
|
118
|
+
const binaryData = new Uint8Array([1, 2, 3, 4, 5]);
|
|
119
|
+
await mesh.sendBinaryData(targetPeerId, binaryData);
|
|
120
|
+
|
|
121
|
+
// Broadcast binary to all peers
|
|
122
|
+
const count = await mesh.broadcastBinaryData(binaryData);
|
|
123
|
+
|
|
124
|
+
// Receive binary messages
|
|
125
|
+
mesh.on('binaryMessageReceived', ({ from, data, size }) => {
|
|
126
|
+
console.log(`Received ${size} bytes from ${from}`);
|
|
127
|
+
// data is Uint8Array
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
// Send files
|
|
131
|
+
const file = fileInput.files[0];
|
|
132
|
+
const buffer = await file.arrayBuffer();
|
|
133
|
+
await mesh.sendBinaryData(peerId, new Uint8Array(buffer));
|
|
134
|
+
```
|
|
135
|
+
|
|
81
136
|
### Distributed Storage
|
|
82
137
|
|
|
83
138
|
```javascript
|
|
@@ -150,6 +205,8 @@ await hub2.start();
|
|
|
150
205
|
### Core Guides
|
|
151
206
|
- **[API Documentation](docs/API_DOCUMENTATION.md)** - Complete API reference
|
|
152
207
|
- **[CLI Guide](docs/CLI_README.md)** - Command-line interface
|
|
208
|
+
- **[Binary Messages](docs/BINARY_MESSAGES.md)** - Efficient binary data transfer
|
|
209
|
+
- **[Streaming API](docs/STREAMING_API.md)** - Large file transfers with ReadableStream/WritableStream
|
|
153
210
|
- **[Network Namespaces](docs/NETWORK_NAMESPACES.md)** - Isolated peer networks
|
|
154
211
|
- **[Selective Streaming](docs/SELECTIVE_STREAMING_GUIDE.md)** - Media streaming optimization
|
|
155
212
|
|
|
@@ -161,6 +218,8 @@ await hub2.start();
|
|
|
161
218
|
|
|
162
219
|
### Examples
|
|
163
220
|
- **[Browser Examples](examples/browser/)** - Web applications
|
|
221
|
+
- **[Binary Message Demo](examples/binary-message-demo.html)** - Interactive binary transfer demo
|
|
222
|
+
- **[Stream File Transfer Demo](examples/stream-file-transfer-demo.html)** - Large file transfer with progress
|
|
164
223
|
- **[Node.js Examples](examples/node/)** - Server-side usage
|
|
165
224
|
- **[NativeScript Examples](examples/nativescript/)** - Mobile apps
|
|
166
225
|
|
|
@@ -4089,6 +4089,7 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4089
4089
|
this.connectionPromise = null;
|
|
4090
4090
|
this.reconnectTimeout = null;
|
|
4091
4091
|
this.isReconnecting = false;
|
|
4092
|
+
this.deliberateDisconnect = false;
|
|
4092
4093
|
}
|
|
4093
4094
|
setConnectionType(type) {
|
|
4094
4095
|
this.debug.log(`WebSocket-only implementation - connection type setting ignored: ${type}`);
|
|
@@ -4226,13 +4227,14 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4226
4227
|
this.connected = false;
|
|
4227
4228
|
this.connectionPromise = null;
|
|
4228
4229
|
this.debug.log("WebSocket closed:", event.code, event.reason);
|
|
4229
|
-
|
|
4230
|
-
|
|
4231
|
-
} else {
|
|
4230
|
+
this.emit("disconnected");
|
|
4231
|
+
if (!this.deliberateDisconnect) {
|
|
4232
4232
|
this.emit("statusChanged", { type: "warning", message: "WebSocket connection lost - reconnecting..." });
|
|
4233
4233
|
if (!this.isReconnecting) {
|
|
4234
4234
|
this.attemptReconnect();
|
|
4235
4235
|
}
|
|
4236
|
+
} else {
|
|
4237
|
+
this.deliberateDisconnect = false;
|
|
4236
4238
|
}
|
|
4237
4239
|
};
|
|
4238
4240
|
this.websocket.onerror = (error) => {
|
|
@@ -4300,6 +4302,7 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4300
4302
|
}, delay);
|
|
4301
4303
|
}
|
|
4302
4304
|
disconnect() {
|
|
4305
|
+
this.deliberateDisconnect = true;
|
|
4303
4306
|
this.isReconnecting = false;
|
|
4304
4307
|
if (this.reconnectTimeout) {
|
|
4305
4308
|
clearTimeout(this.reconnectTimeout);
|
|
@@ -4611,6 +4614,10 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4611
4614
|
this.isClosing = false;
|
|
4612
4615
|
this.iceTimeoutId = null;
|
|
4613
4616
|
this._forcedStatus = null;
|
|
4617
|
+
this._pendingBinaryPayloads = [];
|
|
4618
|
+
this._activeStreams = /* @__PURE__ */ new Map();
|
|
4619
|
+
this._streamChunks = /* @__PURE__ */ new Map();
|
|
4620
|
+
this._streamMetadata = /* @__PURE__ */ new Map();
|
|
4614
4621
|
this.localStream = options.localStream || null;
|
|
4615
4622
|
this.remoteStream = null;
|
|
4616
4623
|
this.enableVideo = options.enableVideo || false;
|
|
@@ -4848,6 +4855,11 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4848
4855
|
};
|
|
4849
4856
|
}
|
|
4850
4857
|
setupDataChannel() {
|
|
4858
|
+
if (!this.dataChannel) {
|
|
4859
|
+
this.debug.error("setupDataChannel called without data channel instance");
|
|
4860
|
+
return;
|
|
4861
|
+
}
|
|
4862
|
+
this.dataChannel.binaryType = "arraybuffer";
|
|
4851
4863
|
this.dataChannel.onopen = () => {
|
|
4852
4864
|
this.debug.log(`Data channel opened with ${this.peerId}`);
|
|
4853
4865
|
this.dataChannelReady = true;
|
|
@@ -4856,13 +4868,60 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4856
4868
|
this.dataChannel.onclose = () => {
|
|
4857
4869
|
this.debug.log(`Data channel closed with ${this.peerId}`);
|
|
4858
4870
|
this.dataChannelReady = false;
|
|
4871
|
+
this._pendingBinaryPayloads.length = 0;
|
|
4859
4872
|
if (!this.isClosing) {
|
|
4860
4873
|
this.emit("disconnected", { peerId: this.peerId, reason: "data channel closed" });
|
|
4861
4874
|
}
|
|
4862
4875
|
};
|
|
4863
4876
|
this.dataChannel.onmessage = (event) => {
|
|
4877
|
+
const handleBinaryPayload = (buffer) => {
|
|
4878
|
+
if (!buffer) return;
|
|
4879
|
+
if (this._pendingBinaryPayloads.length === 0) {
|
|
4880
|
+
this.debug.warn("Received unexpected binary payload without metadata");
|
|
4881
|
+
return;
|
|
4882
|
+
}
|
|
4883
|
+
const payload = this._pendingBinaryPayloads.shift();
|
|
4884
|
+
const uint8Array = new Uint8Array(buffer);
|
|
4885
|
+
if (payload.type === "binaryMessage") {
|
|
4886
|
+
if (payload.size && payload.size !== uint8Array.byteLength) {
|
|
4887
|
+
this.debug.warn(`Binary message size mismatch: expected ${payload.size}, got ${uint8Array.byteLength}`);
|
|
4888
|
+
}
|
|
4889
|
+
this.debug.log(`\u{1F4E6} Received binary message (${uint8Array.byteLength} bytes) from ${this.peerId.substring(0, 8)}...`);
|
|
4890
|
+
this.emit("message", {
|
|
4891
|
+
peerId: this.peerId,
|
|
4892
|
+
message: {
|
|
4893
|
+
type: "binary",
|
|
4894
|
+
data: uint8Array,
|
|
4895
|
+
size: uint8Array.byteLength
|
|
4896
|
+
}
|
|
4897
|
+
});
|
|
4898
|
+
return;
|
|
4899
|
+
}
|
|
4900
|
+
if (payload.type === "streamChunk") {
|
|
4901
|
+
this._handleStreamChunkBinary(payload.header, uint8Array);
|
|
4902
|
+
return;
|
|
4903
|
+
}
|
|
4904
|
+
this.debug.warn(`Received binary payload with unknown handler type: ${payload.type}`);
|
|
4905
|
+
};
|
|
4906
|
+
if (event.data instanceof ArrayBuffer) {
|
|
4907
|
+
handleBinaryPayload(event.data);
|
|
4908
|
+
return;
|
|
4909
|
+
}
|
|
4910
|
+
if (typeof Blob !== "undefined" && event.data instanceof Blob) {
|
|
4911
|
+
event.data.arrayBuffer().then(handleBinaryPayload).catch((error) => this.debug.error("Failed to read binary payload:", error));
|
|
4912
|
+
return;
|
|
4913
|
+
}
|
|
4864
4914
|
try {
|
|
4865
4915
|
const message = JSON.parse(event.data);
|
|
4916
|
+
if (message.type === "__BINARY__") {
|
|
4917
|
+
this._pendingBinaryPayloads.push({ type: "binaryMessage", size: message.size });
|
|
4918
|
+
this.debug.log(`\u{1F4E6} Binary message header received, expecting ${message.size} bytes`);
|
|
4919
|
+
return;
|
|
4920
|
+
}
|
|
4921
|
+
if (message.type && message.type.startsWith("__STREAM_")) {
|
|
4922
|
+
this._handleStreamMessage(message);
|
|
4923
|
+
return;
|
|
4924
|
+
}
|
|
4866
4925
|
this.emit("message", { peerId: this.peerId, message });
|
|
4867
4926
|
} catch (error) {
|
|
4868
4927
|
this.debug.error("Failed to parse message:", error);
|
|
@@ -4872,6 +4931,7 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4872
4931
|
this.dataChannel.onerror = (error) => {
|
|
4873
4932
|
this.debug.error(`Data channel error with ${this.peerId}:`, error);
|
|
4874
4933
|
this.dataChannelReady = false;
|
|
4934
|
+
this._pendingBinaryPayloads.length = 0;
|
|
4875
4935
|
if (!this.isClosing) {
|
|
4876
4936
|
this.emit("disconnected", { peerId: this.peerId, reason: "data channel error" });
|
|
4877
4937
|
}
|
|
@@ -5095,8 +5155,17 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
5095
5155
|
sendMessage(message) {
|
|
5096
5156
|
if (this.dataChannel && this.dataChannel.readyState === "open") {
|
|
5097
5157
|
try {
|
|
5098
|
-
|
|
5099
|
-
|
|
5158
|
+
if (message instanceof ArrayBuffer || ArrayBuffer.isView(message)) {
|
|
5159
|
+
this.debug.log(`\u{1F4E6} Sending binary message (${message.byteLength || message.buffer.byteLength} bytes) to ${this.peerId.substring(0, 8)}...`);
|
|
5160
|
+
const buffer = ArrayBuffer.isView(message) ? message.buffer : message;
|
|
5161
|
+
const header = JSON.stringify({ type: "__BINARY__", size: buffer.byteLength });
|
|
5162
|
+
this.dataChannel.send(header);
|
|
5163
|
+
this.dataChannel.send(buffer);
|
|
5164
|
+
return true;
|
|
5165
|
+
} else {
|
|
5166
|
+
this.dataChannel.send(JSON.stringify(message));
|
|
5167
|
+
return true;
|
|
5168
|
+
}
|
|
5100
5169
|
} catch (error) {
|
|
5101
5170
|
this.debug.error(`Failed to send message to ${this.peerId}:`, error);
|
|
5102
5171
|
return false;
|
|
@@ -5104,6 +5173,246 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
5104
5173
|
}
|
|
5105
5174
|
return false;
|
|
5106
5175
|
}
|
|
5176
|
+
/**
|
|
5177
|
+
* Create a WritableStream for sending data to this peer
|
|
5178
|
+
* @param {object} options - Stream options
|
|
5179
|
+
* @returns {WritableStream} A writable stream for sending data
|
|
5180
|
+
*/
|
|
5181
|
+
createWritableStream(options = {}) {
|
|
5182
|
+
const streamId = options.streamId || this._generateStreamId();
|
|
5183
|
+
const metadata = {
|
|
5184
|
+
streamId,
|
|
5185
|
+
type: options.type || "binary",
|
|
5186
|
+
filename: options.filename,
|
|
5187
|
+
mimeType: options.mimeType,
|
|
5188
|
+
totalSize: options.totalSize,
|
|
5189
|
+
chunkSize: options.chunkSize,
|
|
5190
|
+
timestamp: Date.now()
|
|
5191
|
+
};
|
|
5192
|
+
this.debug.log(`\u{1F4E4} Creating writable stream ${streamId} to ${this.peerId.substring(0, 8)}...`);
|
|
5193
|
+
const configuredChunkSize = typeof metadata.chunkSize === "number" && Number.isFinite(metadata.chunkSize) ? metadata.chunkSize : 16384;
|
|
5194
|
+
const chunkSize = Math.max(4096, Math.min(configuredChunkSize, 65536));
|
|
5195
|
+
metadata.chunkSize = chunkSize;
|
|
5196
|
+
const highWaterMark = chunkSize * 32;
|
|
5197
|
+
const lowWaterMark = chunkSize * 8;
|
|
5198
|
+
const ensureChannelOpen = () => {
|
|
5199
|
+
if (!this.dataChannel || this.dataChannel.readyState !== "open") {
|
|
5200
|
+
throw new Error("Data channel not open");
|
|
5201
|
+
}
|
|
5202
|
+
};
|
|
5203
|
+
const waitForBufferDrain = () => {
|
|
5204
|
+
if (!this.dataChannel || this.dataChannel.readyState !== "open") {
|
|
5205
|
+
return Promise.resolve();
|
|
5206
|
+
}
|
|
5207
|
+
if (this.dataChannel.bufferedAmount <= lowWaterMark) {
|
|
5208
|
+
return Promise.resolve();
|
|
5209
|
+
}
|
|
5210
|
+
return new Promise((resolve) => {
|
|
5211
|
+
const checkBuffer = () => {
|
|
5212
|
+
if (!this.dataChannel || this.dataChannel.readyState !== "open") {
|
|
5213
|
+
resolve();
|
|
5214
|
+
return;
|
|
5215
|
+
}
|
|
5216
|
+
if (this.dataChannel.bufferedAmount <= lowWaterMark) {
|
|
5217
|
+
resolve();
|
|
5218
|
+
} else {
|
|
5219
|
+
setTimeout(checkBuffer, 20);
|
|
5220
|
+
}
|
|
5221
|
+
};
|
|
5222
|
+
checkBuffer();
|
|
5223
|
+
});
|
|
5224
|
+
};
|
|
5225
|
+
this.sendMessage({
|
|
5226
|
+
type: "__STREAM_INIT__",
|
|
5227
|
+
streamId,
|
|
5228
|
+
metadata
|
|
5229
|
+
});
|
|
5230
|
+
let chunkIndex = 0;
|
|
5231
|
+
const self2 = this;
|
|
5232
|
+
return new WritableStream({
|
|
5233
|
+
async write(chunk) {
|
|
5234
|
+
ensureChannelOpen();
|
|
5235
|
+
const data = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
|
|
5236
|
+
let offset = 0;
|
|
5237
|
+
while (offset < data.byteLength) {
|
|
5238
|
+
ensureChannelOpen();
|
|
5239
|
+
const sliceEnd = Math.min(offset + chunkSize, data.byteLength);
|
|
5240
|
+
const slice = data.subarray(offset, sliceEnd);
|
|
5241
|
+
const sliceBuffer = slice.byteOffset === 0 && slice.byteLength === slice.buffer.byteLength ? slice.buffer : slice.buffer.slice(slice.byteOffset, slice.byteOffset + slice.byteLength);
|
|
5242
|
+
const chunkMessage = {
|
|
5243
|
+
type: "__STREAM_CHUNK__",
|
|
5244
|
+
streamId,
|
|
5245
|
+
chunkIndex: chunkIndex++,
|
|
5246
|
+
size: slice.byteLength,
|
|
5247
|
+
encoding: "binary"
|
|
5248
|
+
};
|
|
5249
|
+
try {
|
|
5250
|
+
self2.dataChannel.send(JSON.stringify(chunkMessage));
|
|
5251
|
+
self2.dataChannel.send(sliceBuffer);
|
|
5252
|
+
} catch (error) {
|
|
5253
|
+
throw error;
|
|
5254
|
+
}
|
|
5255
|
+
offset = sliceEnd;
|
|
5256
|
+
if (self2.dataChannel && self2.dataChannel.bufferedAmount > highWaterMark) {
|
|
5257
|
+
await waitForBufferDrain();
|
|
5258
|
+
}
|
|
5259
|
+
}
|
|
5260
|
+
},
|
|
5261
|
+
async close() {
|
|
5262
|
+
if (self2.dataChannel && self2.dataChannel.readyState === "open") {
|
|
5263
|
+
await waitForBufferDrain();
|
|
5264
|
+
self2.sendMessage({
|
|
5265
|
+
type: "__STREAM_END__",
|
|
5266
|
+
streamId,
|
|
5267
|
+
totalChunks: chunkIndex
|
|
5268
|
+
});
|
|
5269
|
+
}
|
|
5270
|
+
self2._activeStreams.delete(streamId);
|
|
5271
|
+
self2.debug.log(`\u{1F4E4} Closed writable stream ${streamId}`);
|
|
5272
|
+
},
|
|
5273
|
+
async abort(reason) {
|
|
5274
|
+
if (self2.dataChannel && self2.dataChannel.readyState === "open") {
|
|
5275
|
+
self2.sendMessage({
|
|
5276
|
+
type: "__STREAM_ABORT__",
|
|
5277
|
+
streamId,
|
|
5278
|
+
reason: reason?.message || "Stream aborted"
|
|
5279
|
+
});
|
|
5280
|
+
}
|
|
5281
|
+
self2._activeStreams.delete(streamId);
|
|
5282
|
+
self2.debug.log(`\u274C Aborted writable stream ${streamId}: ${reason}`);
|
|
5283
|
+
}
|
|
5284
|
+
});
|
|
5285
|
+
}
|
|
5286
|
+
/**
|
|
5287
|
+
* Handle incoming stream messages and create ReadableStream
|
|
5288
|
+
* @private
|
|
5289
|
+
*/
|
|
5290
|
+
_handleStreamMessage(message) {
|
|
5291
|
+
const { type } = message;
|
|
5292
|
+
switch (type) {
|
|
5293
|
+
case "__STREAM_INIT__":
|
|
5294
|
+
this._handleStreamInit(message);
|
|
5295
|
+
break;
|
|
5296
|
+
case "__STREAM_CHUNK__":
|
|
5297
|
+
if (message.encoding === "binary") {
|
|
5298
|
+
this._pendingBinaryPayloads.push({
|
|
5299
|
+
type: "streamChunk",
|
|
5300
|
+
header: message
|
|
5301
|
+
});
|
|
5302
|
+
} else {
|
|
5303
|
+
this._handleStreamChunkLegacy(message);
|
|
5304
|
+
}
|
|
5305
|
+
break;
|
|
5306
|
+
case "__STREAM_END__":
|
|
5307
|
+
this._handleStreamEnd(message);
|
|
5308
|
+
break;
|
|
5309
|
+
case "__STREAM_ABORT__":
|
|
5310
|
+
this._handleStreamAbort(message);
|
|
5311
|
+
break;
|
|
5312
|
+
}
|
|
5313
|
+
}
|
|
5314
|
+
_handleStreamInit(message) {
|
|
5315
|
+
const { streamId, metadata } = message;
|
|
5316
|
+
this.debug.log(`\u{1F4E5} Receiving stream ${streamId} from ${this.peerId.substring(0, 8)}...`);
|
|
5317
|
+
this._streamMetadata.set(streamId, metadata);
|
|
5318
|
+
this._streamChunks.set(streamId, []);
|
|
5319
|
+
const chunks = this._streamChunks.get(streamId);
|
|
5320
|
+
let controller;
|
|
5321
|
+
const readable = new ReadableStream({
|
|
5322
|
+
start(ctrl) {
|
|
5323
|
+
controller = ctrl;
|
|
5324
|
+
},
|
|
5325
|
+
cancel: (reason) => {
|
|
5326
|
+
this.debug.log(`\u{1F4E5} Stream ${streamId} cancelled: ${reason}`);
|
|
5327
|
+
}
|
|
5328
|
+
});
|
|
5329
|
+
this._activeStreams.set(streamId, {
|
|
5330
|
+
type: "readable",
|
|
5331
|
+
stream: readable,
|
|
5332
|
+
controller,
|
|
5333
|
+
metadata,
|
|
5334
|
+
chunks
|
|
5335
|
+
});
|
|
5336
|
+
this.emit("streamReceived", {
|
|
5337
|
+
peerId: this.peerId,
|
|
5338
|
+
streamId,
|
|
5339
|
+
stream: readable,
|
|
5340
|
+
metadata
|
|
5341
|
+
});
|
|
5342
|
+
}
|
|
5343
|
+
_handleStreamChunkLegacy(message) {
|
|
5344
|
+
const { streamId, chunkIndex, data } = message;
|
|
5345
|
+
const streamData = this._activeStreams.get(streamId);
|
|
5346
|
+
if (!streamData) {
|
|
5347
|
+
this.debug.warn(`Received chunk for unknown stream ${streamId}`);
|
|
5348
|
+
return;
|
|
5349
|
+
}
|
|
5350
|
+
const chunk = new Uint8Array(data);
|
|
5351
|
+
if (streamData.controller) {
|
|
5352
|
+
streamData.controller.enqueue(chunk);
|
|
5353
|
+
}
|
|
5354
|
+
if (Array.isArray(streamData.chunks)) {
|
|
5355
|
+
streamData.chunks.push(chunk);
|
|
5356
|
+
}
|
|
5357
|
+
this.debug.log(`\u{1F4E5} Received chunk ${chunkIndex} for stream ${streamId} (${chunk.length} bytes)`);
|
|
5358
|
+
}
|
|
5359
|
+
_handleStreamChunkBinary(header, chunk) {
|
|
5360
|
+
const { streamId, chunkIndex, size } = header;
|
|
5361
|
+
const streamData = this._activeStreams.get(streamId);
|
|
5362
|
+
if (!streamData) {
|
|
5363
|
+
this.debug.warn(`Received binary chunk for unknown stream ${streamId}`);
|
|
5364
|
+
return;
|
|
5365
|
+
}
|
|
5366
|
+
if (size && size !== chunk.byteLength) {
|
|
5367
|
+
this.debug.warn(`Stream ${streamId} chunk ${chunkIndex} size mismatch: expected ${size}, got ${chunk.byteLength}`);
|
|
5368
|
+
}
|
|
5369
|
+
if (streamData.controller) {
|
|
5370
|
+
streamData.controller.enqueue(chunk);
|
|
5371
|
+
}
|
|
5372
|
+
if (Array.isArray(streamData.chunks)) {
|
|
5373
|
+
streamData.chunks.push(chunk);
|
|
5374
|
+
}
|
|
5375
|
+
this.debug.log(`\u{1F4E5} Received chunk ${chunkIndex} for stream ${streamId} (${chunk.byteLength} bytes)`);
|
|
5376
|
+
}
|
|
5377
|
+
_handleStreamEnd(message) {
|
|
5378
|
+
const { streamId, totalChunks } = message;
|
|
5379
|
+
const streamData = this._activeStreams.get(streamId);
|
|
5380
|
+
if (!streamData) {
|
|
5381
|
+
this.debug.warn(`Received end for unknown stream ${streamId}`);
|
|
5382
|
+
return;
|
|
5383
|
+
}
|
|
5384
|
+
if (streamData.controller) {
|
|
5385
|
+
streamData.controller.close();
|
|
5386
|
+
}
|
|
5387
|
+
this.debug.log(`\u{1F4E5} Stream ${streamId} completed (${totalChunks} chunks)`);
|
|
5388
|
+
this._activeStreams.delete(streamId);
|
|
5389
|
+
this._streamChunks.delete(streamId);
|
|
5390
|
+
this._streamMetadata.delete(streamId);
|
|
5391
|
+
this.emit("streamCompleted", {
|
|
5392
|
+
peerId: this.peerId,
|
|
5393
|
+
streamId,
|
|
5394
|
+
totalChunks
|
|
5395
|
+
});
|
|
5396
|
+
}
|
|
5397
|
+
_handleStreamAbort(message) {
|
|
5398
|
+
const { streamId, reason } = message;
|
|
5399
|
+
const streamData = this._activeStreams.get(streamId);
|
|
5400
|
+
if (streamData && streamData.controller) {
|
|
5401
|
+
streamData.controller.error(new Error(reason));
|
|
5402
|
+
}
|
|
5403
|
+
this.debug.log(`\u274C Stream ${streamId} aborted: ${reason}`);
|
|
5404
|
+
this._activeStreams.delete(streamId);
|
|
5405
|
+
this._streamChunks.delete(streamId);
|
|
5406
|
+
this._streamMetadata.delete(streamId);
|
|
5407
|
+
this.emit("streamAborted", {
|
|
5408
|
+
peerId: this.peerId,
|
|
5409
|
+
streamId,
|
|
5410
|
+
reason
|
|
5411
|
+
});
|
|
5412
|
+
}
|
|
5413
|
+
_generateStreamId() {
|
|
5414
|
+
return `stream-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
5415
|
+
}
|
|
5107
5416
|
/**
|
|
5108
5417
|
* CRITICAL FIX: Manually check for new remote tracks after renegotiation
|
|
5109
5418
|
* This is needed because replaceTrack() doesn't trigger ontrack events
|
|
@@ -5927,6 +6236,18 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
5927
6236
|
this.emit("remoteStream", event);
|
|
5928
6237
|
this.debug.log("\u{1F504} MEDIA FORWARDING: Disabled to prevent renegotiation conflicts with 3+ peers");
|
|
5929
6238
|
});
|
|
6239
|
+
peerConnection.addEventListener("streamReceived", (event) => {
|
|
6240
|
+
this.debug.log(`[EVENT] Data stream received from ${event.peerId.substring(0, 8)}...`);
|
|
6241
|
+
this.mesh.emit("streamReceived", event);
|
|
6242
|
+
});
|
|
6243
|
+
peerConnection.addEventListener("streamCompleted", (event) => {
|
|
6244
|
+
this.debug.log(`[EVENT] Data stream completed from ${event.peerId.substring(0, 8)}...`);
|
|
6245
|
+
this.mesh.emit("streamCompleted", event);
|
|
6246
|
+
});
|
|
6247
|
+
peerConnection.addEventListener("streamAborted", (event) => {
|
|
6248
|
+
this.debug.log(`[EVENT] Data stream aborted from ${event.peerId.substring(0, 8)}...`);
|
|
6249
|
+
this.mesh.emit("streamAborted", event);
|
|
6250
|
+
});
|
|
5930
6251
|
peerConnection.addEventListener("renegotiationNeeded", async (event) => {
|
|
5931
6252
|
this.debug.log(`\u{1F504} Renegotiation needed for ${event.peerId.substring(0, 8)}...`);
|
|
5932
6253
|
if (this.activeRenegotiations.size >= this.maxConcurrentRenegotiations) {
|
|
@@ -6284,6 +6605,16 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
6284
6605
|
this.debug.warn("Received invalid message from", fromPeerId?.substring(0, 8));
|
|
6285
6606
|
return;
|
|
6286
6607
|
}
|
|
6608
|
+
if (message.type === "binary" && message.data instanceof Uint8Array) {
|
|
6609
|
+
this.debug.log(`\u{1F4E6} Received binary message (${message.size} bytes) from ${fromPeerId.substring(0, 8)}...`);
|
|
6610
|
+
this.mesh.emit("binaryMessageReceived", {
|
|
6611
|
+
from: fromPeerId,
|
|
6612
|
+
data: message.data,
|
|
6613
|
+
size: message.size,
|
|
6614
|
+
timestamp: Date.now()
|
|
6615
|
+
});
|
|
6616
|
+
return;
|
|
6617
|
+
}
|
|
6287
6618
|
const filteredMessageTypes = /* @__PURE__ */ new Set([
|
|
6288
6619
|
"signaling-relay",
|
|
6289
6620
|
"peer-announce-relay",
|
|
@@ -11221,7 +11552,6 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
11221
11552
|
this.connected = false;
|
|
11222
11553
|
this.polling = false;
|
|
11223
11554
|
this.peerDiscovery.stop();
|
|
11224
|
-
this.connectionManager.disconnectAllPeers();
|
|
11225
11555
|
this.emit("statusChanged", { type: "disconnected" });
|
|
11226
11556
|
});
|
|
11227
11557
|
this.signalingClient.addEventListener("signalingMessage", (message) => {
|
|
@@ -11509,6 +11839,108 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
11509
11839
|
async sendMessage(content) {
|
|
11510
11840
|
return await this.gossipManager.broadcastMessage(content, "chat");
|
|
11511
11841
|
}
|
|
11842
|
+
/**
|
|
11843
|
+
* Send binary data to a specific peer
|
|
11844
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
11845
|
+
* @param {Uint8Array|ArrayBuffer} binaryData - The binary data to send
|
|
11846
|
+
* @returns {boolean} True if sent successfully
|
|
11847
|
+
*/
|
|
11848
|
+
async sendBinaryData(targetPeerId, binaryData) {
|
|
11849
|
+
if (!targetPeerId || typeof targetPeerId !== "string") {
|
|
11850
|
+
this.debug.error("Invalid targetPeerId for binary message");
|
|
11851
|
+
return false;
|
|
11852
|
+
}
|
|
11853
|
+
const peerConnection = this.connectionManager.peers.get(targetPeerId);
|
|
11854
|
+
if (!peerConnection) {
|
|
11855
|
+
this.debug.error(`No connection to peer ${targetPeerId.substring(0, 8)}...`);
|
|
11856
|
+
return false;
|
|
11857
|
+
}
|
|
11858
|
+
return peerConnection.sendMessage(binaryData);
|
|
11859
|
+
}
|
|
11860
|
+
/**
|
|
11861
|
+
* Broadcast binary data to all connected peers
|
|
11862
|
+
* @param {Uint8Array|ArrayBuffer} binaryData - The binary data to broadcast
|
|
11863
|
+
* @returns {number} Number of peers the data was sent to
|
|
11864
|
+
*/
|
|
11865
|
+
async broadcastBinaryData(binaryData) {
|
|
11866
|
+
const peers = this.getConnectedPeers();
|
|
11867
|
+
let sentCount = 0;
|
|
11868
|
+
for (const peer of peers) {
|
|
11869
|
+
if (await this.sendBinaryData(peer.peerId, binaryData)) {
|
|
11870
|
+
sentCount++;
|
|
11871
|
+
}
|
|
11872
|
+
}
|
|
11873
|
+
this.debug.log(`\u{1F4E6} Binary data broadcasted to ${sentCount}/${peers.length} peers`);
|
|
11874
|
+
return sentCount;
|
|
11875
|
+
}
|
|
11876
|
+
/**
|
|
11877
|
+
* Create a writable stream to send data to a specific peer
|
|
11878
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
11879
|
+
* @param {object} options - Stream options (filename, mimeType, totalSize, etc.)
|
|
11880
|
+
* @returns {WritableStream} A writable stream
|
|
11881
|
+
*/
|
|
11882
|
+
createStreamToPeer(targetPeerId, options = {}) {
|
|
11883
|
+
if (!targetPeerId || typeof targetPeerId !== "string") {
|
|
11884
|
+
throw new Error("Invalid targetPeerId for stream");
|
|
11885
|
+
}
|
|
11886
|
+
const peerConnection = this.connectionManager.peers.get(targetPeerId);
|
|
11887
|
+
if (!peerConnection) {
|
|
11888
|
+
throw new Error(`No connection to peer ${targetPeerId.substring(0, 8)}...`);
|
|
11889
|
+
}
|
|
11890
|
+
return peerConnection.createWritableStream(options);
|
|
11891
|
+
}
|
|
11892
|
+
/**
|
|
11893
|
+
* Send a ReadableStream to a peer
|
|
11894
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
11895
|
+
* @param {ReadableStream} readableStream - The stream to send
|
|
11896
|
+
* @param {object} options - Stream options (filename, mimeType, etc.)
|
|
11897
|
+
* @returns {Promise<void>}
|
|
11898
|
+
*/
|
|
11899
|
+
async sendStream(targetPeerId, readableStream, options = {}) {
|
|
11900
|
+
const writableStream = this.createStreamToPeer(targetPeerId, options);
|
|
11901
|
+
try {
|
|
11902
|
+
await readableStream.pipeTo(writableStream);
|
|
11903
|
+
this.debug.log(`\u2705 Stream sent successfully to ${targetPeerId.substring(0, 8)}...`);
|
|
11904
|
+
} catch (error) {
|
|
11905
|
+
this.debug.error(`\u274C Failed to send stream to ${targetPeerId.substring(0, 8)}...:`, error);
|
|
11906
|
+
throw error;
|
|
11907
|
+
}
|
|
11908
|
+
}
|
|
11909
|
+
/**
|
|
11910
|
+
* Send a File to a peer using streams
|
|
11911
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
11912
|
+
* @param {File} file - The file to send
|
|
11913
|
+
* @returns {Promise<void>}
|
|
11914
|
+
*/
|
|
11915
|
+
async sendFile(targetPeerId, file) {
|
|
11916
|
+
this.debug.log(`\u{1F4C1} Sending file "${file.name}" (${file.size} bytes) to ${targetPeerId.substring(0, 8)}...`);
|
|
11917
|
+
const options = {
|
|
11918
|
+
filename: file.name,
|
|
11919
|
+
mimeType: file.type,
|
|
11920
|
+
totalSize: file.size,
|
|
11921
|
+
type: "file"
|
|
11922
|
+
};
|
|
11923
|
+
const stream = file.stream();
|
|
11924
|
+
await this.sendStream(targetPeerId, stream, options);
|
|
11925
|
+
}
|
|
11926
|
+
/**
|
|
11927
|
+
* Send a Blob to a peer using streams
|
|
11928
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
11929
|
+
* @param {Blob} blob - The blob to send
|
|
11930
|
+
* @param {object} options - Additional options
|
|
11931
|
+
* @returns {Promise<void>}
|
|
11932
|
+
*/
|
|
11933
|
+
async sendBlob(targetPeerId, blob, options = {}) {
|
|
11934
|
+
this.debug.log(`\u{1F4E6} Sending blob (${blob.size} bytes) to ${targetPeerId.substring(0, 8)}...`);
|
|
11935
|
+
const streamOptions = {
|
|
11936
|
+
...options,
|
|
11937
|
+
mimeType: blob.type,
|
|
11938
|
+
totalSize: blob.size,
|
|
11939
|
+
type: "blob"
|
|
11940
|
+
};
|
|
11941
|
+
const stream = blob.stream();
|
|
11942
|
+
await this.sendStream(targetPeerId, stream, streamOptions);
|
|
11943
|
+
}
|
|
11512
11944
|
// Helper methods for backward compatibility
|
|
11513
11945
|
canAcceptMorePeers() {
|
|
11514
11946
|
return this.connectionManager.canAcceptMorePeers();
|
|
@@ -12470,6 +12902,7 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
12470
12902
|
RTCAdapter,
|
|
12471
12903
|
default: createPigeonRTC
|
|
12472
12904
|
};
|
|
12905
|
+
window.PeerPigeonMesh = PeerPigeonMesh;
|
|
12473
12906
|
}
|
|
12474
12907
|
console.log("\u{1F510} PeerPigeon browser bundle loaded with embedded UnSEA crypto and PigeonRTC");
|
|
12475
12908
|
return __toCommonJS(browser_entry_exports);
|