@dimchansky/meshpost 0.4.2 → 0.5.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
@@ -189,27 +189,19 @@ All `on*` methods (on `Room`, `Channel`, `CodecChannel`, `PeerState`, `BlobChann
189
189
 
190
190
  `room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
191
191
 
192
- ### Verifiable peer identity (`createIdentity` / `exportIdentity` / `importIdentity`)
192
+ ### Verifiable peer identity (`createIdentityStore` / `createIdentity`)
193
193
 
194
194
  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):
195
195
 
196
- - `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`).
197
- - `exportIdentity(identity): Promise<SerializedIdentity>` — exports `{ v: 1, crv: 'P-256', x, y, d }` for JSON storage (e.g. `localStorage`).
198
- - `importIdentity(data, options?: CreateIdentityOptions): Promise<PeerIdentity>` — validates shape, verifies `(x, y)` cryptographically against `d` via a challenge signature, and restores `PeerIdentity`.
199
- - `isSerializedIdentity(value): value is SerializedIdentity` — runtime type guard for untrusted storage payloads.
196
+ - `createIdentityStore({ key, storage? }): IdentityStore` — race-safe persistent identity manager (`load()`, `rotate()`, `clear()`) backed by `localStorage` by default (safely degrading to ephemeral in-memory caching on `SecurityError`/non-DOM runtimes, coalescing concurrent `load()` calls, self-healing corrupt storage, and preventing `load()` vs `rotate()` races via a monotonic epoch). _(Security note: `localStorage` stores an extractable JWK readable by same-origin scripts; for stronger XSS isolation, use `createIdentity({ extractable: false })` with IndexedDB.)_
197
+ - Low-level primitives: `createIdentity(options?: CreateIdentityOptions)`, `exportIdentity(identity)`, `importIdentity(data, options?)`, and `isSerializedIdentity(value)`.
198
+ - Exported identity types: `PeerIdentity`, `SerializedIdentity`, `CreateIdentityOptions`, `IdentityStorage`, `IdentityStoreOptions`, `IdentityStore`.
200
199
 
201
200
  ```ts
202
- import {
203
- createIdentity,
204
- exportIdentity,
205
- importIdentity,
206
- isSerializedIdentity,
207
- joinRoom
208
- } from '@dimchansky/meshpost'
209
-
210
- const raw = JSON.parse(localStorage.getItem('my-id') ?? 'null')
211
- const identity = isSerializedIdentity(raw) ? await importIdentity(raw) : await createIdentity()
212
- localStorage.setItem('my-id', JSON.stringify(await exportIdentity(identity)))
201
+ import { createIdentityStore, joinRoom } from '@dimchansky/meshpost'
202
+
203
+ const identityStore = createIdentityStore({ key: 'my-app:identity' })
204
+ const identity = await identityStore.load()
213
205
 
214
206
  const room = joinRoom('lobby', { signaling, identity })
215
207
  console.log('My verified userId:', room.userId)
@@ -229,18 +221,20 @@ Headless P2P voice chat controller built on top of `room.addStream()` / `room.on
229
221
  - 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).
230
222
  - 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).
231
223
 
232
- | `VoiceOptions` field | Type | Default | Purpose |
233
- | -------------------- | ------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
234
- | `volume` | `number` | `1` | Initial playback volume (`0` to `1`) for incoming peer audio. |
235
- | `deafened` | `boolean` | `false` | Start with incoming peer audio muted locally (`audio.muted = true`). |
236
- | `audioConstraints` | `MediaTrackConstraints \| true` | `{ echoCancellation: true, noiseSuppression: true, autoGainControl: true }` | Audio track constraints passed to `getUserMedia`. |
237
- | `autoUnlock` | `boolean` | `true` | Attach global `{ capture: true }` gesture & `visibilitychange` listeners to unlock blocked playback. |
238
- | `speakingDetection` | `boolean` | `true` | Enable shared lazy `AudioContext` + `AnalyserNode` speaking detection. |
239
- | `speakingThreshold` | `number` | `0.03` | RMS amplitude threshold (`0` to `1`) for `selfSpeaking` and `speakingPeers`. |
240
- | `speakingIntervalMs` | `number` | `180` | Polling interval in milliseconds (`50` to `60_000`) for speaking detection. |
241
- | `to` | `string` | `undefined` | Scope outgoing microphone audio to a single target peer ID (incoming audio from all peers plays). |
242
- | `streamTag` | `string` | `'voice'` | Stream tag attached to outgoing mic streams and matched on incoming streams (`[a-zA-Z0-9._-]{1,32}`). |
243
- | `strictStreamTag` | `boolean` | `false` | When `true`, also ignore untagged (`meta.tag === undefined`) incoming audio streams. |
224
+ | `VoiceOptions` field | Type | Default | Purpose |
225
+ | ----------------------------- | ------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
226
+ | `volume` | `number` | `1` | Initial playback volume (`0` to `1`) for incoming peer audio. |
227
+ | `deafened` | `boolean` | `false` | Start with incoming peer audio muted locally (`audio.muted = true`). |
228
+ | `deviceId` | `string \| null` | `null` | Preferred microphone `deviceId` (`null` / `''` for system default). Preserves `defaultAudioConstraints`. |
229
+ | `fallbackToDefaultOnNotFound` | `boolean` | `false` | On initial mic start (`toggleMic` / `startMic`), auto-retry with system default if `deviceId` fails with `'not-found'`. |
230
+ | `audioConstraints` | `MediaTrackConstraints \| true` | `{ echoCancellation: true, noiseSuppression: true, autoGainControl: true }` | Audio track constraints passed to `getUserMedia`. |
231
+ | `autoUnlock` | `boolean` | `true` | Attach global `{ capture: true }` gesture & `visibilitychange` listeners to unlock blocked playback. |
232
+ | `speakingDetection` | `boolean` | `true` | Enable shared lazy `AudioContext` + `AnalyserNode` speaking detection. |
233
+ | `speakingThreshold` | `number` | `0.03` | RMS amplitude threshold (`0` to `1`) for `selfSpeaking` and `speakingPeers`. |
234
+ | `speakingIntervalMs` | `number` | `180` | Polling interval in milliseconds (`50` to `60_000`) for speaking detection. |
235
+ | `to` | `string` | `undefined` | Scope outgoing microphone audio to a single target peer ID (incoming audio from all peers plays). |
236
+ | `streamTag` | `string` | `'voice'` | Stream tag attached to outgoing mic streams and matched on incoming streams (`[a-zA-Z0-9._-]{1,32}`). |
237
+ | `strictStreamTag` | `boolean` | `false` | When `true`, also ignore untagged (`meta.tag === undefined`) incoming audio streams. |
244
238
 
245
239
  | `Voice` member | Description |
246
240
  | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -271,7 +265,7 @@ Headless P2P voice chat controller built on top of `room.addStream()` / `room.on
271
265
  | `voice.onChange(fn, options?: ListenOptions)` | Subscribes to `VoiceSnapshot` changes (`(snapshot: VoiceSnapshot) => ...`). Returns unsubscribe. |
272
266
  | `voice.close()` | Releases mic tracks, removes hidden `<audio>` elements, closes `AudioContext`, restores `audioSession`, and detaches all listeners (runs automatically on `room.leave()`). |
273
267
 
274
- Exported voice types: `Voice`, `VoiceOptions`, `VoiceSnapshot`, `MicStatus`, `MicError`, `MicErrorCode`.
268
+ Exported voice helpers & types: `listAudioInputs()`, `onAudioInputsChange(fn, options?: ListenOptions)`, `AudioInputDevice`, `Voice`, `VoiceOptions`, `VoiceSnapshot`, `MicStatus`, `MicError`, `MicErrorCode`.
275
269
 
276
270
  ```ts
277
271
  import { createVoice } from '@dimchansky/meshpost'
@@ -446,17 +440,17 @@ const results = await files.send(fileBytes, {
446
440
 
447
441
  ### Signaling exports
448
442
 
449
- - `publicSignaling({ wsUrls?, mqtt?, nostr?, localTabs?, wsEncrypt?, privateTopic?, appId?, wsHandshakeTimeoutMs?, handshakeTimeoutMs?, WebSocket? })` — Ready-made URL-agnostic composite adapter combining `mqttSignaling()` + port-443 `nostrSignaling()`, wrapped in `withLocalTabs(...)` (defaults: `mqtt: true`, `nostr: true`, `localTabs: true`, `wsEncrypt: true`, `privateTopic: false`, `wsHandshakeTimeoutMs: 4_000`, `handshakeTimeoutMs: 10_000`), plus zero or more app-supplied opportunistic WebSocket relays (`wsUrls?: string | readonly string[]`, max `8` unique URLs). Any unreachable or `403`-rejected `wsUrls` entry closes silently without reconnect storms while public relays carry the room.
443
+ - `publicSignaling({ wsUrls?, mqtt?, nostr?, localTabs?, wsEncrypt?, privateTopic?, appId?, wsHandshakeTimeoutMs?, handshakeTimeoutMs?, WebSocket?, onTransportChange? })` — Ready-made URL-agnostic composite adapter combining `mqttSignaling()` + port-443 `nostrSignaling()`, wrapped in `withLocalTabs(...)` (defaults: `mqtt: true`, `nostr: true`, `localTabs: true`, `wsEncrypt: true`, `privateTopic: false`, `wsHandshakeTimeoutMs: 4_000`, `handshakeTimeoutMs: 10_000`), plus zero or more app-supplied opportunistic WebSocket relays (`wsUrls?: string | readonly string[]`, max `8` unique URLs). Any unreachable or `403`-rejected `wsUrls` entry closes silently without reconnect storms while public relays carry the room. Pass `onTransportChange?: (event: PublicTransportEvent) => void` to observe per-transport (`'ws' | 'mqtt' | 'nostr' | 'tabs'`) lifecycle transitions (`state`, optional `url` for `'ws'`, and optional `reason`); note that per the WHATWG WebSocket spec, browsers hide HTTP `403`/TLS failure details behind opaque close code `1006`, while client-side handshake timeouts and non-`1006` close codes appear in `reason`.
450
444
  - `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.
451
445
  - `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.
452
446
  - `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.
453
- - `optionalWsSignaling(url, { handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Opportunistic `wsSignaling` wrapper (`reconnect: false`, `4,000` ms default handshake timeout) that transitions cleanly to `'closed'` and suppresses `'signaling-error'` if unreachable while preserving `'decrypt-failed'` and `'clock-skew'` diagnostics.
447
+ - `optionalWsSignaling(url, { handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Opportunistic `wsSignaling` wrapper (`reconnect: false`, `4,000` ms default handshake timeout) that transitions cleanly to `'closed'` (forwarding the close/timeout `reason`) and suppresses `'signaling-error'` if unreachable while preserving `'decrypt-failed'` and `'clock-skew'` diagnostics.
454
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.
455
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())`).
456
450
  - `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
457
451
  - `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
458
452
  - `defaultIceServers` — Built-in Cloudflare and Google public servers (STUN) that help browsers find their public network address.
459
- - Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `PublicSignalingOptions`, `MqttSignalingOptions`, `NostrSignalingOptions`, `WsSignalingOptions`, `OptionalWsSignalingOptions`, `RTCPeerConnectionConstructor`, `WebSocketConstructor`, `defaultMqttRelays`, `defaultNostrRelays`, `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`, `PublicSignalingOptions`, `PublicTransportKind`, `PublicTransportEvent`, `MqttSignalingOptions`, `NostrSignalingOptions`, `WsSignalingOptions`, `OptionalWsSignalingOptions`, `RTCPeerConnectionConstructor`, `WebSocketConstructor`, `defaultMqttRelays`, `defaultNostrRelays`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
460
454
 
461
455
  ## Connecting through strict firewalls (TURN)
462
456
 
@@ -550,11 +544,11 @@ Open **dist/playground.html** directly in two browsers (`file://`). Enter the sa
550
544
 
551
545
  All `@dimchansky/meshpost` usage in the playground is intentionally concentrated in **one file** so you can learn the full API in one place:
552
546
 
553
- - [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()`.
554
- - [examples/playground/relay.js](examples/playground/relay.js) — `autoSignaling()` composing `tabSignaling()` and `wsSignaling()` with a silent fallback to `tabSignaling()` on plain static localhost servers.
547
+ - [examples/playground/mesh.js](examples/playground/mesh.js) — **Start here.** Single facade using `@dimchansky/meshpost/*` subpath imports to wire `joinRoom()`, `createIdentityStore()`, signaling adapters (`publicSignaling({ onTransportChange })`, `withLocalTabs`, `wsSignaling`, `manualSignaling`), `fetchTurnCredentials()`, `createPeerState()` (`presence`, `cursor`), `createChannel()` (`ripple`, `draw`), `createCodecChannel()` + `jsonCodec()` (`chat`, `direct`), `createRpc()` (`ping`), `createBlobChannel()` (`draw-snap`, `file`), `createVoice()` + `listAudioInputs()` / `onAudioInputsChange()`, `ListenOptions` (`{ signal }`), `room.onError()`, and `room.getStats()`.
548
+ - [examples/playground/relay.js](examples/playground/relay.js) — `autoSignaling()` composing `tabSignaling()` and `optionalWsSignaling()` with per-transport status reporting and a silent fallback to `tabSignaling()` on plain static localhost servers.
555
549
  - [examples/playground/codec.js](examples/playground/codec.js) — Pure binary codecs (`cursorCodec`, canvas strokes, file metadata envelopes) and payload type guards.
556
550
  - [examples/playground/canvas.js](examples/playground/canvas.js) — Collaborative 2D drawing canvas and remote cursor/ripple overlays.
557
- - [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()`.
551
+ - [examples/playground/voice.js](examples/playground/voice.js) — Thin DOM binding connecting microphone buttons, persistent pre-join/live mic selector (`listAudioInputs`, `onAudioInputsChange`, `switchDevice`, `fallbackToDefaultOnNotFound`), per-peer volume/mute controls, autoplay banner, and `KeyM` to `createVoice()`.
558
552
  - [examples/playground/session.js](examples/playground/session.js) — Compact `#c=` invite URLs and `sessionStorage` auto-rejoin.
559
553
  - [examples/playground/app.js](examples/playground/app.js) — Thin UI controller connecting DOM controls to `mesh.js` and the helper modules.
560
554
  - [examples/playground/index.html](examples/playground/index.html) — Minimal HTML markup for the playground.
package/dist/combine.js CHANGED
@@ -323,20 +323,8 @@ function canUseLocalTabs() {
323
323
  }
324
324
  return true;
325
325
  }
326
- /**
327
- * Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
328
- * same-browser `BroadcastChannel` discovery (`tabSignaling()`).
329
- *
330
- * - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
331
- * (avoiding a permanently `'online'` indicator when network connectivity is lost).
332
- * - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
333
- * - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
334
- * origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
335
- */
336
- export function withLocalTabs(primary) {
337
- if (typeof primary !== 'function') {
338
- throw new TypeError('Expected a signaling adapter function');
339
- }
326
+ /** @internal */
327
+ export function withLocalTabsInternal(primary, wrapTabs) {
340
328
  return (discovery) => {
341
329
  if (!canUseLocalTabs())
342
330
  return primary(discovery);
@@ -349,7 +337,24 @@ export function withLocalTabs(primary) {
349
337
  catch {
350
338
  return primary(discovery);
351
339
  }
352
- const tabs = tabSignaling();
340
+ const baseTabs = tabSignaling();
341
+ const tabs = wrapTabs ? wrapTabs(baseTabs) : baseTabs;
353
342
  return createCompositeSession(discovery, [tabs, primary], 1);
354
343
  };
355
344
  }
345
+ /**
346
+ * Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
347
+ * same-browser `BroadcastChannel` discovery (`tabSignaling()`).
348
+ *
349
+ * - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
350
+ * (avoiding a permanently `'online'` indicator when network connectivity is lost).
351
+ * - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
352
+ * - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
353
+ * origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
354
+ */
355
+ export function withLocalTabs(primary) {
356
+ if (typeof primary !== 'function') {
357
+ throw new TypeError('Expected a signaling adapter function');
358
+ }
359
+ return withLocalTabsInternal(primary);
360
+ }
@@ -27,6 +27,39 @@ export interface SerializedIdentity {
27
27
  /** 32-byte canonical base64url private scalar (43 chars). */
28
28
  readonly d: string;
29
29
  }
30
+ /** Minimal synchronous `Storage`-compatible interface accepted by `createIdentityStore()`. */
31
+ export interface IdentityStorage {
32
+ getItem(key: string): string | null;
33
+ setItem(key: string, value: string): void;
34
+ removeItem(key: string): void;
35
+ }
36
+ /** Options passed to `createIdentityStore()`. */
37
+ export interface IdentityStoreOptions {
38
+ /** Required storage key isolating identities across apps on the same origin (`1..256` chars). */
39
+ key: string;
40
+ /**
41
+ * Storage backend (`localStorage`, `sessionStorage`, or custom `IdentityStorage`).
42
+ * Defaults to safely probing `globalThis.localStorage` inside `try/catch` (degrading to
43
+ * ephemeral in-memory caching when unavailable or throwing `SecurityError`).
44
+ * Pass `null` for strictly ephemeral in-memory caching without persistence.
45
+ */
46
+ storage?: IdentityStorage | null;
47
+ }
48
+ /**
49
+ * Race-safe persistent identity manager backed by `createIdentity()` / `importIdentity()` / `exportIdentity()`.
50
+ *
51
+ * Security note: persisting serialized keys in `localStorage` stores an extractable JWK readable by
52
+ * same-origin scripts (XSS). For stronger key isolation, use `createIdentity({ extractable: false })`
53
+ * with IndexedDB directly.
54
+ */
55
+ export interface IdentityStore {
56
+ /** Load the stored identity or generate and persist a fresh one (coalesces concurrent calls; self-heals corrupt storage). */
57
+ load(): Promise<PeerIdentity>;
58
+ /** Generate a fresh identity, persist it, and supersede any in-flight `load()` or earlier `rotate()`. */
59
+ rotate(): Promise<PeerIdentity>;
60
+ /** Clear the in-memory cache, remove the stored key (best-effort), and invalidate in-flight operations. */
61
+ clear(): void;
62
+ }
30
63
  /**
31
64
  * Generate a fresh WebCrypto `ECDSA P-256` peer identity with a deterministic 128-bit `userId`.
32
65
  */
@@ -43,3 +76,13 @@ export declare function isSerializedIdentity(value: unknown): value is Serialize
43
76
  * Import and cryptographically self-verify a `SerializedIdentity` (`(x, y)` verified against `d`).
44
77
  */
45
78
  export declare function importIdentity(data: unknown, options?: CreateIdentityOptions): Promise<PeerIdentity>;
79
+ /**
80
+ * Create a race-safe persistent `PeerIdentity` store backed by `localStorage` (by default) or a custom `IdentityStorage`.
81
+ *
82
+ * - Coalesces concurrent `load()` calls and uses a monotonic `epoch` guard so `rotate()` or `clear()`
83
+ * cannot be overwritten by an earlier in-flight operation.
84
+ * - Caps stored JSON reads at `1,024` chars, cryptographically verifies imported keys, and silently
85
+ * regenerates corrupt entries (preserving stored entries untouched if `crypto.subtle` is unavailable).
86
+ * - Degrades cleanly to in-memory caching when `localStorage` throws `SecurityError` or is unavailable.
87
+ */
88
+ export declare function createIdentityStore(options: IdentityStoreOptions): IdentityStore;
package/dist/identity.js CHANGED
@@ -262,3 +262,195 @@ export async function sha256Base64Url(input) {
262
262
  return null;
263
263
  }
264
264
  }
265
+ const maxStoredIdentityChars = 1024;
266
+ function isValidIdentityStorage(value) {
267
+ return (Boolean(value) &&
268
+ typeof value === 'object' &&
269
+ typeof value.getItem === 'function' &&
270
+ typeof value.setItem === 'function' &&
271
+ typeof value.removeItem === 'function');
272
+ }
273
+ /**
274
+ * Create a race-safe persistent `PeerIdentity` store backed by `localStorage` (by default) or a custom `IdentityStorage`.
275
+ *
276
+ * - Coalesces concurrent `load()` calls and uses a monotonic `epoch` guard so `rotate()` or `clear()`
277
+ * cannot be overwritten by an earlier in-flight operation.
278
+ * - Caps stored JSON reads at `1,024` chars, cryptographically verifies imported keys, and silently
279
+ * regenerates corrupt entries (preserving stored entries untouched if `crypto.subtle` is unavailable).
280
+ * - Degrades cleanly to in-memory caching when `localStorage` throws `SecurityError` or is unavailable.
281
+ */
282
+ export function createIdentityStore(options) {
283
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
284
+ throw new TypeError('Invalid identity store options');
285
+ }
286
+ const { key, storage: customStorage } = options;
287
+ if (typeof key !== 'string' || key.length === 0 || key.length > 256) {
288
+ throw new TypeError('Expected identity store key to be a non-empty string (1..256 chars)');
289
+ }
290
+ if (customStorage !== undefined &&
291
+ customStorage !== null &&
292
+ !isValidIdentityStorage(customStorage)) {
293
+ throw new TypeError('Invalid identity storage backend');
294
+ }
295
+ let cached = null;
296
+ let inFlightLoad = null;
297
+ let inFlightRotate = null;
298
+ let epoch = 0;
299
+ const resolveStorage = () => {
300
+ if (customStorage === null)
301
+ return null;
302
+ if (customStorage !== undefined)
303
+ return customStorage;
304
+ try {
305
+ const candidate = globalThis.localStorage;
306
+ return isValidIdentityStorage(candidate) ? candidate : null;
307
+ }
308
+ catch {
309
+ return null;
310
+ }
311
+ };
312
+ const safeRead = (storage) => {
313
+ if (!storage)
314
+ return null;
315
+ try {
316
+ const raw = storage.getItem(key);
317
+ return typeof raw === 'string' ? raw : null;
318
+ }
319
+ catch {
320
+ return null;
321
+ }
322
+ };
323
+ const safeWrite = (storage, serialized) => {
324
+ if (!storage)
325
+ return;
326
+ try {
327
+ storage.setItem(key, JSON.stringify(serialized));
328
+ }
329
+ catch {
330
+ // Ignore quota or restricted-storage errors; keep identity cached in memory.
331
+ }
332
+ };
333
+ const safeRemove = (storage) => {
334
+ if (!storage)
335
+ return;
336
+ try {
337
+ storage.removeItem(key);
338
+ }
339
+ catch {
340
+ // Ignore restricted-storage errors.
341
+ }
342
+ };
343
+ return {
344
+ load() {
345
+ if (cached)
346
+ return Promise.resolve(cached);
347
+ if (inFlightRotate)
348
+ return inFlightRotate;
349
+ if (inFlightLoad)
350
+ return inFlightLoad;
351
+ const myEpoch = epoch;
352
+ const promise = (async () => {
353
+ // Verify WebCrypto availability before touching storage so non-secure contexts
354
+ // never misclassify a missing SubtleCrypto error as corrupt storage and delete the key.
355
+ requireSubtleCrypto();
356
+ const storage = resolveStorage();
357
+ const raw = safeRead(storage);
358
+ if (raw !== null) {
359
+ let loaded = null;
360
+ if (raw.length > 0 && raw.length <= maxStoredIdentityChars) {
361
+ try {
362
+ const parsed = JSON.parse(raw);
363
+ if (isSerializedIdentity(parsed)) {
364
+ loaded = await importIdentity(parsed);
365
+ }
366
+ }
367
+ catch {
368
+ loaded = null;
369
+ }
370
+ }
371
+ if (myEpoch !== epoch) {
372
+ if (cached)
373
+ return cached;
374
+ if (inFlightRotate)
375
+ return inFlightRotate;
376
+ return loaded ?? createIdentity();
377
+ }
378
+ if (loaded) {
379
+ cached = loaded;
380
+ return loaded;
381
+ }
382
+ safeRemove(storage);
383
+ }
384
+ const fresh = await createIdentity();
385
+ if (myEpoch !== epoch) {
386
+ if (cached)
387
+ return cached;
388
+ if (inFlightRotate)
389
+ return inFlightRotate;
390
+ return fresh;
391
+ }
392
+ if (storage) {
393
+ const exported = await exportIdentity(fresh);
394
+ if (myEpoch !== epoch) {
395
+ if (cached)
396
+ return cached;
397
+ if (inFlightRotate)
398
+ return inFlightRotate;
399
+ return fresh;
400
+ }
401
+ safeWrite(storage, exported);
402
+ }
403
+ cached = fresh;
404
+ return fresh;
405
+ })().finally(() => {
406
+ if (inFlightLoad === promise)
407
+ inFlightLoad = null;
408
+ });
409
+ inFlightLoad = promise;
410
+ return promise;
411
+ },
412
+ rotate() {
413
+ const myEpoch = ++epoch;
414
+ cached = null;
415
+ inFlightLoad = null;
416
+ let promise = null;
417
+ promise = (async () => {
418
+ requireSubtleCrypto();
419
+ const storage = resolveStorage();
420
+ const fresh = await createIdentity();
421
+ if (myEpoch !== epoch) {
422
+ if (cached)
423
+ return cached;
424
+ if (inFlightRotate && inFlightRotate !== promise)
425
+ return inFlightRotate;
426
+ return fresh;
427
+ }
428
+ if (storage) {
429
+ const exported = await exportIdentity(fresh);
430
+ if (myEpoch !== epoch) {
431
+ if (cached)
432
+ return cached;
433
+ if (inFlightRotate && inFlightRotate !== promise)
434
+ return inFlightRotate;
435
+ return fresh;
436
+ }
437
+ safeWrite(storage, exported);
438
+ }
439
+ cached = fresh;
440
+ return fresh;
441
+ })().finally(() => {
442
+ if (inFlightRotate === promise)
443
+ inFlightRotate = null;
444
+ });
445
+ inFlightRotate = promise;
446
+ return promise;
447
+ },
448
+ clear() {
449
+ epoch++;
450
+ cached = null;
451
+ inFlightLoad = null;
452
+ inFlightRotate = null;
453
+ safeRemove(resolveStorage());
454
+ }
455
+ };
456
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { defaultIceServers, joinRoom } from './room.js';
2
- export { createIdentity, exportIdentity, importIdentity, isSerializedIdentity } from './identity.js';
3
- export type { CreateIdentityOptions, PeerIdentity, SerializedIdentity } from './identity.js';
2
+ export { createIdentity, createIdentityStore, exportIdentity, importIdentity, isSerializedIdentity } from './identity.js';
3
+ export type { CreateIdentityOptions, IdentityStorage, IdentityStore, IdentityStoreOptions, PeerIdentity, SerializedIdentity } from './identity.js';
4
4
  export type { AddStreamOptions, Delivery, ListenOptions, PeerRoute, PeerStats, PeerStreamMeta, RemoveStreamOptions, Room, RoomError, RoomErrorCode, RoomOptions, RTCPeerConnectionConstructor, SendOptions, SendResult } from './room.js';
5
5
  export { binaryCodec, createChannel, createCodecChannel, jsonCodec, textCodec } from './channel.js';
6
6
  export type { Channel, ChannelOptions, ChannelSendOptions, Codec, CodecChannel } from './channel.js';
@@ -10,8 +10,8 @@ export { createPeerState } from './state.js';
10
10
  export type { PeerState, PeerStateChangeReason, PeerStateOptions } from './state.js';
11
11
  export { createBlobChannel } from './blob.js';
12
12
  export type { BlobChannel, BlobChannelOptions, BlobProgress, BlobSendOptions, BlobSendStatus } from './blob.js';
13
- export { createVoice } from './voice.js';
14
- export type { MicError, MicErrorCode, MicStatus, Voice, VoiceOptions, VoiceSnapshot } from './voice.js';
13
+ export { createVoice, listAudioInputs, onAudioInputsChange } from './voice.js';
14
+ export type { AudioInputDevice, MicError, MicErrorCode, MicStatus, Voice, VoiceOptions, VoiceSnapshot } from './voice.js';
15
15
  export { fetchTurnCredentials } from './turn.js';
16
16
  export type { FetchTurnOptions } from './turn.js';
17
17
  export { tabSignaling } from './tabs.js';
@@ -24,7 +24,7 @@ export type { NostrSignalingOptions } from './nostr.js';
24
24
  export { optionalWsSignaling, wsSignaling } from './ws.js';
25
25
  export type { OptionalWsSignalingOptions, WsSignalingOptions } from './ws.js';
26
26
  export { publicSignaling } from './public.js';
27
- export type { PublicSignalingOptions } from './public.js';
27
+ export type { PublicSignalingOptions, PublicTransportEvent, PublicTransportKind } from './public.js';
28
28
  export { combineSignaling, withLocalTabs } from './combine.js';
29
29
  export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
30
30
  export type { Discovery, IceCandidatePayload, Signal, Signaling, SignalingErrorCode, SignalingSession, SignalingState, WebSocketConstructor } from './signaling.js';
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  export { defaultIceServers, joinRoom } from './room.js';
2
- export { createIdentity, exportIdentity, importIdentity, isSerializedIdentity } from './identity.js';
2
+ export { createIdentity, createIdentityStore, exportIdentity, importIdentity, isSerializedIdentity } from './identity.js';
3
3
  export { binaryCodec, createChannel, createCodecChannel, jsonCodec, textCodec } from './channel.js';
4
4
  export { createRpc, RpcError } from './rpc.js';
5
5
  export { createPeerState } from './state.js';
6
6
  export { createBlobChannel } from './blob.js';
7
- export { createVoice } from './voice.js';
7
+ export { createVoice, listAudioInputs, onAudioInputsChange } from './voice.js';
8
8
  export { fetchTurnCredentials } from './turn.js';
9
9
  export { tabSignaling } from './tabs.js';
10
10
  export { manualSignaling } from './manual.js';
package/dist/public.d.ts CHANGED
@@ -1,4 +1,12 @@
1
- import type { Signaling, WebSocketConstructor } from './signaling.js';
1
+ import type { Signaling, SignalingState, WebSocketConstructor } from './signaling.js';
2
+ export type PublicTransportKind = 'ws' | 'mqtt' | 'nostr' | 'tabs';
3
+ export interface PublicTransportEvent {
4
+ readonly transport: PublicTransportKind;
5
+ /** Normalized WebSocket relay URL when `transport === 'ws'`. */
6
+ readonly url?: string;
7
+ readonly state: SignalingState;
8
+ readonly reason?: string;
9
+ }
2
10
  export interface PublicSignalingOptions {
3
11
  /**
4
12
  * Optional opportunistic WebSocket signaling URL(s) (`ws://` or `wss://`, max 8 unique URLs)
@@ -43,6 +51,16 @@ export interface PublicSignalingOptions {
43
51
  handshakeTimeoutMs?: number;
44
52
  /** Optional custom `WebSocket` constructor forwarded to WS, MQTT, and Nostr transports. */
45
53
  WebSocket?: WebSocketConstructor;
54
+ /**
55
+ * Optional per-transport lifecycle observer (`'ws'`, `'mqtt'`, `'nostr'`, and `'tabs'` when
56
+ * `localTabs: true` and `BroadcastChannel` is available). Fires on each child transport's state
57
+ * transitions (`'connecting'`, `'online'`, `'offline'`, `'closed'`).
58
+ *
59
+ * Note: Per the WHATWG WebSocket specification, browsers intentionally hide HTTP status codes
60
+ * (such as `403` origin rejections) and TLS handshake details behind opaque close code `1006`;
61
+ * client-side handshake timeouts and non-`1006` close codes are reported in `reason`.
62
+ */
63
+ onTransportChange?: (event: PublicTransportEvent) => void;
46
64
  }
47
65
  /**
48
66
  * Out-of-the-box composite signaling combining public MQTT + port-443 Nostr relays,
package/dist/public.js CHANGED
@@ -1,4 +1,4 @@
1
- import { combineSignaling, withLocalTabs } from './combine.js';
1
+ import { combineSignaling, withLocalTabsInternal } from './combine.js';
2
2
  import { mqttSignaling } from './mqtt.js';
3
3
  import { nostrSignaling } from './nostr.js';
4
4
  import { optionalWsSignaling } from './ws.js';
@@ -11,6 +11,62 @@ function validateTimeoutMs(value, label) {
11
11
  throw new RangeError(`Invalid ${label}`);
12
12
  }
13
13
  }
14
+ function notifyTransport(callback, event) {
15
+ try {
16
+ callback(event);
17
+ }
18
+ catch (error) {
19
+ if (typeof globalThis.reportError === 'function') {
20
+ globalThis.reportError(error);
21
+ }
22
+ else {
23
+ queueMicrotask(() => {
24
+ throw error;
25
+ });
26
+ }
27
+ }
28
+ }
29
+ function observeTransport(adapter, transport, onTransportChange, url) {
30
+ return (discovery) => {
31
+ let lastState;
32
+ let closed = false;
33
+ const emit = (state, reason) => {
34
+ if (state === lastState)
35
+ return;
36
+ lastState = state;
37
+ notifyTransport(onTransportChange, Object.freeze({
38
+ transport,
39
+ ...(url !== undefined ? { url } : {}),
40
+ state,
41
+ ...(reason !== undefined ? { reason } : {})
42
+ }));
43
+ };
44
+ const session = adapter({
45
+ ...discovery,
46
+ status(state, reason) {
47
+ if (closed)
48
+ return;
49
+ emit(state, reason);
50
+ discovery.status(state, reason);
51
+ }
52
+ });
53
+ if (!closed && lastState === undefined) {
54
+ emit('connecting');
55
+ }
56
+ return {
57
+ ...(session.trickle !== undefined ? { trickle: session.trickle } : {}),
58
+ ...(session.canReach ? { canReach: (peerId) => session.canReach(peerId) } : {}),
59
+ send: (to, signal) => session.send(to, signal),
60
+ close() {
61
+ if (closed)
62
+ return;
63
+ closed = true;
64
+ session.close();
65
+ emit('closed');
66
+ }
67
+ };
68
+ };
69
+ }
14
70
  function normalizeWsUrls(raw) {
15
71
  if (raw === undefined)
16
72
  return [];
@@ -56,7 +112,7 @@ export function publicSignaling(options = {}) {
56
112
  if (!options || typeof options !== 'object' || Array.isArray(options)) {
57
113
  throw new TypeError('Invalid publicSignaling options');
58
114
  }
59
- const { wsUrls, mqtt = true, nostr = true, localTabs = true, wsEncrypt = true, privateTopic = false, appId, wsHandshakeTimeoutMs = defaultWsHandshakeTimeoutMs, handshakeTimeoutMs = defaultPublicHandshakeTimeoutMs, WebSocket: WsCtor } = options;
115
+ const { wsUrls, mqtt = true, nostr = true, localTabs = true, wsEncrypt = true, privateTopic = false, appId, wsHandshakeTimeoutMs = defaultWsHandshakeTimeoutMs, handshakeTimeoutMs = defaultPublicHandshakeTimeoutMs, WebSocket: WsCtor, onTransportChange } = options;
60
116
  if (typeof localTabs !== 'boolean')
61
117
  throw new TypeError('Invalid localTabs option');
62
118
  if (typeof wsEncrypt !== 'boolean')
@@ -69,6 +125,9 @@ export function publicSignaling(options = {}) {
69
125
  if (WsCtor !== undefined && typeof WsCtor !== 'function') {
70
126
  throw new TypeError('Invalid WebSocket constructor');
71
127
  }
128
+ if (onTransportChange !== undefined && typeof onTransportChange !== 'function') {
129
+ throw new TypeError('Invalid onTransportChange callback');
130
+ }
72
131
  if (mqtt !== true && mqtt !== false && !Array.isArray(mqtt)) {
73
132
  throw new TypeError('mqtt option must be a boolean or an array of broker URLs');
74
133
  }
@@ -82,31 +141,32 @@ export function publicSignaling(options = {}) {
82
141
  validateTimeoutMs(handshakeTimeoutMs, 'handshakeTimeoutMs');
83
142
  const normalizedWsUrls = normalizeWsUrls(wsUrls);
84
143
  const adapters = [];
144
+ const maybeObserve = (adapter, kind, url) => onTransportChange ? observeTransport(adapter, kind, onTransportChange, url) : adapter;
85
145
  for (const url of normalizedWsUrls) {
86
- adapters.push(optionalWsSignaling(url, {
146
+ adapters.push(maybeObserve(optionalWsSignaling(url, {
87
147
  handshakeTimeoutMs: wsHandshakeTimeoutMs,
88
148
  encrypt: wsEncrypt,
89
149
  privateTopic,
90
150
  ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
91
- }));
151
+ }), 'ws', url));
92
152
  }
93
153
  if (mqtt !== false) {
94
- adapters.push(mqttSignaling({
154
+ adapters.push(maybeObserve(mqttSignaling({
95
155
  ...(Array.isArray(mqtt) ? { urls: mqtt } : {}),
96
156
  ...(appId !== undefined ? { appId } : {}),
97
157
  privateTopic,
98
158
  handshakeTimeoutMs,
99
159
  ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
100
- }));
160
+ }), 'mqtt'));
101
161
  }
102
162
  if (nostr !== false) {
103
- adapters.push(nostrSignaling({
163
+ adapters.push(maybeObserve(nostrSignaling({
104
164
  ...(Array.isArray(nostr) ? { urls: nostr } : {}),
105
165
  ...(appId !== undefined ? { appId } : {}),
106
166
  privateTopic,
107
167
  handshakeTimeoutMs,
108
168
  ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
109
- }));
169
+ }), 'nostr'));
110
170
  }
111
171
  const network = combineSignaling(...adapters);
112
172
  const pooledNetwork = (discovery) => {
@@ -129,5 +189,7 @@ export function publicSignaling(options = {}) {
129
189
  }
130
190
  });
131
191
  };
132
- return localTabs ? withLocalTabs(pooledNetwork) : pooledNetwork;
192
+ return localTabs
193
+ ? withLocalTabsInternal(pooledNetwork, onTransportChange ? (tabs) => observeTransport(tabs, 'tabs', onTransportChange) : undefined)
194
+ : pooledNetwork;
133
195
  }
package/dist/voice.d.ts CHANGED
@@ -24,12 +24,31 @@ export interface VoiceSnapshot {
24
24
  /** Sparse map of overridden per-peer playback volumes (`!== 1`). Peers absent from this map default to `1`. */
25
25
  readonly peerVolumes: Readonly<Record<string, number>>;
26
26
  }
27
+ /** Audio input device descriptor returned by `listAudioInputs()` and `onAudioInputsChange()`. */
28
+ export interface AudioInputDevice {
29
+ readonly deviceId: string;
30
+ readonly label: string;
31
+ readonly groupId: string;
32
+ }
27
33
  /** Configuration options for `createVoice()`. */
28
34
  export interface VoiceOptions {
29
35
  /** Initial playback volume for incoming peer audio (`0` to `1`). @default 1 */
30
36
  volume?: number;
31
37
  /** Start with incoming peer audio muted locally (`audio.muted = true`). @default false */
32
38
  deafened?: boolean;
39
+ /**
40
+ * Preferred local microphone `deviceId` (or `null` / `''` for system default).
41
+ * Takes precedence over `audioConstraints.deviceId` without overwriting `defaultAudioConstraints`.
42
+ */
43
+ deviceId?: string | null;
44
+ /**
45
+ * When `true` and initial microphone acquisition (`toggleMic()` / `startMic()`) fails with `'not-found'`
46
+ * for a non-null `deviceId` (e.g. an unplugged saved USB headset), automatically retry once using
47
+ * the system default microphone within the same request (no `'error'` flash).
48
+ * Does not auto-fallback during an explicit live `switchDevice(brokenId)` call.
49
+ * @default false
50
+ */
51
+ fallbackToDefaultOnNotFound?: boolean;
33
52
  /**
34
53
  * Custom audio track constraints passed to `getUserMedia`.
35
54
  * @default { echoCancellation: true, noiseSuppression: true, autoGainControl: true }
@@ -101,6 +120,18 @@ export interface Voice extends VoiceSnapshot {
101
120
  /** Release microphone tracks, remove hidden `<audio>` elements, close `AudioContext`, restore `audioSession`, and detach all listeners. */
102
121
  close(): void;
103
122
  }
123
+ /**
124
+ * List available audio input (microphone) devices safely across browser and non-DOM runtimes.
125
+ * Returns an empty frozen array if `navigator.mediaDevices.enumerateDevices()` is unavailable or rejects.
126
+ * Entries are deduplicated by non-empty `deviceId` and returned with trimmed labels (may be `''` before first `getUserMedia`).
127
+ */
128
+ export declare function listAudioInputs(): Promise<readonly AudioInputDevice[]>;
129
+ /**
130
+ * Subscribe to `navigator.mediaDevices` `'devicechange'` events and receive the updated
131
+ * `listAudioInputs()` array (guarded against out-of-order async enumerations and supporting `ListenOptions`).
132
+ * Returns an idempotent unsubscribe function.
133
+ */
134
+ export declare function onAudioInputsChange(fn: (devices: readonly AudioInputDevice[]) => void, options?: ListenOptions): () => void;
104
135
  /**
105
136
  * Create a headless P2P voice chat controller attached to a `Room`.
106
137
  *
package/dist/voice.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createListeners } from './listeners.js';
1
+ import { bindAbort, createListeners } from './listeners.js';
2
2
  import { getRoomRemoteStreams, isRoomClosed, onRoomClose } from './room.js';
3
3
  const defaultAudioConstraints = Object.freeze({
4
4
  echoCancellation: true,
@@ -58,6 +58,103 @@ function classifyMicError(err) {
58
58
  message: 'Could not access microphone'
59
59
  });
60
60
  }
61
+ function normalizeDeviceIdArg(deviceId) {
62
+ if (deviceId === undefined || deviceId === null || deviceId === '')
63
+ return null;
64
+ if (typeof deviceId !== 'string' || deviceId.trim().length === 0) {
65
+ throw new TypeError('Expected deviceId to be a non-empty string, null, or undefined');
66
+ }
67
+ return deviceId;
68
+ }
69
+ /**
70
+ * List available audio input (microphone) devices safely across browser and non-DOM runtimes.
71
+ * Returns an empty frozen array if `navigator.mediaDevices.enumerateDevices()` is unavailable or rejects.
72
+ * Entries are deduplicated by non-empty `deviceId` and returned with trimmed labels (may be `''` before first `getUserMedia`).
73
+ */
74
+ export async function listAudioInputs() {
75
+ if (typeof navigator === 'undefined' ||
76
+ typeof navigator.mediaDevices?.enumerateDevices !== 'function') {
77
+ return Object.freeze([]);
78
+ }
79
+ let raw;
80
+ try {
81
+ raw = await navigator.mediaDevices.enumerateDevices();
82
+ }
83
+ catch {
84
+ return Object.freeze([]);
85
+ }
86
+ const seen = new Set();
87
+ const result = [];
88
+ for (const dev of raw) {
89
+ if (!dev || dev.kind !== 'audioinput')
90
+ continue;
91
+ if (typeof dev.deviceId !== 'string' || dev.deviceId.length === 0)
92
+ continue;
93
+ if (seen.has(dev.deviceId))
94
+ continue;
95
+ seen.add(dev.deviceId);
96
+ result.push(Object.freeze({
97
+ deviceId: dev.deviceId,
98
+ label: typeof dev.label === 'string' ? dev.label.trim() : '',
99
+ groupId: typeof dev.groupId === 'string' ? dev.groupId : ''
100
+ }));
101
+ }
102
+ return Object.freeze(result);
103
+ }
104
+ /**
105
+ * Subscribe to `navigator.mediaDevices` `'devicechange'` events and receive the updated
106
+ * `listAudioInputs()` array (guarded against out-of-order async enumerations and supporting `ListenOptions`).
107
+ * Returns an idempotent unsubscribe function.
108
+ */
109
+ export function onAudioInputsChange(fn, options) {
110
+ if (typeof fn !== 'function')
111
+ throw new TypeError('Expected a listener function');
112
+ const signal = options?.signal;
113
+ if (signal?.aborted)
114
+ return () => { };
115
+ if (typeof navigator === 'undefined' ||
116
+ typeof navigator.mediaDevices?.addEventListener !== 'function') {
117
+ return () => { };
118
+ }
119
+ const mediaDevices = navigator.mediaDevices;
120
+ const once = Boolean(options?.once);
121
+ let active = true;
122
+ let epoch = 0;
123
+ let unbindAbort;
124
+ const off = () => {
125
+ if (!active)
126
+ return;
127
+ active = false;
128
+ epoch++;
129
+ unbindAbort?.();
130
+ try {
131
+ mediaDevices.removeEventListener('devicechange', handleChange);
132
+ }
133
+ catch {
134
+ // Ignore cleanup errors on restricted runtimes.
135
+ }
136
+ };
137
+ const handleChange = () => {
138
+ if (!active)
139
+ return;
140
+ const myEpoch = ++epoch;
141
+ void listAudioInputs().then((devices) => {
142
+ if (!active || myEpoch !== epoch)
143
+ return;
144
+ if (once)
145
+ off();
146
+ try {
147
+ fn(devices);
148
+ }
149
+ catch (error) {
150
+ globalThis.reportError?.(error);
151
+ }
152
+ });
153
+ };
154
+ mediaDevices.addEventListener('devicechange', handleChange);
155
+ unbindAbort = bindAbort(signal, off);
156
+ return off;
157
+ }
61
158
  const listeners = createListeners;
62
159
  function applyAudioVolume(audio, volume) {
63
160
  try {
@@ -126,11 +223,20 @@ export function createVoice(room, options) {
126
223
  throw new TypeError('Expected strictStreamTag to be a boolean');
127
224
  }
128
225
  const strictStreamTag = options?.strictStreamTag ?? false;
226
+ if (options?.fallbackToDefaultOnNotFound !== undefined &&
227
+ typeof options.fallbackToDefaultOnNotFound !== 'boolean') {
228
+ throw new TypeError('Expected fallbackToDefaultOnNotFound to be a boolean');
229
+ }
230
+ const fallbackToDefaultOnNotFound = options?.fallbackToDefaultOnNotFound ?? false;
129
231
  const autoUnlock = options?.autoUnlock !== false;
130
232
  const speakingDetection = options?.speakingDetection !== false;
131
233
  let selectedDeviceId = null;
132
234
  let selectedDeviceExact = false;
133
- if (typeof baseConstraints === 'object' && baseConstraints.deviceId !== undefined) {
235
+ if (options?.deviceId !== undefined) {
236
+ selectedDeviceId = normalizeDeviceIdArg(options.deviceId);
237
+ selectedDeviceExact = selectedDeviceId !== null;
238
+ }
239
+ else if (typeof baseConstraints === 'object' && baseConstraints.deviceId !== undefined) {
134
240
  const rawDev = baseConstraints.deviceId;
135
241
  if (typeof rawDev === 'string' && rawDev.trim().length > 0) {
136
242
  selectedDeviceId = rawDev;
@@ -548,6 +654,7 @@ export function createVoice(room, options) {
548
654
  switchAudioSessionForMic();
549
655
  const promise = (async () => {
550
656
  let stream;
657
+ let fellBackToDefault = false;
551
658
  try {
552
659
  stream = await navigator.mediaDevices.getUserMedia({
553
660
  audio: buildAudioConstraints(requestedDeviceId, requestedDeviceExact)
@@ -556,11 +663,33 @@ export function createVoice(room, options) {
556
663
  catch (err) {
557
664
  if (closed || epoch !== micEpoch)
558
665
  return 'off';
559
- restoreAudioSession();
560
- micStatus = 'error';
561
- micError = classifyMicError(err);
562
- emitChange();
563
- return 'error';
666
+ const classified = classifyMicError(err);
667
+ if (fallbackToDefaultOnNotFound &&
668
+ requestedDeviceId !== null &&
669
+ classified.code === 'not-found') {
670
+ try {
671
+ stream = await navigator.mediaDevices.getUserMedia({
672
+ audio: buildAudioConstraints(null, false)
673
+ });
674
+ fellBackToDefault = true;
675
+ }
676
+ catch (fallbackErr) {
677
+ if (closed || epoch !== micEpoch)
678
+ return 'off';
679
+ restoreAudioSession();
680
+ micStatus = 'error';
681
+ micError = classifyMicError(fallbackErr);
682
+ emitChange();
683
+ return 'error';
684
+ }
685
+ }
686
+ else {
687
+ restoreAudioSession();
688
+ micStatus = 'error';
689
+ micError = classified;
690
+ emitChange();
691
+ return 'error';
692
+ }
564
693
  }
565
694
  if (closed || epoch !== micEpoch || isRoomClosed(room)) {
566
695
  for (const track of stream.getTracks())
@@ -597,9 +726,14 @@ export function createVoice(room, options) {
597
726
  }
598
727
  localStream = stream;
599
728
  const actualDeviceId = stream.getAudioTracks()[0]?.getSettings?.().deviceId;
600
- selectedDeviceId =
601
- requestedDeviceId ??
602
- (typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null);
729
+ const resolvedActual = typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null;
730
+ if (fellBackToDefault) {
731
+ selectedDeviceId = resolvedActual;
732
+ selectedDeviceExact = false;
733
+ }
734
+ else {
735
+ selectedDeviceId = requestedDeviceId ?? resolvedActual;
736
+ }
603
737
  micStatus = 'live';
604
738
  micError = null;
605
739
  bindLocalTrackEnded(stream);
@@ -855,13 +989,7 @@ export function createVoice(room, options) {
855
989
  emitChange();
856
990
  },
857
991
  async switchDevice(deviceId) {
858
- let nextDeviceId = null;
859
- if (deviceId !== undefined && deviceId !== null && deviceId !== '') {
860
- if (typeof deviceId !== 'string' || deviceId.trim().length === 0) {
861
- throw new TypeError('Expected deviceId to be a non-empty string, null, or undefined');
862
- }
863
- nextDeviceId = deviceId;
864
- }
992
+ const nextDeviceId = normalizeDeviceIdArg(deviceId);
865
993
  if (closed)
866
994
  return 'off';
867
995
  if (inFlightMic !== null) {
package/dist/ws.js CHANGED
@@ -191,9 +191,11 @@ export function wsSignaling(url, options = {}) {
191
191
  ws = socket;
192
192
  awaitingPong = false;
193
193
  let settled = false;
194
+ let timedOut = false;
194
195
  handshakeTimer = setTimeout(() => {
195
196
  if (closed || ws !== socket || settled)
196
197
  return;
198
+ timedOut = true;
197
199
  try {
198
200
  socket.close();
199
201
  }
@@ -370,16 +372,31 @@ export function wsSignaling(url, options = {}) {
370
372
  // Ignore close errors.
371
373
  }
372
374
  };
373
- socket.onclose = () => {
375
+ socket.onclose = (event) => {
374
376
  if (ws !== socket)
375
377
  return;
376
378
  ws = undefined;
377
379
  clearTimers();
378
380
  if (closed)
379
381
  return;
380
- const reason = settled
381
- ? 'WebSocket signaling disconnected'
382
- : 'WebSocket signaling connection failed';
382
+ const code = typeof event?.code === 'number' &&
383
+ Number.isInteger(event.code) &&
384
+ event.code >= 1000 &&
385
+ event.code <= 4999 &&
386
+ event.code !== 1000 &&
387
+ event.code !== 1005 &&
388
+ event.code !== 1006
389
+ ? event.code
390
+ : undefined;
391
+ const reason = timedOut
392
+ ? 'WebSocket signaling handshake timed out'
393
+ : settled
394
+ ? code !== undefined
395
+ ? `WebSocket signaling disconnected (${code})`
396
+ : 'WebSocket signaling disconnected'
397
+ : code !== undefined
398
+ ? `WebSocket signaling connection failed (${code})`
399
+ : 'WebSocket signaling connection failed';
383
400
  reportOffline(reason);
384
401
  scheduleReconnect();
385
402
  };
@@ -516,7 +533,7 @@ export function optionalWsSignaling(url, options = {}) {
516
533
  else {
517
534
  abandoned = true;
518
535
  session?.close();
519
- discovery.status('closed');
536
+ discovery.status('closed', reason);
520
537
  }
521
538
  },
522
539
  error(code, message) {
package/docs/behavior.md CHANGED
@@ -35,7 +35,7 @@ This document specifies limits, lifecycle rules, wire formats, and security boun
35
35
  - In browser tabs with `crypto.subtle`, `joinRoom()` automatically commits a 128-bit one-time Lamport preimage (`SHA-256("meshpost/1/reclaim:" + self + ":" + secret)`) in its WebRTC `hello` frame and writes `{ id, secret, ts }` to `sessionStorage` **only on `pagehide`** (so duplicating a live tab never clones the secret), alongside a best-effort `meshpost/1/leave` notice when `!event.persisted`. When a reloaded tab (`F5`) reconnects within `60 s`, remote peers verify the preimage, drop the superseded ghost connection (`onPeerLeave(oldId)` fires strictly before `onPeerJoin(newId)`), and ignore `oldId` in future roster snapshots (`128`-entry FIFO cap) without waiting `8,000 ms` `disconnectGrace`.
36
36
  - `joinRoom()` returns synchronously and starts discovery immediately.
37
37
  - `room.peers` returns a snapshot array of remote peer IDs whose unreliable and reliable channels have opened and completed the `'meshpost/1/hello:'` handshake.
38
- - Subscribe to `onPeerJoin` and `onPeerLeave` for future changes. Each subscription (`onPacket`, `onDrain`, `onPeerJoin`, `onPeerLeave`, `onSignalingChange`, `onError`, `onPeerStream`, `onPeerStreamEnd`, `channel.onPacket`, `codecChannel.onMessage`, `peerState.onChange`, `rpc.handle`, `blobChannel.onBlob`, `blobChannel.onProgress`, and `voice.onChange`) returns an idempotent unsubscribe function and optionally accepts `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`).
38
+ - Subscribe to `onPeerJoin` and `onPeerLeave` for future changes. Each subscription (`onPacket`, `onDrain`, `onPeerJoin`, `onPeerLeave`, `onSignalingChange`, `onError`, `onPeerStream`, `onPeerStreamEnd`, `channel.onPacket`, `codecChannel.onMessage`, `peerState.onChange`, `rpc.handle`, `blobChannel.onBlob`, `blobChannel.onProgress`, `voice.onChange`, and `onAudioInputsChange`) returns an idempotent unsubscribe function and optionally accepts `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`).
39
39
  - Subscribing with an already-aborted `signal` (or after `room.leave()`) is a no-op. Unsubscribing, firing a `once` listener, or calling `room.leave()` detaches any registered `'abort'` listener from `signal`. On `channel.onPacket`, `once` unsubscribes only after a packet matches both delivery mode and channel name; on `codecChannel.onMessage` and `rpc.handle`, `once` unsubscribes only after `codec.decode` succeeds.
40
40
  - A room of `N` peers forms up to `N(N - 1) / 2` direct connections (bounded per peer by `maxPeers`).
41
41
  - There is no host election, packet forwarding, or history replay. Any peer can join first.
@@ -76,7 +76,7 @@ Note: when `privateTopic` is `false` (default), `mqttSignaling()`, `nostrSignali
76
76
  ### Synchronous errors
77
77
 
78
78
  - `joinRoom()` throws `TypeError` for invalid `name` (`^[a-zA-Z0-9_-]{1,64}$`), invalid `appId` (`^[a-zA-Z0-9._-]{1,64}$`), empty `password`, an invalid/forged `identity` (`PeerIdentity`), or a non-function `RTCPeerConnection` option, and throws `Error` if `RTCPeerConnection` is unavailable on `globalThis` and not provided via `options.RTCPeerConnection`.
79
- - `createIdentity()`, `exportIdentity()`, and `importIdentity()` reject with `Error` when `crypto.subtle` is unavailable, `exportIdentity()` rejects with `Error` when `extractable: false`, `importIdentity()` rejects with `TypeError` on invalid shape (`!isSerializedIdentity`) or `Error` if `(x, y)` fails a challenge signature check against `d`.
79
+ - `createIdentity()`, `exportIdentity()`, and `importIdentity()` reject with `Error` when `crypto.subtle` is unavailable, `exportIdentity()` rejects with `Error` when `extractable: false`, `importIdentity()` rejects with `TypeError` on invalid shape (`!isSerializedIdentity`) or `Error` if `(x, y)` fails a challenge signature check against `d`. `createIdentityStore()` throws `TypeError` for an invalid `key` (`1..256` chars) or `storage` backend; `load()` / `rotate()` reject with `Error` when `crypto.subtle` is unavailable (without removing any stored entry).
80
80
  - `joinRoom()` throws `RangeError` for invalid timeouts or `maxPeers`, throws browser errors immediately if `rtcConfig` is malformed, and throws `Error` if `mqttSignaling()`, `nostrSignaling()`, or default `wsSignaling()` (`encrypt: true`) is used with `password` without `crypto.subtle`.
81
81
  - `room.send()` throws `Error` after `leave()`, and `TypeError` for non-`Uint8Array` payloads or invalid `delivery`.
82
82
  - `room.addStream()` throws `Error` after `leave()`, and `TypeError` for non-`MediaStream` arguments, invalid `AddStreamOptions`, or invalid `tag` (`^[a-zA-Z0-9._-]{1,32}$`). `room.replaceStreamTrack()` rejects with `Error` if the room is closed or the stream is not attached, and `TypeError` for invalid or mismatched-`kind` tracks.
@@ -86,11 +86,11 @@ Note: when `privateTopic` is `false` (default), `mqttSignaling()`, `nostrSignali
86
86
  - `createPeerState()` throws `TypeError` for an invalid `room`, `delivery`, `coalesce`, `codec`, `undefined` state value, or non-function `onChange` listener; `RangeError` if `initial` or `set(value)` encodes past the 16 KiB packet limit; and `Error` when calling `set()` or `clear()` after `close()` or `room.leave()`.
87
87
  - `createBlobChannel()` throws `RangeError` for invalid `maxReceiveBytes`, `chunkSize`, `receiveTimeoutMs`, or `maxConcurrentPerPeer`. `blobChannel.send()` rejects with `Error` when closed and `TypeError` for non-`Uint8Array` payloads.
88
88
  - `wsSignaling()` and `optionalWsSignaling()` throw `TypeError` for non-`ws:`/`wss:` URLs, non-boolean `encrypt`/`privateTopic`, `privateTopic: true` without `password`, or a non-function `WebSocket` option; `Error` if `privateTopic: true` is combined with `encrypt: false` or if `WebSocket` is unavailable at session startup; and `RangeError` for invalid `handshakeTimeoutMs` or `pingIntervalMs`.
89
- - `publicSignaling()` throws `TypeError` for invalid options, non-`ws:`/`wss:` or empty-string `wsUrls`, non-boolean `localTabs`/`wsEncrypt`/`privateTopic`, invalid `mqtt`/`nostr`/`appId`, or a non-function `WebSocket` option; and `RangeError` when both `mqtt: false` and `nostr: false`, when `mqtt`/`nostr` is an empty array, when `wsUrls` exceeds `8` unique (`64` raw) entries, or when `wsHandshakeTimeoutMs` / `handshakeTimeoutMs` is out of range.
89
+ - `publicSignaling()` throws `TypeError` for invalid options, non-`ws:`/`wss:` or empty-string `wsUrls`, non-boolean `localTabs`/`wsEncrypt`/`privateTopic`, invalid `mqtt`/`nostr`/`appId`, a non-function `WebSocket` option, or a non-function `onTransportChange` callback; and `RangeError` when both `mqtt: false` and `nostr: false`, when `mqtt`/`nostr` is an empty array, when `wsUrls` exceeds `8` unique (`64` raw) entries, or when `wsHandshakeTimeoutMs` / `handshakeTimeoutMs` is out of range.
90
90
  - `combineSignaling()` throws `RangeError` when given 0 adapters and `TypeError` if any argument is not a function; `withLocalTabs()` throws `TypeError` if `primary` is not a function.
91
91
  - `mqttSignaling()` throws `RangeError` for empty `urls` or invalid `handshakeTimeoutMs`, `TypeError` for an empty `password`, non-boolean `privateTopic`, `privateTopic: true` without `password`, or a non-function `WebSocket` option, and `Error` if `WebSocket` is unavailable at session startup.
92
92
  - `nostrSignaling()` throws `RangeError` for empty `urls` or invalid `handshakeTimeoutMs`, `TypeError` for non-`ws:`/`wss:` `urls`, invalid `appId`, empty `password`, non-boolean `privateTopic`, `privateTopic: true` without `password`, or a non-function `WebSocket` option, and `Error` if `WebSocket` is unavailable at session startup.
93
- - `createVoice()` throws `TypeError` for invalid `room`, `audioConstraints`, `to`, `streamTag`, or `strictStreamTag`, and `RangeError` for out-of-range `volume`, `speakingThreshold`, or `speakingIntervalMs`. `voice.setVolume()` and `voice.setPeerVolume()` throw `RangeError` for non-finite numbers; `voice.setPeerVolume()` and `voice.setPeerMuted()` throw `TypeError` for invalid `peerId` strings (`1..128` chars); `voice.switchDevice()` rejects with `TypeError` for whitespace-only/non-string `deviceId` values.
93
+ - `createVoice()` throws `TypeError` for invalid `room`, `deviceId`, `fallbackToDefaultOnNotFound`, `audioConstraints`, `to`, `streamTag`, or `strictStreamTag`, and `RangeError` for out-of-range `volume`, `speakingThreshold`, or `speakingIntervalMs`. `onAudioInputsChange()` throws `TypeError` for a non-function listener. `voice.setVolume()` and `voice.setPeerVolume()` throw `RangeError` for non-finite numbers; `voice.setPeerVolume()` and `voice.setPeerMuted()` throw `TypeError` for invalid `peerId` strings (`1..128` chars); `voice.switchDevice()` rejects with `TypeError` for whitespace-only/non-string `deviceId` values.
94
94
  - `fetchTurnCredentials()` rejects with `TypeError` for invalid URLs, disallowed protocols, embedded URL credentials, or invalid `accessKey`, and `RangeError` for invalid `timeoutMs`.
95
95
 
96
96
  ## Sending and receiving
@@ -251,13 +251,14 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
251
251
  - Client sends `{ type: 'join', room, id }` on open (within `handshakeTimeoutMs`, `10,000` ms default), `{ type: 'signal', to, signal | box }` for peer signaling, `{ type: 'ping' }` every `pingIntervalMs` (`25,000` ms default), and `{ type: 'leave' }` on close.
252
252
  - Server sends `{ type: 'roster', peers: string[] }` (validated UUIDs, capped at `256`), `{ type: 'signal', from, signal | box }`, and `{ type: 'pong' }`. Incoming frames larger than `128 KiB` are ignored.
253
253
  - Tracks `awaitingPong`: if no `{ type: 'pong' }` (or other valid server message) arrives before the next ping interval, the socket is closed to trigger reconnect.
254
- - Reconnects with jittered exponential backoff (`500 ms` to `10 s`, `±25%` jitter) when `reconnect` is `true` (default), emitting `'offline'` and `'signaling-error'` once per offline transition.
255
- - `optionalWsSignaling(url, options?)` wraps `wsSignaling` with `reconnect: false` and a `4,000 ms` default `handshakeTimeoutMs`, forwarding `'online'` while healthy and transitioning cleanly to `'closed'` (closing the underlying session and suppressing `'signaling-error'`) on any non-`'online'` transition while still forwarding `'decrypt-failed'` and `'clock-skew'`.
254
+ - Reconnects with jittered exponential backoff (`500 ms` to `10 s`, `±25%` jitter) when `reconnect` is `true` (default), emitting `'offline'` and `'signaling-error'` once per offline transition. Distinguishes client-side handshake timeouts (`'WebSocket signaling handshake timed out'`) and non-standard numeric WebSocket close codes (`code !== 1000 && code !== 1005 && code !== 1006`) in `reason` without interpolating untrusted remote `CloseEvent.reason` strings.
255
+ - `optionalWsSignaling(url, options?)` wraps `wsSignaling` with `reconnect: false` and a `4,000 ms` default `handshakeTimeoutMs`, forwarding `'online'` while healthy and transitioning cleanly to `'closed'` (forwarding `reason`, closing the underlying session, and suppressing `'signaling-error'`) on any non-`'online'` transition while still forwarding `'decrypt-failed'` and `'clock-skew'`.
256
256
 
257
257
  ### `publicSignaling(options?)`
258
258
 
259
259
  - Flattens zero or more `optionalWsSignaling(url, ...)` children (`wsUrls?: string | readonly string[]`, validated `ws:`/`wss:`, deduplicated, capped at `8` unique URLs and `64` raw entries) together with `mqttSignaling()` (`mqtt: true` default) and `nostrSignaling()` (`nostr: true` default) into a single `combineSignaling(...)` instance, wrapped in `withLocalTabs(...)` when `localTabs` is `true` (default).
260
260
  - Treats enabled transports as a single redundant pool: suppresses per-transport `'signaling-error'` while any sibling transport is `'online'` or `'connecting'` (e.g. when corporate Wi-Fi blocks MQTT ports while port-443 Nostr or `wsUrls` succeeds) and emits `'signaling-error'` once per aggregate `'offline'` transition, while forwarding `'decrypt-failed'` and `'clock-skew'`.
261
+ - Optional `onTransportChange?: (event: PublicTransportEvent) => void` observes per-transport (`'ws' | 'mqtt' | 'nostr' | 'tabs'`) state transitions with frozen events (`{ transport, url?, state, reason? }`), deduplicating repeated states, isolating callback errors via `reportError`, preserving child `trickle` and `canReach` capabilities, and omitting `'tabs'` events when `BroadcastChannel` is unavailable. Note: per the WHATWG WebSocket specification, browsers hide HTTP status codes (`403`, etc.) and TLS errors behind close code `1006`; client-side handshake timeouts and non-`1006` close codes appear in `reason`.
261
262
  - Requires at least one persistent public relay transport (`mqtt !== false || nostr !== false`).
262
263
 
263
264
  ### `combineSignaling(...adapters)`
@@ -276,7 +277,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
276
277
 
277
278
  ### `createVoice(room, options?)` and `fetchTurnCredentials(url, options?)`
278
279
 
279
- - `createVoice(room, options?)` tags outgoing mic streams with `streamTag` (`'voice'` default) and attaches hidden `<audio autoplay>` elements for up to `4` matching remote audio streams per peer (`meta.tag === streamTag`, plus untagged streams when `strictStreamTag` is `false`; hydrating any streams already active on `room` at construction), supports per-peer volume (`setPeerVolume`, scaled by master `volume`, `128`-peer cap) and per-peer mute (`setPeerMuted`, independent of `deafened`, `128`-peer cap), hot-swaps microphone input devices via serialized `switchDevice(deviceId?)` + `room.replaceStreamTrack()` with zero SDP renegotiation, coalesces concurrent `startMic()`/`toggleMic()` calls, cancels pending `getUserMedia` via `micEpoch`/`switchEpoch` on `stopMic()`/`close()`, saves/restores `navigator.audioSession.type` (`'play-and-record'`) across all exit paths, routes `AnalyserNode` through a zero-gain `GainNode` to `destination` for WebKit pull-graph compatibility, unlocks blocked audio via lock-free `{ capture: true }` gestures + `visibilitychange`, and closes automatically on `room.leave()` without redundant `removeStream()` renegotiation.
280
+ - `createVoice(room, options?)` tags outgoing mic streams with `streamTag` (`'voice'` default) and attaches hidden `<audio autoplay>` elements for up to `4` matching remote audio streams per peer (`meta.tag === streamTag`, plus untagged streams when `strictStreamTag` is `false`; hydrating any streams already active on `room` at construction), supports optional initial `deviceId` with `fallbackToDefaultOnNotFound` (silent single-epoch fallback to system default only on initial mic acquisition, never on live `switchDevice`), per-peer volume (`setPeerVolume`, scaled by master `volume`, exposed as immutable sparse `peerVolumes`, `128`-peer cap) and per-peer mute (`setPeerMuted`, independent of `deafened`, `128`-peer cap), hot-swaps microphone input devices via serialized `switchDevice(deviceId?)` + `room.replaceStreamTrack()` with zero SDP renegotiation, coalesces concurrent `startMic()`/`toggleMic()` calls, cancels pending `getUserMedia` via `micEpoch`/`switchEpoch` on `stopMic()`/`close()`, saves/restores `navigator.audioSession.type` (`'play-and-record'`) across all exit paths, routes `AnalyserNode` through a zero-gain `GainNode` to `destination` for WebKit pull-graph compatibility, unlocks blocked audio via lock-free `{ capture: true }` gestures + `visibilitychange`, and closes automatically on `room.leave()` without redundant `removeStream()` renegotiation. Separate tree-shakeable `listAudioInputs()` and `onAudioInputsChange(cb, options?)` helpers enumerate and watch audio inputs (filtering out raw `'default'` / `'communications'` aliases when hardware devices exist).
280
281
  - `fetchTurnCredentials(url, options?)` validates `https://` (or `http://localhost` / `127.0.0.1` / `[::1]`) without embedded credentials, sends `POST` with `redirect: 'error'`, `credentials: 'omit'`, `cache: 'no-store'`, enforces `timeoutMs` (`5,000` ms default) and a `64 KiB` streaming body limit, and returns `1..16` sanitized `RTCIceServer` entries (`^(stuns?|turns?):[^\s]+$`).
281
282
 
282
283
  ### `manualSignaling(outgoing)`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dimchansky/meshpost",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "author": "Dmitrij Koniajev",
5
5
  "license": "MIT",
6
6
  "type": "module",