@dimchansky/meshpost 0.2.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,47 +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
- | `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 |
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 |
106
105
 
107
106
  ### Local tabs (`tabSignaling`)
108
107
 
@@ -135,7 +134,7 @@ manual.accept(pastedTextFromPeer) // Paste incoming contact cards and replies he
135
134
  manual.forget(oldPeerId) // Optional: stop retrying an old contact.
136
135
  ```
137
136
 
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.)
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).
139
138
 
140
139
  ## Public API reference
141
140
 
@@ -146,61 +145,178 @@ Creates a room, assigns a random peer ID (`room.id`), and immediately starts loo
146
145
  - `name`: Room name. Must match `^[a-zA-Z0-9_-]{1,64}$`.
147
146
  - Throws an error immediately if `name`, `appId`, `password`, timeouts, `maxPeers`, or `rtcConfig` are invalid.
148
147
 
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. |
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. |
159
160
 
160
161
  ### `Room`
161
162
 
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.
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.
182
186
 
183
187
  `room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
184
188
 
185
- #### P2P Voice / MediaStreams
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
+
220
+ ### `createVoice(room, options?: VoiceOptions)`
221
+
222
+ Headless P2P voice chat controller built on top of `room.addStream()` / `room.onPeerStream()`:
223
+
224
+ - Plays incoming peer audio streams automatically via hidden `<audio autoplay playsinline>` elements (hydrating any streams already active when `createVoice(room)` is called, up to `4` streams per peer).
225
+ - Manages local microphone capture with instant soft-mute (`track.enabled`, zero WebRTC renegotiation) vs full hardware release (`stopMic()`), plus automatic cleanup when `room.leave()` runs.
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).
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).
228
+
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. |
241
+
242
+ | `Voice` member | Description |
243
+ | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
244
+ | `voice.micStatus` | Current `MicStatus`: `'off' \| 'requesting' \| 'live' \| 'muted' \| 'error'`. |
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. |
247
+ | `voice.autoplayBlocked` | `true` while any incoming `<audio>` element was blocked by browser Autoplay Policy and awaits a user gesture. |
248
+ | `voice.deafened` | Whether incoming peer audio is muted locally. |
249
+ | `voice.volume` | Current master incoming playback volume (`0` to `1`). |
250
+ | `voice.selfSpeaking` | `true` when local microphone is `'live'` and exceeds `speakingThreshold`. |
251
+ | `voice.remotePeers` | Snapshot array of peer IDs currently sending voice audio. |
252
+ | `voice.speakingPeers` | Snapshot array of remote peer IDs currently exceeding `speakingThreshold`. |
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`). |
255
+ | `voice.toggleMic()` | Acquires mic on first call (`'off' \| 'error'` → `'requesting'` → `'live'`), or toggles soft-mute (`'live'` ↔ `'muted'`). Coalesces concurrent `'requesting'` calls. |
256
+ | `voice.startMic()` | Acquires mic if inactive, or unmutes if `'muted'`. Coalesces concurrent `'requesting'` calls; resolves to `'off'` if closed. |
257
+ | `voice.setMuted(muted)` | Soft-mutes (`true`) or unmutes (`false`) an already-acquired mic (`'live' \| 'muted'`). No-op otherwise. |
258
+ | `voice.stopMic()` | Detaches stream from room (`removeStream`), cancels any pending `getUserMedia`, and stops hardware tracks (`track.stop()`). |
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`. |
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()`. |
266
+ | `voice.unlockAudio()` | Synchronously retries `AudioContext.resume()` and `audio.play()` on paused remote streams (e.g. from a custom unlock banner click). |
267
+ | `voice.onChange(fn, options?: ListenOptions)` | Subscribes to `VoiceSnapshot` changes (`(snapshot: VoiceSnapshot) => ...`). Returns unsubscribe. |
268
+ | `voice.close()` | Releases mic tracks, removes hidden `<audio>` elements, closes `AudioContext`, restores `audioSession`, and detaches all listeners (runs automatically on `room.leave()`). |
269
+
270
+ Exported voice types: `Voice`, `VoiceOptions`, `VoiceSnapshot`, `MicStatus`, `MicError`, `MicErrorCode`.
186
271
 
187
272
  ```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)
273
+ import { createVoice } from '@dimchansky/meshpost'
190
274
 
191
- room.onPeerStream((peerId, stream) => {
192
- const audio = new Audio()
193
- audio.srcObject = stream
194
- audio.play()
275
+ const voice = createVoice(room)
276
+
277
+ // Synchronous state inspection (e.g. exit Pointer Lock in 3D games only before first permission prompt)
278
+ if (voice.micStatus === 'off' || voice.micStatus === 'error') {
279
+ document.exitPointerLock?.()
280
+ }
281
+ await voice.toggleMic() // 1st call: getUserMedia + addStream ('live'); next calls: soft-mute ('muted' <-> 'live')
282
+
283
+ voice.onChange((snap) => {
284
+ // snap: { micStatus, micError, deviceId, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers, mutedPeers }
285
+ if (snap.autoplayBlocked) showUnlockBanner()
195
286
  })
196
- room.onPeerStreamEnd((peerId, stream) => console.log('Stream ended:', peerId, stream.id))
197
287
 
198
- // Later: detach from room and stop local microphone tracks yourself.
199
- room.removeStream(mic)
200
- for (const track of mic.getTracks()) track.stop()
288
+ voice.setVolume(0.8)
289
+ voice.setDeafened(false)
290
+ voice.stopMic() // Release microphone hardware while staying in the room (voice.close() runs automatically on room.leave())
201
291
  ```
202
292
 
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.
293
+ #### Low-level `MediaStream` API (`addStream` / `onPeerStream`)
294
+
295
+ For custom video, screen sharing, or bespoke audio pipelines, use the low-level `Room` methods directly:
296
+
297
+ ```ts
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!
300
+
301
+ room.onPeerStream((peerId, stream, meta) => {
302
+ if (meta.tag === 'screen') {
303
+ videoEl.srcObject = stream
304
+ }
305
+ })
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()
313
+
314
+ // Later: detach from room and stop local tracks yourself.
315
+ room.removeStream(screen)
316
+ for (const track of screen.getTracks()) track.stop()
317
+ ```
318
+
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.
204
320
 
205
321
  ### `SendResult`
206
322
 
@@ -228,12 +344,80 @@ for (const track of mic.getTracks()) track.stop()
228
344
 
229
345
  ### `createChannel(room, name, options?: ChannelOptions)`
230
346
 
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.
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.
232
348
 
233
349
  - `name`: 1–64 UTF-8 bytes. Uses `1 + nameBytes.length` bytes of the 16,384-byte packet limit.
234
350
  - `options` (`ChannelOptions`): `{ delivery?: Delivery }`. Defaults to `'unreliable'`.
235
351
  - Returns a `Channel` with `{ name, delivery, send(bytes, options?: ChannelSendOptions), onPacket((from, bytes) => ..., options?: ListenOptions) }` (`ChannelSendOptions` is `{ to?: string }`).
236
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
+
237
421
  ### `createBlobChannel(room, name, options?: BlobChannelOptions)`
238
422
 
239
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`.
@@ -258,25 +442,73 @@ const results = await files.send(fileBytes, {
258
442
 
259
443
  ### Signaling exports
260
444
 
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'))`).
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.
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.
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())`).
264
450
  - `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
265
451
  - `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
266
452
  - `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).
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).
268
454
 
269
455
  ## Connecting through strict firewalls (TURN)
270
456
 
271
457
  - 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
458
  - 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:
459
+ - Add your TURN credentials directly or fetch short-lived credentials from Meshpost's reference Cloudflare Worker ([examples/turn-worker/](examples/turn-worker/README.md)) using `fetchTurnCredentials(url, options?: FetchTurnOptions)` (`options`: `{ accessKey?, signal?, timeoutMs? }`; `5,000` ms default timeout, `timeoutMs: 0` disables timeout, `redirect: 'error'`, `64 KiB` response cap):
274
460
 
275
461
  ```ts
462
+ import { fetchTurnCredentials, joinRoom, mqttSignaling, withLocalTabs } from '@dimchansky/meshpost'
463
+
464
+ const turnConfig = await fetchTurnCredentials('https://your-turn.workers.dev', {
465
+ accessKey: 'shared-key'
466
+ })
467
+
276
468
  const room = joinRoom('lobby', {
277
469
  appId: 'my-app',
278
- signaling: mqttSignaling(),
279
- turnConfig: [{ urls: 'turns:turn.example.org:5349', username: 'user', credential: 'secret' }]
470
+ signaling: withLocalTabs(mqttSignaling()),
471
+ turnConfig
472
+ })
473
+ ```
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 })
280
512
  })
281
513
  ```
282
514
 
@@ -304,7 +536,7 @@ npm run demo
304
536
 
305
537
  Open **dist/playground.html** directly in two browsers (`file://`). Enter the same room name and click **Join room**.
306
538
 
307
- - By default, `dist/playground.html` uses `mqttSignaling()` when opened via `file://` or 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).
308
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).
309
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).
310
542
 
@@ -312,27 +544,29 @@ Open **dist/playground.html** directly in two browsers (`file://`). Enter the sa
312
544
 
313
545
  All `@dimchansky/meshpost` usage in the playground is intentionally concentrated in **one file** so you can learn the full API in one place:
314
546
 
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()`.
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()`.
316
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.
317
- - [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.
318
550
  - [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.
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()`.
552
+ - [examples/playground/session.js](examples/playground/session.js) — Compact `#c=` invite URLs and `sessionStorage` auto-rejoin.
321
553
  - [examples/playground/app.js](examples/playground/app.js) — Thin UI controller connecting DOM controls to `mesh.js` and the helper modules.
322
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.
323
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.
324
557
 
325
558
  ## Project layout and tests
326
559
 
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` |
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` |
336
570
 
337
571
  Run the test suite:
338
572
 
@@ -346,10 +580,10 @@ To use an already-installed Google Chrome instead of downloading Chromium, run `
346
580
 
347
581
  For full limits, wire protocol details, edge cases, and the security model, read [docs/behavior.md](docs/behavior.md).
348
582
 
349
- ## Browser support
583
+ ## Runtime support
350
584
 
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`).
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`).
353
587
 
354
588
  ## License
355
589