@dimchansky/meshpost 0.3.0 → 0.4.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/README.md CHANGED
@@ -5,12 +5,12 @@
5
5
 
6
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
7
 
8
- Meshpost connects browsers directly to send small binary packets (up to 16 KiB) with no backend server for app traffic.
8
+ Meshpost connects peers directly over WebRTC to exchange binary packets, typed messages, RPC calls, per-peer state, large files, and voice/media with **no central backend for app traffic**.
9
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.
10
+ - **Direct peer-to-peer:** Browsers (and headless Node.js / Bun / Deno peers) connect directly to each other with no host election or central data relay.
11
+ - **Two delivery modes + batteries included:** Fast unreliable or ordered reliable packets, plus tree-shakeable typed codecs (`createCodecChannel`), request-response RPC (`createRpc`), per-peer state sync (`createPeerState`), chunked transfers (`createBlobChannel`), headless P2P voice (`createVoice`), and DTLS-bound `ECDSA P-256` identity (`createIdentity`).
12
+ - **Flexible E2E-encrypted discovery:** Built-in MQTT, port-443 Nostr (`kind: 25050`), WebSocket (with a ready-to-deploy Cloudflare Durable Object Worker), `BroadcastChannel`, and offline copy-paste signaling — connected peers keep talking even if discovery goes offline.
13
+ - **Zero runtime dependencies:** Pure TypeScript ES modules with granular `@dimchansky/meshpost/*` subpath exports (`importmap`-ready).
14
14
 
15
15
  ## Quick start: 2-browser chat in 30 lines
16
16
 
@@ -62,48 +62,46 @@ Meshpost connects browsers directly to send small binary packets (up to 16 KiB)
62
62
  }
63
63
  }
64
64
 
65
- // Clean up when the tab closes.
66
- window.addEventListener(
67
- 'pagehide',
68
- () => {
69
- stop()
70
- room.leave()
71
- },
72
- { once: true }
73
- )
65
+ // Explicitly leave when your UI unmounts or the user clicks "Leave".
66
+ // (Tab closes and F5 page reloads are handled automatically by Meshpost.)
67
+ function leaveChat() {
68
+ stop()
69
+ room.leave()
70
+ }
74
71
  ```
75
72
 
76
- 3. Use `createChannel` when your app has multiple message types (so modules do not collide):
73
+ 3. Use `createChannel` (or typed `createCodecChannel` with `jsonCodec` / `textCodec`) when your app has multiple message types so modules do not collide:
77
74
 
78
75
  ```ts
79
- import { createChannel } from '@dimchansky/meshpost'
76
+ import { createChannel, createCodecChannel, textCodec } from '@dimchansky/meshpost'
80
77
 
81
78
  const cursors = createChannel(room, 'cursor', { delivery: 'unreliable' })
82
- const chat = createChannel(room, 'chat', { delivery: 'reliable' })
79
+ const chat = createCodecChannel(room, 'chat', textCodec, { delivery: 'reliable' })
83
80
 
84
81
  cursors.onPacket((from, bytes) => updateCursor(from, bytes))
85
- chat.onPacket((from, bytes) => showChat(from, decoder.decode(bytes)))
82
+ chat.onMessage((from, text) => showChat(from, text))
86
83
 
87
84
  // Broadcast a cursor update to everyone.
88
85
  cursors.send(cursorBytes)
89
86
 
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)
87
+ // Send a reliable message to one specific peer and inspect the synchronous SendResult.
88
+ const status = chat.send('hello', { to: peerId }).get(peerId)
92
89
  ```
93
90
 
94
91
  ## Choose a signaling adapter
95
92
 
96
93
  Browsers need a signaling adapter only to find each other and start the connection. After that, data travels directly between browsers.
97
94
 
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
- | `withLocalTabs(primary)` | Instant same-browser tabs + remote MQTT/WebSocket with accurate network state | Same as `primary` |
105
- | `combineSignaling(...list)` | Composing multiple network adapters (stays `'online'` if any child is online) | Depends on list |
106
- | Custom `Signaling` | Custom transports (such as Server-Sent Events or an existing backend channel) | Your server |
95
+ | Adapter | Best for | Server needed? |
96
+ | ---------------------------- | ----------------------------------------------------------------------------- | ------------------- |
97
+ | `mqttSignaling(options?)` | Different browsers, devices, and networks out of the box | No (public relays) |
98
+ | `nostrSignaling(options?)` | Corporate/school Wi-Fi blocking MQTT ports (runs over port-443 `wss://`) | No (public relays) |
99
+ | `wsSignaling(url, options?)` | Production apps with your own WebSocket relay (see `examples/ws-worker/`) | Your WS / CF Worker |
100
+ | `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
101
+ | `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
102
+ | `withLocalTabs(primary)` | Instant same-browser tabs + remote MQTT/Nostr/WS with accurate network state | Same as `primary` |
103
+ | `combineSignaling(...list)` | Composing multiple network adapters (e.g. `mqttSignaling` + `nostrSignaling`) | Depends on list |
104
+ | Custom `Signaling` | Custom transports (such as Server-Sent Events or an existing backend channel) | Your server |
107
105
 
108
106
  ### Local tabs (`tabSignaling`)
109
107
 
@@ -136,7 +134,7 @@ manual.accept(pastedTextFromPeer) // Paste incoming contact cards and replies he
136
134
  manual.forget(oldPeerId) // Optional: stop retrying an old contact.
137
135
  ```
138
136
 
139
- > **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.)
137
+ > **Password note:** Pass `password: 'secret'` to `joinRoom()` so only peers with the same password can join the room. With `mqttSignaling()`, `nostrSignaling()`, and `wsSignaling()` (by default), this also end-to-end encrypts setup messages with `AES-256-GCM` so relays only see opaque ciphertexts. Browsers expose Web Crypto (`crypto.subtle`) only on `https://` pages or `http://localhost` (`127.0.0.1`), so using `password` with `mqttSignaling()`, `nostrSignaling()`, or default `wsSignaling()` on `file://` or plain `http://<lan-ip>` throws an error (pass `{ encrypt: false }` to `wsSignaling()` only for plaintext HTTP LAN testing; `tabSignaling()` and `manualSignaling()` work everywhere). Pass `{ privateTopic: true }` to `mqttSignaling()`, `nostrSignaling()`, or `wsSignaling()` when you also want to derive the relay topic/tag/room key cryptographically from `password` (disabling `'decrypt-failed'` wrong-password hints).
140
138
 
141
139
  ## Public API reference
142
140
 
@@ -147,42 +145,78 @@ Creates a room, assigns a random peer ID (`room.id`), and immediately starts loo
147
145
  - `name`: Room name. Must match `^[a-zA-Z0-9_-]{1,64}$`.
148
146
  - Throws an error immediately if `name`, `appId`, `password`, timeouts, `maxPeers`, or `rtcConfig` are invalid.
149
147
 
150
- | `RoomOptions` field | Type | Default | Purpose |
151
- | ----------------------- | ------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------- |
152
- | `signaling` | `Signaling` | _(required)_ | Adapter that helps browsers find each other and start direct connections. |
153
- | `appId` | `string` | `'meshpost'` | Keeps your app's rooms separate from other apps on the same relay (`[a-zA-Z0-9._-]{1,64}`). |
154
- | `password` | `string` | `undefined` | Optional shared password. Keeps rooms separate and encrypts setup messages on MQTT. |
155
- | `turnConfig` | `readonly RTCIceServer[]` | `[]` | Extra TURN (or STUN) servers appended to `rtcConfig.iceServers` (or `defaultIceServers` when omitted). |
156
- | `rtcConfig` | `RTCConfiguration` | `defaultIceServers` | Custom WebRTC config. Keeps `defaultIceServers` unless you set `iceServers` (pass `{ iceServers: [] }` offline). |
157
- | `handshakeTimeoutMs` | `number` | `35_000` | Max time to wait per connection attempt before retrying. |
158
- | `iceGatheringTimeoutMs` | `number` | `2_500` | Max time to wait for network addresses before starting a connection. |
159
- | `maxPeers` | `number` | `32` | Maximum simultaneous peer connections. |
148
+ | `RoomOptions` field | Type | Default | Purpose |
149
+ | ----------------------- | ------------------------------ | ------------------------------ | ---------------------------------------------------------------------------------------------------------------- |
150
+ | `signaling` | `Signaling` | _(required)_ | Adapter that helps browsers find each other and start direct connections. |
151
+ | `appId` | `string` | `'meshpost'` | Keeps your app's rooms separate from other apps on the same relay (`[a-zA-Z0-9._-]{1,64}`). |
152
+ | `password` | `string` | `undefined` | Optional shared password. Isolates rooms and end-to-end encrypts setup messages on MQTT, Nostr, & WebSocket. |
153
+ | `turnConfig` | `readonly RTCIceServer[]` | `[]` | Extra TURN (or STUN) servers appended to `rtcConfig.iceServers` (or `defaultIceServers` when omitted). |
154
+ | `rtcConfig` | `RTCConfiguration` | `defaultIceServers` | Custom WebRTC config. Keeps `defaultIceServers` unless you set `iceServers` (pass `{ iceServers: [] }` offline). |
155
+ | `handshakeTimeoutMs` | `number` | `35_000` | Max time to wait per connection attempt before retrying. |
156
+ | `iceGatheringTimeoutMs` | `number` | `2_500` | Max time to wait for network addresses before starting a connection. |
157
+ | `maxPeers` | `number` | `32` | Maximum simultaneous peer connections. |
158
+ | `identity` | `PeerIdentity` | `undefined` | Optional persistent WebCrypto `ECDSA P-256` identity proven to peers over each WebRTC link (`room.peerUserId`). |
159
+ | `RTCPeerConnection` | `RTCPeerConnectionConstructor` | `globalThis.RTCPeerConnection` | Optional custom `RTCPeerConnection` constructor for headless runtimes (Node.js, Bun, Deno) or tests. |
160
160
 
161
161
  ### `Room`
162
162
 
163
- | Member | Description |
164
- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
165
- | `room.id` | Your peer ID (`string`). A page reload creates a new peer ID. |
166
- | `room.peers` | Current list of connected peer IDs (returns a fresh copy each time). |
167
- | `room.signalingState` | Current adapter state: `'connecting' \| 'online' \| 'offline' \| 'closed'`. |
168
- | `room.send(bytes, options?: SendOptions)` | Sends a `Uint8Array`. `options` accepts `{ to?: string, delivery?: Delivery }` (`Delivery` is `'unreliable' \| 'reliable'`, default `'unreliable'`). Returns `ReadonlyMap<string, SendResult>`. |
169
- | `room.getStats(peerId)` | Returns `Promise<PeerStats \| null>` with ping, route, byte counts, and send buffer sizes (`null` if not connected). |
170
- | `room.onPacket(fn, options?: ListenOptions)` | Runs when a packet arrives (`(from, bytes, delivery) => ...`). Returns an unsubscribe function. |
171
- | `room.onDrain(fn, options?: ListenOptions)` | Runs when a full send buffer has space again (`(peerId, delivery) => ...`, after `send()` returned `'busy'`). Returns unsubscribe. |
172
- | `room.onPeerJoin(fn, options?: ListenOptions)` | Runs when a peer finishes connecting and is ready to exchange packets (`(peerId) => ...`). Returns unsubscribe. |
173
- | `room.onPeerLeave(fn, options?: ListenOptions)` | Runs when a connected peer disconnects (`(peerId) => ...`). Returns unsubscribe. |
174
- | `room.onSignalingChange(fn, options?: ListenOptions)` | Runs on future `signalingState` changes (`(state, reason?) => ...`). Returns unsubscribe. |
175
- | `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. |
176
- | `room.addStream(stream, to?)` | Attaches a local `MediaStream` (audio/video) to all connected and future peers, or selectively to one peer (`to`). |
177
- | `room.removeStream(stream, to?)` | Detaches a previously added local `MediaStream` from all peers, or from one peer (`to`). |
178
- | `room.onPeerStream(fn, options?: ListenOptions)` | Runs when a remote peer adds a `MediaStream` (`(peerId, stream) => ...`). Fires strictly after `onPeerJoin`. Returns unsubscribe. |
179
- | `room.onPeerStreamEnd(fn, options?: ListenOptions)` | Runs when a remote peer removes a `MediaStream` or disconnects (`(peerId, stream) => ...`). Returns unsubscribe. |
180
- | `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
181
-
182
- All `on*` methods (on `Room`, `Channel`, `BlobChannel`, and `Voice`) optionally accept `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`) to auto-unsubscribe after the first invocation or when an `AbortSignal` aborts.
163
+ | Member | Description |
164
+ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
165
+ | `room.id` | Your peer ID (`string`). A page reload creates a new peer ID (and automatically reclaims any stale ghost session from the same tab). |
166
+ | `room.userId` | Your verified 22-char `userId` (`string`) when `options.identity` was passed, or `null` if anonymous. |
167
+ | `room.peers` | Current list of connected peer IDs (returns a fresh copy each time). |
168
+ | `room.signalingState` | Current adapter state: `'connecting' \| 'online' \| 'offline' \| 'closed'`. |
169
+ | `room.peerUserId(peerId)` | Returns the cryptographically verified `userId` (`string`) of a connected peer (already verified before `onPeerJoin` fires), or `null` if anonymous or disconnected. |
170
+ | `room.send(bytes, options?: SendOptions)` | Sends a `Uint8Array`. `options` accepts `{ to?: string, delivery?: Delivery }` (`Delivery` is `'unreliable' \| 'reliable'`, default `'unreliable'`). Returns `ReadonlyMap<string, SendResult>`. |
171
+ | `room.getStats(peerId)` | Returns `Promise<PeerStats \| null>` with ping, route, byte counts, and send buffer sizes (`null` if not connected). |
172
+ | `room.onPacket(fn, options?: ListenOptions)` | Runs when a packet arrives (`(from, bytes, delivery) => ...`). Returns an unsubscribe function. |
173
+ | `room.onDrain(fn, options?: ListenOptions)` | Runs when a full send buffer has space again (`(peerId, delivery) => ...`, after `send()` returned `'busy'`). Returns unsubscribe. |
174
+ | `room.onPeerJoin(fn, options?: ListenOptions)` | Runs when a peer finishes connecting and verifying its handshake (`(peerId) => ...`). Returns unsubscribe. |
175
+ | `room.onPeerLeave(fn, options?: ListenOptions)` | Runs when a connected peer disconnects (`(peerId) => ...`). Returns unsubscribe. |
176
+ | `room.onSignalingChange(fn, options?: ListenOptions)` | Runs on future `signalingState` changes (`(state, reason?) => ...`). Returns unsubscribe. |
177
+ | `room.onError(fn, options?: ListenOptions)` | Runs on structured room or signaling errors (`(error: RoomError) => ...`, codes `'room-full' \| 'ice-failed' \| 'media-error' \| 'auth-failed' \| 'decrypt-failed' \| 'clock-skew' \| 'signaling-error'`). Returns unsubscribe. |
178
+ | `room.addStream(stream, toOrOptions?)` | Attaches a local `MediaStream` to all connected/future peers, or selectively via `peerId` or `AddStreamOptions` (`{ to?: string, tag?: string }`). |
179
+ | `room.removeStream(stream, toOrOptions?)` | Detaches a previously added local `MediaStream` from all peers, or from one peer (`peerId` or `RemoveStreamOptions` `{ to?: string }`). |
180
+ | `room.replaceStreamTrack(stream, oldTrack, newTrack)` | Hot-swaps a track inside an attached `MediaStream` via `RTCRtpSender.replaceTrack()` with zero WebRTC SDP renegotiation (`Promise<void>`). |
181
+ | `room.onPeerStream(fn, options?: ListenOptions)` | Runs when a remote peer adds a `MediaStream` (`(peerId, stream, meta: PeerStreamMeta) => ...`, where `meta` has `{ tag?: string }`). Fires strictly after `onPeerJoin`. Returns unsubscribe. |
182
+ | `room.onPeerStreamEnd(fn, options?: ListenOptions)` | Runs when a remote peer removes a `MediaStream` or disconnects (`(peerId, stream, meta: PeerStreamMeta) => ...`). Returns unsubscribe. |
183
+ | `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
184
+
185
+ All `on*` methods (on `Room`, `Channel`, `CodecChannel`, `PeerState`, `BlobChannel`, `Voice`, plus `rpc.handle()`) optionally accept `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`) to auto-unsubscribe after the first invocation or when an `AbortSignal` aborts.
183
186
 
184
187
  `room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
185
188
 
189
+ ### Verifiable peer identity (`createIdentity` / `exportIdentity` / `importIdentity`)
190
+
191
+ Zero-dependency persistent peer identity powered by native WebCrypto `ECDSA P-256` (`SHA-256`), with **DTLS certificate fingerprint channel binding** so signatures cannot be MitM-relayed or replayed across rooms, apps, or connections (even on unencrypted signaling relays):
192
+
193
+ - `createIdentity(options?: CreateIdentityOptions): Promise<PeerIdentity>` — generates a fresh `P-256` keypair (`{ extractable?: boolean }`, default `true`) and returns a frozen `{ userId, publicKey }` handle (`userId` is a deterministic 22-char base64url 128-bit fingerprint; private key material stays inside an internal `WeakMap`).
194
+ - `exportIdentity(identity): Promise<SerializedIdentity>` — exports `{ v: 1, crv: 'P-256', x, y, d }` for JSON storage (e.g. `localStorage`).
195
+ - `importIdentity(data, options?: CreateIdentityOptions): Promise<PeerIdentity>` — validates shape, verifies `(x, y)` cryptographically against `d` via a challenge signature, and restores `PeerIdentity`.
196
+ - `isSerializedIdentity(value): value is SerializedIdentity` — runtime type guard for untrusted storage payloads.
197
+
198
+ ```ts
199
+ import {
200
+ createIdentity,
201
+ exportIdentity,
202
+ importIdentity,
203
+ isSerializedIdentity,
204
+ joinRoom
205
+ } from '@dimchansky/meshpost'
206
+
207
+ const raw = JSON.parse(localStorage.getItem('my-id') ?? 'null')
208
+ const identity = isSerializedIdentity(raw) ? await importIdentity(raw) : await createIdentity()
209
+ localStorage.setItem('my-id', JSON.stringify(await exportIdentity(identity)))
210
+
211
+ const room = joinRoom('lobby', { signaling, identity })
212
+ console.log('My verified userId:', room.userId)
213
+
214
+ room.onPeerJoin((peerId) => {
215
+ // Already verified over WebRTC with DTLS channel binding before onPeerJoin fires!
216
+ console.log('Peer joined:', peerId, 'verified userId:', room.peerUserId(peerId))
217
+ })
218
+ ```
219
+
186
220
  ### `createVoice(room, options?: VoiceOptions)`
187
221
 
188
222
  Headless P2P voice chat controller built on top of `room.addStream()` / `room.onPeerStream()`:
@@ -192,34 +226,43 @@ Headless P2P voice chat controller built on top of `room.addStream()` / `room.on
192
226
  - Tracks speaking peers (`speakingPeers`) and local mic activity (`selfSpeaking`) via a shared lazy `AudioContext` + `AnalyserNode` (routed through a `GainNode(0)` sink for WebKit/iOS Safari compatibility).
193
227
  - Handles browser Autoplay Policy & iOS Safari quirks out of the box (lock-free `{ capture: true }` gesture unlocking on `pointerdown`/`pointerup`/`touchend`/`click`/`keydown`, iOS `'interrupted'` `AudioContext` recovery, `visibilitychange` foreground resume, and 6-path `navigator.audioSession` `'play-and-record'` save/restore).
194
228
 
195
- | `VoiceOptions` field | Type | Default | Purpose |
196
- | -------------------- | ------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
197
- | `volume` | `number` | `1` | Initial playback volume (`0` to `1`) for incoming peer audio. |
198
- | `deafened` | `boolean` | `false` | Start with incoming peer audio muted locally (`audio.muted = true`). |
199
- | `audioConstraints` | `MediaTrackConstraints \| true` | `{ echoCancellation: true, noiseSuppression: true, autoGainControl: true }` | Audio track constraints passed to `getUserMedia`. |
200
- | `autoUnlock` | `boolean` | `true` | Attach global `{ capture: true }` gesture & `visibilitychange` listeners to unlock blocked playback. |
201
- | `speakingDetection` | `boolean` | `true` | Enable shared lazy `AudioContext` + `AnalyserNode` speaking detection. |
202
- | `speakingThreshold` | `number` | `0.03` | RMS amplitude threshold (`0` to `1`) for `selfSpeaking` and `speakingPeers`. |
203
- | `speakingIntervalMs` | `number` | `180` | Polling interval in milliseconds (`50` to `60_000`) for speaking detection. |
204
- | `to` | `string` | `undefined` | Scope outgoing microphone audio to a single target peer ID (incoming audio from all peers plays). |
229
+ | `VoiceOptions` field | Type | Default | Purpose |
230
+ | -------------------- | ------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
231
+ | `volume` | `number` | `1` | Initial playback volume (`0` to `1`) for incoming peer audio. |
232
+ | `deafened` | `boolean` | `false` | Start with incoming peer audio muted locally (`audio.muted = true`). |
233
+ | `audioConstraints` | `MediaTrackConstraints \| true` | `{ echoCancellation: true, noiseSuppression: true, autoGainControl: true }` | Audio track constraints passed to `getUserMedia`. |
234
+ | `autoUnlock` | `boolean` | `true` | Attach global `{ capture: true }` gesture & `visibilitychange` listeners to unlock blocked playback. |
235
+ | `speakingDetection` | `boolean` | `true` | Enable shared lazy `AudioContext` + `AnalyserNode` speaking detection. |
236
+ | `speakingThreshold` | `number` | `0.03` | RMS amplitude threshold (`0` to `1`) for `selfSpeaking` and `speakingPeers`. |
237
+ | `speakingIntervalMs` | `number` | `180` | Polling interval in milliseconds (`50` to `60_000`) for speaking detection. |
238
+ | `to` | `string` | `undefined` | Scope outgoing microphone audio to a single target peer ID (incoming audio from all peers plays). |
239
+ | `streamTag` | `string` | `'voice'` | Stream tag attached to outgoing mic streams and matched on incoming streams (`[a-zA-Z0-9._-]{1,32}`). |
240
+ | `strictStreamTag` | `boolean` | `false` | When `true`, also ignore untagged (`meta.tag === undefined`) incoming audio streams. |
205
241
 
206
242
  | `Voice` member | Description |
207
243
  | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
208
244
  | `voice.micStatus` | Current `MicStatus`: `'off' \| 'requesting' \| 'live' \| 'muted' \| 'error'`. |
209
245
  | `voice.micError` | `MicError \| null` (`{ code: MicErrorCode, message: string }`; codes: `'permission-denied' \| 'not-found' \| 'in-use' \| 'insecure-context' \| 'room-closed' \| 'unknown'`). |
246
+ | `voice.deviceId` | Active or selected microphone `deviceId` (`string`), or `null` for system default. |
210
247
  | `voice.autoplayBlocked` | `true` while any incoming `<audio>` element was blocked by browser Autoplay Policy and awaits a user gesture. |
211
248
  | `voice.deafened` | Whether incoming peer audio is muted locally. |
212
- | `voice.volume` | Current incoming playback volume (`0` to `1`). |
249
+ | `voice.volume` | Current master incoming playback volume (`0` to `1`). |
213
250
  | `voice.selfSpeaking` | `true` when local microphone is `'live'` and exceeds `speakingThreshold`. |
214
- | `voice.remotePeers` | Snapshot array of peer IDs currently sending audio. |
251
+ | `voice.remotePeers` | Snapshot array of peer IDs currently sending voice audio. |
215
252
  | `voice.speakingPeers` | Snapshot array of remote peer IDs currently exceeding `speakingThreshold`. |
216
- | `voice.getSnapshot()` | Returns an immutable `VoiceSnapshot` object with all 8 state fields above (`Voice extends VoiceSnapshot`). |
253
+ | `voice.mutedPeers` | Snapshot array of remote peer IDs locally muted via `voice.setPeerMuted(peerId, true)`. |
254
+ | `voice.getSnapshot()` | Returns an immutable `VoiceSnapshot` object with all 10 state fields above (`Voice extends VoiceSnapshot`). |
217
255
  | `voice.toggleMic()` | Acquires mic on first call (`'off' \| 'error'` → `'requesting'` → `'live'`), or toggles soft-mute (`'live'` ↔ `'muted'`). Coalesces concurrent `'requesting'` calls. |
218
256
  | `voice.startMic()` | Acquires mic if inactive, or unmutes if `'muted'`. Coalesces concurrent `'requesting'` calls; resolves to `'off'` if closed. |
219
257
  | `voice.setMuted(muted)` | Soft-mutes (`true`) or unmutes (`false`) an already-acquired mic (`'live' \| 'muted'`). No-op otherwise. |
220
258
  | `voice.stopMic()` | Detaches stream from room (`removeStream`), cancels any pending `getUserMedia`, and stops hardware tracks (`track.stop()`). |
221
- | `voice.setVolume(volume)` | Sets incoming playback volume (`0` to `1`, clamped; throws `RangeError` if non-finite). |
259
+ | `voice.switchDevice(deviceId?)` | Selects or hot-swaps microphone device (`string \| null \| undefined`) via `room.replaceStreamTrack()` with zero WebRTC SDP renegotiation (`Promise<MicStatus>`). |
260
+ | `voice.setVolume(volume)` | Sets master incoming playback volume (`0` to `1`, clamped; throws `RangeError` if non-finite). |
261
+ | `voice.setPeerVolume(peerId, volume)` | Sets local playback volume (`0` to `1`, clamped, scaled by master `voice.volume`) for one peer. |
262
+ | `voice.getPeerVolume(peerId)` | Returns configured local playback volume (`0` to `1`, default `1`) for `peerId`. |
222
263
  | `voice.setDeafened(deafened)` | Mutes (`true`) or unmutes (`false`) incoming remote `<audio>` elements locally (unmuting also calls `unlockAudio()`). |
264
+ | `voice.setPeerMuted(peerId, muted)` | Locally mutes (`true`) or unmutes (`false`) incoming audio from one peer (independent of `deafened`). |
265
+ | `voice.isPeerMuted(peerId)` | Returns whether `peerId` is locally muted via `setPeerMuted()`. |
223
266
  | `voice.unlockAudio()` | Synchronously retries `AudioContext.resume()` and `audio.play()` on paused remote streams (e.g. from a custom unlock banner click). |
224
267
  | `voice.onChange(fn, options?: ListenOptions)` | Subscribes to `VoiceSnapshot` changes (`(snapshot: VoiceSnapshot) => ...`). Returns unsubscribe. |
225
268
  | `voice.close()` | Releases mic tracks, removes hidden `<audio>` elements, closes `AudioContext`, restores `audioSession`, and detaches all listeners (runs automatically on `room.leave()`). |
@@ -238,7 +281,7 @@ if (voice.micStatus === 'off' || voice.micStatus === 'error') {
238
281
  await voice.toggleMic() // 1st call: getUserMedia + addStream ('live'); next calls: soft-mute ('muted' <-> 'live')
239
282
 
240
283
  voice.onChange((snap) => {
241
- // snap: { micStatus, micError, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers }
284
+ // snap: { micStatus, micError, deviceId, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers, mutedPeers }
242
285
  if (snap.autoplayBlocked) showUnlockBanner()
243
286
  })
244
287
 
@@ -252,22 +295,28 @@ voice.stopMic() // Release microphone hardware while staying in the room (voice.
252
295
  For custom video, screen sharing, or bespoke audio pipelines, use the low-level `Room` methods directly:
253
296
 
254
297
  ```ts
255
- const mic = await navigator.mediaDevices.getUserMedia({ audio: true })
256
- room.addStream(mic) // Broadcast to all current & future peers (or pass peerId as 2nd arg)
298
+ const screen = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: true })
299
+ room.addStream(screen, { tag: 'screen' }) // Tagged so createVoice() will not hijack screen audio!
257
300
 
258
- room.onPeerStream((peerId, stream) => {
259
- const audio = new Audio()
260
- audio.srcObject = stream
261
- audio.play()
301
+ room.onPeerStream((peerId, stream, meta) => {
302
+ if (meta.tag === 'screen') {
303
+ videoEl.srcObject = stream
304
+ }
262
305
  })
263
- room.onPeerStreamEnd((peerId, stream) => console.log('Stream ended:', peerId, stream.id))
306
+ room.onPeerStreamEnd((peerId, stream, meta) =>
307
+ console.log('Stream ended:', peerId, stream.id, meta.tag)
308
+ )
309
+
310
+ // Hot-swap a track (e.g. camera/mic switch) with zero WebRTC SDP renegotiation:
311
+ await room.replaceStreamTrack(screen, oldVideoTrack, newVideoTrack)
312
+ oldVideoTrack.stop()
264
313
 
265
- // Later: detach from room and stop local microphone tracks yourself.
266
- room.removeStream(mic)
267
- for (const track of mic.getTracks()) track.stop()
314
+ // Later: detach from room and stop local tracks yourself.
315
+ room.removeStream(screen)
316
+ for (const track of screen.getTracks()) track.stop()
268
317
  ```
269
318
 
270
- > **Note:** `removeStream()` does not stop local `MediaStreamTrack`s (call `track.stop()` when done, or use `createVoice()`), and streams with 0 tracks or tracks added to a `MediaStream` _after_ `addStream()` are not renegotiated automatically.
319
+ > **Note:** `removeStream()` and `replaceStreamTrack()` do not stop local `MediaStreamTrack`s (call `track.stop()` when done, or use `createVoice()`), and streams with 0 tracks or tracks added manually to a `MediaStream` _without_ `replaceStreamTrack()` are not renegotiated automatically.
271
320
 
272
321
  ### `SendResult`
273
322
 
@@ -295,12 +344,80 @@ for (const track of mic.getTracks()) track.stop()
295
344
 
296
345
  ### `createChannel(room, name, options?: ChannelOptions)`
297
346
 
298
- 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.
347
+ Creates a named message stream (such as `'chat'` or `'cursor'`) on your existing room connections, dispatched in `O(1)` time through a single shared per-`Room` router. Each channel only receives packets sent to its own name and delivery mode.
299
348
 
300
349
  - `name`: 1–64 UTF-8 bytes. Uses `1 + nameBytes.length` bytes of the 16,384-byte packet limit.
301
350
  - `options` (`ChannelOptions`): `{ delivery?: Delivery }`. Defaults to `'unreliable'`.
302
351
  - Returns a `Channel` with `{ name, delivery, send(bytes, options?: ChannelSendOptions), onPacket((from, bytes) => ..., options?: ListenOptions) }` (`ChannelSendOptions` is `{ to?: string }`).
303
352
 
353
+ ### `createCodecChannel(room, name, codec, options?: ChannelOptions)`
354
+
355
+ Creates a typed logical channel using a synchronous `Codec<T>` (`{ encode(value: T): Uint8Array, decode(bytes: Uint8Array): T }`), **preserving synchronous `ReadonlyMap<string, SendResult>` backpressure** on `send()` while automatically ignoring malformed incoming frames (without consuming `{ once: true }` subscriptions).
356
+
357
+ - Built-in codecs:
358
+ - `jsonCodec<T>(validate?)` — UTF-8 JSON serializer/deserializer. Pass a TypeScript type guard (`(v): v is ChatMsg => ...`) to validate untrusted peer input and infer `Codec<ChatMsg>` automatically.
359
+ - `textCodec` — Strict UTF-8 string codec (`Codec<string>`).
360
+ - `binaryCodec` — Zero-copy `Uint8Array` identity codec (`Codec<Uint8Array>`).
361
+ - Returns a `CodecChannel<T>` with `{ name, delivery, send(value, options?: ChannelSendOptions), onMessage((from, value) => ..., options?: ListenOptions) }`.
362
+
363
+ ```ts
364
+ import { createCodecChannel, jsonCodec } from '@dimchansky/meshpost'
365
+
366
+ interface ChatMsg {
367
+ text: string
368
+ }
369
+
370
+ const isChatMsg = (v: unknown): v is ChatMsg =>
371
+ Boolean(v) && typeof v === 'object' && typeof (v as ChatMsg).text === 'string'
372
+
373
+ const chat = createCodecChannel(room, 'chat', jsonCodec(isChatMsg), { delivery: 'reliable' })
374
+ chat.onMessage((from, msg) => console.log(from, msg.text))
375
+ chat.send({ text: 'hello!' })
376
+ ```
377
+
378
+ ### `createRpc<Req, Res>(room, name, options?: RpcOptions<Req, Res>)`
379
+
380
+ Creates a lightweight reliable request-response RPC endpoint over `createChannel(room, name, { delivery: 'reliable' })` with automatic correlation IDs, `timeoutMs`, `AbortSignal`, `onPeerLeave` disconnect rejection, anti-spoofing peer verification, and immediate structured `RpcError` codes (`'timeout' | 'aborted' | 'disconnected' | 'unavailable' | 'busy' | 'too-large' | 'unhandled' | 'remote-error' | 'closed'`).
381
+
382
+ - `options` (`RpcOptions<Req, Res>`): `{ timeoutMs?, requestCodec?, responseCodec?, maxPendingCalls?, maxConcurrentPerPeer? }` (defaults: `10_000` ms timeout, `jsonCodec()`, `256` max pending calls, `16` max concurrent incoming requests per peer).
383
+ - Returns an `RpcEndpoint<Req, Res>` with `{ name, call(peerId, request, options?: RpcCallOptions), handle((from, request) => response | Promise<response>, options?: ListenOptions), close() }` (`RpcCallOptions` is `{ timeoutMs?: number, signal?: AbortSignal }`; exported error types: `RpcError`, `RpcErrorCode`).
384
+
385
+ ```ts
386
+ import { createRpc } from '@dimchansky/meshpost'
387
+
388
+ const ping = createRpc<{ sentAt: number }, { serverNow: number }>(room, 'ping', {
389
+ timeoutMs: 5_000
390
+ })
391
+
392
+ ping.handle(() => ({ serverNow: Date.now() }))
393
+
394
+ const { serverNow } = await ping.call(peerId, { sentAt: Date.now() })
395
+ ```
396
+
397
+ ### `createPeerState<T>(room, name, options?: PeerStateOptions<T>)`
398
+
399
+ Creates a single-writer per-peer state synchronization store (zero CRDT bloat): each peer owns its own slot (`set(value)` / `clear()`), while remote peers' latest states are automatically ordered via RFC 1982 `u32` sequence numbers, **hydrated reliably on `onPeerJoin`** (even when live updates use `delivery: 'unreliable'`), cleaned up on `onPeerLeave`, and coalesced in `O(1)` memory on `room.onDrain` when send buffers are `'busy'`.
400
+
401
+ - `options` (`PeerStateOptions<T>`): `{ delivery?: Delivery, codec?: Codec<T>, initial?: T, coalesce?: boolean }` (defaults: `delivery: 'reliable'`, `codec: jsonCodec()`, `coalesce: true`).
402
+ - Returns a `PeerState<T>` with `{ name, delivery, getSelf(), get(peerId), getAll(), set(value), clear(), onChange((peerId, next, prev) => ..., options?: ListenOptions), close() }`.
403
+
404
+ ```ts
405
+ import { createPeerState } from '@dimchansky/meshpost'
406
+
407
+ const cursors = createPeerState<{ x: number; y: number }>(room, 'cursor', {
408
+ delivery: 'unreliable',
409
+ coalesce: true
410
+ })
411
+
412
+ cursors.onChange((peerId, pos) => {
413
+ if (!pos)
414
+ removeCursor(peerId) // Peer left or called clear()
415
+ else renderCursor(peerId, pos.x, pos.y)
416
+ })
417
+
418
+ cursors.set({ x: 0.5, y: 0.25 })
419
+ ```
420
+
304
421
  ### `createBlobChannel(room, name, options?: BlobChannelOptions)`
305
422
 
306
423
  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`.
@@ -325,14 +442,15 @@ const results = await files.send(fileBytes, {
325
442
 
326
443
  ### Signaling exports
327
444
 
328
- - `mqttSignaling({ urls?, appId?, password?, handshakeTimeoutMs? })` — Connects browsers across different devices and networks using built-in public MQTT relay servers (`defaultMqttRelays`).
329
- - `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.
445
+ - `mqttSignaling({ urls?, appId?, password?, privateTopic?, handshakeTimeoutMs?, WebSocket? })` — Connects browsers across different devices and networks using built-in public MQTT relay servers (`defaultMqttRelays`), with optional `AES-256-GCM` E2E encryption, `privateTopic` topic hiding, and optional custom `WebSocket` constructor injection.
446
+ - `nostrSignaling({ urls?, appId?, password?, privateTopic?, handshakeTimeoutMs?, WebSocket? })` — Zero-server signaling over public **port-443** NIP-01 Nostr relays (`defaultNostrRelays`) using ephemeral `kind: 25050` events (never persisted by relays), pure-TS BIP-340 Schnorr signatures (0 dependencies, tree-shakeable), optional `AES-256-GCM` E2E encryption + `privateTopic` tag hiding, and optional custom `WebSocket` constructor injection.
447
+ - `wsSignaling(url, { reconnect?, handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Connects browsers through your own WebSocket (`ws://` / `wss://`) signaling server (defaults: `reconnect: true`, `handshakeTimeoutMs: 10_000`, `pingIntervalMs: 25_000`, `encrypt: true`, `privateTopic: false`). Automatically appends `?room=<roomKey>` for stateless per-room sharding and E2E-encrypts signaling (`box` envelopes) when `password` is set. See [examples/ws-worker/](examples/ws-worker/README.md) for a ready-to-deploy Cloudflare Worker + Durable Object (WebSocket Hibernation) relay, or [examples/serve.mjs](examples/serve.mjs) for Node.js.
330
448
  - `withLocalTabs(primary)` — Decorates a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant same-browser `BroadcastChannel` discovery (`tabSignaling()`) while **preserving `primary`'s `SignalingState`** for `room.signalingState` / `room.onSignalingChange` (avoiding a stuck `'online'` state when internet connectivity drops, while still connecting local tabs offline). Safely falls back to `primary` on `file:` / opaque origins or when `BroadcastChannel` is unavailable.
331
449
  - `combineSignaling(...adapters)` — Combines multiple `Signaling` adapters, merging peer rosters and keeping discovery online as long as any child adapter is online (e.g. `combineSignaling(wsSignaling('wss://primary.example/ws'), mqttSignaling())`).
332
450
  - `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
333
451
  - `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
334
452
  - `defaultIceServers` — Built-in Cloudflare and Google public servers (STUN) that help browsers find their public network address.
335
- - 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).
453
+ - Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `MqttSignalingOptions`, `NostrSignalingOptions`, `WsSignalingOptions`, `RTCPeerConnectionConstructor`, `WebSocketConstructor`, `defaultMqttRelays`, `defaultNostrRelays`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
336
454
 
337
455
  ## Connecting through strict firewalls (TURN)
338
456
 
@@ -354,6 +472,46 @@ const room = joinRoom('lobby', {
354
472
  })
355
473
  ```
356
474
 
475
+ ### Subpath exports & bundler-free `<script type="importmap">`
476
+
477
+ Every feature module is available as a dedicated subpath export (`@dimchansky/meshpost/room`, `/channel`, `/rpc`, `/state`, `/blob`, `/voice`, `/turn`, `/identity`, `/mqtt`, `/nostr`, `/ws`, `/tabs`, `/manual`, `/combine`, `/signaling`) so bundler-free `<script type="importmap">` apps only download the modules they actually import:
478
+
479
+ ```html
480
+ <script type="importmap">
481
+ {
482
+ "imports": {
483
+ "@dimchansky/meshpost/room": "https://cdn.jsdelivr.net/npm/@dimchansky/meshpost/dist/room.js",
484
+ "@dimchansky/meshpost/nostr": "https://cdn.jsdelivr.net/npm/@dimchansky/meshpost/dist/nostr.js",
485
+ "@dimchansky/meshpost/channel": "https://cdn.jsdelivr.net/npm/@dimchansky/meshpost/dist/channel.js"
486
+ }
487
+ }
488
+ </script>
489
+ <script type="module">
490
+ import { joinRoom } from '@dimchansky/meshpost/room'
491
+ import { nostrSignaling } from '@dimchansky/meshpost/nostr'
492
+ import { createCodecChannel, textCodec } from '@dimchansky/meshpost/channel'
493
+
494
+ const room = joinRoom('lobby', { password: 'secret', signaling: nostrSignaling() })
495
+ const chat = createCodecChannel(room, 'chat', textCodec, { delivery: 'reliable' })
496
+ </script>
497
+ ```
498
+
499
+ ### Headless peers (Node.js 22+, Bun, Deno)
500
+
501
+ Inject a userland `RTCPeerConnection` implementation (such as `werift` or `@roamhq/wrtc`) — and optionally a custom `WebSocket` constructor — without mutating `globalThis`:
502
+
503
+ ```ts
504
+ import { RTCPeerConnection } from 'werift'
505
+ import { joinRoom } from '@dimchansky/meshpost/room'
506
+ import { wsSignaling } from '@dimchansky/meshpost/ws'
507
+
508
+ const botRoom = joinRoom('game-1', {
509
+ password: 'secret',
510
+ RTCPeerConnection,
511
+ signaling: wsSignaling('wss://relay.example/ws') // Node 22+, Bun, & Deno provide global WebSocket (or pass { WebSocket })
512
+ })
513
+ ```
514
+
357
515
  ## Try the interactive playground
358
516
 
359
517
  ### Option 1: Local dev server (recommended)
@@ -378,7 +536,7 @@ npm run demo
378
536
 
379
537
  Open **dist/playground.html** directly in two browsers (`file://`). Enter the same room name and click **Join room**.
380
538
 
381
- - By default, `dist/playground.html` uses `mqttSignaling()` when opened via `file://` and `withLocalTabs(mqttSignaling())` when hosted on a public `https://` origin (such as GitHub Pages).
539
+ - By default, `dist/playground.html` combines `mqttSignaling()` and port-443 `nostrSignaling()` when opened via `file://` or hosted on a public `https://` origin (wrapped in `withLocalTabs(...)` on HTTP/HTTPS).
382
540
  - For completely offline copy-paste exchange with zero network requests, open `dist/playground.html#mode=manual` (or click **Offline mode** on the join screen).
383
541
  - 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).
384
542
 
@@ -386,27 +544,29 @@ Open **dist/playground.html** directly in two browsers (`file://`). Enter the sa
386
544
 
387
545
  All `@dimchansky/meshpost` usage in the playground is intentionally concentrated in **one file** so you can learn the full API in one place:
388
546
 
389
- - [examples/playground/mesh.js](examples/playground/mesh.js) — **Start here.** Single facade wiring `joinRoom()`, signaling adapters (`withLocalTabs`, `mqttSignaling`, `wsSignaling`, `manualSignaling`), `fetchTurnCredentials()`, `createChannel()` (`pointer`, `draw`, `chat`, `direct`, `profile`), `createBlobChannel()` (`draw-snap`, `file`), `createVoice()`, `ListenOptions` (`{ signal }`), `room.onError()`, and `room.getStats()`.
547
+ - [examples/playground/mesh.js](examples/playground/mesh.js) — **Start here.** Single facade using `@dimchansky/meshpost/*` subpath imports to wire `joinRoom()`, `createIdentity()` / `exportIdentity()` / `importIdentity()` / `isSerializedIdentity()`, signaling adapters (`withLocalTabs`, `combineSignaling`, `mqttSignaling`, `nostrSignaling`, `wsSignaling`, `manualSignaling`), `fetchTurnCredentials()`, `createPeerState()` (`presence`, `cursor`), `createChannel()` (`ripple`, `draw`), `createCodecChannel()` + `jsonCodec()` (`chat`, `direct`), `createRpc()` (`ping`), `createBlobChannel()` (`draw-snap`, `file`), `createVoice()`, `ListenOptions` (`{ signal }`), `room.onError()`, and `room.getStats()`.
390
548
  - [examples/playground/relay.js](examples/playground/relay.js) — `autoSignaling()` composing `tabSignaling()` and `wsSignaling()` with a silent fallback to `tabSignaling()` on plain static localhost servers.
391
- - [examples/playground/codec.js](examples/playground/codec.js) — Pure binary codecs for pointer updates, canvas strokes, and file metadata envelopes.
549
+ - [examples/playground/codec.js](examples/playground/codec.js) — Pure binary codecs (`cursorCodec`, canvas strokes, file metadata envelopes) and payload type guards.
392
550
  - [examples/playground/canvas.js](examples/playground/canvas.js) — Collaborative 2D drawing canvas and remote cursor/ripple overlays.
393
- - [examples/playground/voice.js](examples/playground/voice.js) — Thin DOM binding connecting microphone buttons, autoplay banner, and `KeyM` to `createVoice()`.
551
+ - [examples/playground/voice.js](examples/playground/voice.js) — Thin DOM binding connecting microphone buttons, zero-renegotiation mic switcher (`switchDevice`), per-peer volume/mute controls, autoplay banner, and `KeyM` to `createVoice()`.
394
552
  - [examples/playground/session.js](examples/playground/session.js) — Compact `#c=` invite URLs and `sessionStorage` auto-rejoin.
395
553
  - [examples/playground/app.js](examples/playground/app.js) — Thin UI controller connecting DOM controls to `mesh.js` and the helper modules.
396
554
  - [examples/playground/index.html](examples/playground/index.html) — Minimal HTML markup for the playground.
555
+ - [examples/ws-worker/](examples/ws-worker/README.md) — Ready-to-deploy Cloudflare Worker + Durable Object (WebSocket Hibernation) signaling server for `wsSignaling()` with per-room sharding and zero-wake keepalives.
397
556
  - [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.
398
557
 
399
558
  ## Project layout and tests
400
559
 
401
- | Path | Purpose |
402
- | ----------------------- | ------------------------------------------------------------------------------ |
403
- | `src/` | Core room lifecycle, channels, and signaling adapters |
404
- | `examples/playground/` | Interactive demo source |
405
- | `examples/turn-worker/` | Optional Cloudflare Worker credential broker for Metered, CF TURN, or `coturn` |
406
- | `examples/build.mjs` | Bundles the playground into one portable HTML file |
407
- | `examples/serve.mjs` | Local dev server with WebSocket (`/ws`) and SSE signaling relays |
408
- | `tests/` | Playwright E2E tests using real browser WebRTC data channels |
409
- | `dist/` | Built ES modules, `.d.ts` declarations, and `playground.html` |
560
+ | Path | Purpose |
561
+ | ----------------------- | --------------------------------------------------------------------------------- |
562
+ | `src/` | Core room lifecycle, channels, state, RPC, voice, and signaling adapters |
563
+ | `examples/playground/` | Interactive demo source |
564
+ | `examples/ws-worker/` | Optional Cloudflare Worker + Durable Object (Hibernation) relay for `wsSignaling` |
565
+ | `examples/turn-worker/` | Optional Cloudflare Worker credential broker for Metered, CF TURN, or `coturn` |
566
+ | `examples/build.mjs` | Bundles the playground into one portable HTML file |
567
+ | `examples/serve.mjs` | Local dev server with WebSocket (`/ws`) and SSE signaling relays |
568
+ | `tests/` | Playwright E2E tests using real browser WebRTC data channels |
569
+ | `dist/` | Built ES modules, `.d.ts` declarations, and `playground.html` |
410
570
 
411
571
  Run the test suite:
412
572
 
@@ -420,10 +580,10 @@ To use an already-installed Google Chrome instead of downloading Chromium, run `
420
580
 
421
581
  For full limits, wire protocol details, edge cases, and the security model, read [docs/behavior.md](docs/behavior.md).
422
582
 
423
- ## Browser support
583
+ ## Runtime support
424
584
 
425
- - Runs in modern browsers (Chrome, Firefox, Safari) with WebRTC `RTCDataChannel`, `WebSocket`, and `BroadcastChannel`. Meshpost is a browser library (not for Node.js).
426
- - `mqttSignaling()` with `password` uses browser Web Crypto (`crypto.subtle`), which requires `https://` or `http://localhost` (`127.0.0.1`).
585
+ - Runs in modern browsers (Chrome, Firefox, Safari) with WebRTC `RTCDataChannel`, `WebSocket`, and `BroadcastChannel`, as well as headless runtimes (Node.js 22+, Bun, Deno) when passing `RTCPeerConnection` (and optional `WebSocket`) constructors.
586
+ - `mqttSignaling()`, `nostrSignaling()`, and `wsSignaling()` (unless `encrypt: false`) with `password` — as well as `createIdentity()` — use Web Crypto (`crypto.subtle`), which in browsers requires `https://` or `http://localhost` (`127.0.0.1`).
427
587
 
428
588
  ## License
429
589