@dimchansky/meshpost 0.4.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +66 -550
  2. package/dist/bip340.d.ts +1 -0
  3. package/dist/bip340.js +346 -0
  4. package/dist/blob.d.ts +1 -1
  5. package/dist/blob.js +15 -16
  6. package/dist/channel.js +15 -44
  7. package/dist/combine.js +25 -39
  8. package/dist/crypto.js +10 -9
  9. package/dist/identity.d.ts +45 -0
  10. package/dist/identity.js +188 -28
  11. package/dist/index.d.ts +6 -6
  12. package/dist/index.js +3 -3
  13. package/dist/listeners.js +18 -3
  14. package/dist/mqtt.js +193 -408
  15. package/dist/nostr.js +163 -745
  16. package/dist/public.d.ts +19 -1
  17. package/dist/public.js +26 -9
  18. package/dist/relay-core.d.ts +1 -0
  19. package/dist/relay-core.js +323 -0
  20. package/dist/room-hello.d.ts +1 -0
  21. package/dist/room-hello.js +129 -0
  22. package/dist/room-ice.d.ts +1 -0
  23. package/dist/room-ice.js +115 -0
  24. package/dist/room-media.d.ts +1 -0
  25. package/dist/room-media.js +477 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +111 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +109 -919
  31. package/dist/signaling.d.ts +8 -0
  32. package/dist/signaling.js +64 -0
  33. package/dist/state.js +1 -2
  34. package/dist/voice-helpers.d.ts +1 -0
  35. package/dist/voice-helpers.js +100 -0
  36. package/dist/voice-meter.d.ts +1 -0
  37. package/dist/voice-meter.js +79 -0
  38. package/dist/voice.d.ts +41 -0
  39. package/dist/voice.js +205 -273
  40. package/dist/ws.js +60 -146
  41. package/docs/api.md +217 -0
  42. package/docs/behavior.md +16 -9
  43. package/docs/guide.md +404 -0
  44. package/docs/signaling-and-production.md +312 -0
  45. package/docs/voice-and-media.md +193 -0
  46. package/package.json +3 -2
@@ -69,3 +69,11 @@ export declare function isSignal(value: unknown): value is Signal;
69
69
  * Preserve the original candidate and its priority. Never transmit this local hint.
70
70
  */
71
71
  export declare function withLoopbackFallback<T extends Signal>(signal: T): T;
72
+ /**
73
+ * Decorate any `Signaling` adapter to observe per-session `SignalingState` transitions
74
+ * (`'connecting'`, `'online'`, `'offline'`, `'closed'`) without altering `Room` or `Discovery`.
75
+ *
76
+ * - Deduplicates repeated consecutive states and isolates callback errors via `reportError`.
77
+ * - Preserves `trickle` and `canReach` on the underlying `SignalingSession`.
78
+ */
79
+ export declare function observeSignaling(adapter: Signaling, onChange: (state: SignalingState, reason?: string) => void): Signaling;
package/dist/signaling.js CHANGED
@@ -124,3 +124,67 @@ export function withLoopbackFallback(signal) {
124
124
  }
125
125
  return index ? { ...signal, sdp: lines.join(eol) } : signal;
126
126
  }
127
+ function reportObserverError(error) {
128
+ if (typeof globalThis.reportError === 'function') {
129
+ globalThis.reportError(error);
130
+ }
131
+ else {
132
+ queueMicrotask(() => {
133
+ throw error;
134
+ });
135
+ }
136
+ }
137
+ /**
138
+ * Decorate any `Signaling` adapter to observe per-session `SignalingState` transitions
139
+ * (`'connecting'`, `'online'`, `'offline'`, `'closed'`) without altering `Room` or `Discovery`.
140
+ *
141
+ * - Deduplicates repeated consecutive states and isolates callback errors via `reportError`.
142
+ * - Preserves `trickle` and `canReach` on the underlying `SignalingSession`.
143
+ */
144
+ export function observeSignaling(adapter, onChange) {
145
+ if (typeof adapter !== 'function') {
146
+ throw new TypeError('Expected a signaling adapter function');
147
+ }
148
+ if (typeof onChange !== 'function') {
149
+ throw new TypeError('Expected an onChange callback function');
150
+ }
151
+ return (discovery) => {
152
+ let lastState;
153
+ let closed = false;
154
+ const emit = (state, reason) => {
155
+ if (state === lastState)
156
+ return;
157
+ lastState = state;
158
+ try {
159
+ onChange(state, reason);
160
+ }
161
+ catch (error) {
162
+ reportObserverError(error);
163
+ }
164
+ };
165
+ const session = adapter({
166
+ ...discovery,
167
+ status(state, reason) {
168
+ if (closed)
169
+ return;
170
+ emit(state, reason);
171
+ discovery.status(state, reason);
172
+ }
173
+ });
174
+ if (!closed && lastState === undefined) {
175
+ emit('connecting');
176
+ }
177
+ return {
178
+ ...(session.trickle !== undefined ? { trickle: session.trickle } : {}),
179
+ ...(session.canReach ? { canReach: (peerId) => session.canReach(peerId) } : {}),
180
+ send: (to, signal) => session.send(to, signal),
181
+ close() {
182
+ if (closed)
183
+ return;
184
+ closed = true;
185
+ session.close();
186
+ emit('closed');
187
+ }
188
+ };
189
+ };
190
+ }
package/dist/state.js CHANGED
@@ -26,7 +26,6 @@ function buildClearFrame(seq) {
26
26
  new DataView(frame.buffer).setUint32(1, seq >>> 0);
27
27
  return frame;
28
28
  }
29
- const listeners = createListeners;
30
29
  /**
31
30
  * Create a single-writer per-peer state synchronization store over a named logical channel.
32
31
  * Filters out-of-order updates via RFC 1982 `u32` sequence numbers, hydrates state reliably
@@ -86,7 +85,7 @@ export function createPeerState(room, name, options = {}) {
86
85
  const lastSeqByPeer = new Map();
87
86
  const dirtyLive = new Set();
88
87
  const dirtyReliable = new Set();
89
- const changes = listeners();
88
+ const changes = createListeners();
90
89
  let closed = isRoomClosed(room);
91
90
  if (closed)
92
91
  changes.clear();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,100 @@
1
+ /** @internal */
2
+ export const defaultAudioConstraints = Object.freeze({
3
+ echoCancellation: true,
4
+ noiseSuppression: true,
5
+ autoGainControl: true
6
+ });
7
+ /** @internal */
8
+ export function getIosAudioSession() {
9
+ if (typeof navigator === 'undefined')
10
+ return null;
11
+ const session = navigator.audioSession;
12
+ return session && typeof session === 'object' && typeof session.type === 'string' ? session : null;
13
+ }
14
+ /** @internal */
15
+ export function classifyMicError(err) {
16
+ const name = err && typeof err === 'object' && 'name' in err ? String(err.name) : '';
17
+ if (name === 'NotAllowedError' || name === 'PermissionDeniedError') {
18
+ return Object.freeze({
19
+ code: 'permission-denied',
20
+ message: 'Microphone permission denied'
21
+ });
22
+ }
23
+ if (name === 'NotFoundError' ||
24
+ name === 'DevicesNotFoundError' ||
25
+ name === 'OverconstrainedError' ||
26
+ name === 'ConstraintNotSatisfiedError') {
27
+ return Object.freeze({
28
+ code: 'not-found',
29
+ message: 'No matching microphone device found'
30
+ });
31
+ }
32
+ if (name === 'NotReadableError' || name === 'TrackStartError') {
33
+ return Object.freeze({
34
+ code: 'in-use',
35
+ message: 'Microphone is already in use by another application'
36
+ });
37
+ }
38
+ if (name === 'SecurityError') {
39
+ return Object.freeze({
40
+ code: 'insecure-context',
41
+ message: 'Microphone access requires HTTPS or localhost'
42
+ });
43
+ }
44
+ return Object.freeze({
45
+ code: 'unknown',
46
+ message: 'Could not access microphone'
47
+ });
48
+ }
49
+ /** @internal */
50
+ export function normalizeDeviceIdArg(deviceId) {
51
+ if (deviceId === undefined || deviceId === null || deviceId === '')
52
+ return null;
53
+ if (typeof deviceId !== 'string' || deviceId.trim().length === 0) {
54
+ throw new TypeError('Expected deviceId to be a non-empty string, null, or undefined');
55
+ }
56
+ return deviceId;
57
+ }
58
+ /** @internal */
59
+ export function buildAudioConstraints(baseConstraints, deviceOverride, exact) {
60
+ if (deviceOverride !== null) {
61
+ const base = typeof baseConstraints === 'object' ? { ...baseConstraints } : { ...defaultAudioConstraints };
62
+ base.deviceId = exact ? { exact: deviceOverride } : { ideal: deviceOverride };
63
+ return base;
64
+ }
65
+ if (baseConstraints === true)
66
+ return true;
67
+ const copy = { ...baseConstraints };
68
+ delete copy.deviceId;
69
+ return copy;
70
+ }
71
+ /** @internal */
72
+ export function applyAudioVolume(audio, volume) {
73
+ try {
74
+ audio.volume = volume;
75
+ }
76
+ catch {
77
+ // Ignore read-only volume property on certain iOS WebKit builds.
78
+ }
79
+ }
80
+ /** @internal */
81
+ export function validatePeerIdArg(peerId) {
82
+ if (typeof peerId !== 'string' || peerId.length === 0 || peerId.length > 128) {
83
+ throw new TypeError('Expected a non-empty peerId string');
84
+ }
85
+ }
86
+ /** @internal */
87
+ export function evictPeerPref(collection, activePeers, maxSize) {
88
+ if (collection.size < maxSize)
89
+ return;
90
+ let victim;
91
+ for (const k of collection.keys()) {
92
+ if (!activePeers.has(k)) {
93
+ victim = k;
94
+ break;
95
+ }
96
+ }
97
+ victim ??= collection.keys().next().value;
98
+ if (victim !== undefined)
99
+ collection.delete(victim);
100
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,79 @@
1
+ /** @internal */
2
+ export function createVoiceMeter(params) {
3
+ const { enabled, threshold, isClosed, onContextPaused, onContextRunning } = params;
4
+ let audioCtx = null;
5
+ let silentSink = null;
6
+ const isPaused = () => audioCtx !== null && audioCtx.state !== 'running' && audioCtx.state !== 'closed';
7
+ return {
8
+ isPaused,
9
+ resume(onResumed) {
10
+ if (!isPaused() || !audioCtx)
11
+ return;
12
+ void audioCtx
13
+ .resume()
14
+ .then(() => onResumed?.())
15
+ .catch(() => { });
16
+ },
17
+ createAnalyser(stream) {
18
+ if (!enabled || typeof AudioContext !== 'function')
19
+ return {};
20
+ try {
21
+ if (!audioCtx) {
22
+ const ctx = new AudioContext();
23
+ ctx.onstatechange = () => {
24
+ if (isClosed() || audioCtx !== ctx)
25
+ return;
26
+ if (isPaused())
27
+ onContextPaused();
28
+ else
29
+ onContextRunning();
30
+ };
31
+ const gain = ctx.createGain();
32
+ gain.gain.value = 0;
33
+ gain.connect(ctx.destination);
34
+ audioCtx = ctx;
35
+ silentSink = gain;
36
+ }
37
+ if (isPaused()) {
38
+ void audioCtx.resume().catch(() => { });
39
+ onContextPaused();
40
+ }
41
+ const source = audioCtx.createMediaStreamSource(stream);
42
+ const analyser = audioCtx.createAnalyser();
43
+ analyser.fftSize = 256;
44
+ source.connect(analyser);
45
+ if (silentSink)
46
+ analyser.connect(silentSink);
47
+ return { source, analyser, data: new Uint8Array(analyser.fftSize) };
48
+ }
49
+ catch {
50
+ return {};
51
+ }
52
+ },
53
+ isActive(entry) {
54
+ if (!entry?.analyser || !entry.data)
55
+ return false;
56
+ entry.analyser.getByteTimeDomainData(entry.data);
57
+ let sum = 0;
58
+ for (let i = 0; i < entry.data.length; i++) {
59
+ const d = (entry.data[i] - 128) / 128;
60
+ sum += d * d;
61
+ }
62
+ return Math.sqrt(sum / entry.data.length) > threshold;
63
+ },
64
+ disconnect(entry) {
65
+ entry?.source?.disconnect();
66
+ entry?.analyser?.disconnect();
67
+ },
68
+ closeContext() {
69
+ if (!audioCtx)
70
+ return;
71
+ const ctx = audioCtx;
72
+ audioCtx = null;
73
+ silentSink?.disconnect();
74
+ silentSink = null;
75
+ ctx.onstatechange = null;
76
+ void ctx.close().catch(() => { });
77
+ }
78
+ };
79
+ }
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,28 @@ 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
+ /** Options for `onAudioInputsChange()`. */
130
+ export interface AudioInputsChangeOptions extends ListenOptions {
131
+ /**
132
+ * Immediately run `listAudioInputs()` and invoke the listener using the same internal epoch
133
+ * guard as `'devicechange'` events (preventing out-of-order initial vs hot-plug races).
134
+ * @default false
135
+ */
136
+ immediate?: boolean;
137
+ }
138
+ /**
139
+ * Subscribe to `navigator.mediaDevices` `'devicechange'` events and receive the updated
140
+ * `listAudioInputs()` array (guarded against out-of-order async enumerations and supporting `ListenOptions`).
141
+ * Pass `{ immediate: true }` to also deliver the initial device list through the same race guard.
142
+ * Returns an idempotent unsubscribe function.
143
+ */
144
+ export declare function onAudioInputsChange(fn: (devices: readonly AudioInputDevice[]) => void, options?: AudioInputsChangeOptions): () => void;
104
145
  /**
105
146
  * Create a headless P2P voice chat controller attached to a `Room`.
106
147
  *