@dimchansky/meshpost 0.4.2 → 0.6.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.
Files changed (46) hide show
  1. package/README.md +66 -550
  2. package/dist/bip340.d.ts +1 -0
  3. package/dist/bip340.js +346 -0
  4. package/dist/blob.d.ts +1 -1
  5. package/dist/blob.js +15 -16
  6. package/dist/channel.js +15 -44
  7. package/dist/combine.js +25 -39
  8. package/dist/crypto.js +10 -9
  9. package/dist/identity.d.ts +45 -0
  10. package/dist/identity.js +188 -28
  11. package/dist/index.d.ts +6 -6
  12. package/dist/index.js +3 -3
  13. package/dist/listeners.js +18 -3
  14. package/dist/mqtt.js +193 -408
  15. package/dist/nostr.js +163 -745
  16. package/dist/public.d.ts +19 -1
  17. package/dist/public.js +26 -9
  18. package/dist/relay-core.d.ts +1 -0
  19. package/dist/relay-core.js +323 -0
  20. package/dist/room-hello.d.ts +1 -0
  21. package/dist/room-hello.js +129 -0
  22. package/dist/room-ice.d.ts +1 -0
  23. package/dist/room-ice.js +115 -0
  24. package/dist/room-media.d.ts +1 -0
  25. package/dist/room-media.js +477 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +111 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +109 -919
  31. package/dist/signaling.d.ts +8 -0
  32. package/dist/signaling.js +64 -0
  33. package/dist/state.js +1 -2
  34. package/dist/voice-helpers.d.ts +1 -0
  35. package/dist/voice-helpers.js +100 -0
  36. package/dist/voice-meter.d.ts +1 -0
  37. package/dist/voice-meter.js +79 -0
  38. package/dist/voice.d.ts +41 -0
  39. package/dist/voice.js +205 -273
  40. package/dist/ws.js +60 -146
  41. package/docs/api.md +217 -0
  42. package/docs/behavior.md +16 -9
  43. package/docs/guide.md +404 -0
  44. package/docs/signaling-and-production.md +312 -0
  45. package/docs/voice-and-media.md +193 -0
  46. package/package.json +3 -2
package/dist/ws.js CHANGED
@@ -1,4 +1,5 @@
1
- import { createReplayGuard, deriveSignalingKeys, errorCooldownMs, fromBase64Url, openEnvelope, sealEnvelope, toBase64Url } from './crypto.js';
1
+ import { createReplayGuard, deriveSignalingKeys, fromBase64Url, openEnvelope, sealEnvelope, toBase64Url } from './crypto.js';
2
+ import { createErrorThrottle, normalizeWsRelayUrl, safeCloseSocket, validatePositiveTimeout } from './relay-core.js';
2
3
  import { isSignal, isUuid, namespaceHash } from './signaling.js';
3
4
  const wsOpen = 1;
4
5
  const defaultOptionalHandshakeTimeoutMs = 4_000;
@@ -9,35 +10,14 @@ const maxDecryptQueueDepth = 64;
9
10
  const defaultHandshakeTimeoutMs = 10_000;
10
11
  const defaultPingIntervalMs = 25_000;
11
12
  const insecureWsMessage = 'Password encryption requires a secure context (crypto.subtle); pass encrypt: false for plaintext LAN testing';
12
- /**
13
- * Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
14
- * When a room `password` is set, SDP and ICE payloads are end-to-end encrypted with AES-256-GCM by default.
15
- */
16
- export function wsSignaling(url, options = {}) {
17
- let parsed;
18
- try {
19
- parsed = new URL(url);
20
- }
21
- catch {
22
- throw new TypeError('Invalid WebSocket signaling URL');
23
- }
24
- if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
25
- throw new TypeError('WebSocket signaling URL must use ws: or wss:');
26
- }
27
- const normalizedUrl = parsed.toString();
28
- const shouldReconnect = options.reconnect ?? true;
29
- const handshakeTimeoutMs = options.handshakeTimeoutMs ?? defaultHandshakeTimeoutMs;
30
- if (!Number.isSafeInteger(handshakeTimeoutMs) ||
31
- handshakeTimeoutMs <= 0 ||
32
- handshakeTimeoutMs > 2_147_483_647) {
33
- throw new RangeError('Invalid WebSocket handshake timeout');
34
- }
13
+ function createWsSignaling(url, options, optional) {
14
+ const normalizedUrl = normalizeWsRelayUrl(url, 'Invalid WebSocket signaling URL', 'WebSocket signaling URL must use ws: or wss:');
15
+ const shouldReconnect = optional ? false : (options.reconnect ?? true);
16
+ const handshakeTimeoutMs = options.handshakeTimeoutMs ??
17
+ (optional ? defaultOptionalHandshakeTimeoutMs : defaultHandshakeTimeoutMs);
18
+ validatePositiveTimeout(handshakeTimeoutMs, 'Invalid WebSocket handshake timeout');
35
19
  const pingIntervalMs = options.pingIntervalMs ?? defaultPingIntervalMs;
36
- if (!Number.isSafeInteger(pingIntervalMs) ||
37
- pingIntervalMs <= 0 ||
38
- pingIntervalMs > 2_147_483_647) {
39
- throw new RangeError('Invalid WebSocket ping interval');
40
- }
20
+ validatePositiveTimeout(pingIntervalMs, 'Invalid WebSocket ping interval');
41
21
  if (options.encrypt !== undefined && typeof options.encrypt !== 'boolean') {
42
22
  throw new TypeError('Invalid encrypt option');
43
23
  }
@@ -76,6 +56,7 @@ export function wsSignaling(url, options = {}) {
76
56
  : namespaceHash(baseScope + (!useEncryption && password !== undefined ? ':' + password : ''));
77
57
  const knownPeers = new Set();
78
58
  const replayGuard = createReplayGuard();
59
+ const emitError = createErrorThrottle(discovery);
79
60
  let ws;
80
61
  let closed = false;
81
62
  let reportedOnline = false;
@@ -88,8 +69,6 @@ export function wsSignaling(url, options = {}) {
88
69
  let pendingTotalRecvCount = 0;
89
70
  let sendChain = Promise.resolve();
90
71
  let recvChain = Promise.resolve();
91
- let lastDecryptErrorAt = -Infinity;
92
- let lastClockSkewErrorAt = -Infinity;
93
72
  let resolvedKey;
94
73
  const keysPromise = useEncryption
95
74
  ? deriveSignalingKeys(password, baseScope, insecureWsMessage)
@@ -103,20 +82,8 @@ export function wsSignaling(url, options = {}) {
103
82
  clearInterval(pingTimer);
104
83
  pingTimer = undefined;
105
84
  };
106
- const emitDecryptFailed = (message) => {
107
- const now = Date.now();
108
- if (now - lastDecryptErrorAt >= errorCooldownMs) {
109
- lastDecryptErrorAt = now;
110
- discovery.error?.('decrypt-failed', message);
111
- }
112
- };
113
- const emitClockSkew = () => {
114
- const now = Date.now();
115
- if (now - lastClockSkewErrorAt >= errorCooldownMs) {
116
- lastClockSkewErrorAt = now;
117
- discovery.error?.('clock-skew', 'WebSocket signaling message rejected due to system clock skew (>60s)');
118
- }
119
- };
85
+ const emitDecryptFailed = (message) => emitError('decrypt-failed', message);
86
+ const emitClockSkew = () => emitError('clock-skew', 'WebSocket signaling message rejected due to system clock skew (>60s)');
120
87
  const applyRoster = (peers) => {
121
88
  knownPeers.clear();
122
89
  for (const id of peers) {
@@ -154,6 +121,17 @@ export function wsSignaling(url, options = {}) {
154
121
  const reportOffline = (reason) => {
155
122
  if (closed)
156
123
  return;
124
+ if (optional) {
125
+ closed = true;
126
+ clearTimers();
127
+ clearTimeout(reconnectTimer);
128
+ reconnectTimer = undefined;
129
+ const current = ws;
130
+ ws = undefined;
131
+ safeCloseSocket(current);
132
+ discovery.status('closed', reason);
133
+ return;
134
+ }
157
135
  if (reportedOnline || !reportedOffline) {
158
136
  reportedOnline = false;
159
137
  reportedOffline = true;
@@ -191,24 +169,16 @@ export function wsSignaling(url, options = {}) {
191
169
  ws = socket;
192
170
  awaitingPong = false;
193
171
  let settled = false;
172
+ let timedOut = false;
194
173
  handshakeTimer = setTimeout(() => {
195
174
  if (closed || ws !== socket || settled)
196
175
  return;
197
- try {
198
- socket.close();
199
- }
200
- catch {
201
- // Ignore close errors.
202
- }
176
+ timedOut = true;
177
+ safeCloseSocket(socket);
203
178
  }, handshakeTimeoutMs);
204
179
  socket.onopen = () => {
205
180
  if (closed || ws !== socket) {
206
- try {
207
- socket.close();
208
- }
209
- catch {
210
- // Ignore close errors.
211
- }
181
+ safeCloseSocket(socket);
212
182
  return;
213
183
  }
214
184
  settled = true;
@@ -217,12 +187,7 @@ export function wsSignaling(url, options = {}) {
217
187
  attempt = 0;
218
188
  awaitingPong = false;
219
189
  if (!sendJson({ type: 'join', room: roomKey, id: discovery.self })) {
220
- try {
221
- socket.close();
222
- }
223
- catch {
224
- // Ignore close errors.
225
- }
190
+ safeCloseSocket(socket);
226
191
  return;
227
192
  }
228
193
  if (!reportedOnline) {
@@ -236,22 +201,12 @@ export function wsSignaling(url, options = {}) {
236
201
  if (useEncryption)
237
202
  replayGuard.prune();
238
203
  if (awaitingPong) {
239
- try {
240
- socket.close();
241
- }
242
- catch {
243
- // Ignore close errors.
244
- }
204
+ safeCloseSocket(socket);
245
205
  return;
246
206
  }
247
207
  awaitingPong = true;
248
208
  if (!sendJson({ type: 'ping' })) {
249
- try {
250
- socket.close();
251
- }
252
- catch {
253
- // Ignore close errors.
254
- }
209
+ safeCloseSocket(socket);
255
210
  }
256
211
  }, pingIntervalMs);
257
212
  };
@@ -363,23 +318,33 @@ export function wsSignaling(url, options = {}) {
363
318
  socket.onerror = () => {
364
319
  if (ws !== socket)
365
320
  return;
366
- try {
367
- socket.close();
368
- }
369
- catch {
370
- // Ignore close errors.
371
- }
321
+ safeCloseSocket(socket);
372
322
  };
373
- socket.onclose = () => {
323
+ socket.onclose = (event) => {
374
324
  if (ws !== socket)
375
325
  return;
376
326
  ws = undefined;
377
327
  clearTimers();
378
328
  if (closed)
379
329
  return;
380
- const reason = settled
381
- ? 'WebSocket signaling disconnected'
382
- : 'WebSocket signaling connection failed';
330
+ const code = typeof event?.code === 'number' &&
331
+ Number.isInteger(event.code) &&
332
+ event.code >= 1000 &&
333
+ event.code <= 4999 &&
334
+ event.code !== 1000 &&
335
+ event.code !== 1005 &&
336
+ event.code !== 1006
337
+ ? event.code
338
+ : undefined;
339
+ const reason = timedOut
340
+ ? 'WebSocket signaling handshake timed out'
341
+ : settled
342
+ ? code !== undefined
343
+ ? `WebSocket signaling disconnected (${code})`
344
+ : 'WebSocket signaling disconnected'
345
+ : code !== undefined
346
+ ? `WebSocket signaling connection failed (${code})`
347
+ : 'WebSocket signaling connection failed';
383
348
  reportOffline(reason);
384
349
  scheduleReconnect();
385
350
  };
@@ -409,12 +374,7 @@ export function wsSignaling(url, options = {}) {
409
374
  if (closed)
410
375
  return;
411
376
  reportOffline('WebSocket signaling key derivation failed');
412
- try {
413
- ws?.close();
414
- }
415
- catch {
416
- // Ignore close errors.
417
- }
377
+ safeCloseSocket(ws);
418
378
  });
419
379
  }
420
380
  // Defer initial connect so synchronous errors never fire before callers attach listeners.
@@ -475,17 +435,19 @@ export function wsSignaling(url, options = {}) {
475
435
  // Ignore send errors during close.
476
436
  }
477
437
  }
478
- try {
479
- current.close();
480
- }
481
- catch {
482
- // Ignore close errors.
483
- }
438
+ safeCloseSocket(current);
484
439
  }
485
440
  }
486
441
  };
487
442
  };
488
443
  }
444
+ /**
445
+ * Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
446
+ * When a room `password` is set, SDP and ICE payloads are end-to-end encrypted with AES-256-GCM by default.
447
+ */
448
+ export function wsSignaling(url, options = {}) {
449
+ return createWsSignaling(url, options, false);
450
+ }
489
451
  /**
490
452
  * Opportunistic WebSocket signaling adapter designed for composition inside `combineSignaling(...)` or `publicSignaling(...)`:
491
453
  * - Uses `reconnect: false` so an absent `/ws` endpoint, `403` origin check, ISP block, or exhausted quota
@@ -494,53 +456,5 @@ export function wsSignaling(url, options = {}) {
494
456
  * the room silently, while still forwarding `'decrypt-failed'` and `'clock-skew'` diagnostics.
495
457
  */
496
458
  export function optionalWsSignaling(url, options = {}) {
497
- const baseWs = wsSignaling(url, {
498
- handshakeTimeoutMs: options.handshakeTimeoutMs ?? defaultOptionalHandshakeTimeoutMs,
499
- ...(options.pingIntervalMs !== undefined ? { pingIntervalMs: options.pingIntervalMs } : {}),
500
- ...(options.encrypt !== undefined ? { encrypt: options.encrypt } : {}),
501
- ...(options.privateTopic !== undefined ? { privateTopic: options.privateTopic } : {}),
502
- ...(options.WebSocket !== undefined ? { WebSocket: options.WebSocket } : {}),
503
- reconnect: false
504
- });
505
- return (discovery) => {
506
- let abandoned = false;
507
- let session;
508
- session = baseWs({
509
- ...discovery,
510
- status(state, reason) {
511
- if (abandoned)
512
- return;
513
- if (state === 'online') {
514
- discovery.status('online', reason);
515
- }
516
- else {
517
- abandoned = true;
518
- session?.close();
519
- discovery.status('closed');
520
- }
521
- },
522
- error(code, message) {
523
- if (abandoned)
524
- return;
525
- if (code === 'decrypt-failed' || code === 'clock-skew') {
526
- discovery.error?.(code, message);
527
- }
528
- }
529
- });
530
- if (abandoned) {
531
- session.close();
532
- }
533
- return {
534
- ...(session.trickle !== undefined ? { trickle: session.trickle } : {}),
535
- send(to, signal) {
536
- if (abandoned)
537
- return false;
538
- return session.send(to, signal);
539
- },
540
- close() {
541
- abandoned = true;
542
- session.close();
543
- }
544
- };
545
- };
459
+ return createWsSignaling(url, options, true);
546
460
  }
package/docs/api.md ADDED
@@ -0,0 +1,217 @@
1
+ # API Reference
2
+
3
+ `@dimchansky/meshpost` is a zero-dependency ESM package with `"sideEffects": false`. Import from granular subpaths for optimal tree-shaking, or from the root barrel `@dimchansky/meshpost` for convenience.
4
+
5
+ ## Package entry points
6
+
7
+ | Subpath | Purpose |
8
+ | -------------------------------- | --------------------------------------------------------------------------------------------------- |
9
+ | `@dimchansky/meshpost` | Root barrel re-exporting all public symbols and types |
10
+ | `@dimchansky/meshpost/room` | `joinRoom`, `defaultIceServers`, core `Room` types |
11
+ | `@dimchansky/meshpost/channel` | `createChannel`, `createCodecChannel`, `binaryCodec`, `textCodec`, `jsonCodec` |
12
+ | `@dimchansky/meshpost/state` | `createPeerState` (replicated per-peer state with auto-hydration & drain coalescing) |
13
+ | `@dimchansky/meshpost/rpc` | `createRpc`, `RpcError` (typed request-response RPC) |
14
+ | `@dimchansky/meshpost/blob` | `createBlobChannel` (chunked reliable binary transfers >16 KiB) |
15
+ | `@dimchansky/meshpost/voice` | `createVoice`, `listAudioInputs`, `onAudioInputsChange` |
16
+ | `@dimchansky/meshpost/identity` | `createIdentity`, `createIdentityStore`, `exportIdentity`, `importIdentity`, `isSerializedIdentity` |
17
+ | `@dimchansky/meshpost/turn` | `fetchTurnCredentials` |
18
+ | `@dimchansky/meshpost/public` | `publicSignaling` (out-of-the-box WS + MQTT + Nostr + LocalTabs pool) |
19
+ | `@dimchansky/meshpost/ws` | `wsSignaling`, `optionalWsSignaling` |
20
+ | `@dimchansky/meshpost/mqtt` | `mqttSignaling`, `defaultMqttRelays` |
21
+ | `@dimchansky/meshpost/nostr` | `nostrSignaling`, `defaultNostrRelays` |
22
+ | `@dimchansky/meshpost/tabs` | `tabSignaling` |
23
+ | `@dimchansky/meshpost/manual` | `manualSignaling` |
24
+ | `@dimchansky/meshpost/combine` | `combineSignaling`, `withLocalTabs` |
25
+ | `@dimchansky/meshpost/signaling` | `observeSignaling`, `isUuid`, `isSignal`, `withLoopbackFallback`, adapter types |
26
+
27
+ ---
28
+
29
+ ## `@dimchansky/meshpost/room`
30
+
31
+ - `joinRoom(name: string, options: RoomOptions): Room` — Joins a room and starts peer discovery immediately.
32
+ - `defaultIceServers: readonly RTCIceServer[]` — Built-in Cloudflare and Google public STUN servers.
33
+
34
+ ### `RoomOptions`
35
+
36
+ | Option | Type | Default | Notes |
37
+ | ----------------------- | ------------------------------ | ------------------------------ | --------------------------------------------------------------------------------- |
38
+ | `signaling` | `Signaling` | **required** | Signaling adapter factory |
39
+ | `appId` | `string` | `'meshpost'` | Application namespace isolating rooms across apps |
40
+ | `password` | `string` | — | Optional non-empty shared password isolating & encrypting signaling |
41
+ | `rtcConfig` | `RTCConfiguration` | — | Custom WebRTC config; keeps `defaultIceServers` unless `iceServers` is set |
42
+ | `turnConfig` | `readonly RTCIceServer[]` | — | Extra TURN/STUN servers appended to `rtcConfig.iceServers` or `defaultIceServers` |
43
+ | `handshakeTimeoutMs` | `number` | `35000` | Max ms per connection attempt before retrying |
44
+ | `iceGatheringTimeoutMs` | `number` | `2500` | Soft cap ms for ICE gathering on non-trickle adapters |
45
+ | `maxPeers` | `number` | `32` | Maximum simultaneous peer connections (positive safe integer) |
46
+ | `identity` | `PeerIdentity` | — | Optional WebCrypto ECDSA P-256 identity proven over each DTLS link |
47
+ | `RTCPeerConnection` | `RTCPeerConnectionConstructor` | `globalThis.RTCPeerConnection` | Custom constructor for Node.js/Bun/Deno or tests |
48
+
49
+ ### `Room`
50
+
51
+ - Properties: `id: string`, `userId: string | null`, `peers: readonly string[]`, `signalingState: SignalingState`.
52
+ - Identity: `peerUserId(peerId: string): string | null`.
53
+ - Data: `send(bytes: Uint8Array, options?: SendOptions): ReadonlyMap<string, SendResult>`, `onPacket(fn, options?)`, `onDrain(fn, options?)`.
54
+ - `Delivery = 'unreliable' | 'reliable'` (default `'unreliable'`).
55
+ - `SendResult = 'accepted' | 'unavailable' | 'busy' | 'too-large'`.
56
+ - Lifecycle & diagnostics: `onPeerJoin(fn, options?)`, `onPeerLeave(fn, options?)`, `onSignalingChange(fn, options?)`, `onError(fn, options?)`, `getStats(peerId): Promise<PeerStats | null>`, `leave(): void`.
57
+ - `RoomErrorCode = 'room-full' | 'ice-failed' | 'media-error' | 'auth-failed' | SignalingErrorCode`.
58
+ - `PeerStats = { rttMs: number | null, route: 'direct' | 'relay' | 'unknown', bytesSent: number, bytesReceived: number, bufferedUnreliable: number, bufferedReliable: number }`.
59
+ - Media streams: `addStream(stream, toOrOptions?: string | AddStreamOptions)`, `removeStream(stream, toOrOptions?: string | RemoveStreamOptions)`, `replaceStreamTrack(stream, oldTrack, newTrack): Promise<void>`, `onPeerStream(fn, options?)`, `onPeerStreamEnd(fn, options?)`.
60
+ - `AddStreamOptions = { to?: string, tag?: string }` (`tag`: `1..32` chars `[a-zA-Z0-9._-]`).
61
+ - `PeerStreamMeta = { readonly tag?: string }`.
62
+ - `ListenOptions = { once?: boolean, signal?: AbortSignal }` — supported on every `on*` method across the library.
63
+
64
+ ---
65
+
66
+ ## `@dimchansky/meshpost/channel`
67
+
68
+ - `createChannel(room: Room, name: string, options?: ChannelOptions): Channel`
69
+ - Multiplexes a named channel (`1..64` UTF-8 bytes) over the room's existing data channels in `O(1)` dispatch time.
70
+ - `ChannelOptions = { delivery?: Delivery }` (default `'unreliable'`).
71
+ - `Channel`: `name`, `delivery`, `send(bytes, options?: { to?: string }): ReadonlyMap<string, SendResult>`, `onPacket(fn, options?)`.
72
+ - `createCodecChannel<T>(room: Room, name: string, codec: Codec<T>, options?: ChannelOptions): CodecChannel<T>`
73
+ - `Codec<T> = { encode(value: T): Uint8Array, decode(bytes: Uint8Array): T }`.
74
+ - `CodecChannel<T>`: `name`, `delivery`, `send(value, options?: { to?: string }): ReadonlyMap<string, SendResult>`, `onMessage(fn, options?)`. Malformed frames are dropped without consuming `{ once: true }`.
75
+ - Built-in codecs:
76
+ - `binaryCodec: Codec<Uint8Array>` (zero-copy identity)
77
+ - `textCodec: Codec<string>` (strict UTF-8)
78
+ - `jsonCodec<T>(validate?: ((value: unknown) => value is T) | ((value: unknown) => boolean)): Codec<T>`
79
+
80
+ ---
81
+
82
+ ## `@dimchansky/meshpost/state`
83
+
84
+ - `createPeerState<T = unknown>(room: Room, name: string, options?: PeerStateOptions<T>): PeerState<T>`
85
+ - Options: `delivery?: Delivery` (default `'reliable'`), `codec?: Codec<T>` (default `jsonCodec()`), `initial?: T`, `coalesce?: boolean` (default `true`).
86
+ - Methods: `getSelf()`, `get(peerId)`, `getAll()`, `set(value)`, `clear()`, `onChange(fn: (peerId, next, prev, reason: PeerStateChangeReason) => void, options?)`, `close()`.
87
+ - `PeerStateChangeReason = 'set' | 'clear' | 'leave'`.
88
+ - Closes automatically on `room.leave()`.
89
+
90
+ ---
91
+
92
+ ## `@dimchansky/meshpost/rpc`
93
+
94
+ - `createRpc<Req = unknown, Res = unknown>(room: Room, name: string, options?: RpcOptions<Req, Res>): RpcEndpoint<Req, Res>`
95
+ - Options: `timeoutMs` (default `10000`), `requestCodec` (default `jsonCodec()`), `responseCodec` (default `jsonCodec()`), `maxPendingCalls` (default `256`, `1..4096`), `maxConcurrentPerPeer` (default `16`, `1..256`).
96
+ - Methods: `call(peerId, request, options?: { timeoutMs?: number, signal?: AbortSignal }): Promise<Res>`, `handle(fn, options?: ListenOptions): () => void` (at most one active handler per endpoint), `close()`.
97
+ - `class RpcError extends Error` — Properties: `code: RpcErrorCode`, `peerId: string`.
98
+ - `RpcErrorCode = 'timeout' | 'aborted' | 'disconnected' | 'unavailable' | 'busy' | 'too-large' | 'unhandled' | 'remote-error' | 'closed'`.
99
+ - Closes automatically on `room.leave()`.
100
+
101
+ ---
102
+
103
+ ## `@dimchansky/meshpost/blob`
104
+
105
+ - `createBlobChannel(room: Room, name: string, options?: BlobChannelOptions): BlobChannel`
106
+ - Options: `maxReceiveBytes` (default `4194304` = `4 MiB`), `chunkSize` (default `15360`), `receiveTimeoutMs` (default `30000`), `maxConcurrentPerPeer` (default `4`).
107
+ - Methods:
108
+ - `send(bytes: Uint8Array, options?: { to?: string, onProgress?: (peerId, sentBytes, totalBytes) => void, signal?: AbortSignal }): Promise<ReadonlyMap<string, BlobSendStatus>>` (`'sent' | 'aborted' | 'unavailable' | 'too-large'`).
109
+ - `onBlob(fn: (from, bytes) => void, options?)`
110
+ - `onProgress(fn: (from, progress: BlobProgress) => void, options?)`
111
+ - `close()` (also runs automatically on `room.leave()`).
112
+
113
+ ---
114
+
115
+ ## `@dimchansky/meshpost/voice`
116
+
117
+ - `createVoice(room: Room, options?: VoiceOptions): Voice`
118
+ - Options: `volume` (`1`), `deafened` (`false`), `deviceId` (`null`), `fallbackToDefaultOnNotFound` (`false`), `audioConstraints` (`{ echoCancellation: true, noiseSuppression: true, autoGainControl: true }`), `autoUnlock` (`true`), `speakingDetection` (`true`), `speakingThreshold` (`0.03`), `speakingIntervalMs` (`180`), `to`, `streamTag` (`'voice'`), `strictStreamTag` (`false`).
119
+ - Snapshot fields (also exposed directly as readonly properties on `Voice`): `micStatus: MicStatus`, `micError: MicError | null`, `deviceId: string | null`, `autoplayBlocked: boolean`, `deafened: boolean`, `volume: number`, `selfSpeaking: boolean`, `remotePeers: readonly string[]`, `speakingPeers: readonly string[]`, `mutedPeers: readonly string[]`, `peerVolumes: Readonly<Record<string, number>>`.
120
+ - Methods: `getSnapshot()`, `toggleMic()`, `startMic()`, `setMuted(muted)`, `stopMic()`, `switchDevice(deviceId?)`, `setVolume(volume)`, `setPeerVolume(peerId, volume)`, `getPeerVolume(peerId)`, `setDeafened(deafened)`, `setPeerMuted(peerId, muted)`, `isPeerMuted(peerId)`, `unlockAudio()`, `onChange(fn, options?)`, `close()` (also runs automatically on `room.leave()`).
121
+ - `MicStatus = 'off' | 'requesting' | 'live' | 'muted' | 'error'`.
122
+ - `MicErrorCode = 'permission-denied' | 'not-found' | 'in-use' | 'insecure-context' | 'room-closed' | 'unknown'`.
123
+ - `listAudioInputs(): Promise<readonly AudioInputDevice[]>` — Safe cross-runtime audio input enumeration (`{ deviceId, label, groupId }`).
124
+ - `onAudioInputsChange(fn: (devices: readonly AudioInputDevice[]) => void, options?: AudioInputsChangeOptions): () => void`
125
+ - `AudioInputsChangeOptions` extends `ListenOptions` with `immediate?: boolean` (default `false`).
126
+
127
+ ---
128
+
129
+ ## `@dimchansky/meshpost/identity`
130
+
131
+ - `createIdentity(options?: { extractable?: boolean }): Promise<PeerIdentity>` (`extractable` defaults to `true`).
132
+ - `PeerIdentity = { readonly userId: string, readonly publicKey: string }`.
133
+ - `exportIdentity(identity: PeerIdentity): Promise<SerializedIdentity>`
134
+ - `importIdentity(data: unknown, options?: { extractable?: boolean }): Promise<PeerIdentity>` (cryptographically verifies `(x, y)` against `d`).
135
+ - `isSerializedIdentity(value: unknown): value is SerializedIdentity`
136
+ - `createIdentityStore(options: { key: string, storage?: IdentityStorage | null }): IdentityStore`
137
+ - `IdentityStore`: `readonly current: PeerIdentity | null`, `load(): Promise<PeerIdentity>`, `rotate(): Promise<PeerIdentity>`, `clear(): void`.
138
+
139
+ ---
140
+
141
+ ## `@dimchansky/meshpost/turn`
142
+
143
+ - `fetchTurnCredentials(url: string, options?: FetchTurnOptions): Promise<RTCIceServer[]>`
144
+ - `FetchTurnOptions = { accessKey?: string, signal?: AbortSignal, timeoutMs?: number }` (`timeoutMs` defaults to `5000`; pass `0` to disable).
145
+
146
+ ---
147
+
148
+ ## `@dimchansky/meshpost/public`
149
+
150
+ - `publicSignaling(options?: PublicSignalingOptions): Signaling`
151
+ - Options: `wsUrls?: string | readonly string[]` (0..8 unique `ws:`/`wss:` URLs), `mqtt?: boolean | readonly string[]` (`true`), `nostr?: boolean | readonly string[]` (`true`), `localTabs?: boolean` (`true`), `wsEncrypt?: boolean` (`true`), `privateTopic?: boolean` (`false`), `appId?: string`, `wsHandshakeTimeoutMs?: number` (`4000`), `handshakeTimeoutMs?: number` (`10000`), `WebSocket?: WebSocketConstructor`, `onTransportChange?: (event: PublicTransportEvent) => void`.
152
+ - `PublicTransportKind = 'ws' | 'mqtt' | 'nostr' | 'tabs'`.
153
+ - `PublicTransportEvent = { readonly transport: PublicTransportKind, readonly url?: string, readonly state: SignalingState, readonly reason?: string }`.
154
+
155
+ ---
156
+
157
+ ## `@dimchansky/meshpost/ws`
158
+
159
+ - `wsSignaling(url: string, options?: WsSignalingOptions): Signaling`
160
+ - Options: `reconnect` (`true`), `handshakeTimeoutMs` (`10000`), `pingIntervalMs` (`25000`), `encrypt` (`true`), `privateTopic` (`false`), `WebSocket`.
161
+ - `optionalWsSignaling(url: string, options?: OptionalWsSignalingOptions): Signaling`
162
+ - Opportunistic single-shot WS adapter (`reconnect: false`, `handshakeTimeoutMs: 4000` default, suppresses `'signaling-error'`).
163
+
164
+ ---
165
+
166
+ ## `@dimchansky/meshpost/mqtt`
167
+
168
+ - `mqttSignaling(options?: MqttSignalingOptions): Signaling`
169
+ - Options: `urls` (`defaultMqttRelays`), `appId`, `password`, `privateTopic` (`false`), `handshakeTimeoutMs` (`10000`), `WebSocket`.
170
+ - `defaultMqttRelays: readonly string[]`
171
+
172
+ ---
173
+
174
+ ## `@dimchansky/meshpost/nostr`
175
+
176
+ - `nostrSignaling(options?: NostrSignalingOptions): Signaling`
177
+ - Options: `urls` (`defaultNostrRelays`), `appId`, `password`, `privateTopic` (`false`), `handshakeTimeoutMs` (`10000`), `WebSocket`.
178
+ - `defaultNostrRelays: readonly string[]`
179
+
180
+ ---
181
+
182
+ ## `@dimchansky/meshpost/tabs`
183
+
184
+ - `tabSignaling(): Signaling` — Same-origin `BroadcastChannel` signaling (zero network).
185
+
186
+ ---
187
+
188
+ ## `@dimchansky/meshpost/manual`
189
+
190
+ - `manualSignaling(outgoing: (to: string, text: string) => void): ManualSignaling`
191
+ - `ManualSignaling = { readonly signaling: Signaling, contact(): string, accept(text: string): void, forget(peerId: string): void }`.
192
+
193
+ ---
194
+
195
+ ## `@dimchansky/meshpost/combine`
196
+
197
+ - `combineSignaling(...adapters: readonly Signaling[]): Signaling`
198
+ - `withLocalTabs(primary: Signaling): Signaling`
199
+
200
+ ---
201
+
202
+ ## `@dimchansky/meshpost/signaling`
203
+
204
+ - `observeSignaling(adapter: Signaling, onChange: (state: SignalingState, reason?: string) => void): Signaling`
205
+ - `isUuid(value: unknown): value is string`
206
+ - `isSignal(value: unknown): value is Signal`
207
+ - `withLoopbackFallback<T extends Signal>(signal: T): T`
208
+ - Types: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `WebSocketConstructor`.
209
+
210
+ ---
211
+
212
+ ## See also
213
+
214
+ - [Guide](./guide.md) — step-by-step usage examples
215
+ - [Voice & Media](./voice-and-media.md) — voice and custom `MediaStream` guide
216
+ - [Signaling & Production](./signaling-and-production.md) — signaling recipes, TURN, edge workers, and headless peers
217
+ - [Behavior & Security Spec](./behavior.md) — protocol details, invariants, limits, and security model