peerpigeon 1.0.4 → 1.0.7
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 +800 -36
- 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/BROADCAST_STREAMING.md +388 -0
- package/docs/PEER_DISCOVERY_FIXES.md +140 -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/broadcast-stream-demo.html +539 -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 +1 -1
- package/server/index.js +175 -38
- package/src/ConnectionManager.js +68 -8
- package/src/GossipManager.js +22 -0
- package/src/PeerConnection.js +421 -11
- package/src/PeerDiscovery.js +33 -18
- package/src/PeerPigeonMesh.js +453 -1
- package/src/SignalingClient.js +12 -5
- package/src/SignalingHandler.js +18 -5
- package/src/browser-entry.js +5 -1
|
@@ -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);
|
|
@@ -4394,20 +4397,37 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4394
4397
|
this.connectionAttempts.clear();
|
|
4395
4398
|
}
|
|
4396
4399
|
addDiscoveredPeer(peerId) {
|
|
4397
|
-
|
|
4398
|
-
|
|
4399
|
-
|
|
4400
|
+
const wasKnown = this.discoveredPeers.has(peerId);
|
|
4401
|
+
const now = Date.now();
|
|
4402
|
+
this.discoveredPeers.set(peerId, now);
|
|
4403
|
+
if (wasKnown) {
|
|
4404
|
+
this.debug.log(`Re-discovered peer ${peerId.substring(0, 8)}... (updating timestamp)`);
|
|
4405
|
+
if (this.connectionAttempts.has(peerId)) {
|
|
4406
|
+
const attemptTime = this.connectionAttempts.get(peerId);
|
|
4407
|
+
if (now - attemptTime > 5e3) {
|
|
4408
|
+
this.debug.log(`Clearing stale connection attempt for ${peerId.substring(0, 8)}...`);
|
|
4409
|
+
this.connectionAttempts.delete(peerId);
|
|
4410
|
+
}
|
|
4411
|
+
}
|
|
4412
|
+
} else {
|
|
4413
|
+
this.debug.log(`Discovered new peer ${peerId.substring(0, 8)}...`);
|
|
4414
|
+
this.emit("peerDiscovered", { peerId });
|
|
4400
4415
|
}
|
|
4401
|
-
this.
|
|
4402
|
-
this.
|
|
4403
|
-
this.
|
|
4404
|
-
|
|
4405
|
-
this.debug.log(`Considering connection to ${peerId.substring(0, 8)}...`);
|
|
4416
|
+
const alreadyTrying = this.connectionAttempts.has(peerId);
|
|
4417
|
+
const shouldInitiate = this.shouldInitiateConnection(peerId);
|
|
4418
|
+
if (this.autoDiscovery && shouldInitiate && !alreadyTrying) {
|
|
4419
|
+
this.debug.log(`Considering connection to ${peerId.substring(0, 8)}... (shouldInitiate: ${shouldInitiate}, alreadyTrying: ${alreadyTrying})`);
|
|
4406
4420
|
const canAccept = this.canAcceptMorePeers();
|
|
4407
4421
|
if (canAccept) {
|
|
4408
|
-
this.debug.log(
|
|
4422
|
+
this.debug.log(`\u{1F517} Initiating connection to ${peerId.substring(0, 8)}...`);
|
|
4409
4423
|
this.emit("connectToPeer", { peerId });
|
|
4424
|
+
} else {
|
|
4425
|
+
this.debug.log(`Cannot connect to ${peerId.substring(0, 8)}... (at max peers)`);
|
|
4410
4426
|
}
|
|
4427
|
+
} else if (alreadyTrying) {
|
|
4428
|
+
this.debug.log(`Already attempting connection to ${peerId.substring(0, 8)}...`);
|
|
4429
|
+
} else if (!shouldInitiate) {
|
|
4430
|
+
this.debug.log(`Not initiating to ${peerId.substring(0, 8)}... (should wait for them to initiate)`);
|
|
4411
4431
|
}
|
|
4412
4432
|
this.scheduleMeshOptimization();
|
|
4413
4433
|
}
|
|
@@ -4436,9 +4456,6 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4436
4456
|
return distance;
|
|
4437
4457
|
}
|
|
4438
4458
|
shouldInitiateConnection(targetPeerId) {
|
|
4439
|
-
if (this.connectionAttempts.has(targetPeerId)) {
|
|
4440
|
-
return false;
|
|
4441
|
-
}
|
|
4442
4459
|
this.emit("checkCapacity");
|
|
4443
4460
|
const currentConnectionCount = this._currentConnectionCount || 0;
|
|
4444
4461
|
const lexicographicShouldInitiate = this.peerId > targetPeerId;
|
|
@@ -4611,6 +4628,10 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4611
4628
|
this.isClosing = false;
|
|
4612
4629
|
this.iceTimeoutId = null;
|
|
4613
4630
|
this._forcedStatus = null;
|
|
4631
|
+
this._pendingBinaryPayloads = [];
|
|
4632
|
+
this._activeStreams = /* @__PURE__ */ new Map();
|
|
4633
|
+
this._streamChunks = /* @__PURE__ */ new Map();
|
|
4634
|
+
this._streamMetadata = /* @__PURE__ */ new Map();
|
|
4614
4635
|
this.localStream = options.localStream || null;
|
|
4615
4636
|
this.remoteStream = null;
|
|
4616
4637
|
this.enableVideo = options.enableVideo || false;
|
|
@@ -4805,19 +4826,18 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4805
4826
|
const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
|
|
4806
4827
|
const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
|
|
4807
4828
|
if (hasSignaling || hasMeshConnectivity) {
|
|
4808
|
-
this.debug.log(`\
|
|
4829
|
+
this.debug.log(`\u26A0\uFE0F ICE remained disconnected for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
|
|
4809
4830
|
try {
|
|
4810
4831
|
this.restartIceViaSignaling().catch((error) => {
|
|
4811
4832
|
this.debug.error("Failed to restart ICE after disconnection:", error);
|
|
4812
|
-
this.
|
|
4833
|
+
this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
|
|
4813
4834
|
});
|
|
4814
4835
|
} catch (error) {
|
|
4815
4836
|
this.debug.error("Failed to restart ICE after disconnection:", error);
|
|
4816
|
-
this.
|
|
4837
|
+
this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
|
|
4817
4838
|
}
|
|
4818
4839
|
} else {
|
|
4819
|
-
this.debug.log(`\
|
|
4820
|
-
this.emit("disconnected", { peerId: this.peerId, reason: "ICE disconnected" });
|
|
4840
|
+
this.debug.log(`\u26A0\uFE0F ICE disconnected for ${this.peerId} without signaling - waiting for ICE state to resolve naturally`);
|
|
4821
4841
|
}
|
|
4822
4842
|
}
|
|
4823
4843
|
}, 5e3);
|
|
@@ -4848,6 +4868,11 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4848
4868
|
};
|
|
4849
4869
|
}
|
|
4850
4870
|
setupDataChannel() {
|
|
4871
|
+
if (!this.dataChannel) {
|
|
4872
|
+
this.debug.error("setupDataChannel called without data channel instance");
|
|
4873
|
+
return;
|
|
4874
|
+
}
|
|
4875
|
+
this.dataChannel.binaryType = "arraybuffer";
|
|
4851
4876
|
this.dataChannel.onopen = () => {
|
|
4852
4877
|
this.debug.log(`Data channel opened with ${this.peerId}`);
|
|
4853
4878
|
this.dataChannelReady = true;
|
|
@@ -4856,13 +4881,60 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4856
4881
|
this.dataChannel.onclose = () => {
|
|
4857
4882
|
this.debug.log(`Data channel closed with ${this.peerId}`);
|
|
4858
4883
|
this.dataChannelReady = false;
|
|
4884
|
+
this._pendingBinaryPayloads.length = 0;
|
|
4859
4885
|
if (!this.isClosing) {
|
|
4860
4886
|
this.emit("disconnected", { peerId: this.peerId, reason: "data channel closed" });
|
|
4861
4887
|
}
|
|
4862
4888
|
};
|
|
4863
4889
|
this.dataChannel.onmessage = (event) => {
|
|
4890
|
+
const handleBinaryPayload = (buffer) => {
|
|
4891
|
+
if (!buffer) return;
|
|
4892
|
+
if (this._pendingBinaryPayloads.length === 0) {
|
|
4893
|
+
this.debug.warn("Received unexpected binary payload without metadata");
|
|
4894
|
+
return;
|
|
4895
|
+
}
|
|
4896
|
+
const payload = this._pendingBinaryPayloads.shift();
|
|
4897
|
+
const uint8Array = new Uint8Array(buffer);
|
|
4898
|
+
if (payload.type === "binaryMessage") {
|
|
4899
|
+
if (payload.size && payload.size !== uint8Array.byteLength) {
|
|
4900
|
+
this.debug.warn(`Binary message size mismatch: expected ${payload.size}, got ${uint8Array.byteLength}`);
|
|
4901
|
+
}
|
|
4902
|
+
this.debug.log(`\u{1F4E6} Received binary message (${uint8Array.byteLength} bytes) from ${this.peerId.substring(0, 8)}...`);
|
|
4903
|
+
this.emit("message", {
|
|
4904
|
+
peerId: this.peerId,
|
|
4905
|
+
message: {
|
|
4906
|
+
type: "binary",
|
|
4907
|
+
data: uint8Array,
|
|
4908
|
+
size: uint8Array.byteLength
|
|
4909
|
+
}
|
|
4910
|
+
});
|
|
4911
|
+
return;
|
|
4912
|
+
}
|
|
4913
|
+
if (payload.type === "streamChunk") {
|
|
4914
|
+
this._handleStreamChunkBinary(payload.header, uint8Array);
|
|
4915
|
+
return;
|
|
4916
|
+
}
|
|
4917
|
+
this.debug.warn(`Received binary payload with unknown handler type: ${payload.type}`);
|
|
4918
|
+
};
|
|
4919
|
+
if (event.data instanceof ArrayBuffer) {
|
|
4920
|
+
handleBinaryPayload(event.data);
|
|
4921
|
+
return;
|
|
4922
|
+
}
|
|
4923
|
+
if (typeof Blob !== "undefined" && event.data instanceof Blob) {
|
|
4924
|
+
event.data.arrayBuffer().then(handleBinaryPayload).catch((error) => this.debug.error("Failed to read binary payload:", error));
|
|
4925
|
+
return;
|
|
4926
|
+
}
|
|
4864
4927
|
try {
|
|
4865
4928
|
const message = JSON.parse(event.data);
|
|
4929
|
+
if (message.type === "__BINARY__") {
|
|
4930
|
+
this._pendingBinaryPayloads.push({ type: "binaryMessage", size: message.size });
|
|
4931
|
+
this.debug.log(`\u{1F4E6} Binary message header received, expecting ${message.size} bytes`);
|
|
4932
|
+
return;
|
|
4933
|
+
}
|
|
4934
|
+
if (message.type && message.type.startsWith("__STREAM_")) {
|
|
4935
|
+
this._handleStreamMessage(message);
|
|
4936
|
+
return;
|
|
4937
|
+
}
|
|
4866
4938
|
this.emit("message", { peerId: this.peerId, message });
|
|
4867
4939
|
} catch (error) {
|
|
4868
4940
|
this.debug.error("Failed to parse message:", error);
|
|
@@ -4872,6 +4944,7 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4872
4944
|
this.dataChannel.onerror = (error) => {
|
|
4873
4945
|
this.debug.error(`Data channel error with ${this.peerId}:`, error);
|
|
4874
4946
|
this.dataChannelReady = false;
|
|
4947
|
+
this._pendingBinaryPayloads.length = 0;
|
|
4875
4948
|
if (!this.isClosing) {
|
|
4876
4949
|
this.emit("disconnected", { peerId: this.peerId, reason: "data channel error" });
|
|
4877
4950
|
}
|
|
@@ -5095,8 +5168,17 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
5095
5168
|
sendMessage(message) {
|
|
5096
5169
|
if (this.dataChannel && this.dataChannel.readyState === "open") {
|
|
5097
5170
|
try {
|
|
5098
|
-
|
|
5099
|
-
|
|
5171
|
+
if (message instanceof ArrayBuffer || ArrayBuffer.isView(message)) {
|
|
5172
|
+
this.debug.log(`\u{1F4E6} Sending binary message (${message.byteLength || message.buffer.byteLength} bytes) to ${this.peerId.substring(0, 8)}...`);
|
|
5173
|
+
const buffer = ArrayBuffer.isView(message) ? message.buffer : message;
|
|
5174
|
+
const header = JSON.stringify({ type: "__BINARY__", size: buffer.byteLength });
|
|
5175
|
+
this.dataChannel.send(header);
|
|
5176
|
+
this.dataChannel.send(buffer);
|
|
5177
|
+
return true;
|
|
5178
|
+
} else {
|
|
5179
|
+
this.dataChannel.send(JSON.stringify(message));
|
|
5180
|
+
return true;
|
|
5181
|
+
}
|
|
5100
5182
|
} catch (error) {
|
|
5101
5183
|
this.debug.error(`Failed to send message to ${this.peerId}:`, error);
|
|
5102
5184
|
return false;
|
|
@@ -5104,6 +5186,246 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
5104
5186
|
}
|
|
5105
5187
|
return false;
|
|
5106
5188
|
}
|
|
5189
|
+
/**
|
|
5190
|
+
* Create a WritableStream for sending data to this peer
|
|
5191
|
+
* @param {object} options - Stream options
|
|
5192
|
+
* @returns {WritableStream} A writable stream for sending data
|
|
5193
|
+
*/
|
|
5194
|
+
createWritableStream(options = {}) {
|
|
5195
|
+
const streamId = options.streamId || this._generateStreamId();
|
|
5196
|
+
const metadata = {
|
|
5197
|
+
streamId,
|
|
5198
|
+
type: options.type || "binary",
|
|
5199
|
+
filename: options.filename,
|
|
5200
|
+
mimeType: options.mimeType,
|
|
5201
|
+
totalSize: options.totalSize,
|
|
5202
|
+
chunkSize: options.chunkSize,
|
|
5203
|
+
timestamp: Date.now()
|
|
5204
|
+
};
|
|
5205
|
+
this.debug.log(`\u{1F4E4} Creating writable stream ${streamId} to ${this.peerId.substring(0, 8)}...`);
|
|
5206
|
+
const configuredChunkSize = typeof metadata.chunkSize === "number" && Number.isFinite(metadata.chunkSize) ? metadata.chunkSize : 16384;
|
|
5207
|
+
const chunkSize = Math.max(4096, Math.min(configuredChunkSize, 65536));
|
|
5208
|
+
metadata.chunkSize = chunkSize;
|
|
5209
|
+
const highWaterMark = chunkSize * 32;
|
|
5210
|
+
const lowWaterMark = chunkSize * 8;
|
|
5211
|
+
const ensureChannelOpen = () => {
|
|
5212
|
+
if (!this.dataChannel || this.dataChannel.readyState !== "open") {
|
|
5213
|
+
throw new Error("Data channel not open");
|
|
5214
|
+
}
|
|
5215
|
+
};
|
|
5216
|
+
const waitForBufferDrain = () => {
|
|
5217
|
+
if (!this.dataChannel || this.dataChannel.readyState !== "open") {
|
|
5218
|
+
return Promise.resolve();
|
|
5219
|
+
}
|
|
5220
|
+
if (this.dataChannel.bufferedAmount <= lowWaterMark) {
|
|
5221
|
+
return Promise.resolve();
|
|
5222
|
+
}
|
|
5223
|
+
return new Promise((resolve) => {
|
|
5224
|
+
const checkBuffer = () => {
|
|
5225
|
+
if (!this.dataChannel || this.dataChannel.readyState !== "open") {
|
|
5226
|
+
resolve();
|
|
5227
|
+
return;
|
|
5228
|
+
}
|
|
5229
|
+
if (this.dataChannel.bufferedAmount <= lowWaterMark) {
|
|
5230
|
+
resolve();
|
|
5231
|
+
} else {
|
|
5232
|
+
setTimeout(checkBuffer, 20);
|
|
5233
|
+
}
|
|
5234
|
+
};
|
|
5235
|
+
checkBuffer();
|
|
5236
|
+
});
|
|
5237
|
+
};
|
|
5238
|
+
this.sendMessage({
|
|
5239
|
+
type: "__STREAM_INIT__",
|
|
5240
|
+
streamId,
|
|
5241
|
+
metadata
|
|
5242
|
+
});
|
|
5243
|
+
let chunkIndex = 0;
|
|
5244
|
+
const self2 = this;
|
|
5245
|
+
return new WritableStream({
|
|
5246
|
+
async write(chunk) {
|
|
5247
|
+
ensureChannelOpen();
|
|
5248
|
+
const data = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
|
|
5249
|
+
let offset = 0;
|
|
5250
|
+
while (offset < data.byteLength) {
|
|
5251
|
+
ensureChannelOpen();
|
|
5252
|
+
const sliceEnd = Math.min(offset + chunkSize, data.byteLength);
|
|
5253
|
+
const slice = data.subarray(offset, sliceEnd);
|
|
5254
|
+
const sliceBuffer = slice.byteOffset === 0 && slice.byteLength === slice.buffer.byteLength ? slice.buffer : slice.buffer.slice(slice.byteOffset, slice.byteOffset + slice.byteLength);
|
|
5255
|
+
const chunkMessage = {
|
|
5256
|
+
type: "__STREAM_CHUNK__",
|
|
5257
|
+
streamId,
|
|
5258
|
+
chunkIndex: chunkIndex++,
|
|
5259
|
+
size: slice.byteLength,
|
|
5260
|
+
encoding: "binary"
|
|
5261
|
+
};
|
|
5262
|
+
try {
|
|
5263
|
+
self2.dataChannel.send(JSON.stringify(chunkMessage));
|
|
5264
|
+
self2.dataChannel.send(sliceBuffer);
|
|
5265
|
+
} catch (error) {
|
|
5266
|
+
throw error;
|
|
5267
|
+
}
|
|
5268
|
+
offset = sliceEnd;
|
|
5269
|
+
if (self2.dataChannel && self2.dataChannel.bufferedAmount > highWaterMark) {
|
|
5270
|
+
await waitForBufferDrain();
|
|
5271
|
+
}
|
|
5272
|
+
}
|
|
5273
|
+
},
|
|
5274
|
+
async close() {
|
|
5275
|
+
if (self2.dataChannel && self2.dataChannel.readyState === "open") {
|
|
5276
|
+
await waitForBufferDrain();
|
|
5277
|
+
self2.sendMessage({
|
|
5278
|
+
type: "__STREAM_END__",
|
|
5279
|
+
streamId,
|
|
5280
|
+
totalChunks: chunkIndex
|
|
5281
|
+
});
|
|
5282
|
+
}
|
|
5283
|
+
self2._activeStreams.delete(streamId);
|
|
5284
|
+
self2.debug.log(`\u{1F4E4} Closed writable stream ${streamId}`);
|
|
5285
|
+
},
|
|
5286
|
+
async abort(reason) {
|
|
5287
|
+
if (self2.dataChannel && self2.dataChannel.readyState === "open") {
|
|
5288
|
+
self2.sendMessage({
|
|
5289
|
+
type: "__STREAM_ABORT__",
|
|
5290
|
+
streamId,
|
|
5291
|
+
reason: reason?.message || "Stream aborted"
|
|
5292
|
+
});
|
|
5293
|
+
}
|
|
5294
|
+
self2._activeStreams.delete(streamId);
|
|
5295
|
+
self2.debug.log(`\u274C Aborted writable stream ${streamId}: ${reason}`);
|
|
5296
|
+
}
|
|
5297
|
+
});
|
|
5298
|
+
}
|
|
5299
|
+
/**
|
|
5300
|
+
* Handle incoming stream messages and create ReadableStream
|
|
5301
|
+
* @private
|
|
5302
|
+
*/
|
|
5303
|
+
_handleStreamMessage(message) {
|
|
5304
|
+
const { type } = message;
|
|
5305
|
+
switch (type) {
|
|
5306
|
+
case "__STREAM_INIT__":
|
|
5307
|
+
this._handleStreamInit(message);
|
|
5308
|
+
break;
|
|
5309
|
+
case "__STREAM_CHUNK__":
|
|
5310
|
+
if (message.encoding === "binary") {
|
|
5311
|
+
this._pendingBinaryPayloads.push({
|
|
5312
|
+
type: "streamChunk",
|
|
5313
|
+
header: message
|
|
5314
|
+
});
|
|
5315
|
+
} else {
|
|
5316
|
+
this._handleStreamChunkLegacy(message);
|
|
5317
|
+
}
|
|
5318
|
+
break;
|
|
5319
|
+
case "__STREAM_END__":
|
|
5320
|
+
this._handleStreamEnd(message);
|
|
5321
|
+
break;
|
|
5322
|
+
case "__STREAM_ABORT__":
|
|
5323
|
+
this._handleStreamAbort(message);
|
|
5324
|
+
break;
|
|
5325
|
+
}
|
|
5326
|
+
}
|
|
5327
|
+
_handleStreamInit(message) {
|
|
5328
|
+
const { streamId, metadata } = message;
|
|
5329
|
+
this.debug.log(`\u{1F4E5} Receiving stream ${streamId} from ${this.peerId.substring(0, 8)}...`);
|
|
5330
|
+
this._streamMetadata.set(streamId, metadata);
|
|
5331
|
+
this._streamChunks.set(streamId, []);
|
|
5332
|
+
const chunks = this._streamChunks.get(streamId);
|
|
5333
|
+
let controller;
|
|
5334
|
+
const readable = new ReadableStream({
|
|
5335
|
+
start(ctrl) {
|
|
5336
|
+
controller = ctrl;
|
|
5337
|
+
},
|
|
5338
|
+
cancel: (reason) => {
|
|
5339
|
+
this.debug.log(`\u{1F4E5} Stream ${streamId} cancelled: ${reason}`);
|
|
5340
|
+
}
|
|
5341
|
+
});
|
|
5342
|
+
this._activeStreams.set(streamId, {
|
|
5343
|
+
type: "readable",
|
|
5344
|
+
stream: readable,
|
|
5345
|
+
controller,
|
|
5346
|
+
metadata,
|
|
5347
|
+
chunks
|
|
5348
|
+
});
|
|
5349
|
+
this.emit("streamReceived", {
|
|
5350
|
+
peerId: this.peerId,
|
|
5351
|
+
streamId,
|
|
5352
|
+
stream: readable,
|
|
5353
|
+
metadata
|
|
5354
|
+
});
|
|
5355
|
+
}
|
|
5356
|
+
_handleStreamChunkLegacy(message) {
|
|
5357
|
+
const { streamId, chunkIndex, data } = message;
|
|
5358
|
+
const streamData = this._activeStreams.get(streamId);
|
|
5359
|
+
if (!streamData) {
|
|
5360
|
+
this.debug.warn(`Received chunk for unknown stream ${streamId}`);
|
|
5361
|
+
return;
|
|
5362
|
+
}
|
|
5363
|
+
const chunk = new Uint8Array(data);
|
|
5364
|
+
if (streamData.controller) {
|
|
5365
|
+
streamData.controller.enqueue(chunk);
|
|
5366
|
+
}
|
|
5367
|
+
if (Array.isArray(streamData.chunks)) {
|
|
5368
|
+
streamData.chunks.push(chunk);
|
|
5369
|
+
}
|
|
5370
|
+
this.debug.log(`\u{1F4E5} Received chunk ${chunkIndex} for stream ${streamId} (${chunk.length} bytes)`);
|
|
5371
|
+
}
|
|
5372
|
+
_handleStreamChunkBinary(header, chunk) {
|
|
5373
|
+
const { streamId, chunkIndex, size } = header;
|
|
5374
|
+
const streamData = this._activeStreams.get(streamId);
|
|
5375
|
+
if (!streamData) {
|
|
5376
|
+
this.debug.warn(`Received binary chunk for unknown stream ${streamId}`);
|
|
5377
|
+
return;
|
|
5378
|
+
}
|
|
5379
|
+
if (size && size !== chunk.byteLength) {
|
|
5380
|
+
this.debug.warn(`Stream ${streamId} chunk ${chunkIndex} size mismatch: expected ${size}, got ${chunk.byteLength}`);
|
|
5381
|
+
}
|
|
5382
|
+
if (streamData.controller) {
|
|
5383
|
+
streamData.controller.enqueue(chunk);
|
|
5384
|
+
}
|
|
5385
|
+
if (Array.isArray(streamData.chunks)) {
|
|
5386
|
+
streamData.chunks.push(chunk);
|
|
5387
|
+
}
|
|
5388
|
+
this.debug.log(`\u{1F4E5} Received chunk ${chunkIndex} for stream ${streamId} (${chunk.byteLength} bytes)`);
|
|
5389
|
+
}
|
|
5390
|
+
_handleStreamEnd(message) {
|
|
5391
|
+
const { streamId, totalChunks } = message;
|
|
5392
|
+
const streamData = this._activeStreams.get(streamId);
|
|
5393
|
+
if (!streamData) {
|
|
5394
|
+
this.debug.warn(`Received end for unknown stream ${streamId}`);
|
|
5395
|
+
return;
|
|
5396
|
+
}
|
|
5397
|
+
if (streamData.controller) {
|
|
5398
|
+
streamData.controller.close();
|
|
5399
|
+
}
|
|
5400
|
+
this.debug.log(`\u{1F4E5} Stream ${streamId} completed (${totalChunks} chunks)`);
|
|
5401
|
+
this._activeStreams.delete(streamId);
|
|
5402
|
+
this._streamChunks.delete(streamId);
|
|
5403
|
+
this._streamMetadata.delete(streamId);
|
|
5404
|
+
this.emit("streamCompleted", {
|
|
5405
|
+
peerId: this.peerId,
|
|
5406
|
+
streamId,
|
|
5407
|
+
totalChunks
|
|
5408
|
+
});
|
|
5409
|
+
}
|
|
5410
|
+
_handleStreamAbort(message) {
|
|
5411
|
+
const { streamId, reason } = message;
|
|
5412
|
+
const streamData = this._activeStreams.get(streamId);
|
|
5413
|
+
if (streamData && streamData.controller) {
|
|
5414
|
+
streamData.controller.error(new Error(reason));
|
|
5415
|
+
}
|
|
5416
|
+
this.debug.log(`\u274C Stream ${streamId} aborted: ${reason}`);
|
|
5417
|
+
this._activeStreams.delete(streamId);
|
|
5418
|
+
this._streamChunks.delete(streamId);
|
|
5419
|
+
this._streamMetadata.delete(streamId);
|
|
5420
|
+
this.emit("streamAborted", {
|
|
5421
|
+
peerId: this.peerId,
|
|
5422
|
+
streamId,
|
|
5423
|
+
reason
|
|
5424
|
+
});
|
|
5425
|
+
}
|
|
5426
|
+
_generateStreamId() {
|
|
5427
|
+
return `stream-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
5428
|
+
}
|
|
5107
5429
|
/**
|
|
5108
5430
|
* CRITICAL FIX: Manually check for new remote tracks after renegotiation
|
|
5109
5431
|
* This is needed because replaceTrack() doesn't trigger ontrack events
|
|
@@ -5757,12 +6079,30 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
5757
6079
|
async connectToPeer(targetPeerId) {
|
|
5758
6080
|
this.debug.log(`connectToPeer called for ${targetPeerId.substring(0, 8)}...`);
|
|
5759
6081
|
if (this.peers.has(targetPeerId)) {
|
|
5760
|
-
this.
|
|
5761
|
-
|
|
6082
|
+
const existingPeer = this.peers.get(targetPeerId);
|
|
6083
|
+
const status = existingPeer.getStatus();
|
|
6084
|
+
if (status === "connected") {
|
|
6085
|
+
this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}... (status: ${status})`);
|
|
6086
|
+
return;
|
|
6087
|
+
}
|
|
6088
|
+
if (status === "connecting") {
|
|
6089
|
+
const connectionAge = Date.now() - (existingPeer.createdAt || 0);
|
|
6090
|
+
if (connectionAge < 1e4) {
|
|
6091
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... still in progress (${Math.round(connectionAge / 1e3)}s)`);
|
|
6092
|
+
return;
|
|
6093
|
+
}
|
|
6094
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... appears stuck (${Math.round(connectionAge / 1e3)}s), will retry`);
|
|
6095
|
+
this.cleanupFailedConnection(targetPeerId);
|
|
6096
|
+
}
|
|
5762
6097
|
}
|
|
5763
6098
|
if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
|
|
5764
|
-
|
|
5765
|
-
|
|
6099
|
+
const attemptAge = Date.now() - (this.lastConnectionAttempt.get(targetPeerId) || 0);
|
|
6100
|
+
if (attemptAge < 1e4) {
|
|
6101
|
+
this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery (${Math.round(attemptAge / 1e3)}s ago)`);
|
|
6102
|
+
return;
|
|
6103
|
+
}
|
|
6104
|
+
this.debug.log(`Old connection attempt to ${targetPeerId.substring(0, 8)}... (${Math.round(attemptAge / 1e3)}s ago), allowing retry`);
|
|
6105
|
+
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
5766
6106
|
}
|
|
5767
6107
|
const shouldBeInitiator = this.mesh.peerId > targetPeerId;
|
|
5768
6108
|
if (!shouldBeInitiator) {
|
|
@@ -5778,17 +6118,22 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
5778
6118
|
const attempts = this.connectionAttempts.get(targetPeerId) || 0;
|
|
5779
6119
|
if (attempts > 0) {
|
|
5780
6120
|
const lastAttempt = this.lastConnectionAttempt.get(targetPeerId) || 0;
|
|
5781
|
-
const
|
|
5782
|
-
const retryDelay =
|
|
6121
|
+
const connectedCount2 = this.getConnectedPeerCount();
|
|
6122
|
+
const retryDelay = connectedCount2 === 0 ? 200 : this.retryDelay;
|
|
5783
6123
|
if (now - lastAttempt < retryDelay) {
|
|
5784
6124
|
const remaining = retryDelay - (now - lastAttempt);
|
|
5785
|
-
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining
|
|
6125
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining)}ms remaining, isolated: ${connectedCount2 === 0})`);
|
|
5786
6126
|
return;
|
|
5787
6127
|
}
|
|
5788
6128
|
}
|
|
5789
|
-
|
|
6129
|
+
const connectedCount = this.getConnectedPeerCount();
|
|
6130
|
+
const maxAttempts = connectedCount === 0 ? this.maxConnectionAttempts * 2 : this.maxConnectionAttempts;
|
|
6131
|
+
if (attempts >= maxAttempts) {
|
|
6132
|
+
this.debug.log(`Max connection attempts (${maxAttempts}) reached for ${targetPeerId.substring(0, 8)}...`);
|
|
5790
6133
|
this.mesh.emit("statusChanged", { type: "warning", message: `Max connection attempts reached for ${targetPeerId.substring(0, 8)}...` });
|
|
5791
|
-
this.
|
|
6134
|
+
this.connectionAttempts.delete(targetPeerId);
|
|
6135
|
+
this.lastConnectionAttempt.delete(targetPeerId);
|
|
6136
|
+
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
5792
6137
|
return;
|
|
5793
6138
|
}
|
|
5794
6139
|
this.debug.log(`Starting connection to ${targetPeerId.substring(0, 8)}... (attempt ${attempts + 1})`);
|
|
@@ -5927,6 +6272,18 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
5927
6272
|
this.emit("remoteStream", event);
|
|
5928
6273
|
this.debug.log("\u{1F504} MEDIA FORWARDING: Disabled to prevent renegotiation conflicts with 3+ peers");
|
|
5929
6274
|
});
|
|
6275
|
+
peerConnection.addEventListener("streamReceived", (event) => {
|
|
6276
|
+
this.debug.log(`[EVENT] Data stream received from ${event.peerId.substring(0, 8)}...`);
|
|
6277
|
+
this.mesh.emit("streamReceived", event);
|
|
6278
|
+
});
|
|
6279
|
+
peerConnection.addEventListener("streamCompleted", (event) => {
|
|
6280
|
+
this.debug.log(`[EVENT] Data stream completed from ${event.peerId.substring(0, 8)}...`);
|
|
6281
|
+
this.mesh.emit("streamCompleted", event);
|
|
6282
|
+
});
|
|
6283
|
+
peerConnection.addEventListener("streamAborted", (event) => {
|
|
6284
|
+
this.debug.log(`[EVENT] Data stream aborted from ${event.peerId.substring(0, 8)}...`);
|
|
6285
|
+
this.mesh.emit("streamAborted", event);
|
|
6286
|
+
});
|
|
5930
6287
|
peerConnection.addEventListener("renegotiationNeeded", async (event) => {
|
|
5931
6288
|
this.debug.log(`\u{1F504} Renegotiation needed for ${event.peerId.substring(0, 8)}...`);
|
|
5932
6289
|
if (this.activeRenegotiations.size >= this.maxConcurrentRenegotiations) {
|
|
@@ -6284,6 +6641,16 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
6284
6641
|
this.debug.warn("Received invalid message from", fromPeerId?.substring(0, 8));
|
|
6285
6642
|
return;
|
|
6286
6643
|
}
|
|
6644
|
+
if (message.type === "binary" && message.data instanceof Uint8Array) {
|
|
6645
|
+
this.debug.log(`\u{1F4E6} Received binary message (${message.size} bytes) from ${fromPeerId.substring(0, 8)}...`);
|
|
6646
|
+
this.mesh.emit("binaryMessageReceived", {
|
|
6647
|
+
from: fromPeerId,
|
|
6648
|
+
data: message.data,
|
|
6649
|
+
size: message.size,
|
|
6650
|
+
timestamp: Date.now()
|
|
6651
|
+
});
|
|
6652
|
+
return;
|
|
6653
|
+
}
|
|
6287
6654
|
const filteredMessageTypes = /* @__PURE__ */ new Set([
|
|
6288
6655
|
"signaling-relay",
|
|
6289
6656
|
"peer-announce-relay",
|
|
@@ -6697,11 +7064,22 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
6697
7064
|
}
|
|
6698
7065
|
}
|
|
6699
7066
|
handlePeerAnnouncement(fromPeerId) {
|
|
6700
|
-
if (this.
|
|
6701
|
-
this.
|
|
6702
|
-
|
|
7067
|
+
if (this.connectionManager.hasPeer(fromPeerId)) {
|
|
7068
|
+
const peerStatus = this.connectionManager.getPeer(fromPeerId).getStatus();
|
|
7069
|
+
if (peerStatus === "connected") {
|
|
7070
|
+
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already connected (${peerStatus}), updating timestamp`);
|
|
7071
|
+
this.mesh.peerDiscovery.updateDiscoveryTimestamp(fromPeerId);
|
|
7072
|
+
return;
|
|
7073
|
+
}
|
|
7074
|
+
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... exists but not connected (${peerStatus}), allowing re-discovery`);
|
|
6703
7075
|
}
|
|
6704
|
-
this.mesh.
|
|
7076
|
+
const wasKnown = this.mesh.peerDiscovery.hasPeer(fromPeerId);
|
|
7077
|
+
if (wasKnown) {
|
|
7078
|
+
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already known, refreshing discovery`);
|
|
7079
|
+
} else {
|
|
7080
|
+
this.debug.log(`New peer discovered: ${fromPeerId.substring(0, 8)}...`);
|
|
7081
|
+
}
|
|
7082
|
+
this.mesh.emit("statusChanged", { type: "info", message: `Peer ${fromPeerId.substring(0, 8)}... ${wasKnown ? "re-announced" : "announced"}` });
|
|
6705
7083
|
this.debug.log(`Adding discovered peer: ${fromPeerId.substring(0, 8)}... to PeerDiscovery`);
|
|
6706
7084
|
this.debug.log(`Current peer count: ${this.connectionManager.getConnectedPeerCount()}/${this.mesh.maxPeers}`);
|
|
6707
7085
|
this.debug.log(`All discovered peers: ${Array.from(this.mesh.peerDiscovery.discoveredPeers.keys()).map((p) => p.substring(0, 8)).join(", ")}`);
|
|
@@ -7802,6 +8180,26 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
7802
8180
|
this.handlePeerAnnouncement(content, originPeerId);
|
|
7803
8181
|
} else if (subtype === "mediaEvent") {
|
|
7804
8182
|
this.handleMediaEvent(content, originPeerId);
|
|
8183
|
+
} else if (subtype === "stream-chunk") {
|
|
8184
|
+
this.emit("messageReceived", {
|
|
8185
|
+
from: originPeerId,
|
|
8186
|
+
message: {
|
|
8187
|
+
type: "stream-chunk",
|
|
8188
|
+
...content
|
|
8189
|
+
},
|
|
8190
|
+
timestamp,
|
|
8191
|
+
messageId
|
|
8192
|
+
});
|
|
8193
|
+
} else if (subtype === "stream-control") {
|
|
8194
|
+
this.emit("messageReceived", {
|
|
8195
|
+
from: originPeerId,
|
|
8196
|
+
message: {
|
|
8197
|
+
type: "stream-control",
|
|
8198
|
+
...content
|
|
8199
|
+
},
|
|
8200
|
+
timestamp,
|
|
8201
|
+
messageId
|
|
8202
|
+
});
|
|
7805
8203
|
} else if (subtype === "dm") {
|
|
7806
8204
|
if (typeof to === "string" && typeof this.mesh.peerId === "string" && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
|
|
7807
8205
|
this.debug.log(`\u{1F50D} DM DEBUG: Received DM from ${originPeerId?.substring(0, 8)}, content type: ${typeof processedContent}`);
|
|
@@ -10945,6 +11343,7 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
10945
11343
|
this.discoveredPeers = /* @__PURE__ */ new Map();
|
|
10946
11344
|
this.ongoingKeyExchanges = /* @__PURE__ */ new Set();
|
|
10947
11345
|
this.emittedPeerKeyEvents = /* @__PURE__ */ new Set();
|
|
11346
|
+
this.gossipStreams = /* @__PURE__ */ new Map();
|
|
10948
11347
|
this.storageManager = new StorageManager(this);
|
|
10949
11348
|
this.mediaManager = new MediaManager();
|
|
10950
11349
|
this.connectionManager = new ConnectionManager(this);
|
|
@@ -10987,6 +11386,14 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
10987
11386
|
this.webDHT.handleMessage(data.message, data.from);
|
|
10988
11387
|
return;
|
|
10989
11388
|
}
|
|
11389
|
+
if (data.message && data.message.type === "stream-chunk") {
|
|
11390
|
+
this._handleGossipStreamChunk(data.message, data.from);
|
|
11391
|
+
return;
|
|
11392
|
+
}
|
|
11393
|
+
if (data.message && data.message.type === "stream-control") {
|
|
11394
|
+
this._handleGossipStreamControl(data.message, data.from);
|
|
11395
|
+
return;
|
|
11396
|
+
}
|
|
10990
11397
|
if (data.content && typeof data.content === "string") {
|
|
10991
11398
|
try {
|
|
10992
11399
|
const parsedContent = JSON.parse(data.content);
|
|
@@ -11221,7 +11628,6 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
11221
11628
|
this.connected = false;
|
|
11222
11629
|
this.polling = false;
|
|
11223
11630
|
this.peerDiscovery.stop();
|
|
11224
|
-
this.connectionManager.disconnectAllPeers();
|
|
11225
11631
|
this.emit("statusChanged", { type: "disconnected" });
|
|
11226
11632
|
});
|
|
11227
11633
|
this.signalingClient.addEventListener("signalingMessage", (message) => {
|
|
@@ -11509,6 +11915,251 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
11509
11915
|
async sendMessage(content) {
|
|
11510
11916
|
return await this.gossipManager.broadcastMessage(content, "chat");
|
|
11511
11917
|
}
|
|
11918
|
+
/**
|
|
11919
|
+
* Send binary data to a specific peer
|
|
11920
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
11921
|
+
* @param {Uint8Array|ArrayBuffer} binaryData - The binary data to send
|
|
11922
|
+
* @returns {boolean} True if sent successfully
|
|
11923
|
+
*/
|
|
11924
|
+
async sendBinaryData(targetPeerId, binaryData) {
|
|
11925
|
+
if (!targetPeerId || typeof targetPeerId !== "string") {
|
|
11926
|
+
this.debug.error("Invalid targetPeerId for binary message");
|
|
11927
|
+
return false;
|
|
11928
|
+
}
|
|
11929
|
+
const peerConnection = this.connectionManager.peers.get(targetPeerId);
|
|
11930
|
+
if (!peerConnection) {
|
|
11931
|
+
this.debug.error(`No connection to peer ${targetPeerId.substring(0, 8)}...`);
|
|
11932
|
+
return false;
|
|
11933
|
+
}
|
|
11934
|
+
return peerConnection.sendMessage(binaryData);
|
|
11935
|
+
}
|
|
11936
|
+
/**
|
|
11937
|
+
* Broadcast binary data to all connected peers
|
|
11938
|
+
* @param {Uint8Array|ArrayBuffer} binaryData - The binary data to broadcast
|
|
11939
|
+
* @returns {number} Number of peers the data was sent to
|
|
11940
|
+
*/
|
|
11941
|
+
async broadcastBinaryData(binaryData) {
|
|
11942
|
+
const peers = this.getConnectedPeers();
|
|
11943
|
+
let sentCount = 0;
|
|
11944
|
+
for (const peer of peers) {
|
|
11945
|
+
if (await this.sendBinaryData(peer.peerId, binaryData)) {
|
|
11946
|
+
sentCount++;
|
|
11947
|
+
}
|
|
11948
|
+
}
|
|
11949
|
+
this.debug.log(`\u{1F4E6} Binary data broadcasted to ${sentCount}/${peers.length} peers`);
|
|
11950
|
+
return sentCount;
|
|
11951
|
+
}
|
|
11952
|
+
/**
|
|
11953
|
+
* Create a writable stream to send data to a specific peer
|
|
11954
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
11955
|
+
* @param {object} options - Stream options (filename, mimeType, totalSize, etc.)
|
|
11956
|
+
* @returns {WritableStream} A writable stream
|
|
11957
|
+
*/
|
|
11958
|
+
createStreamToPeer(targetPeerId, options = {}) {
|
|
11959
|
+
if (!targetPeerId || typeof targetPeerId !== "string") {
|
|
11960
|
+
throw new Error("Invalid targetPeerId for stream");
|
|
11961
|
+
}
|
|
11962
|
+
const peerConnection = this.connectionManager.peers.get(targetPeerId);
|
|
11963
|
+
if (!peerConnection) {
|
|
11964
|
+
throw new Error(`No connection to peer ${targetPeerId.substring(0, 8)}...`);
|
|
11965
|
+
}
|
|
11966
|
+
return peerConnection.createWritableStream(options);
|
|
11967
|
+
}
|
|
11968
|
+
/**
|
|
11969
|
+
* Send a ReadableStream to a peer
|
|
11970
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
11971
|
+
* @param {ReadableStream} readableStream - The stream to send
|
|
11972
|
+
* @param {object} options - Stream options (filename, mimeType, etc.)
|
|
11973
|
+
* @returns {Promise<void>}
|
|
11974
|
+
*/
|
|
11975
|
+
async sendStream(targetPeerId, readableStream, options = {}) {
|
|
11976
|
+
const writableStream = this.createStreamToPeer(targetPeerId, options);
|
|
11977
|
+
try {
|
|
11978
|
+
await readableStream.pipeTo(writableStream);
|
|
11979
|
+
this.debug.log(`\u2705 Stream sent successfully to ${targetPeerId.substring(0, 8)}...`);
|
|
11980
|
+
} catch (error) {
|
|
11981
|
+
this.debug.error(`\u274C Failed to send stream to ${targetPeerId.substring(0, 8)}...:`, error);
|
|
11982
|
+
throw error;
|
|
11983
|
+
}
|
|
11984
|
+
}
|
|
11985
|
+
/**
|
|
11986
|
+
* Send a File to a peer using streams
|
|
11987
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
11988
|
+
* @param {File} file - The file to send
|
|
11989
|
+
* @returns {Promise<void>}
|
|
11990
|
+
*/
|
|
11991
|
+
async sendFile(targetPeerId, file) {
|
|
11992
|
+
this.debug.log(`\u{1F4C1} Sending file "${file.name}" (${file.size} bytes) to ${targetPeerId.substring(0, 8)}...`);
|
|
11993
|
+
const options = {
|
|
11994
|
+
filename: file.name,
|
|
11995
|
+
mimeType: file.type,
|
|
11996
|
+
totalSize: file.size,
|
|
11997
|
+
type: "file"
|
|
11998
|
+
};
|
|
11999
|
+
const stream = file.stream();
|
|
12000
|
+
await this.sendStream(targetPeerId, stream, options);
|
|
12001
|
+
}
|
|
12002
|
+
/**
|
|
12003
|
+
* Send a Blob to a peer using streams
|
|
12004
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
12005
|
+
* @param {Blob} blob - The blob to send
|
|
12006
|
+
* @param {object} options - Additional options
|
|
12007
|
+
* @returns {Promise<void>}
|
|
12008
|
+
*/
|
|
12009
|
+
async sendBlob(targetPeerId, blob, options = {}) {
|
|
12010
|
+
this.debug.log(`\u{1F4E6} Sending blob (${blob.size} bytes) to ${targetPeerId.substring(0, 8)}...`);
|
|
12011
|
+
const streamOptions = {
|
|
12012
|
+
...options,
|
|
12013
|
+
mimeType: blob.type,
|
|
12014
|
+
totalSize: blob.size,
|
|
12015
|
+
type: "blob"
|
|
12016
|
+
};
|
|
12017
|
+
const stream = blob.stream();
|
|
12018
|
+
await this.sendStream(targetPeerId, stream, streamOptions);
|
|
12019
|
+
}
|
|
12020
|
+
/**
|
|
12021
|
+
* Create a writable stream that broadcasts data to all peers in the mesh using gossip
|
|
12022
|
+
* @param {object} options - Stream options (filename, mimeType, totalSize, etc.)
|
|
12023
|
+
* @returns {WritableStream} A writable stream that broadcasts via gossip protocol
|
|
12024
|
+
*/
|
|
12025
|
+
createBroadcastStream(options = {}) {
|
|
12026
|
+
const streamId = options.streamId || this._generateStreamId();
|
|
12027
|
+
const metadata = {
|
|
12028
|
+
streamId,
|
|
12029
|
+
type: options.type || "broadcast",
|
|
12030
|
+
filename: options.filename,
|
|
12031
|
+
mimeType: options.mimeType,
|
|
12032
|
+
totalSize: options.totalSize,
|
|
12033
|
+
timestamp: Date.now(),
|
|
12034
|
+
...options
|
|
12035
|
+
};
|
|
12036
|
+
const chunks = [];
|
|
12037
|
+
let chunkIndex = 0;
|
|
12038
|
+
let totalBytesWritten = 0;
|
|
12039
|
+
const self2 = this;
|
|
12040
|
+
this.debug.log(`\u{1F4E1} Creating gossip broadcast stream: ${streamId}`);
|
|
12041
|
+
return new WritableStream({
|
|
12042
|
+
async write(chunk) {
|
|
12043
|
+
const chunkData = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
|
|
12044
|
+
const chunkId = chunkIndex++;
|
|
12045
|
+
chunks.push({
|
|
12046
|
+
index: chunkId,
|
|
12047
|
+
data: chunkData
|
|
12048
|
+
});
|
|
12049
|
+
totalBytesWritten += chunkData.length;
|
|
12050
|
+
try {
|
|
12051
|
+
await self2.gossipManager.broadcastMessage({
|
|
12052
|
+
streamId,
|
|
12053
|
+
chunkIndex: chunkId,
|
|
12054
|
+
data: Array.from(chunkData),
|
|
12055
|
+
// Convert to regular array for JSON
|
|
12056
|
+
totalSize: metadata.totalSize,
|
|
12057
|
+
metadata: chunkId === 0 ? metadata : void 0
|
|
12058
|
+
// Include metadata with first chunk
|
|
12059
|
+
}, "stream-chunk");
|
|
12060
|
+
self2.debug.log(`\u{1F4E1} Gossiped chunk ${chunkId} (${chunkData.length} bytes) for stream ${streamId.substring(0, 8)}...`);
|
|
12061
|
+
} catch (error) {
|
|
12062
|
+
self2.debug.error(`Failed to gossip chunk ${chunkId}:`, error);
|
|
12063
|
+
throw error;
|
|
12064
|
+
}
|
|
12065
|
+
},
|
|
12066
|
+
async close() {
|
|
12067
|
+
try {
|
|
12068
|
+
await self2.gossipManager.broadcastMessage({
|
|
12069
|
+
streamId,
|
|
12070
|
+
action: "end",
|
|
12071
|
+
totalChunks: chunkIndex,
|
|
12072
|
+
totalBytes: totalBytesWritten,
|
|
12073
|
+
metadata
|
|
12074
|
+
}, "stream-control");
|
|
12075
|
+
self2.debug.log(`\u{1F4E1} Broadcast stream completed via gossip: ${totalBytesWritten} bytes in ${chunkIndex} chunks`);
|
|
12076
|
+
self2.emit("broadcastStreamComplete", {
|
|
12077
|
+
streamId,
|
|
12078
|
+
totalBytes: totalBytesWritten,
|
|
12079
|
+
totalChunks: chunkIndex,
|
|
12080
|
+
metadata
|
|
12081
|
+
});
|
|
12082
|
+
} catch (error) {
|
|
12083
|
+
self2.debug.error("Failed to broadcast stream end:", error);
|
|
12084
|
+
throw error;
|
|
12085
|
+
}
|
|
12086
|
+
},
|
|
12087
|
+
async abort(reason) {
|
|
12088
|
+
try {
|
|
12089
|
+
await self2.gossipManager.broadcastMessage({
|
|
12090
|
+
streamId,
|
|
12091
|
+
action: "abort",
|
|
12092
|
+
reason: reason?.message || String(reason),
|
|
12093
|
+
metadata
|
|
12094
|
+
}, "stream-control");
|
|
12095
|
+
self2.debug.log(`\u274C Broadcast stream aborted via gossip: ${reason}`);
|
|
12096
|
+
self2.emit("broadcastStreamAborted", {
|
|
12097
|
+
streamId,
|
|
12098
|
+
reason: reason?.message || String(reason),
|
|
12099
|
+
metadata
|
|
12100
|
+
});
|
|
12101
|
+
} catch (error) {
|
|
12102
|
+
self2.debug.error("Failed to broadcast stream abort:", error);
|
|
12103
|
+
}
|
|
12104
|
+
}
|
|
12105
|
+
});
|
|
12106
|
+
}
|
|
12107
|
+
/**
|
|
12108
|
+
* Broadcast a ReadableStream to all connected peers
|
|
12109
|
+
* @param {ReadableStream} readableStream - The stream to broadcast
|
|
12110
|
+
* @param {object} options - Stream options (filename, mimeType, etc.)
|
|
12111
|
+
* @returns {Promise<void>}
|
|
12112
|
+
*/
|
|
12113
|
+
async broadcastStream(readableStream, options = {}) {
|
|
12114
|
+
const writableStream = this.createBroadcastStream(options);
|
|
12115
|
+
try {
|
|
12116
|
+
await readableStream.pipeTo(writableStream);
|
|
12117
|
+
this.debug.log(`\u2705 Stream broadcasted successfully to all peers`);
|
|
12118
|
+
} catch (error) {
|
|
12119
|
+
this.debug.error(`\u274C Failed to broadcast stream:`, error);
|
|
12120
|
+
throw error;
|
|
12121
|
+
}
|
|
12122
|
+
}
|
|
12123
|
+
/**
|
|
12124
|
+
* Broadcast a File to all connected peers using streams
|
|
12125
|
+
* @param {File} file - The file to broadcast
|
|
12126
|
+
* @returns {Promise<void>}
|
|
12127
|
+
*/
|
|
12128
|
+
async broadcastFile(file) {
|
|
12129
|
+
this.debug.log(`\u{1F4C1} Broadcasting file "${file.name}" (${file.size} bytes) to all peers`);
|
|
12130
|
+
const options = {
|
|
12131
|
+
filename: file.name,
|
|
12132
|
+
mimeType: file.type,
|
|
12133
|
+
totalSize: file.size,
|
|
12134
|
+
type: "file"
|
|
12135
|
+
};
|
|
12136
|
+
const stream = file.stream();
|
|
12137
|
+
await this.broadcastStream(stream, options);
|
|
12138
|
+
}
|
|
12139
|
+
/**
|
|
12140
|
+
* Broadcast a Blob to all connected peers using streams
|
|
12141
|
+
* @param {Blob} blob - The blob to broadcast
|
|
12142
|
+
* @param {object} options - Additional options
|
|
12143
|
+
* @returns {Promise<void>}
|
|
12144
|
+
*/
|
|
12145
|
+
async broadcastBlob(blob, options = {}) {
|
|
12146
|
+
this.debug.log(`\u{1F4E6} Broadcasting blob (${blob.size} bytes) to all peers`);
|
|
12147
|
+
const streamOptions = {
|
|
12148
|
+
...options,
|
|
12149
|
+
mimeType: blob.type,
|
|
12150
|
+
totalSize: blob.size,
|
|
12151
|
+
type: "blob"
|
|
12152
|
+
};
|
|
12153
|
+
const stream = blob.stream();
|
|
12154
|
+
await this.broadcastStream(stream, streamOptions);
|
|
12155
|
+
}
|
|
12156
|
+
/**
|
|
12157
|
+
* Generate a unique stream ID
|
|
12158
|
+
* @private
|
|
12159
|
+
*/
|
|
12160
|
+
_generateStreamId() {
|
|
12161
|
+
return `stream_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
|
|
12162
|
+
}
|
|
11512
12163
|
// Helper methods for backward compatibility
|
|
11513
12164
|
canAcceptMorePeers() {
|
|
11514
12165
|
return this.connectionManager.canAcceptMorePeers();
|
|
@@ -12167,6 +12818,118 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
12167
12818
|
};
|
|
12168
12819
|
this.signalingHandler.handleSignalingMessage(reconstitutedMessage);
|
|
12169
12820
|
}
|
|
12821
|
+
/**
|
|
12822
|
+
* Handle incoming gossip stream chunk
|
|
12823
|
+
* @param {Object} message - The stream chunk message
|
|
12824
|
+
* @param {string} from - Sender peer ID
|
|
12825
|
+
* @private
|
|
12826
|
+
*/
|
|
12827
|
+
_handleGossipStreamChunk(message, from) {
|
|
12828
|
+
const { streamId, chunkIndex, data, metadata } = message;
|
|
12829
|
+
if (!streamId || chunkIndex === void 0 || !data) {
|
|
12830
|
+
this.debug.error("Invalid gossip stream chunk format");
|
|
12831
|
+
return;
|
|
12832
|
+
}
|
|
12833
|
+
this.debug.log(`\u{1F4E5} Received gossip stream chunk ${chunkIndex} for ${streamId.substring(0, 8)}... from ${from.substring(0, 8)}...`);
|
|
12834
|
+
if (!this.gossipStreams.has(streamId)) {
|
|
12835
|
+
const chunks = /* @__PURE__ */ new Map();
|
|
12836
|
+
let controller;
|
|
12837
|
+
const readable = new ReadableStream({
|
|
12838
|
+
start(ctrl) {
|
|
12839
|
+
controller = ctrl;
|
|
12840
|
+
},
|
|
12841
|
+
cancel: (reason) => {
|
|
12842
|
+
this.debug.log(`\u{1F4E5} Gossip stream ${streamId.substring(0, 8)}... cancelled: ${reason}`);
|
|
12843
|
+
}
|
|
12844
|
+
});
|
|
12845
|
+
this.gossipStreams.set(streamId, {
|
|
12846
|
+
chunks,
|
|
12847
|
+
metadata: metadata || {},
|
|
12848
|
+
controller,
|
|
12849
|
+
stream: readable,
|
|
12850
|
+
from,
|
|
12851
|
+
totalChunks: null
|
|
12852
|
+
});
|
|
12853
|
+
this.emit("streamReceived", {
|
|
12854
|
+
peerId: from,
|
|
12855
|
+
streamId,
|
|
12856
|
+
stream: readable,
|
|
12857
|
+
metadata: metadata || {}
|
|
12858
|
+
});
|
|
12859
|
+
}
|
|
12860
|
+
const streamData = this.gossipStreams.get(streamId);
|
|
12861
|
+
streamData.chunks.set(chunkIndex, new Uint8Array(data));
|
|
12862
|
+
this._enqueueOrderedChunks(streamId);
|
|
12863
|
+
}
|
|
12864
|
+
/**
|
|
12865
|
+
* Handle incoming gossip stream control message
|
|
12866
|
+
* @param {Object} message - The stream control message
|
|
12867
|
+
* @param {string} from - Sender peer ID
|
|
12868
|
+
* @private
|
|
12869
|
+
*/
|
|
12870
|
+
_handleGossipStreamControl(message, from) {
|
|
12871
|
+
const { streamId, action, totalChunks, totalBytes, metadata, reason } = message;
|
|
12872
|
+
if (!streamId || !action) {
|
|
12873
|
+
this.debug.error("Invalid gossip stream control format");
|
|
12874
|
+
return;
|
|
12875
|
+
}
|
|
12876
|
+
const streamData = this.gossipStreams.get(streamId);
|
|
12877
|
+
if (!streamData) {
|
|
12878
|
+
this.debug.warn(`Received control message for unknown stream: ${streamId.substring(0, 8)}...`);
|
|
12879
|
+
return;
|
|
12880
|
+
}
|
|
12881
|
+
if (action === "end") {
|
|
12882
|
+
this.debug.log(`\u{1F4E5} Gossip stream ${streamId.substring(0, 8)}... ended: ${totalBytes} bytes in ${totalChunks} chunks`);
|
|
12883
|
+
streamData.totalChunks = totalChunks;
|
|
12884
|
+
this._enqueueOrderedChunks(streamId);
|
|
12885
|
+
if (streamData.controller) {
|
|
12886
|
+
streamData.controller.close();
|
|
12887
|
+
}
|
|
12888
|
+
this.emit("streamCompleted", {
|
|
12889
|
+
peerId: from,
|
|
12890
|
+
streamId,
|
|
12891
|
+
totalChunks,
|
|
12892
|
+
totalBytes
|
|
12893
|
+
});
|
|
12894
|
+
setTimeout(() => {
|
|
12895
|
+
this.gossipStreams.delete(streamId);
|
|
12896
|
+
}, 5e3);
|
|
12897
|
+
} else if (action === "abort") {
|
|
12898
|
+
this.debug.log(`\u274C Gossip stream ${streamId.substring(0, 8)}... aborted: ${reason}`);
|
|
12899
|
+
if (streamData.controller) {
|
|
12900
|
+
streamData.controller.error(new Error(reason || "Stream aborted"));
|
|
12901
|
+
}
|
|
12902
|
+
this.emit("streamAborted", {
|
|
12903
|
+
peerId: from,
|
|
12904
|
+
streamId,
|
|
12905
|
+
reason
|
|
12906
|
+
});
|
|
12907
|
+
this.gossipStreams.delete(streamId);
|
|
12908
|
+
}
|
|
12909
|
+
}
|
|
12910
|
+
/**
|
|
12911
|
+
* Enqueue ordered chunks to the readable stream
|
|
12912
|
+
* @param {string} streamId - The stream ID
|
|
12913
|
+
* @private
|
|
12914
|
+
*/
|
|
12915
|
+
_enqueueOrderedChunks(streamId) {
|
|
12916
|
+
const streamData = this.gossipStreams.get(streamId);
|
|
12917
|
+
if (!streamData || !streamData.controller) return;
|
|
12918
|
+
const { chunks, controller } = streamData;
|
|
12919
|
+
let nextIndex = streamData.nextIndex || 0;
|
|
12920
|
+
while (chunks.has(nextIndex)) {
|
|
12921
|
+
const chunk = chunks.get(nextIndex);
|
|
12922
|
+
try {
|
|
12923
|
+
controller.enqueue(chunk);
|
|
12924
|
+
chunks.delete(nextIndex);
|
|
12925
|
+
nextIndex++;
|
|
12926
|
+
} catch (error) {
|
|
12927
|
+
this.debug.error(`Failed to enqueue chunk ${nextIndex}:`, error);
|
|
12928
|
+
break;
|
|
12929
|
+
}
|
|
12930
|
+
}
|
|
12931
|
+
streamData.nextIndex = nextIndex;
|
|
12932
|
+
}
|
|
12170
12933
|
/**
|
|
12171
12934
|
* Send a signaling message, using mesh connections for renegotiation
|
|
12172
12935
|
* @param {Object} message - The signaling message
|
|
@@ -12470,6 +13233,7 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
12470
13233
|
RTCAdapter,
|
|
12471
13234
|
default: createPigeonRTC
|
|
12472
13235
|
};
|
|
13236
|
+
window.PeerPigeonMesh = PeerPigeonMesh;
|
|
12473
13237
|
}
|
|
12474
13238
|
console.log("\u{1F510} PeerPigeon browser bundle loaded with embedded UnSEA crypto and PigeonRTC");
|
|
12475
13239
|
return __toCommonJS(browser_entry_exports);
|