add WASM browser module and browser demo
This commit is contained in:
331
browser/host/file-host.js
Normal file
331
browser/host/file-host.js
Normal file
@@ -0,0 +1,331 @@
|
||||
/**
|
||||
* File Host — provides extern "env" file I/O functions for WASM.
|
||||
*
|
||||
* Maps to `extern "env" fn js_file_*` declarations in
|
||||
* src/files/filesystem.zig (WASM backend).
|
||||
*
|
||||
* Storage model:
|
||||
* - Upload files: registered as browser File objects (lazy, no upfront copy)
|
||||
* - Small files / WASM-created files: stored as Uint8Array in memory
|
||||
* - Download files: accumulated in memory, retrieved via getFileBlob()
|
||||
* - All files identified by virtual paths (string keys)
|
||||
*
|
||||
* For large uploads, the File object is kept as-is and sliced on demand.
|
||||
* WASM extern "env" reads (js_file_read) work from in-memory data only,
|
||||
* so files must be materialized before WASM can access them. For the
|
||||
* JS-level transfer, we stream directly from the File object.
|
||||
*/
|
||||
|
||||
export class FileHost {
|
||||
/** @type {Map<number, { data: Uint8Array, pos: number, name: string, readOnly: boolean }>} */
|
||||
#files = new Map();
|
||||
/** @type {number} */
|
||||
#nextId = 1;
|
||||
/** @type {Map<string, Uint8Array>} virtual path -> materialized file data */
|
||||
#registered = new Map();
|
||||
/** @type {Map<string, File>} virtual path -> browser File object (lazy, not loaded) */
|
||||
#browserFiles = new Map();
|
||||
/** @type {Set<string>} virtual directory paths */
|
||||
#directories = new Set();
|
||||
/** @type {() => WebAssembly.Memory} */
|
||||
#getMemory;
|
||||
|
||||
/**
|
||||
* @param {() => WebAssembly.Memory} getMemory - Returns the WASM memory instance
|
||||
*/
|
||||
constructor(getMemory) {
|
||||
this.#getMemory = getMemory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register in-memory data for virtual file access (small files, WASM downloads).
|
||||
* @param {string} virtualPath
|
||||
* @param {Uint8Array} data
|
||||
*/
|
||||
registerFile(virtualPath, data) {
|
||||
this.#registered.set(virtualPath, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a browser File object for streaming access.
|
||||
* Does NOT read the file into memory — stores the File handle for
|
||||
* on-demand slice reads via readFileChunk().
|
||||
* @param {File} file
|
||||
* @returns {string} virtual path
|
||||
*/
|
||||
registerBrowserFile(file) {
|
||||
const virtualPath = file.name;
|
||||
this.#browserFiles.set(virtualPath, file);
|
||||
return virtualPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Materialize a browser File into memory so WASM extern "env" can access it.
|
||||
* Only needed if WASM-side code needs to read the file (hashing, etc.).
|
||||
* For JS-level transfers, use readFileChunk() instead.
|
||||
* @param {string} virtualPath
|
||||
* @param {(loaded: number, total: number) => void} [onProgress]
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async materializeFile(virtualPath, onProgress) {
|
||||
const file = this.#browserFiles.get(virtualPath);
|
||||
if (!file) return;
|
||||
if (this.#registered.has(virtualPath)) return; // already materialized
|
||||
|
||||
const total = file.size;
|
||||
const data = new Uint8Array(total);
|
||||
const chunkSize = 4 * 1024 * 1024; // 4MB chunks
|
||||
let offset = 0;
|
||||
|
||||
while (offset < total) {
|
||||
const end = Math.min(offset + chunkSize, total);
|
||||
const slice = file.slice(offset, end);
|
||||
const buf = await slice.arrayBuffer();
|
||||
data.set(new Uint8Array(buf), offset);
|
||||
offset = end;
|
||||
if (onProgress) onProgress(offset, total);
|
||||
}
|
||||
|
||||
this.#registered.set(virtualPath, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a chunk from a browser File without loading the whole file.
|
||||
* Returns a Uint8Array of the requested range.
|
||||
* @param {string} virtualPath
|
||||
* @param {number} offset
|
||||
* @param {number} length
|
||||
* @returns {Promise<Uint8Array>}
|
||||
*/
|
||||
async readFileChunk(virtualPath, offset, length) {
|
||||
// Prefer in-memory data if available
|
||||
const data = this.#registered.get(virtualPath);
|
||||
if (data) {
|
||||
const end = Math.min(offset + length, data.length);
|
||||
return data.subarray(offset, end);
|
||||
}
|
||||
|
||||
// Stream from File object
|
||||
const file = this.#browserFiles.get(virtualPath);
|
||||
if (!file) throw new Error(`File not found: ${virtualPath}`);
|
||||
const end = Math.min(offset + length, file.size);
|
||||
const slice = file.slice(offset, end);
|
||||
const buf = await slice.arrayBuffer();
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get file size without loading into memory.
|
||||
* @param {string} virtualPath
|
||||
* @returns {number | null}
|
||||
*/
|
||||
getFileSize(virtualPath) {
|
||||
const data = this.#registered.get(virtualPath);
|
||||
if (data) return data.length;
|
||||
const file = this.#browserFiles.get(virtualPath);
|
||||
if (file) return file.size;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a completed download as a Blob.
|
||||
* @param {string} virtualPath
|
||||
* @returns {Blob | null}
|
||||
*/
|
||||
getFileBlob(virtualPath) {
|
||||
const data = this.#registered.get(virtualPath);
|
||||
if (data) return new Blob([data]);
|
||||
const file = this.#browserFiles.get(virtualPath);
|
||||
if (file) return file; // File is already a Blob
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file is registered (either in-memory or as File handle).
|
||||
* @param {string} virtualPath
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasFile(virtualPath) {
|
||||
return this.#registered.has(virtualPath) || this.#browserFiles.has(virtualPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered file paths.
|
||||
* @returns {string[]}
|
||||
*/
|
||||
listFiles() {
|
||||
return [...new Set([...this.#registered.keys(), ...this.#browserFiles.keys()])];
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// extern "env" implementations (work with in-memory data only)
|
||||
// ============================================================
|
||||
|
||||
#readString(ptr, len) {
|
||||
const bytes = new Uint8Array(this.#getMemory().buffer, ptr, len);
|
||||
return new TextDecoder().decode(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open an existing file. Returns file_id >= 0 or -1 on error.
|
||||
* Only works with materialized (in-memory) files.
|
||||
*/
|
||||
js_file_open(pathPtr, pathLen, readOnly) {
|
||||
const path = this.#readString(pathPtr, pathLen);
|
||||
const data = this.#registered.get(path);
|
||||
if (!data) return -1;
|
||||
|
||||
const fileId = this.#nextId++;
|
||||
this.#files.set(fileId, {
|
||||
data: readOnly ? data : new Uint8Array(data), // copy for writable
|
||||
pos: 0,
|
||||
name: path,
|
||||
readOnly: readOnly === 1,
|
||||
});
|
||||
return fileId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new file. Returns file_id >= 0 or -1 on error.
|
||||
*/
|
||||
js_file_create(pathPtr, pathLen) {
|
||||
const path = this.#readString(pathPtr, pathLen);
|
||||
|
||||
const fileId = this.#nextId++;
|
||||
const data = new Uint8Array(0);
|
||||
this.#registered.set(path, data);
|
||||
this.#files.set(fileId, {
|
||||
data,
|
||||
pos: 0,
|
||||
name: path,
|
||||
readOnly: false,
|
||||
});
|
||||
return fileId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read from file at offset. Returns bytes read or -1 on error.
|
||||
*/
|
||||
js_file_read(fileId, bufPtr, bufLen, offset) {
|
||||
const file = this.#files.get(fileId);
|
||||
if (!file) return -1;
|
||||
|
||||
// Use BigInt-safe conversion (offset comes as i64 from WASM)
|
||||
const off = Number(offset);
|
||||
const available = Math.max(0, file.data.length - off);
|
||||
const toRead = Math.min(bufLen, available);
|
||||
if (toRead <= 0) return 0;
|
||||
|
||||
const dest = new Uint8Array(this.#getMemory().buffer, bufPtr, toRead);
|
||||
dest.set(file.data.subarray(off, off + toRead));
|
||||
return toRead;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write to file at offset. Returns bytes written or -1 on error.
|
||||
*/
|
||||
js_file_write(fileId, dataPtr, dataLen, offset) {
|
||||
const file = this.#files.get(fileId);
|
||||
if (!file || file.readOnly) return -1;
|
||||
|
||||
const off = Number(offset);
|
||||
const src = new Uint8Array(this.#getMemory().buffer, dataPtr, dataLen);
|
||||
|
||||
// Grow file if needed
|
||||
const needed = off + dataLen;
|
||||
if (needed > file.data.length) {
|
||||
const newData = new Uint8Array(needed);
|
||||
newData.set(file.data);
|
||||
file.data = newData;
|
||||
// Update registered copy
|
||||
this.#registered.set(file.name, file.data);
|
||||
}
|
||||
|
||||
file.data.set(src, off);
|
||||
return dataLen;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get file size. Returns size >= 0 or -1 on error.
|
||||
*/
|
||||
js_file_get_size(fileId) {
|
||||
const file = this.#files.get(fileId);
|
||||
if (!file) return -1n; // BigInt for i64 return
|
||||
return BigInt(file.data.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Close a file handle.
|
||||
*/
|
||||
js_file_close(fileId) {
|
||||
this.#files.delete(fileId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file exists. Returns 1 if exists, 0 if not.
|
||||
*/
|
||||
js_file_exists(pathPtr, pathLen) {
|
||||
const path = this.#readString(pathPtr, pathLen);
|
||||
return this.#registered.has(path) || this.#browserFiles.has(path) || this.#directories.has(path) ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a file. Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
js_file_delete(pathPtr, pathLen) {
|
||||
const path = this.#readString(pathPtr, pathLen);
|
||||
const a = this.#registered.delete(path);
|
||||
const b = this.#browserFiles.delete(path);
|
||||
return (a || b) ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename a file. Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
js_file_rename(oldPtr, oldLen, newPtr, newLen) {
|
||||
const oldPath = this.#readString(oldPtr, oldLen);
|
||||
const newPath = this.#readString(newPtr, newLen);
|
||||
const data = this.#registered.get(oldPath);
|
||||
if (data) {
|
||||
this.#registered.delete(oldPath);
|
||||
this.#registered.set(newPath, data);
|
||||
return 1;
|
||||
}
|
||||
const file = this.#browserFiles.get(oldPath);
|
||||
if (file) {
|
||||
this.#browserFiles.delete(oldPath);
|
||||
this.#browserFiles.set(newPath, file);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a directory (no-op in memory model, just track it).
|
||||
* Returns 1 on success.
|
||||
*/
|
||||
js_file_mkdir(pathPtr, pathLen) {
|
||||
const path = this.#readString(pathPtr, pathLen);
|
||||
this.#directories.add(path);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the env bindings to merge into the WASM import object.
|
||||
* @returns {Record<string, Function>}
|
||||
*/
|
||||
getEnvBindings() {
|
||||
return {
|
||||
js_file_open: (p, l, r) => this.js_file_open(p, l, r),
|
||||
js_file_create: (p, l) => this.js_file_create(p, l),
|
||||
js_file_read: (f, b, l, o) => this.js_file_read(f, b, l, o),
|
||||
js_file_write: (f, d, l, o) => this.js_file_write(f, d, l, o),
|
||||
js_file_get_size: (f) => this.js_file_get_size(f),
|
||||
js_file_close: (f) => this.js_file_close(f),
|
||||
js_file_exists: (p, l) => this.js_file_exists(p, l),
|
||||
js_file_delete: (p, l) => this.js_file_delete(p, l),
|
||||
js_file_rename: (op, ol, np, nl) => this.js_file_rename(op, ol, np, nl),
|
||||
js_file_mkdir: (p, l) => this.js_file_mkdir(p, l),
|
||||
};
|
||||
}
|
||||
}
|
||||
16
browser/host/package.json
Normal file
16
browser/host/package.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "@zig-p2p/browser-host",
|
||||
"version": "0.1.0",
|
||||
"description": "Browser host for zig-p2p WASM module",
|
||||
"type": "module",
|
||||
"main": "zig-p2p.js",
|
||||
"exports": {
|
||||
".": "./zig-p2p.js"
|
||||
},
|
||||
"files": [
|
||||
"zig-p2p.js",
|
||||
"platform-env.js",
|
||||
"webrtc-host.js",
|
||||
"signaling.js"
|
||||
]
|
||||
}
|
||||
66
browser/host/platform-env.js
Normal file
66
browser/host/platform-env.js
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Platform environment — provides extern "env" functions for the WASM module.
|
||||
*
|
||||
* These map directly to the `extern "env" fn js_*` declarations in the Zig
|
||||
* platform abstraction layer (src/platform/time.zig, random.zig, etc.).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Create the env import object for WASM instantiation.
|
||||
* @param {() => WebAssembly.Memory} getMemory - Returns the WASM memory instance
|
||||
* @returns {Record<string, Function>} env imports
|
||||
*/
|
||||
export function createPlatformEnv(getMemory) {
|
||||
return {
|
||||
// -- Time (src/platform/time.zig) --
|
||||
|
||||
/** @returns {bigint} milliseconds since epoch */
|
||||
js_timestamp_ms() {
|
||||
return BigInt(Date.now());
|
||||
},
|
||||
|
||||
/** @returns {bigint} nanoseconds since epoch (ms precision in browser) */
|
||||
js_timestamp_ns() {
|
||||
return BigInt(Date.now()) * 1_000_000n;
|
||||
},
|
||||
|
||||
// -- Random (src/platform/random.zig) --
|
||||
|
||||
/** Fill buffer with cryptographically secure random bytes */
|
||||
js_random_bytes(ptr, len) {
|
||||
const bytes = new Uint8Array(getMemory().buffer, ptr, len);
|
||||
crypto.getRandomValues(bytes);
|
||||
},
|
||||
|
||||
// -- Logging (src/wasm/main.zig) --
|
||||
|
||||
/** Log a message from WASM to the browser console */
|
||||
js_log(ptr, len) {
|
||||
const bytes = new Uint8Array(getMemory().buffer, ptr, len);
|
||||
const msg = new TextDecoder().decode(bytes);
|
||||
console.log('[zig-p2p]', msg);
|
||||
},
|
||||
|
||||
// -- WebRTC DataChannel (src/platform/webrtc_wasm.zig) --
|
||||
// These are called by the WASM transport when sending data.
|
||||
// They are wired to the WebRTCHost by zig-p2p.js during initialization.
|
||||
|
||||
/** Send data on a DataChannel. Returns 0 on success, -1 on error. */
|
||||
js_datachannel_send(channelId, dataPtr, dataLen) {
|
||||
// Overridden by zig-p2p.js to route to WebRTCHost
|
||||
console.warn('[zig-p2p] js_datachannel_send called before WebRTCHost wired');
|
||||
return -1;
|
||||
},
|
||||
|
||||
/** Close a DataChannel */
|
||||
js_datachannel_close(channelId) {
|
||||
// Overridden by zig-p2p.js to route to WebRTCHost
|
||||
},
|
||||
|
||||
/** Get buffered amount for a DataChannel */
|
||||
js_datachannel_buffered_amount(channelId) {
|
||||
// Overridden by zig-p2p.js to route to WebRTCHost
|
||||
return 0;
|
||||
},
|
||||
};
|
||||
}
|
||||
137
browser/host/signaling.js
Normal file
137
browser/host/signaling.js
Normal file
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* WebSocket signaling client for WebRTC SDP/ICE exchange.
|
||||
*
|
||||
* Connects to the signaling server and relays offers, answers, and ICE
|
||||
* candidates between peers. The signaling server is a simple JSON relay
|
||||
* (see browser/signaling-server/server.js).
|
||||
*/
|
||||
|
||||
export class SignalingClient {
|
||||
/** @type {WebSocket | null} */
|
||||
#ws = null;
|
||||
/** @type {string} */
|
||||
#url;
|
||||
/** @type {string} */
|
||||
#peerId;
|
||||
/** @type {Map<string, Function[]>} */
|
||||
#handlers = new Map();
|
||||
/** @type {boolean} */
|
||||
#connected = false;
|
||||
/** @type {number | null} */
|
||||
#heartbeatTimer = null;
|
||||
|
||||
/**
|
||||
* @param {string} url - WebSocket URL of the signaling server
|
||||
* @param {string} peerId - This peer's unique ID
|
||||
*/
|
||||
constructor(url, peerId) {
|
||||
this.#url = url;
|
||||
this.#peerId = peerId;
|
||||
}
|
||||
|
||||
get connected() {
|
||||
return this.#connected;
|
||||
}
|
||||
|
||||
get peerId() {
|
||||
return this.#peerId;
|
||||
}
|
||||
|
||||
/** Connect to the signaling server. */
|
||||
connect() {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.#ws = new WebSocket(this.#url);
|
||||
|
||||
this.#ws.onopen = () => {
|
||||
this.#connected = true;
|
||||
// Register our peer ID with the server
|
||||
this.#send({ type: 'register', peerId: this.#peerId });
|
||||
// Start heartbeat
|
||||
this.#heartbeatTimer = setInterval(() => {
|
||||
if (this.#connected) this.#send({ type: 'ping' });
|
||||
}, 30_000);
|
||||
resolve();
|
||||
};
|
||||
|
||||
this.#ws.onmessage = (event) => {
|
||||
try {
|
||||
const msg = JSON.parse(event.data);
|
||||
this.#dispatch(msg.type, msg);
|
||||
} catch (e) {
|
||||
console.warn('[signaling] Failed to parse message:', e);
|
||||
}
|
||||
};
|
||||
|
||||
this.#ws.onclose = () => {
|
||||
this.#connected = false;
|
||||
this.#stopHeartbeat();
|
||||
this.#dispatch('disconnect', {});
|
||||
};
|
||||
|
||||
this.#ws.onerror = (err) => {
|
||||
if (!this.#connected) reject(err);
|
||||
this.#dispatch('error', { error: err });
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Disconnect from the signaling server. */
|
||||
disconnect() {
|
||||
this.#stopHeartbeat();
|
||||
if (this.#ws) {
|
||||
this.#ws.close();
|
||||
this.#ws = null;
|
||||
}
|
||||
this.#connected = false;
|
||||
}
|
||||
|
||||
/** Send an SDP offer to a remote peer. */
|
||||
sendOffer(to, sdp) {
|
||||
this.#send({ type: 'offer', to, sdp });
|
||||
}
|
||||
|
||||
/** Send an SDP answer to a remote peer. */
|
||||
sendAnswer(to, sdp) {
|
||||
this.#send({ type: 'answer', to, sdp });
|
||||
}
|
||||
|
||||
/** Send an ICE candidate to a remote peer. */
|
||||
sendCandidate(to, candidate, sdpMid) {
|
||||
this.#send({ type: 'candidate', to, candidate, sdpMid });
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an event handler.
|
||||
* @param {'offer'|'answer'|'candidate'|'error'|'disconnect'} type
|
||||
* @param {Function} handler
|
||||
*/
|
||||
on(type, handler) {
|
||||
if (!this.#handlers.has(type)) this.#handlers.set(type, []);
|
||||
this.#handlers.get(type).push(handler);
|
||||
}
|
||||
|
||||
/** Remove all handlers for a given event type. */
|
||||
off(type) {
|
||||
this.#handlers.delete(type);
|
||||
}
|
||||
|
||||
#send(msg) {
|
||||
if (this.#ws && this.#ws.readyState === WebSocket.OPEN) {
|
||||
this.#ws.send(JSON.stringify(msg));
|
||||
}
|
||||
}
|
||||
|
||||
#dispatch(type, msg) {
|
||||
const handlers = this.#handlers.get(type);
|
||||
if (handlers) {
|
||||
for (const handler of handlers) handler(msg);
|
||||
}
|
||||
}
|
||||
|
||||
#stopHeartbeat() {
|
||||
if (this.#heartbeatTimer !== null) {
|
||||
clearInterval(this.#heartbeatTimer);
|
||||
this.#heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
323
browser/host/webrtc-host.js
Normal file
323
browser/host/webrtc-host.js
Normal file
@@ -0,0 +1,323 @@
|
||||
/**
|
||||
* WebRTC host — manages RTCPeerConnection and DataChannel instances
|
||||
* on behalf of the WASM module.
|
||||
*
|
||||
* The WASM side sees channels as integer IDs. This host maps those IDs
|
||||
* to browser RTCDataChannel objects and routes events back to WASM via
|
||||
* the exported callback functions.
|
||||
*/
|
||||
|
||||
export class WebRTCHost {
|
||||
/** @type {Map<number, RTCDataChannel>} channel_id → DataChannel */
|
||||
#channels = new Map();
|
||||
/** @type {Map<number, boolean>} channelId → true if we created the offer */
|
||||
#channelRoles = new Map();
|
||||
/** @type {Map<string, RTCPeerConnection>} remote_peer_id → PeerConnection */
|
||||
#peerConnections = new Map();
|
||||
/** @type {number} next channel ID to assign */
|
||||
#nextChannelId = 1;
|
||||
/** @type {RTCConfiguration} */
|
||||
#rtcConfig;
|
||||
/** @type {object | null} WASM exports (set after load) */
|
||||
#wasm = null;
|
||||
/** @type {number} WASM instance ID */
|
||||
#instanceId = 0;
|
||||
/** @type {import('./signaling.js').SignalingClient | null} */
|
||||
#signaling = null;
|
||||
/** @type {Array<(channelId: number, appId: number, payload: Uint8Array) => void>} */
|
||||
#directHandlers = [];
|
||||
/** Direct message prefix byte — distinguishes from P2P-framed messages */
|
||||
static DIRECT_PREFIX = 0xFF;
|
||||
|
||||
/**
|
||||
* @param {RTCConfiguration} [rtcConfig] - ICE server configuration
|
||||
*/
|
||||
constructor(rtcConfig) {
|
||||
this.#rtcConfig = rtcConfig || {
|
||||
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind to WASM exports so we can call back into the module.
|
||||
* @param {object} wasmExports - The WASM module's exports
|
||||
* @param {number} instanceId - The P2P instance ID in WASM
|
||||
*/
|
||||
bind(wasmExports, instanceId) {
|
||||
this.#wasm = wasmExports;
|
||||
this.#instanceId = instanceId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind to a signaling client for SDP/ICE exchange.
|
||||
* @param {import('./signaling.js').SignalingClient} signaling
|
||||
*/
|
||||
bindSignaling(signaling) {
|
||||
this.#signaling = signaling;
|
||||
|
||||
signaling.on('offer', (msg) => this.handleOffer(msg.from, msg.sdp));
|
||||
signaling.on('answer', (msg) => this.handleAnswer(msg.from, msg.sdp));
|
||||
signaling.on('candidate', (msg) =>
|
||||
this.handleCandidate(msg.from, msg.candidate, msg.sdpMid)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiate a WebRTC connection to a remote peer.
|
||||
* @param {string} remotePeerId - The remote peer's signaling ID
|
||||
* @returns {Promise<number>} The channel ID assigned to this connection
|
||||
*/
|
||||
async connectToPeer(remotePeerId) {
|
||||
const pc = this.#createPeerConnection(remotePeerId);
|
||||
const dc = pc.createDataChannel('zig-p2p', {
|
||||
protocol: 'zig-p2p',
|
||||
ordered: true,
|
||||
});
|
||||
|
||||
const channelId = this.#registerChannel(dc);
|
||||
this.#channelRoles.set(channelId, true); // outbound = initiator
|
||||
this.#setupDataChannel(dc, channelId);
|
||||
|
||||
const offer = await pc.createOffer();
|
||||
await pc.setLocalDescription(offer);
|
||||
|
||||
this.#signaling?.sendOffer(remotePeerId, pc.localDescription.sdp);
|
||||
return channelId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming SDP offer from a remote peer.
|
||||
* @param {string} fromPeerId
|
||||
* @param {string} sdp
|
||||
*/
|
||||
async handleOffer(fromPeerId, sdp) {
|
||||
const pc = this.#createPeerConnection(fromPeerId);
|
||||
|
||||
pc.ondatachannel = (event) => {
|
||||
const dc = event.channel;
|
||||
const channelId = this.#registerChannel(dc);
|
||||
this.#channelRoles.set(channelId, false); // inbound = responder
|
||||
this.#setupDataChannel(dc, channelId);
|
||||
};
|
||||
|
||||
await pc.setRemoteDescription({ type: 'offer', sdp });
|
||||
const answer = await pc.createAnswer();
|
||||
await pc.setLocalDescription(answer);
|
||||
|
||||
this.#signaling?.sendAnswer(fromPeerId, pc.localDescription.sdp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming SDP answer.
|
||||
* @param {string} fromPeerId
|
||||
* @param {string} sdp
|
||||
*/
|
||||
async handleAnswer(fromPeerId, sdp) {
|
||||
const pc = this.#peerConnections.get(fromPeerId);
|
||||
if (!pc) {
|
||||
console.warn('[webrtc] Got answer from unknown peer:', fromPeerId);
|
||||
return;
|
||||
}
|
||||
await pc.setRemoteDescription({ type: 'answer', sdp });
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming ICE candidate.
|
||||
* @param {string} fromPeerId
|
||||
* @param {string} candidate
|
||||
* @param {string} sdpMid
|
||||
*/
|
||||
async handleCandidate(fromPeerId, candidate, sdpMid) {
|
||||
const pc = this.#peerConnections.get(fromPeerId);
|
||||
if (!pc) return;
|
||||
await pc.addIceCandidate({ candidate, sdpMid });
|
||||
}
|
||||
|
||||
/**
|
||||
* Send data on a channel (called by WASM via extern "env").
|
||||
* @param {number} channelId
|
||||
* @param {Uint8Array} data
|
||||
* @returns {number} 0 on success, -1 on error
|
||||
*/
|
||||
send(channelId, data) {
|
||||
const dc = this.#channels.get(channelId);
|
||||
if (!dc || dc.readyState !== 'open') return -1;
|
||||
try {
|
||||
dc.send(data);
|
||||
return 0;
|
||||
} catch {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close a channel (called by WASM via extern "env").
|
||||
* @param {number} channelId
|
||||
*/
|
||||
closeChannel(channelId) {
|
||||
const dc = this.#channels.get(channelId);
|
||||
if (dc) {
|
||||
dc.close();
|
||||
this.#channels.delete(channelId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get buffered amount for a channel (called by WASM via extern "env").
|
||||
* @param {number} channelId
|
||||
* @returns {number}
|
||||
*/
|
||||
bufferedAmount(channelId) {
|
||||
const dc = this.#channels.get(channelId);
|
||||
return dc ? dc.bufferedAmount : 0;
|
||||
}
|
||||
|
||||
/** Close all connections and clean up. */
|
||||
destroy() {
|
||||
for (const dc of this.#channels.values()) {
|
||||
dc.close();
|
||||
}
|
||||
this.#channels.clear();
|
||||
this.#channelRoles.clear();
|
||||
for (const pc of this.#peerConnections.values()) {
|
||||
pc.close();
|
||||
}
|
||||
this.#peerConnections.clear();
|
||||
}
|
||||
|
||||
/** @returns {number} Number of active channels */
|
||||
get channelCount() {
|
||||
return this.#channels.size;
|
||||
}
|
||||
|
||||
/** @returns {number[]} All active channel IDs */
|
||||
getChannelIds() {
|
||||
return [...this.#channels.keys()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total buffered amount across all channels (for flow control).
|
||||
* @returns {number} Sum of all DataChannel bufferedAmount values
|
||||
*/
|
||||
get totalBufferedAmount() {
|
||||
let total = 0;
|
||||
for (const dc of this.#channels.values()) {
|
||||
total += dc.bufferedAmount;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a pre-formatted direct message on a DataChannel.
|
||||
* The caller must include the [0xFF][app_id] prefix in the data.
|
||||
* This avoids an extra copy for large payloads.
|
||||
* @param {number} channelId
|
||||
* @param {Uint8Array} data - Complete message including 0xFF prefix
|
||||
* @returns {boolean} true on success
|
||||
*/
|
||||
sendDirect(channelId, data) {
|
||||
const dc = this.#channels.get(channelId);
|
||||
if (!dc || dc.readyState !== 'open') return false;
|
||||
try {
|
||||
dc.send(data);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a handler for direct messages (0xFF-prefixed).
|
||||
* Handler receives (channelId, appId, payload).
|
||||
* @param {(channelId: number, appId: number, payload: Uint8Array) => void} handler
|
||||
*/
|
||||
registerDirectHandler(handler) {
|
||||
this.#directHandlers.push(handler);
|
||||
}
|
||||
|
||||
// -- Private helpers --
|
||||
|
||||
#createPeerConnection(remotePeerId) {
|
||||
// Close existing connection to same peer if any
|
||||
const existing = this.#peerConnections.get(remotePeerId);
|
||||
if (existing) existing.close();
|
||||
|
||||
const pc = new RTCPeerConnection(this.#rtcConfig);
|
||||
this.#peerConnections.set(remotePeerId, pc);
|
||||
|
||||
pc.onicecandidate = (event) => {
|
||||
if (event.candidate) {
|
||||
this.#signaling?.sendCandidate(
|
||||
remotePeerId,
|
||||
event.candidate.candidate,
|
||||
event.candidate.sdpMid
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
pc.onconnectionstatechange = () => {
|
||||
if (pc.connectionState === 'failed' || pc.connectionState === 'closed') {
|
||||
this.#peerConnections.delete(remotePeerId);
|
||||
}
|
||||
};
|
||||
|
||||
return pc;
|
||||
}
|
||||
|
||||
#registerChannel(dc) {
|
||||
const channelId = this.#nextChannelId++;
|
||||
this.#channels.set(channelId, dc);
|
||||
return channelId;
|
||||
}
|
||||
|
||||
#setupDataChannel(dc, channelId) {
|
||||
dc.binaryType = 'arraybuffer';
|
||||
|
||||
dc.onopen = () => {
|
||||
const isInitiator = this.#channelRoles.get(channelId) ?? false;
|
||||
this.#wasm?.wasm_on_datachannel_open(this.#instanceId, channelId, isInitiator ? 1 : 0);
|
||||
};
|
||||
|
||||
dc.onmessage = (event) => {
|
||||
const data = new Uint8Array(event.data);
|
||||
|
||||
// Direct message path: 0xFF prefix → JS handlers only, never enters WASM.
|
||||
// This eliminates 3 alloc+copy cycles per message through the WASM stack.
|
||||
if (data.length >= 2 && data[0] === WebRTCHost.DIRECT_PREFIX) {
|
||||
const appId = data[1];
|
||||
const payload = data.subarray(2);
|
||||
for (const handler of this.#directHandlers) {
|
||||
try { handler(channelId, appId, payload); } catch {}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// P2P-framed message → route through WASM
|
||||
if (!this.#wasm) return;
|
||||
const ptr = this.#wasm.wasm_alloc(data.length);
|
||||
if (!ptr) {
|
||||
console.warn('[webrtc] Failed to allocate WASM memory for message');
|
||||
return;
|
||||
}
|
||||
const wasmBuf = new Uint8Array(this.#wasm.memory.buffer, ptr, data.length);
|
||||
wasmBuf.set(data);
|
||||
this.#wasm.wasm_on_datachannel_message(
|
||||
this.#instanceId,
|
||||
channelId,
|
||||
ptr,
|
||||
data.length
|
||||
);
|
||||
this.#wasm.wasm_free(ptr, data.length);
|
||||
};
|
||||
|
||||
dc.onclose = () => {
|
||||
this.#wasm?.wasm_on_datachannel_close(this.#instanceId, channelId);
|
||||
this.#channels.delete(channelId);
|
||||
this.#channelRoles.delete(channelId);
|
||||
};
|
||||
|
||||
dc.onerror = () => {
|
||||
this.#wasm?.wasm_on_datachannel_error(this.#instanceId, channelId);
|
||||
};
|
||||
}
|
||||
}
|
||||
461
browser/host/zig-p2p.js
Normal file
461
browser/host/zig-p2p.js
Normal file
@@ -0,0 +1,461 @@
|
||||
/**
|
||||
* zig-p2p Browser Host
|
||||
*
|
||||
* Loads the WASM module, provides platform APIs, and manages WebRTC
|
||||
* connections. The entire P2P protocol (Noise, DHT, messaging, wire
|
||||
* envelope) runs inside WASM — this is a thin glue layer.
|
||||
*
|
||||
* Usage:
|
||||
* import { ZigP2P } from './zig-p2p.js';
|
||||
*
|
||||
* const p2p = await ZigP2P.load('/zig-p2p.wasm', {
|
||||
* signalingUrl: 'ws://localhost:8080',
|
||||
* iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
|
||||
* });
|
||||
*
|
||||
* p2p.onMessage((peerId, appId, data) => { ... });
|
||||
* await p2p.connectToPeer('remote-peer-id');
|
||||
* p2p.send(peerId, 0x03, new Uint8Array([1, 2, 3]));
|
||||
*/
|
||||
|
||||
import { createPlatformEnv } from './platform-env.js';
|
||||
import { WebRTCHost } from './webrtc-host.js';
|
||||
import { SignalingClient } from './signaling.js';
|
||||
import { FileHost } from './file-host.js';
|
||||
|
||||
export class ZigP2P {
|
||||
/** @type {WebAssembly.Instance} */
|
||||
#wasmInstance;
|
||||
/** @type {WebAssembly.Memory} */
|
||||
#memory;
|
||||
/** @type {object} WASM exports */
|
||||
#exports;
|
||||
/** @type {number} WASM P2P instance ID */
|
||||
#instanceId;
|
||||
/** @type {WebRTCHost} */
|
||||
#webrtcHost;
|
||||
/** @type {SignalingClient} */
|
||||
#signaling;
|
||||
/** @type {number | null} update interval handle */
|
||||
#updateTimer = null;
|
||||
/** @type {Function[]} message handlers */
|
||||
#messageHandlers = [];
|
||||
/** @type {Function[]} connection handlers */
|
||||
#connectionHandlers = [];
|
||||
/** @type {Function[]} file event handlers */
|
||||
#fileEventHandlers = [];
|
||||
/** @type {FileHost} */
|
||||
#fileHost;
|
||||
/** @type {boolean} */
|
||||
#destroyed = false;
|
||||
/** @type {number} WASM pointer for event polling buffer */
|
||||
#eventBufPtr = 0;
|
||||
/** @type {number} */
|
||||
#eventBufLen = 0;
|
||||
/** @type {Map<number, number>} channelId → channelId (identity, for reverse lookup from peerId) */
|
||||
#peerIdToChannel = new Map(); // peerId hex → channelId
|
||||
|
||||
/**
|
||||
* Load the WASM module and initialize the P2P library.
|
||||
*
|
||||
* @param {string | URL | ArrayBuffer} wasmSource - URL to .wasm file, or raw bytes
|
||||
* @param {object} config
|
||||
* @param {string} config.signalingUrl - WebSocket URL of the signaling server
|
||||
* @param {string} [config.peerId] - Peer ID for signaling (random if not set)
|
||||
* @param {number} [config.listenPort=0] - Port (unused in browser, passed to WASM init)
|
||||
* @param {RTCConfiguration} [config.rtcConfig] - WebRTC ICE configuration
|
||||
* @param {number} [config.updateIntervalMs=16] - How often to call wasm_p2p_update
|
||||
* @returns {Promise<ZigP2P>}
|
||||
*/
|
||||
static async load(wasmSource, config) {
|
||||
const instance = new ZigP2P();
|
||||
await instance.#init(wasmSource, config);
|
||||
return instance;
|
||||
}
|
||||
|
||||
async #init(wasmSource, config) {
|
||||
const {
|
||||
signalingUrl,
|
||||
peerId = crypto.randomUUID(),
|
||||
listenPort = 0,
|
||||
rtcConfig,
|
||||
updateIntervalMs = 16,
|
||||
} = config;
|
||||
|
||||
// 1. Create WebRTC host and file host
|
||||
this.#webrtcHost = new WebRTCHost(rtcConfig);
|
||||
let memory;
|
||||
this.#fileHost = new FileHost(() => memory);
|
||||
|
||||
// 2. Create platform env with WebRTC + file wiring
|
||||
const env = {
|
||||
...createPlatformEnv(() => memory),
|
||||
...this.#fileHost.getEnvBindings(),
|
||||
};
|
||||
|
||||
// Wire datachannel extern "env" functions to the WebRTC host
|
||||
env.js_datachannel_send = (channelId, dataPtr, dataLen) => {
|
||||
const data = new Uint8Array(memory.buffer, dataPtr, dataLen);
|
||||
return this.#webrtcHost.send(channelId, data);
|
||||
};
|
||||
env.js_datachannel_close = (channelId) => {
|
||||
this.#webrtcHost.closeChannel(channelId);
|
||||
};
|
||||
env.js_datachannel_buffered_amount = (channelId) => {
|
||||
return this.#webrtcHost.bufferedAmount(channelId);
|
||||
};
|
||||
|
||||
// 3. Load WASM module
|
||||
let wasmBytes;
|
||||
if (wasmSource instanceof ArrayBuffer) {
|
||||
wasmBytes = wasmSource;
|
||||
} else {
|
||||
const response = await fetch(wasmSource);
|
||||
wasmBytes = await response.arrayBuffer();
|
||||
}
|
||||
|
||||
const { instance } = await WebAssembly.instantiate(wasmBytes, { env });
|
||||
this.#wasmInstance = instance;
|
||||
this.#exports = instance.exports;
|
||||
memory = instance.exports.memory;
|
||||
this.#memory = memory;
|
||||
|
||||
// 4. Initialize P2P instance in WASM
|
||||
this.#instanceId = this.#exports.wasm_p2p_init(listenPort);
|
||||
if (this.#instanceId < 0) {
|
||||
throw new Error('Failed to initialize P2P instance in WASM');
|
||||
}
|
||||
|
||||
// 5. Bind WebRTC host to WASM exports
|
||||
this.#webrtcHost.bind(
|
||||
{ ...this.#exports, memory: this.#memory },
|
||||
this.#instanceId
|
||||
);
|
||||
|
||||
// 6. Connect to signaling server
|
||||
this.#signaling = new SignalingClient(signalingUrl, peerId);
|
||||
this.#webrtcHost.bindSignaling(this.#signaling);
|
||||
await this.#signaling.connect();
|
||||
|
||||
// 7. Allocate event polling buffer (reused every tick)
|
||||
// 2MB to support large file chunks (up to 1MB+ per message)
|
||||
this.#eventBufPtr = this.#exports.wasm_alloc(2097152);
|
||||
this.#eventBufLen = 2097152;
|
||||
|
||||
// 8. Start update loop
|
||||
this.#updateTimer = setInterval(() => {
|
||||
if (!this.#destroyed) {
|
||||
this.#exports.wasm_p2p_update(this.#instanceId);
|
||||
this.#drainEvents();
|
||||
}
|
||||
}, updateIntervalMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to a remote peer via WebRTC (through signaling server).
|
||||
* @param {string} remotePeerId - The remote peer's signaling ID
|
||||
* @returns {Promise<number>} Channel ID
|
||||
*/
|
||||
async connectToPeer(remotePeerId) {
|
||||
return this.#webrtcHost.connectToPeer(remotePeerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the 32-byte P2P PeerId for a given WebRTC channel.
|
||||
* @param {number} channelId - The WebRTC channel ID
|
||||
* @returns {Uint8Array | null} 32-byte PeerId, or null on failure
|
||||
*/
|
||||
getPeerIdForChannel(channelId) {
|
||||
if (this.#destroyed) return null;
|
||||
const outPtr = this.#exports.wasm_alloc(32);
|
||||
if (!outPtr) return null;
|
||||
try {
|
||||
const result = this.#exports.wasm_get_peer_id_for_channel(
|
||||
this.#instanceId,
|
||||
channelId,
|
||||
outPtr
|
||||
);
|
||||
if (result !== 0) return null;
|
||||
const bytes = new Uint8Array(32);
|
||||
bytes.set(new Uint8Array(this.#memory.buffer, outPtr, 32));
|
||||
return bytes;
|
||||
} finally {
|
||||
this.#exports.wasm_free(outPtr, 32);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to a peer.
|
||||
* @param {Uint8Array} peerId - 32-byte peer ID
|
||||
* @param {number} appId - Application ID byte
|
||||
* @param {Uint8Array} data - Message payload
|
||||
* @returns {boolean} true on success
|
||||
*/
|
||||
send(peerId, appId, data) {
|
||||
if (this.#destroyed) return false;
|
||||
|
||||
// Allocate WASM memory for peer ID + data
|
||||
const peerPtr = this.#exports.wasm_alloc(peerId.length);
|
||||
const dataPtr = this.#exports.wasm_alloc(data.length);
|
||||
if (!peerPtr || !dataPtr) return false;
|
||||
|
||||
try {
|
||||
new Uint8Array(this.#memory.buffer, peerPtr, peerId.length).set(peerId);
|
||||
new Uint8Array(this.#memory.buffer, dataPtr, data.length).set(data);
|
||||
const result = this.#exports.wasm_p2p_send(
|
||||
this.#instanceId,
|
||||
peerPtr,
|
||||
appId,
|
||||
dataPtr,
|
||||
data.length
|
||||
);
|
||||
return result === 0;
|
||||
} finally {
|
||||
this.#exports.wasm_free(peerPtr, peerId.length);
|
||||
this.#exports.wasm_free(dataPtr, data.length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a message handler.
|
||||
* @param {(peerId: Uint8Array, appId: number, data: Uint8Array) => void} handler
|
||||
*/
|
||||
onMessage(handler) {
|
||||
this.#messageHandlers.push(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a connection handler.
|
||||
* @param {(peerId: string, channelId: number) => void} handler
|
||||
*/
|
||||
onConnection(handler) {
|
||||
this.#connectionHandlers.push(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a pre-formatted direct message on a DataChannel, bypassing WASM.
|
||||
* The data must include the [0xFF][app_id] prefix. Use for high-throughput
|
||||
* data (file chunks) where WASM alloc/copy overhead is wasteful.
|
||||
* @param {number} channelId - The WebRTC channel ID
|
||||
* @param {Uint8Array} data - Complete message including 0xFF prefix
|
||||
* @returns {boolean} true on success
|
||||
*/
|
||||
sendDirect(channelId, data) {
|
||||
if (this.#destroyed) return false;
|
||||
return this.#webrtcHost.sendDirect(channelId, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a handler for direct messages (bypasses WASM).
|
||||
* @param {(channelId: number, appId: number, payload: Uint8Array) => void} handler
|
||||
*/
|
||||
onDirectMessage(handler) {
|
||||
this.#webrtcHost.registerDirectHandler(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all active channel IDs.
|
||||
* @returns {number[]}
|
||||
*/
|
||||
getChannelIds() {
|
||||
return this.#webrtcHost.getChannelIds();
|
||||
}
|
||||
|
||||
/** @returns {number} Library version from WASM */
|
||||
get version() {
|
||||
return this.#exports.wasm_version();
|
||||
}
|
||||
|
||||
/** @returns {string} This peer's signaling ID */
|
||||
get peerId() {
|
||||
return this.#signaling.peerId;
|
||||
}
|
||||
|
||||
/** @returns {boolean} Whether connected to signaling server */
|
||||
get signalingConnected() {
|
||||
return this.#signaling.connected;
|
||||
}
|
||||
|
||||
/** @returns {number} Number of active WebRTC channels */
|
||||
get channelCount() {
|
||||
return this.#webrtcHost.channelCount;
|
||||
}
|
||||
|
||||
/** @returns {number} Total buffered bytes across all DataChannels (for flow control) */
|
||||
get totalBufferedAmount() {
|
||||
return this.#webrtcHost.totalBufferedAmount;
|
||||
}
|
||||
|
||||
/** Drain pending events from the WASM P2P event queue. */
|
||||
#drainEvents() {
|
||||
if (!this.#eventBufPtr) return;
|
||||
for (let i = 0; i < 4096; i++) {
|
||||
const n = this.#exports.wasm_poll_event(
|
||||
this.#instanceId,
|
||||
this.#eventBufPtr,
|
||||
this.#eventBufLen
|
||||
);
|
||||
if (n <= 0) break;
|
||||
|
||||
const buf = new Uint8Array(this.#memory.buffer, this.#eventBufPtr, n);
|
||||
const eventType = buf[0];
|
||||
|
||||
if (eventType === 1 && n >= 34) {
|
||||
// message_received: [1][app_id:1][peer_id:32][data:N]
|
||||
const appId = buf[1];
|
||||
const peerId = new Uint8Array(buf.slice(2, 34));
|
||||
const data = new Uint8Array(buf.slice(34, n));
|
||||
for (const handler of this.#messageHandlers) {
|
||||
try { handler(peerId, appId, data); } catch {}
|
||||
}
|
||||
} else if (eventType === 2 && n >= 33) {
|
||||
// peer_connected: [2][peer_id:32]
|
||||
const peerId = new Uint8Array(buf.slice(1, 33));
|
||||
const peerHex = Array.from(peerId.slice(0, 8))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
for (const handler of this.#connectionHandlers) {
|
||||
try { handler(peerHex, 0); } catch {}
|
||||
}
|
||||
}
|
||||
// type 3 (peer_disconnected) — not wired yet
|
||||
else if (eventType === 4 && n >= 13) {
|
||||
// file_shared: [4][session_id:8 LE][path_len:4 LE][path:N]
|
||||
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
|
||||
const sessionId = view.getBigUint64(1, true);
|
||||
const pathLen = view.getUint32(9, true);
|
||||
const path = new TextDecoder().decode(buf.slice(13, 13 + pathLen));
|
||||
for (const handler of this.#fileEventHandlers) {
|
||||
try { handler({ type: 'shared', sessionId, path }); } catch {}
|
||||
}
|
||||
} else if (eventType === 5 && n >= 13) {
|
||||
// file_download_started: [5][session_id:8 LE][name_len:4 LE][name:N]
|
||||
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
|
||||
const sessionId = view.getBigUint64(1, true);
|
||||
const nameLen = view.getUint32(9, true);
|
||||
const name = new TextDecoder().decode(buf.slice(13, 13 + nameLen));
|
||||
for (const handler of this.#fileEventHandlers) {
|
||||
try { handler({ type: 'download_started', sessionId, name }); } catch {}
|
||||
}
|
||||
} else if (eventType === 6 && n >= 9) {
|
||||
// file_download_completed: [6][session_id:8 LE]
|
||||
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
|
||||
const sessionId = view.getBigUint64(1, true);
|
||||
for (const handler of this.#fileEventHandlers) {
|
||||
try { handler({ type: 'download_completed', sessionId }); } catch {}
|
||||
}
|
||||
} else if (eventType === 7 && n >= 9) {
|
||||
// file_download_failed: [7][session_id:8 LE]
|
||||
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
|
||||
const sessionId = view.getBigUint64(1, true);
|
||||
for (const handler of this.#fileEventHandlers) {
|
||||
try { handler({ type: 'download_failed', sessionId }); } catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// File Transfer API
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* Register a file event handler.
|
||||
* @param {(event: { type: string, sessionId: bigint, path?: string, name?: string }) => void} handler
|
||||
*/
|
||||
onFileEvent(handler) {
|
||||
this.#fileEventHandlers.push(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Share a file with connected peers.
|
||||
*
|
||||
* For small files (<50MB): materializes into WASM memory and registers
|
||||
* with the Zig file manager (full hashing + session management).
|
||||
*
|
||||
* For large files: registers the File handle for streaming JS-level
|
||||
* transfer (no WASM hashing, no full memory copy).
|
||||
*
|
||||
* @param {File} file - Browser File object to share
|
||||
* @returns {Promise<{ virtualPath: string, size: number }>}
|
||||
*/
|
||||
async shareFile(file) {
|
||||
if (this.#destroyed) throw new Error('Instance destroyed');
|
||||
|
||||
const MATERIALIZE_THRESHOLD = 50 * 1024 * 1024; // 50MB
|
||||
const virtualPath = this.#fileHost.registerBrowserFile(file);
|
||||
|
||||
if (file.size <= MATERIALIZE_THRESHOLD) {
|
||||
// Small file: materialize and register with WASM file manager
|
||||
await this.#fileHost.materializeFile(virtualPath);
|
||||
const pathBytes = new TextEncoder().encode(virtualPath);
|
||||
const pathPtr = this.#exports.wasm_alloc(pathBytes.length);
|
||||
if (!pathPtr) throw new Error('WASM alloc failed');
|
||||
|
||||
try {
|
||||
new Uint8Array(this.#memory.buffer, pathPtr, pathBytes.length).set(pathBytes);
|
||||
const sessionId = this.#exports.wasm_file_share(
|
||||
this.#instanceId,
|
||||
pathPtr,
|
||||
pathBytes.length
|
||||
);
|
||||
// wasm_file_share returns -1n (i64) on error; valid session IDs are
|
||||
// u64 values that may appear negative in signed BigInt when > 2^63.
|
||||
if (sessionId === -1n) throw new Error('Failed to share file');
|
||||
} finally {
|
||||
this.#exports.wasm_free(pathPtr, pathBytes.length);
|
||||
}
|
||||
}
|
||||
// Large files: File handle is stored in FileHost for streaming reads.
|
||||
// The JS-level transfer (demo.js) reads via fileHost.readFileChunk().
|
||||
|
||||
return { virtualPath, size: file.size };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a completed download as a Blob for saving.
|
||||
* @param {string} name - File name (virtual path)
|
||||
* @returns {Blob | null}
|
||||
*/
|
||||
getDownloadBlob(name) {
|
||||
return this.#fileHost.getFileBlob(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a browser download for a completed file.
|
||||
* @param {string} name - File name
|
||||
*/
|
||||
downloadToDesktop(name) {
|
||||
const blob = this.#fileHost.getFileBlob(name);
|
||||
if (!blob) return;
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = name;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
/** @returns {FileHost} The file host for advanced use */
|
||||
get fileHost() {
|
||||
return this.#fileHost;
|
||||
}
|
||||
|
||||
/** Shut down everything. */
|
||||
destroy() {
|
||||
this.#destroyed = true;
|
||||
if (this.#updateTimer !== null) {
|
||||
clearInterval(this.#updateTimer);
|
||||
this.#updateTimer = null;
|
||||
}
|
||||
this.#webrtcHost.destroy();
|
||||
this.#signaling.disconnect();
|
||||
if (this.#instanceId >= 0) {
|
||||
this.#exports.wasm_p2p_deinit(this.#instanceId);
|
||||
}
|
||||
if (this.#eventBufPtr) {
|
||||
this.#exports.wasm_free(this.#eventBufPtr, this.#eventBufLen);
|
||||
this.#eventBufPtr = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user