@dimchansky/meshpost 0.4.1 → 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/dist/state.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createChannel, isValidCodec, jsonCodec } from './channel.js';
2
+ import { createListeners } from './listeners.js';
2
3
  import { isRoomClosed, onRoomClose } from './room.js';
3
4
  const opSet = 0x01;
4
5
  const opClear = 0x02;
@@ -25,53 +26,7 @@ function buildClearFrame(seq) {
25
26
  new DataView(frame.buffer).setUint32(1, seq >>> 0);
26
27
  return frame;
27
28
  }
28
- function listeners() {
29
- const entries = new Set();
30
- let closed = false;
31
- return {
32
- add(fn, options) {
33
- if (typeof fn !== 'function')
34
- throw new TypeError('Expected a listener function');
35
- const signal = options?.signal;
36
- if (closed || signal?.aborted)
37
- return () => { };
38
- let removed = false;
39
- const entry = {
40
- fn,
41
- once: Boolean(options?.once),
42
- off() {
43
- if (removed)
44
- return;
45
- removed = true;
46
- entries.delete(entry);
47
- signal?.removeEventListener('abort', entry.off);
48
- }
49
- };
50
- entries.add(entry);
51
- signal?.addEventListener('abort', entry.off, { once: true });
52
- return entry.off;
53
- },
54
- fire(...args) {
55
- for (const entry of [...entries]) {
56
- if (!entries.has(entry))
57
- continue;
58
- if (entry.once)
59
- entry.off();
60
- try {
61
- entry.fn(...args);
62
- }
63
- catch (error) {
64
- globalThis.reportError?.(error);
65
- }
66
- }
67
- },
68
- clear() {
69
- closed = true;
70
- for (const entry of [...entries])
71
- entry.off();
72
- }
73
- };
74
- }
29
+ const listeners = createListeners;
75
30
  /**
76
31
  * Create a single-writer per-peer state synchronization store over a named logical channel.
77
32
  * Filters out-of-order updates via RFC 1982 `u32` sequence numbers, hydrates state reliably
@@ -185,7 +140,7 @@ export function createPeerState(room, name, options = {}) {
185
140
  lastSeqByPeer.set(from, seq);
186
141
  const prev = peersState.get(from);
187
142
  peersState.set(from, decoded);
188
- changes.fire(from, decoded, prev);
143
+ changes.fire(from, decoded, prev, 'set');
189
144
  }
190
145
  else if (op === opClear) {
191
146
  if (bytes.byteLength !== headerBytes)
@@ -194,7 +149,7 @@ export function createPeerState(room, name, options = {}) {
194
149
  if (peersState.has(from)) {
195
150
  const prev = peersState.get(from);
196
151
  peersState.delete(from);
197
- changes.fire(from, undefined, prev);
152
+ changes.fire(from, undefined, prev, 'clear');
198
153
  }
199
154
  }
200
155
  };
@@ -231,7 +186,7 @@ export function createPeerState(room, name, options = {}) {
231
186
  if (peersState.has(peerId)) {
232
187
  const prev = peersState.get(peerId);
233
188
  peersState.delete(peerId);
234
- changes.fire(peerId, undefined, prev);
189
+ changes.fire(peerId, undefined, prev, 'leave');
235
190
  }
236
191
  }, internalListen);
237
192
  if (coalesce) {
package/dist/voice.d.ts CHANGED
@@ -18,8 +18,17 @@ export interface VoiceSnapshot {
18
18
  readonly volume: number;
19
19
  readonly selfSpeaking: boolean;
20
20
  readonly remotePeers: readonly string[];
21
+ /** Remote peer IDs whose incoming audio currently exceeds `speakingThreshold` (independent of `deafened` / `mutedPeers`). */
21
22
  readonly speakingPeers: readonly string[];
22
23
  readonly mutedPeers: readonly string[];
24
+ /** Sparse map of overridden per-peer playback volumes (`!== 1`). Peers absent from this map default to `1`. */
25
+ readonly peerVolumes: Readonly<Record<string, number>>;
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;
23
32
  }
24
33
  /** Configuration options for `createVoice()`. */
25
34
  export interface VoiceOptions {
@@ -27,6 +36,19 @@ export interface VoiceOptions {
27
36
  volume?: number;
28
37
  /** Start with incoming peer audio muted locally (`audio.muted = true`). @default false */
29
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;
30
52
  /**
31
53
  * Custom audio track constraints passed to `getUserMedia`.
32
54
  * @default { echoCancellation: true, noiseSuppression: true, autoGainControl: true }
@@ -98,6 +120,18 @@ export interface Voice extends VoiceSnapshot {
98
120
  /** Release microphone tracks, remove hidden `<audio>` elements, close `AudioContext`, restore `audioSession`, and detach all listeners. */
99
121
  close(): void;
100
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;
101
135
  /**
102
136
  * Create a headless P2P voice chat controller attached to a `Room`.
103
137
  *
package/dist/voice.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { bindAbort, createListeners } from './listeners.js';
1
2
  import { getRoomRemoteStreams, isRoomClosed, onRoomClose } from './room.js';
2
3
  const defaultAudioConstraints = Object.freeze({
3
4
  echoCancellation: true,
@@ -57,48 +58,104 @@ function classifyMicError(err) {
57
58
  message: 'Could not access microphone'
58
59
  });
59
60
  }
60
- function listeners() {
61
- const entries = new Set();
62
- let closed = false;
63
- return {
64
- add(fn, options) {
65
- const signal = options?.signal;
66
- if (closed || signal?.aborted)
67
- return () => { };
68
- const entry = {
69
- fn,
70
- once: Boolean(options?.once),
71
- off() {
72
- if (!entries.delete(entry))
73
- return;
74
- signal?.removeEventListener('abort', entry.off);
75
- }
76
- };
77
- entries.add(entry);
78
- signal?.addEventListener('abort', entry.off, { once: true });
79
- return entry.off;
80
- },
81
- fire(...args) {
82
- for (const entry of [...entries]) {
83
- if (!entries.has(entry))
84
- continue;
85
- if (entry.once)
86
- entry.off();
87
- try {
88
- entry.fn(...args);
89
- }
90
- catch (error) {
91
- globalThis.reportError?.(error);
92
- }
93
- }
94
- },
95
- clear() {
96
- closed = true;
97
- for (const entry of [...entries])
98
- entry.off();
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.
99
135
  }
100
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;
101
157
  }
158
+ const listeners = createListeners;
102
159
  function applyAudioVolume(audio, volume) {
103
160
  try {
104
161
  audio.volume = volume;
@@ -166,30 +223,42 @@ export function createVoice(room, options) {
166
223
  throw new TypeError('Expected strictStreamTag to be a boolean');
167
224
  }
168
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;
169
231
  const autoUnlock = options?.autoUnlock !== false;
170
232
  const speakingDetection = options?.speakingDetection !== false;
171
233
  let selectedDeviceId = null;
172
- if (typeof baseConstraints === 'object' && baseConstraints.deviceId !== undefined) {
234
+ let selectedDeviceExact = false;
235
+ if (options?.deviceId !== undefined) {
236
+ selectedDeviceId = normalizeDeviceIdArg(options.deviceId);
237
+ selectedDeviceExact = selectedDeviceId !== null;
238
+ }
239
+ else if (typeof baseConstraints === 'object' && baseConstraints.deviceId !== undefined) {
173
240
  const rawDev = baseConstraints.deviceId;
174
241
  if (typeof rawDev === 'string' && rawDev.trim().length > 0) {
175
242
  selectedDeviceId = rawDev;
243
+ selectedDeviceExact = false;
176
244
  }
177
245
  else if (rawDev && typeof rawDev === 'object' && !Array.isArray(rawDev)) {
178
- const candidate = typeof rawDev.exact === 'string'
179
- ? rawDev.exact
180
- : typeof rawDev.ideal === 'string'
181
- ? rawDev.ideal
182
- : null;
183
- if (candidate && candidate.trim().length > 0)
184
- selectedDeviceId = candidate;
246
+ if (typeof rawDev.exact === 'string' && rawDev.exact.trim().length > 0) {
247
+ selectedDeviceId = rawDev.exact;
248
+ selectedDeviceExact = true;
249
+ }
250
+ else if (typeof rawDev.ideal === 'string' && rawDev.ideal.trim().length > 0) {
251
+ selectedDeviceId = rawDev.ideal;
252
+ selectedDeviceExact = false;
253
+ }
185
254
  }
186
255
  }
187
- function buildAudioConstraints(deviceOverride) {
256
+ function buildAudioConstraints(deviceOverride, exact) {
188
257
  if (deviceOverride !== null) {
189
258
  const base = typeof baseConstraints === 'object'
190
259
  ? { ...baseConstraints }
191
260
  : { ...defaultAudioConstraints };
192
- base.deviceId = { exact: deviceOverride };
261
+ base.deviceId = exact ? { exact: deviceOverride } : { ideal: deviceOverride };
193
262
  return base;
194
263
  }
195
264
  if (baseConstraints === true)
@@ -235,6 +304,9 @@ export function createVoice(room, options) {
235
304
  throw new TypeError('Expected a non-empty peerId string');
236
305
  }
237
306
  }
307
+ function buildPeerVolumes() {
308
+ return Object.freeze(Object.fromEntries(peerVolumes));
309
+ }
238
310
  function buildSnapshot() {
239
311
  return Object.freeze({
240
312
  micStatus,
@@ -246,7 +318,8 @@ export function createVoice(room, options) {
246
318
  selfSpeaking,
247
319
  remotePeers: Object.freeze([...remotePeers.keys()]),
248
320
  speakingPeers: Object.freeze([...speakingPeers]),
249
- mutedPeers: Object.freeze([...mutedPeers])
321
+ mutedPeers: Object.freeze([...mutedPeers]),
322
+ peerVolumes: buildPeerVolumes()
250
323
  });
251
324
  }
252
325
  function emitChange() {
@@ -572,6 +645,7 @@ export function createVoice(room, options) {
572
645
  }
573
646
  const epoch = ++micEpoch;
574
647
  const requestedDeviceId = selectedDeviceId;
648
+ const requestedDeviceExact = selectedDeviceExact;
575
649
  micStatus = 'requesting';
576
650
  micError = null;
577
651
  emitChange();
@@ -580,19 +654,42 @@ export function createVoice(room, options) {
580
654
  switchAudioSessionForMic();
581
655
  const promise = (async () => {
582
656
  let stream;
657
+ let fellBackToDefault = false;
583
658
  try {
584
659
  stream = await navigator.mediaDevices.getUserMedia({
585
- audio: buildAudioConstraints(requestedDeviceId)
660
+ audio: buildAudioConstraints(requestedDeviceId, requestedDeviceExact)
586
661
  });
587
662
  }
588
663
  catch (err) {
589
664
  if (closed || epoch !== micEpoch)
590
665
  return 'off';
591
- restoreAudioSession();
592
- micStatus = 'error';
593
- micError = classifyMicError(err);
594
- emitChange();
595
- 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
+ }
596
693
  }
597
694
  if (closed || epoch !== micEpoch || isRoomClosed(room)) {
598
695
  for (const track of stream.getTracks())
@@ -629,9 +726,14 @@ export function createVoice(room, options) {
629
726
  }
630
727
  localStream = stream;
631
728
  const actualDeviceId = stream.getAudioTracks()[0]?.getSettings?.().deviceId;
632
- selectedDeviceId =
633
- requestedDeviceId ??
634
- (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
+ }
635
737
  micStatus = 'live';
636
738
  micError = null;
637
739
  bindLocalTrackEnded(stream);
@@ -818,6 +920,9 @@ export function createVoice(room, options) {
818
920
  get mutedPeers() {
819
921
  return Object.freeze([...mutedPeers]);
820
922
  },
923
+ get peerVolumes() {
924
+ return buildPeerVolumes();
925
+ },
821
926
  getSnapshot: buildSnapshot,
822
927
  toggleMic() {
823
928
  if (closed)
@@ -884,13 +989,7 @@ export function createVoice(room, options) {
884
989
  emitChange();
885
990
  },
886
991
  async switchDevice(deviceId) {
887
- let nextDeviceId = null;
888
- if (deviceId !== undefined && deviceId !== null && deviceId !== '') {
889
- if (typeof deviceId !== 'string' || deviceId.trim().length === 0) {
890
- throw new TypeError('Expected deviceId to be a non-empty string, null, or undefined');
891
- }
892
- nextDeviceId = deviceId;
893
- }
992
+ const nextDeviceId = normalizeDeviceIdArg(deviceId);
894
993
  if (closed)
895
994
  return 'off';
896
995
  if (inFlightMic !== null) {
@@ -898,11 +997,19 @@ export function createVoice(room, options) {
898
997
  switchEpoch++;
899
998
  inFlightMic = null;
900
999
  selectedDeviceId = nextDeviceId;
1000
+ selectedDeviceExact = nextDeviceId !== null;
901
1001
  return acquireMic();
902
1002
  }
903
1003
  if (!localStream || (micStatus !== 'live' && micStatus !== 'muted')) {
904
- if (selectedDeviceId !== nextDeviceId) {
905
- selectedDeviceId = nextDeviceId;
1004
+ const hadError = micStatus === 'error' || micError !== null;
1005
+ const deviceChanged = selectedDeviceId !== nextDeviceId;
1006
+ selectedDeviceId = nextDeviceId;
1007
+ selectedDeviceExact = nextDeviceId !== null;
1008
+ if (hadError) {
1009
+ micStatus = 'off';
1010
+ micError = null;
1011
+ }
1012
+ if (hadError || deviceChanged) {
906
1013
  emitChange();
907
1014
  }
908
1015
  return micStatus;
@@ -923,7 +1030,7 @@ export function createVoice(room, options) {
923
1030
  let newStream;
924
1031
  try {
925
1032
  newStream = await navigator.mediaDevices.getUserMedia({
926
- audio: buildAudioConstraints(nextDeviceId)
1033
+ audio: buildAudioConstraints(nextDeviceId, nextDeviceId !== null)
927
1034
  });
928
1035
  }
929
1036
  catch (err) {
@@ -1022,6 +1129,7 @@ export function createVoice(room, options) {
1022
1129
  selectedDeviceId =
1023
1130
  nextDeviceId ??
1024
1131
  (typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null);
1132
+ selectedDeviceExact = nextDeviceId !== null;
1025
1133
  micError = null;
1026
1134
  emitChange();
1027
1135
  resultStatus = micStatus;
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
@@ -193,7 +193,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
193
193
  - `0x01` `SET`: `[0x01, seq, ...codec.encode(value)]`
194
194
  - `0x02` `CLEAR`: `[0x02, seq]` (exact 5 bytes).
195
195
  - Live `set(value)` uses `options.delivery` (`'reliable'` default or `'unreliable'`), while `options.initial`, `onPeerJoin` hydration, and `clear()` always transmit on the `'reliable'` channel for `name`. Both channels feed a single per-peer RFC 1982 `u32` sequence table (`lastSeqByPeer`), updated only after `codec.decode` succeeds (`!== undefined`), so out-of-order unreliable packets or racing hydration frames never regress state or resurrect cleared state.
196
- - When `coalesce` is `true` (default), `createPeerState` retains only the single latest encoded frame (`O(1)` memory) and flushes `'busy'` peers on `room.onDrain` (keeping `dirtyReliable` independent of unreliable `'accepted'` returns so UDP loss cannot drop pending reliable hydrations). Disconnecting peers (`onPeerLeave`) are automatically removed and emit `onChange(peerId, undefined, prev)`.
196
+ - When `coalesce` is `true` (default), `createPeerState` retains only the single latest encoded frame (`O(1)` memory) and flushes `'busy'` peers on `room.onDrain` (keeping `dirtyReliable` independent of unreliable `'accepted'` returns so UDP loss cannot drop pending reliable hydrations). `onChange(peerId, next, prev, reason)` passes `reason` (`'set' | 'clear' | 'leave'`) so apps can distinguish explicit `clear()` from `onPeerLeave` without relying on listener registration order; disconnecting peers (`onPeerLeave`) are automatically removed and emit `onChange(peerId, undefined, prev, 'leave')`.
197
197
 
198
198
  ### Chunked transfers (`createBlobChannel`)
199
199
 
@@ -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.1",
3
+ "version": "0.5.0",
4
4
  "author": "Dmitrij Koniajev",
5
5
  "license": "MIT",
6
6
  "type": "module",