@dimchansky/meshpost 0.0.0-stage → 0.2.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dmitrij Koniajev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,356 @@
1
- # Temporary Holding Version
1
+ # Meshpost
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/dimchansky/meshpost/actions/workflows/ci.yml/badge.svg)](https://github.com/dimchansky/meshpost/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/%40dimchansky%2Fmeshpost)](https://www.npmjs.com/package/@dimchansky/meshpost)
5
+
6
+ **Live demo:** [dimchansky.github.io/meshpost](https://dimchansky.github.io/meshpost/) — open on two devices or browser tabs to test direct peer-to-peer cursors and chat.
7
+
8
+ Meshpost connects browsers directly to send small binary packets (up to 16 KiB) with no backend server for app traffic.
9
+
10
+ - **Direct peer-to-peer:** Browsers connect directly to each other. There is no host or central relay for your data.
11
+ - **Two delivery modes:** Send fast unreliable packets (for cursors or game positions) or ordered reliable packets (for chat or commands).
12
+ - **Resilient:** Connected peers keep talking even if the first person leaves or the discovery server goes offline.
13
+ - **Zero runtime dependencies:** TypeScript ES modules built on native browser WebRTC.
14
+
15
+ ## Quick start: 2-browser chat in 30 lines
16
+
17
+ 1. Install from npm, or clone and build from source (requires Node.js 22+):
18
+
19
+ ```sh
20
+ npm install @dimchansky/meshpost
21
+ ```
22
+
23
+ Or build from source:
24
+
25
+ ```sh
26
+ git clone https://github.com/dimchansky/meshpost.git
27
+ cd meshpost
28
+ npm ci
29
+ npm run build
30
+ ```
31
+
32
+ 2. Import `joinRoom` and a signaling adapter (used only to help browsers find each other) in your browser app (use `@dimchansky/meshpost` if installed as a package, or `./dist/index.js` from a local build):
33
+
34
+ ```ts
35
+ import { joinRoom, mqttSignaling } from '@dimchansky/meshpost'
36
+
37
+ const encoder = new TextEncoder()
38
+ const decoder = new TextDecoder()
39
+
40
+ // Join a room. Browsers with the same appId and room name connect automatically.
41
+ const room = joinRoom('lobby', {
42
+ appId: 'my-chat-app',
43
+ signaling: mqttSignaling()
44
+ })
45
+
46
+ room.onPeerJoin((peerId) => console.log('Joined:', peerId))
47
+ room.onPeerLeave((peerId) => console.log('Left:', peerId))
48
+
49
+ // Receive binary packets and decode text.
50
+ const stop = room.onPacket((from, bytes, delivery) => {
51
+ if (delivery === 'reliable') {
52
+ console.log(from, decoder.decode(bytes))
53
+ }
54
+ })
55
+
56
+ // Send a reliable message to all connected peers.
57
+ // Note: delivery defaults to 'unreliable'. Set 'reliable' for messages that must arrive.
58
+ function sendMessage(text: string) {
59
+ const results = room.send(encoder.encode(text), { delivery: 'reliable' })
60
+ for (const [peerId, status] of results) {
61
+ console.log(peerId, status) // 'accepted' | 'busy' | 'unavailable' | 'too-large'
62
+ }
63
+ }
64
+
65
+ // Clean up when the tab closes.
66
+ window.addEventListener(
67
+ 'pagehide',
68
+ () => {
69
+ stop()
70
+ room.leave()
71
+ },
72
+ { once: true }
73
+ )
74
+ ```
75
+
76
+ 3. Use `createChannel` when your app has multiple message types (so modules do not collide):
77
+
78
+ ```ts
79
+ import { createChannel } from '@dimchansky/meshpost'
80
+
81
+ const cursors = createChannel(room, 'cursor', { delivery: 'unreliable' })
82
+ const chat = createChannel(room, 'chat', { delivery: 'reliable' })
83
+
84
+ cursors.onPacket((from, bytes) => updateCursor(from, bytes))
85
+ chat.onPacket((from, bytes) => showChat(from, decoder.decode(bytes)))
86
+
87
+ // Broadcast a cursor update to everyone.
88
+ cursors.send(cursorBytes)
89
+
90
+ // Send a reliable command to one specific peer and inspect the result.
91
+ const status = chat.send(encoder.encode('hello'), { to: peerId }).get(peerId)
92
+ ```
93
+
94
+ ## Choose a signaling adapter
95
+
96
+ Browsers need a signaling adapter only to find each other and start the connection. After that, data travels directly between browsers.
97
+
98
+ | Adapter | Best for | Server needed? |
99
+ | ---------------------------- | ----------------------------------------------------------------------------- | ------------------ |
100
+ | `mqttSignaling(options?)` | Different browsers, devices, and networks out of the box | No (public relays) |
101
+ | `wsSignaling(url, options?)` | Production apps with your own WebSocket signaling server (`wss://`) | Your WS server |
102
+ | `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
103
+ | `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
104
+ | `combineSignaling(...list)` | Composing multiple adapters (e.g. instant local tabs + remote MQTT/WebSocket) | Depends on list |
105
+ | Custom `Signaling` | Custom transports (such as Server-Sent Events or an existing backend channel) | Your server |
106
+
107
+ ### Local tabs (`tabSignaling`)
108
+
109
+ ```ts
110
+ import { joinRoom, tabSignaling } from '@dimchansky/meshpost'
111
+
112
+ const room = joinRoom('arena', {
113
+ appId: 'my-game',
114
+ signaling: tabSignaling()
115
+ })
116
+ ```
117
+
118
+ ### Offline copy-paste (`manualSignaling`)
119
+
120
+ ```ts
121
+ import { joinRoom, manualSignaling } from '@dimchansky/meshpost'
122
+
123
+ const manual = manualSignaling((toPeerId, replyText) => {
124
+ // Show replyText to the user to send to `toPeerId`.
125
+ })
126
+
127
+ const room = joinRoom('offline-room', {
128
+ appId: 'my-app',
129
+ signaling: manual.signaling,
130
+ handshakeTimeoutMs: 180_000
131
+ })
132
+
133
+ const myContactCard = manual.contact() // Share this text with the other browser.
134
+ manual.accept(pastedTextFromPeer) // Paste incoming contact cards and replies here.
135
+ manual.forget(oldPeerId) // Optional: stop retrying an old contact.
136
+ ```
137
+
138
+ > **Password note:** Pass `password: 'secret'` to `joinRoom()` so only peers with the same password can join the room. With `mqttSignaling()`, this also encrypts setup messages. Browsers allow encryption only on `https://` pages or `http://localhost` (`127.0.0.1`), so using `password` with `mqttSignaling()` on `file://` or plain `http://<lan-ip>` throws an error. (`tabSignaling()`, `wsSignaling()`, and `manualSignaling()` support `password` everywhere.)
139
+
140
+ ## Public API reference
141
+
142
+ ### `joinRoom(name, options)`
143
+
144
+ Creates a room, assigns a random peer ID (`room.id`), and immediately starts looking for other peers.
145
+
146
+ - `name`: Room name. Must match `^[a-zA-Z0-9_-]{1,64}$`.
147
+ - Throws an error immediately if `name`, `appId`, `password`, timeouts, `maxPeers`, or `rtcConfig` are invalid.
148
+
149
+ | `RoomOptions` field | Type | Default | Purpose |
150
+ | ----------------------- | ------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------- |
151
+ | `signaling` | `Signaling` | _(required)_ | Adapter that helps browsers find each other and start direct connections. |
152
+ | `appId` | `string` | `'meshpost'` | Keeps your app's rooms separate from other apps on the same relay (`[a-zA-Z0-9._-]{1,64}`). |
153
+ | `password` | `string` | `undefined` | Optional shared password. Keeps rooms separate and encrypts setup messages on MQTT. |
154
+ | `turnConfig` | `readonly RTCIceServer[]` | `[]` | Extra TURN (or STUN) servers appended to `rtcConfig.iceServers` (or `defaultIceServers` when omitted). |
155
+ | `rtcConfig` | `RTCConfiguration` | `defaultIceServers` | Custom WebRTC config. Keeps `defaultIceServers` unless you set `iceServers` (pass `{ iceServers: [] }` offline). |
156
+ | `handshakeTimeoutMs` | `number` | `35_000` | Max time to wait per connection attempt before retrying. |
157
+ | `iceGatheringTimeoutMs` | `number` | `2_500` | Max time to wait for network addresses before starting a connection. |
158
+ | `maxPeers` | `number` | `32` | Maximum simultaneous peer connections. |
159
+
160
+ ### `Room`
161
+
162
+ | Member | Description |
163
+ | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
164
+ | `room.id` | Your peer ID (`string`). A page reload creates a new peer ID. |
165
+ | `room.peers` | Current list of connected peer IDs (returns a fresh copy each time). |
166
+ | `room.signalingState` | Current adapter state: `'connecting' \| 'online' \| 'offline' \| 'closed'`. |
167
+ | `room.send(bytes, options?: SendOptions)` | Sends a `Uint8Array`. `options` accepts `{ to?: string, delivery?: Delivery }` (`Delivery` is `'unreliable' \| 'reliable'`, default `'unreliable'`). Returns `ReadonlyMap<string, SendResult>`. |
168
+ | `room.getStats(peerId)` | Returns `Promise<PeerStats \| null>` with ping, route, byte counts, and send buffer sizes (`null` if not connected). |
169
+ | `room.onPacket(fn, options?: ListenOptions)` | Runs when a packet arrives (`(from, bytes, delivery) => ...`). Returns an unsubscribe function. |
170
+ | `room.onDrain(fn, options?: ListenOptions)` | Runs when a full send buffer has space again (`(peerId, delivery) => ...`, after `send()` returned `'busy'`). Returns unsubscribe. |
171
+ | `room.onPeerJoin(fn, options?: ListenOptions)` | Runs when a peer finishes connecting and is ready to exchange packets (`(peerId) => ...`). Returns unsubscribe. |
172
+ | `room.onPeerLeave(fn, options?: ListenOptions)` | Runs when a connected peer disconnects (`(peerId) => ...`). Returns unsubscribe. |
173
+ | `room.onSignalingChange(fn, options?: ListenOptions)` | Runs on future `signalingState` changes (`(state, reason?) => ...`). Returns unsubscribe. |
174
+ | `room.onError(fn, options?: ListenOptions)` | Runs on structured room or signaling errors (`(error: RoomError) => ...`, codes `'room-full' \| 'ice-failed' \| 'media-error' \| 'decrypt-failed' \| 'signaling-error'`). Returns unsubscribe. |
175
+ | `room.addStream(stream, to?)` | Attaches a local `MediaStream` (audio/video) to all connected and future peers, or selectively to one peer (`to`). |
176
+ | `room.removeStream(stream, to?)` | Detaches a previously added local `MediaStream` from all peers, or from one peer (`to`). |
177
+ | `room.onPeerStream(fn, options?: ListenOptions)` | Runs when a remote peer adds a `MediaStream` (`(peerId, stream) => ...`). Fires strictly after `onPeerJoin`. Returns unsubscribe. |
178
+ | `room.onPeerStreamEnd(fn, options?: ListenOptions)` | Runs when a remote peer removes a `MediaStream` or disconnects (`(peerId, stream) => ...`). Returns unsubscribe. |
179
+ | `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
180
+
181
+ All `on*` methods (on `Room`, `Channel`, and `BlobChannel`) optionally accept `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`) to auto-unsubscribe after the first invocation or when an `AbortSignal` aborts.
182
+
183
+ `room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
184
+
185
+ #### P2P Voice / MediaStreams
186
+
187
+ ```ts
188
+ const mic = await navigator.mediaDevices.getUserMedia({ audio: true })
189
+ room.addStream(mic) // Broadcast to all current & future peers (or pass peerId as 2nd arg)
190
+
191
+ room.onPeerStream((peerId, stream) => {
192
+ const audio = new Audio()
193
+ audio.srcObject = stream
194
+ audio.play()
195
+ })
196
+ room.onPeerStreamEnd((peerId, stream) => console.log('Stream ended:', peerId, stream.id))
197
+
198
+ // Later: detach from room and stop local microphone tracks yourself.
199
+ room.removeStream(mic)
200
+ for (const track of mic.getTracks()) track.stop()
201
+ ```
202
+
203
+ > **Note:** `removeStream()` does not stop local `MediaStreamTrack`s (call `track.stop()` when done), and streams with 0 tracks or tracks added to a `MediaStream` _after_ `addStream()` are not renegotiated automatically.
204
+
205
+ ### `SendResult`
206
+
207
+ `room.send()` and `channel.send()` return a `ReadonlyMap<string, SendResult>` immediately. Meshpost does not queue failed packets in the background:
208
+
209
+ | Value | Meaning |
210
+ | --------------- | ----------------------------------------------------------------------------------- |
211
+ | `'accepted'` | Browser accepted the packet for sending. |
212
+ | `'busy'` | Send buffer is full (`64 KiB` unreliable / `256 KiB` reliable). Wait for `onDrain`. |
213
+ | `'unavailable'` | Target peer is not connected, unknown, or is yourself. |
214
+ | `'too-large'` | Packet is larger than 16,384 bytes (or larger than the other browser allows). |
215
+
216
+ ### `PeerStats`
217
+
218
+ `await room.getStats(peerId)` returns a read-only snapshot for a connected peer, or `null` if the peer is not connected or the room is closed:
219
+
220
+ | Field | Type | Meaning |
221
+ | -------------------- | ---------------- | ----------------------------------------------------------------------------------------------------- |
222
+ | `rttMs` | `number \| null` | Current round-trip ping in whole milliseconds (`null` if not measured yet). |
223
+ | `route` | `PeerRoute` | `'direct'` for peer-to-peer, `'relay'` through a TURN server, or `'unknown'` if not reported yet. |
224
+ | `bytesSent` | `number` | Total app payload bytes sent to this peer across both delivery modes (unreliable and reliable). |
225
+ | `bytesReceived` | `number` | Total app payload bytes received from this peer across both delivery modes (unreliable and reliable). |
226
+ | `bufferedUnreliable` | `number` | Bytes currently waiting in the unreliable send buffer. |
227
+ | `bufferedReliable` | `number` | Bytes currently waiting in the reliable send buffer. |
228
+
229
+ ### `createChannel(room, name, options?: ChannelOptions)`
230
+
231
+ Creates a named message stream (such as `'chat'` or `'cursor'`) on your existing room connections. Each channel only receives packets sent to its own name.
232
+
233
+ - `name`: 1–64 UTF-8 bytes. Uses `1 + nameBytes.length` bytes of the 16,384-byte packet limit.
234
+ - `options` (`ChannelOptions`): `{ delivery?: Delivery }`. Defaults to `'unreliable'`.
235
+ - Returns a `Channel` with `{ name, delivery, send(bytes, options?: ChannelSendOptions), onPacket((from, bytes) => ..., options?: ListenOptions) }` (`ChannelSendOptions` is `{ to?: string }`).
236
+
237
+ ### `createBlobChannel(room, name, options?: BlobChannelOptions)`
238
+
239
+ Creates an opt-in chunked reliable transfer helper for payloads larger than Meshpost's `16,384`-byte packet limit (such as files, images, or large state snapshots). Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
240
+
241
+ - `options` (`BlobChannelOptions`): `{ maxReceiveBytes?, chunkSize?, receiveTimeoutMs?, maxConcurrentPerPeer? }`. Defaults: `4 MiB` max receive, `15 KiB` chunk size, `30 s` receive inactivity timeout, `4` concurrent incoming transfers per peer.
242
+ - Returns a `BlobChannel` with `{ name, send(bytes, options?: BlobSendOptions), onBlob((from, bytes) => ..., options?: ListenOptions), onProgress((from, progress: BlobProgress) => ..., options?: ListenOptions), close() }` where `BlobProgress` is `{ transferId, receivedBytes, totalBytes }`.
243
+ - `send(bytes, { to?, onProgress?: (peerId, sentBytes, totalBytes) => void, signal? })` paces each recipient independently using `room.onDrain` and resolves to `ReadonlyMap<string, BlobSendStatus>` (`'sent' | 'aborted' | 'unavailable' | 'too-large'`).
244
+
245
+ ```ts
246
+ import { createBlobChannel } from '@dimchansky/meshpost'
247
+
248
+ const files = createBlobChannel(room, 'file', { maxReceiveBytes: 8 * 1024 * 1024 })
249
+ files.onProgress((from, { receivedBytes, totalBytes }) =>
250
+ console.log(from, receivedBytes, totalBytes)
251
+ )
252
+ files.onBlob((from, bytes) => console.log('Received', bytes.byteLength, 'bytes from', from))
253
+
254
+ const results = await files.send(fileBytes, {
255
+ onProgress: (peerId, sent, total) => console.log(peerId, sent, total)
256
+ })
257
+ ```
258
+
259
+ ### Signaling exports
260
+
261
+ - `mqttSignaling({ urls?, appId?, password?, handshakeTimeoutMs? })` — Connects browsers across different devices and networks using built-in public MQTT relay servers (`defaultMqttRelays`).
262
+ - `wsSignaling(url, { reconnect?, handshakeTimeoutMs?, pingIntervalMs? })` — Connects browsers through your own WebSocket (`ws://` / `wss://`) signaling server (defaults: `reconnect: true`, `handshakeTimeoutMs: 10_000`, `pingIntervalMs: 25_000`). See [docs/behavior.md](docs/behavior.md) and [examples/serve.mjs](examples/serve.mjs) for the minimal JSON server protocol.
263
+ - `combineSignaling(...adapters)` — Combines multiple `Signaling` adapters, merging peer rosters and keeping discovery online as long as any child adapter is online (e.g. `combineSignaling(tabSignaling(), wsSignaling('wss://relay.example/ws'))`).
264
+ - `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
265
+ - `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
266
+ - `defaultIceServers` — Built-in Cloudflare and Google public servers (STUN) that help browsers find their public network address.
267
+ - Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `MqttSignalingOptions`, `WsSignalingOptions`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
268
+
269
+ ## Connecting through strict firewalls (TURN)
270
+
271
+ - Most home, mobile, and same-computer connections work out of the box using Meshpost's built-in public STUN servers (`defaultIceServers`) and local-device fallback.
272
+ - Strict corporate firewalls and restrictive routers block direct connections. For those networks, add a TURN relay server (a server that forwards traffic when a direct link fails).
273
+ - Add your TURN credentials without replacing the default servers:
274
+
275
+ ```ts
276
+ const room = joinRoom('lobby', {
277
+ appId: 'my-app',
278
+ signaling: mqttSignaling(),
279
+ turnConfig: [{ urls: 'turns:turn.example.org:5349', username: 'user', credential: 'secret' }]
280
+ })
281
+ ```
282
+
283
+ ## Try the interactive playground
284
+
285
+ ### Option 1: Local dev server (recommended)
286
+
287
+ ```sh
288
+ npm ci
289
+ npm run demo:tabs
290
+ ```
291
+
292
+ Open the printed URL (for example `http://127.0.0.1:4173`) and click **Join room**. New rooms pre-fill a strong random password automatically.
293
+
294
+ - To join from another tab, click **Open another participant**.
295
+ - To join from **another browser** (such as Safari or Firefox) or another device, click **Copy invite link** and open that URL there (or enter the same room name and password).
296
+ - To test from another device on your LAN, run `HOST=0.0.0.0 npm run demo:tabs`.
297
+ - Stopping the server does not disconnect active peer-to-peer links.
298
+
299
+ ### Option 2: Standalone single HTML file (zero server)
300
+
301
+ ```sh
302
+ npm run demo
303
+ ```
304
+
305
+ Open **dist/playground.html** directly in two browsers (`file://`). Enter the same room name and click **Join room**.
306
+
307
+ - By default, `dist/playground.html` uses `mqttSignaling()` when opened via `file://` or hosted on a public `https://` origin (such as GitHub Pages).
308
+ - For completely offline copy-paste exchange with zero network requests, open `dist/playground.html#mode=manual` (or click **Offline mode** on the join screen).
309
+ - When hosted on `localhost` or a LAN host without the demo's local `/ws` relay server, it automatically falls back to `tabSignaling()` (same-browser tabs only).
310
+
311
+ ### Read the example code
312
+
313
+ All `@dimchansky/meshpost` usage in the playground is intentionally concentrated in **one file** so you can learn the full API in one place:
314
+
315
+ - [examples/playground/mesh.js](examples/playground/mesh.js) — **Start here.** Single facade wiring `joinRoom()`, signaling adapters (`combineSignaling`, `mqttSignaling`, `wsSignaling`, `tabSignaling`, `manualSignaling`), `createChannel()` (`pointer`, `draw`, `chat`, `direct`, `profile`), `createBlobChannel()` (`draw-snap`, `file`), `ListenOptions` (`{ signal }`), `room.onError()`, `room.getStats()`, and `room.addStream()` / `onPeerStream()`.
316
+ - [examples/playground/relay.js](examples/playground/relay.js) — `autoSignaling()` composing `tabSignaling()` and `wsSignaling()` with a silent fallback to `tabSignaling()` on plain static localhost servers.
317
+ - [examples/playground/codec.js](examples/playground/codec.js) — Pure binary codecs for pointer updates, canvas strokes, and file metadata envelopes.
318
+ - [examples/playground/canvas.js](examples/playground/canvas.js) — Collaborative 2D drawing canvas and remote cursor/ripple overlays.
319
+ - [examples/playground/voice.js](examples/playground/voice.js) — Local microphone capture, mute toggle, remote `<audio>` playback, and `AnalyserNode` speaking indicator.
320
+ - [examples/playground/session.js](examples/playground/session.js) — Compact `#c=` invite URLs, `sessionStorage` auto-rejoin, and TURN credential broker fetch.
321
+ - [examples/playground/app.js](examples/playground/app.js) — Thin UI controller connecting DOM controls to `mesh.js` and the helper modules.
322
+ - [examples/playground/index.html](examples/playground/index.html) — Minimal HTML markup for the playground.
323
+ - [examples/turn-worker/](examples/turn-worker/README.md) — Ready-to-deploy Cloudflare Worker template that issues short-lived TURN credentials (supporting Metered Open Relay, Cloudflare Realtime TURN, and self-hosted `coturn`) behind an `Origin` allowlist and shared access key.
324
+
325
+ ## Project layout and tests
326
+
327
+ | Path | Purpose |
328
+ | ----------------------- | ------------------------------------------------------------------------------ |
329
+ | `src/` | Core room lifecycle, channels, and signaling adapters |
330
+ | `examples/playground/` | Interactive demo source |
331
+ | `examples/turn-worker/` | Optional Cloudflare Worker credential broker for Metered, CF TURN, or `coturn` |
332
+ | `examples/build.mjs` | Bundles the playground into one portable HTML file |
333
+ | `examples/serve.mjs` | Local dev server with WebSocket (`/ws`) and SSE signaling relays |
334
+ | `tests/` | Playwright E2E tests using real browser WebRTC data channels |
335
+ | `dist/` | Built ES modules, `.d.ts` declarations, and `playground.html` |
336
+
337
+ Run the test suite:
338
+
339
+ ```sh
340
+ npm ci
341
+ npx playwright install chromium
342
+ npm test
343
+ ```
344
+
345
+ To use an already-installed Google Chrome instead of downloading Chromium, run `MESHPOST_CHROME_CHANNEL=chrome npm test`.
346
+
347
+ For full limits, wire protocol details, edge cases, and the security model, read [docs/behavior.md](docs/behavior.md).
348
+
349
+ ## Browser support
350
+
351
+ - Runs in modern browsers (Chrome, Firefox, Safari) with WebRTC `RTCDataChannel`, `WebSocket`, and `BroadcastChannel`. Meshpost is a browser library (not for Node.js).
352
+ - `mqttSignaling()` with `password` uses browser Web Crypto (`crypto.subtle`), which requires `https://` or `http://localhost` (`127.0.0.1`).
353
+
354
+ ## License
355
+
356
+ MIT — see [LICENSE](LICENSE).
package/dist/blob.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ import type { ListenOptions, Room } from './room.js';
2
+ export interface BlobChannelOptions {
3
+ /** Maximum total bytes accepted for a single incoming blob. @default 4194304 (4 MiB) */
4
+ maxReceiveBytes?: number;
5
+ /** Maximum payload bytes per chunk (must fit within the 16 KiB channel budget). @default 15360 */
6
+ chunkSize?: number;
7
+ /** Inactivity timeout in milliseconds for an incomplete incoming transfer. @default 30000 */
8
+ receiveTimeoutMs?: number;
9
+ /** Maximum simultaneous incoming transfers tracked per peer. @default 4 */
10
+ maxConcurrentPerPeer?: number;
11
+ }
12
+ export interface BlobSendOptions {
13
+ /** Optional target peer ID. Omit to send to all currently connected peers. */
14
+ to?: string;
15
+ /** Optional progress callback invoked per recipient as chunks are accepted. */
16
+ onProgress?: (peerId: string, sentBytes: number, totalBytes: number) => void;
17
+ /** Optional AbortSignal to cancel in-flight sending. */
18
+ signal?: AbortSignal;
19
+ }
20
+ /** Final per-recipient outcome returned by `blobChannel.send()`. */
21
+ export type BlobSendStatus = 'sent' | 'aborted' | 'unavailable' | 'too-large';
22
+ /** Progress snapshot emitted by `blobChannel.onProgress()`. */
23
+ export interface BlobProgress {
24
+ readonly transferId: number;
25
+ readonly receivedBytes: number;
26
+ readonly totalBytes: number;
27
+ }
28
+ /** Chunked reliable binary transfer helper built on top of a Room and Channel. */
29
+ export interface BlobChannel {
30
+ /** Logical channel name. */
31
+ readonly name: string;
32
+ /** Send a Uint8Array of arbitrary size (including 0 bytes). Resolves with per-peer final status. */
33
+ send(bytes: Uint8Array, options?: BlobSendOptions): Promise<ReadonlyMap<string, BlobSendStatus>>;
34
+ /** Subscribe to completed incoming blobs. Returns an unsubscribe function. */
35
+ onBlob(fn: (from: string, bytes: Uint8Array) => void, options?: ListenOptions): () => void;
36
+ /** Subscribe to incoming transfer progress updates. Returns an unsubscribe function. */
37
+ onProgress(fn: (from: string, progress: BlobProgress) => void, options?: ListenOptions): () => void;
38
+ /** Detach internal room listeners and cancel all active incoming/outgoing transfers. */
39
+ close(): void;
40
+ }
41
+ /**
42
+ * Create a chunked reliable binary channel for payloads larger than Meshpost's 16 KiB packet limit.
43
+ * Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
44
+ */
45
+ export declare function createBlobChannel(room: Room, name: string, options?: BlobChannelOptions): BlobChannel;