@dimchansky/meshpost 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/state.js ADDED
@@ -0,0 +1,305 @@
1
+ import { createChannel, isValidCodec, jsonCodec } from './channel.js';
2
+ import { isRoomClosed, onRoomClose } from './room.js';
3
+ const opSet = 0x01;
4
+ const opClear = 0x02;
5
+ const headerBytes = 5;
6
+ const maxPacketBytes = 16 * 1024;
7
+ const encoder = new TextEncoder();
8
+ function isNewerSeq(incoming, prev) {
9
+ if (prev === undefined)
10
+ return true;
11
+ if (incoming === prev)
12
+ return false;
13
+ return (incoming - prev) >>> 0 < 0x8000_0000;
14
+ }
15
+ function buildSetFrame(seq, payload) {
16
+ const frame = new Uint8Array(headerBytes + payload.byteLength);
17
+ frame[0] = opSet;
18
+ new DataView(frame.buffer).setUint32(1, seq >>> 0);
19
+ frame.set(payload, headerBytes);
20
+ return frame;
21
+ }
22
+ function buildClearFrame(seq) {
23
+ const frame = new Uint8Array(headerBytes);
24
+ frame[0] = opClear;
25
+ new DataView(frame.buffer).setUint32(1, seq >>> 0);
26
+ return frame;
27
+ }
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
+ }
75
+ /**
76
+ * Create a single-writer per-peer state synchronization store over a named logical channel.
77
+ * Filters out-of-order updates via RFC 1982 `u32` sequence numbers, hydrates state reliably
78
+ * on `room.onPeerJoin`, cleans up on `room.onPeerLeave`, and optionally coalesces `'busy'` updates on `room.onDrain`.
79
+ */
80
+ export function createPeerState(room, name, options = {}) {
81
+ if (!room ||
82
+ typeof room !== 'object' ||
83
+ typeof room.onPeerJoin !== 'function' ||
84
+ typeof room.onPeerLeave !== 'function' ||
85
+ typeof room.onDrain !== 'function' ||
86
+ !Array.isArray(room.peers)) {
87
+ throw new TypeError('Invalid room');
88
+ }
89
+ const delivery = options.delivery ?? 'reliable';
90
+ if (delivery !== 'unreliable' && delivery !== 'reliable') {
91
+ throw new TypeError('Invalid delivery mode');
92
+ }
93
+ const coalesce = options.coalesce ?? true;
94
+ if (typeof coalesce !== 'boolean') {
95
+ throw new TypeError('Invalid coalesce option');
96
+ }
97
+ const codec = options.codec !== undefined ? options.codec : jsonCodec();
98
+ if (!isValidCodec(codec))
99
+ throw new TypeError('Invalid codec');
100
+ const reliableChannel = createChannel(room, name, { delivery: 'reliable' });
101
+ const liveChannel = delivery === 'unreliable'
102
+ ? createChannel(room, name, { delivery: 'unreliable' })
103
+ : reliableChannel;
104
+ const nameBytesLen = encoder.encode(name).length;
105
+ const maxPayloadBytes = maxPacketBytes - (1 + nameBytesLen) - headerBytes;
106
+ const encodeValidated = (value) => {
107
+ if (value === undefined) {
108
+ throw new TypeError('PeerState value cannot be undefined; call clear() instead');
109
+ }
110
+ const bytes = codec.encode(value);
111
+ if (!(bytes instanceof Uint8Array)) {
112
+ throw new TypeError('Codec encode() must return a Uint8Array');
113
+ }
114
+ if (bytes.byteLength > maxPayloadBytes) {
115
+ throw new RangeError('Encoded peer state exceeds 16 KiB packet limit');
116
+ }
117
+ return bytes;
118
+ };
119
+ let selfState;
120
+ let hasSelfState = false;
121
+ let localSeq = 0;
122
+ let currentFrame;
123
+ if (options.initial !== undefined) {
124
+ const initialBytes = encodeValidated(options.initial);
125
+ localSeq = (localSeq + 1) >>> 0;
126
+ selfState = options.initial;
127
+ hasSelfState = true;
128
+ currentFrame = buildSetFrame(localSeq, initialBytes);
129
+ }
130
+ const peersState = new Map();
131
+ const lastSeqByPeer = new Map();
132
+ const dirtyLive = new Set();
133
+ const dirtyReliable = new Set();
134
+ const changes = listeners();
135
+ let closed = isRoomClosed(room);
136
+ if (closed)
137
+ changes.clear();
138
+ const internalAbort = new AbortController();
139
+ const nextSeq = () => {
140
+ localSeq = (localSeq + 1) >>> 0;
141
+ return localSeq;
142
+ };
143
+ const recordReliableResults = (results) => {
144
+ if (!coalesce)
145
+ return;
146
+ for (const [peerId, status] of results) {
147
+ if (status === 'busy') {
148
+ dirtyReliable.add(peerId);
149
+ }
150
+ else {
151
+ dirtyReliable.delete(peerId);
152
+ dirtyLive.delete(peerId);
153
+ }
154
+ }
155
+ };
156
+ const recordUnreliableResults = (results) => {
157
+ if (!coalesce)
158
+ return;
159
+ for (const [peerId, status] of results) {
160
+ if (status === 'busy') {
161
+ dirtyLive.add(peerId);
162
+ }
163
+ else {
164
+ dirtyLive.delete(peerId);
165
+ }
166
+ }
167
+ };
168
+ const handleFrame = (from, bytes) => {
169
+ if (closed || bytes.byteLength < headerBytes || !room.peers.includes(from))
170
+ return;
171
+ const op = bytes[0];
172
+ const seq = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(1);
173
+ if (!isNewerSeq(seq, lastSeqByPeer.get(from)))
174
+ return;
175
+ if (op === opSet) {
176
+ let decoded;
177
+ try {
178
+ decoded = codec.decode(bytes.subarray(headerBytes));
179
+ }
180
+ catch {
181
+ return;
182
+ }
183
+ if (decoded === undefined)
184
+ return;
185
+ lastSeqByPeer.set(from, seq);
186
+ const prev = peersState.get(from);
187
+ peersState.set(from, decoded);
188
+ changes.fire(from, decoded, prev);
189
+ }
190
+ else if (op === opClear) {
191
+ if (bytes.byteLength !== headerBytes)
192
+ return;
193
+ lastSeqByPeer.set(from, seq);
194
+ if (peersState.has(from)) {
195
+ const prev = peersState.get(from);
196
+ peersState.delete(from);
197
+ changes.fire(from, undefined, prev);
198
+ }
199
+ }
200
+ };
201
+ const shutdown = () => {
202
+ if (closed)
203
+ return;
204
+ closed = true;
205
+ internalAbort.abort();
206
+ offRoomClose();
207
+ changes.clear();
208
+ peersState.clear();
209
+ lastSeqByPeer.clear();
210
+ dirtyLive.clear();
211
+ dirtyReliable.clear();
212
+ currentFrame = undefined;
213
+ };
214
+ const offRoomClose = closed ? () => { } : onRoomClose(room, shutdown);
215
+ if (!closed) {
216
+ const internalListen = { signal: internalAbort.signal };
217
+ reliableChannel.onPacket(handleFrame, internalListen);
218
+ if (liveChannel !== reliableChannel) {
219
+ liveChannel.onPacket(handleFrame, internalListen);
220
+ }
221
+ room.onPeerJoin((peerId) => {
222
+ lastSeqByPeer.delete(peerId);
223
+ if (hasSelfState && currentFrame) {
224
+ recordReliableResults(reliableChannel.send(currentFrame, { to: peerId }));
225
+ }
226
+ }, internalListen);
227
+ room.onPeerLeave((peerId) => {
228
+ lastSeqByPeer.delete(peerId);
229
+ dirtyLive.delete(peerId);
230
+ dirtyReliable.delete(peerId);
231
+ if (peersState.has(peerId)) {
232
+ const prev = peersState.get(peerId);
233
+ peersState.delete(peerId);
234
+ changes.fire(peerId, undefined, prev);
235
+ }
236
+ }, internalListen);
237
+ if (coalesce) {
238
+ room.onDrain((peerId, mode) => {
239
+ if (closed || !currentFrame || !room.peers.includes(peerId)) {
240
+ dirtyLive.delete(peerId);
241
+ dirtyReliable.delete(peerId);
242
+ return;
243
+ }
244
+ if (mode === 'reliable' && dirtyReliable.has(peerId)) {
245
+ recordReliableResults(reliableChannel.send(currentFrame, { to: peerId }));
246
+ }
247
+ else if (mode === 'unreliable' &&
248
+ delivery === 'unreliable' &&
249
+ dirtyLive.has(peerId) &&
250
+ hasSelfState) {
251
+ recordUnreliableResults(liveChannel.send(currentFrame, { to: peerId }));
252
+ }
253
+ }, internalListen);
254
+ }
255
+ if (hasSelfState && currentFrame && room.peers.length > 0) {
256
+ recordReliableResults(reliableChannel.send(currentFrame));
257
+ }
258
+ }
259
+ return {
260
+ name: reliableChannel.name,
261
+ delivery,
262
+ getSelf() {
263
+ return selfState;
264
+ },
265
+ get(peerId) {
266
+ return peersState.get(peerId);
267
+ },
268
+ getAll() {
269
+ return new Map(peersState);
270
+ },
271
+ set(value) {
272
+ if (closed || isRoomClosed(room)) {
273
+ shutdown();
274
+ throw new Error('PeerState is closed');
275
+ }
276
+ const encoded = encodeValidated(value);
277
+ const seq = nextSeq();
278
+ selfState = value;
279
+ hasSelfState = true;
280
+ currentFrame = buildSetFrame(seq, encoded);
281
+ const results = liveChannel.send(currentFrame);
282
+ if (delivery === 'reliable')
283
+ recordReliableResults(results);
284
+ else
285
+ recordUnreliableResults(results);
286
+ return results;
287
+ },
288
+ clear() {
289
+ if (closed || isRoomClosed(room)) {
290
+ shutdown();
291
+ throw new Error('PeerState is closed');
292
+ }
293
+ const seq = nextSeq();
294
+ selfState = undefined;
295
+ hasSelfState = false;
296
+ currentFrame = buildClearFrame(seq);
297
+ dirtyLive.clear();
298
+ const results = reliableChannel.send(currentFrame);
299
+ recordReliableResults(results);
300
+ return results;
301
+ },
302
+ onChange: changes.add,
303
+ close: shutdown
304
+ };
305
+ }
package/dist/tabs.js CHANGED
@@ -10,7 +10,14 @@ export function tabSignaling() {
10
10
  const channel = new BroadcastChannel('meshpost/1/' + namespaceHash(scope));
11
11
  const seen = new Map();
12
12
  let closed = false;
13
- const post = (body) => channel.postMessage({ ...body, from: discovery.self });
13
+ const post = (body) => {
14
+ try {
15
+ channel.postMessage({ ...body, from: discovery.self });
16
+ }
17
+ catch {
18
+ // Ignore asynchronous partition or bfcache restrictions.
19
+ }
20
+ };
14
21
  const roster = () => discovery.roster([...seen.keys()]);
15
22
  const touch = (id) => {
16
23
  const known = seen.has(id);
package/dist/turn.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export interface FetchTurnOptions {
2
+ /** Optional shared Bearer token sent in the `Authorization` header. */
3
+ accessKey?: string;
4
+ /** Optional external AbortSignal to cancel the request. */
5
+ signal?: AbortSignal;
6
+ /** Request timeout in milliseconds. Pass `0` to disable timeout. @default 5000 */
7
+ timeoutMs?: number;
8
+ }
9
+ /**
10
+ * Fetch short-lived TURN credentials from an HTTPS broker (`POST` returning `{ iceServers }`),
11
+ * such as Meshpost's reference Cloudflare Worker (`examples/turn-worker/worker.js`).
12
+ */
13
+ export declare function fetchTurnCredentials(url: string, options?: FetchTurnOptions): Promise<RTCIceServer[]>;
package/dist/turn.js ADDED
@@ -0,0 +1,213 @@
1
+ const maxTimeoutMs = 2_147_483_647;
2
+ const defaultTimeoutMs = 5_000;
3
+ const maxAccessKeyLength = 1024;
4
+ const maxResponseBytes = 64 * 1024;
5
+ const maxIceServers = 16;
6
+ const maxUrlsPerServer = 8;
7
+ const maxIceUrlLength = 256;
8
+ const maxCredentialLength = 512;
9
+ const iceUrlPattern = /^(stuns?|turns?):[^\s]+$/i;
10
+ const headerControlPattern = /[\r\n\0]/;
11
+ const decoder = new TextDecoder();
12
+ function validateBrokerUrl(rawUrl) {
13
+ if (typeof rawUrl !== 'string') {
14
+ throw new TypeError('TURN broker URL must be a string');
15
+ }
16
+ const trimmed = rawUrl.trim();
17
+ if (!trimmed) {
18
+ throw new TypeError('TURN broker URL must not be empty');
19
+ }
20
+ let parsed;
21
+ try {
22
+ parsed = new URL(trimmed);
23
+ }
24
+ catch {
25
+ throw new TypeError('TURN broker URL must be a valid https:// URL');
26
+ }
27
+ const isLoopbackHttp = parsed.protocol === 'http:' &&
28
+ (parsed.hostname === 'localhost' ||
29
+ parsed.hostname === '127.0.0.1' ||
30
+ parsed.hostname === '[::1]');
31
+ if (parsed.protocol !== 'https:' && !isLoopbackHttp) {
32
+ throw new TypeError('TURN broker URL must use https:// (or http://localhost for local testing)');
33
+ }
34
+ if (parsed.username || parsed.password) {
35
+ throw new TypeError('TURN broker URL must not include embedded credentials');
36
+ }
37
+ return parsed.href;
38
+ }
39
+ function validateAccessKey(accessKey) {
40
+ if (accessKey === undefined)
41
+ return null;
42
+ if (typeof accessKey !== 'string') {
43
+ throw new TypeError('TURN access key must be a string');
44
+ }
45
+ if (accessKey.length > maxAccessKeyLength || headerControlPattern.test(accessKey)) {
46
+ throw new TypeError('Invalid TURN access key');
47
+ }
48
+ const trimmed = accessKey.trim();
49
+ return trimmed.length > 0 ? trimmed : null;
50
+ }
51
+ async function readBoundedText(response) {
52
+ const contentLength = response.headers.get('content-length');
53
+ if (contentLength !== null) {
54
+ const declared = Number(contentLength);
55
+ if (Number.isFinite(declared) && declared > maxResponseBytes) {
56
+ void response.body?.cancel().catch(() => { });
57
+ throw new Error('TURN broker response exceeded 64 KiB limit');
58
+ }
59
+ }
60
+ const reader = response.body?.getReader();
61
+ if (!reader) {
62
+ const buf = new Uint8Array(await response.arrayBuffer());
63
+ if (buf.byteLength > maxResponseBytes) {
64
+ throw new Error('TURN broker response exceeded 64 KiB limit');
65
+ }
66
+ return decoder.decode(buf);
67
+ }
68
+ const chunks = [];
69
+ let total = 0;
70
+ for (;;) {
71
+ const { done, value } = await reader.read();
72
+ if (done)
73
+ break;
74
+ if (!value || value.byteLength === 0)
75
+ continue;
76
+ total += value.byteLength;
77
+ if (total > maxResponseBytes) {
78
+ void reader.cancel().catch(() => { });
79
+ throw new Error('TURN broker response exceeded 64 KiB limit');
80
+ }
81
+ chunks.push(value);
82
+ }
83
+ if (chunks.length === 0)
84
+ return '';
85
+ if (chunks.length === 1)
86
+ return decoder.decode(chunks[0]);
87
+ const merged = new Uint8Array(total);
88
+ let offset = 0;
89
+ for (const chunk of chunks) {
90
+ merged.set(chunk, offset);
91
+ offset += chunk.byteLength;
92
+ }
93
+ return decoder.decode(merged);
94
+ }
95
+ function sanitizeIceServers(raw) {
96
+ if (!Array.isArray(raw))
97
+ return [];
98
+ const valid = [];
99
+ for (const item of raw) {
100
+ if (!item || typeof item !== 'object' || Array.isArray(item))
101
+ continue;
102
+ const entry = item;
103
+ const rawUrls = Array.isArray(entry.urls) ? entry.urls : [entry.urls];
104
+ const urls = [];
105
+ for (const candidate of rawUrls) {
106
+ if (typeof candidate !== 'string')
107
+ continue;
108
+ const trimmed = candidate.trim();
109
+ if (trimmed.length > 0 && trimmed.length <= maxIceUrlLength && iceUrlPattern.test(trimmed)) {
110
+ urls.push(trimmed);
111
+ if (urls.length >= maxUrlsPerServer)
112
+ break;
113
+ }
114
+ }
115
+ if (urls.length === 0)
116
+ continue;
117
+ const server = { urls: urls.length === 1 ? urls[0] : urls };
118
+ if (typeof entry.username === 'string' &&
119
+ entry.username.length > 0 &&
120
+ entry.username.length <= maxCredentialLength) {
121
+ server.username = entry.username;
122
+ }
123
+ if (typeof entry.credential === 'string' &&
124
+ entry.credential.length > 0 &&
125
+ entry.credential.length <= maxCredentialLength) {
126
+ server.credential = entry.credential;
127
+ }
128
+ valid.push(server);
129
+ if (valid.length >= maxIceServers)
130
+ break;
131
+ }
132
+ return valid;
133
+ }
134
+ /**
135
+ * Fetch short-lived TURN credentials from an HTTPS broker (`POST` returning `{ iceServers }`),
136
+ * such as Meshpost's reference Cloudflare Worker (`examples/turn-worker/worker.js`).
137
+ */
138
+ export async function fetchTurnCredentials(url, options) {
139
+ const validatedUrl = validateBrokerUrl(url);
140
+ const token = validateAccessKey(options?.accessKey);
141
+ const timeoutMs = options?.timeoutMs ?? defaultTimeoutMs;
142
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > maxTimeoutMs) {
143
+ throw new RangeError('Expected a safe integer timeoutMs between 0 and 2147483647');
144
+ }
145
+ const externalSignal = options?.signal;
146
+ if (externalSignal?.aborted) {
147
+ throw externalSignal.reason ?? new DOMException('The operation was aborted.', 'AbortError');
148
+ }
149
+ const controller = new AbortController();
150
+ let timedOut = false;
151
+ let timer;
152
+ const onExternalAbort = () => {
153
+ controller.abort(externalSignal?.reason ?? new DOMException('The operation was aborted.', 'AbortError'));
154
+ };
155
+ if (externalSignal) {
156
+ externalSignal.addEventListener('abort', onExternalAbort, { once: true });
157
+ }
158
+ if (timeoutMs > 0) {
159
+ timer = setTimeout(() => {
160
+ timedOut = true;
161
+ controller.abort(new DOMException('TURN credential request timed out', 'TimeoutError'));
162
+ }, timeoutMs);
163
+ }
164
+ const headers = {};
165
+ if (token !== null) {
166
+ headers.Authorization = `Bearer ${token}`;
167
+ }
168
+ try {
169
+ const response = await fetch(validatedUrl, {
170
+ method: 'POST',
171
+ headers,
172
+ signal: controller.signal,
173
+ redirect: 'error',
174
+ credentials: 'omit',
175
+ cache: 'no-store'
176
+ });
177
+ if (!response.ok) {
178
+ void response.body?.cancel().catch(() => { });
179
+ if (response.status === 401)
180
+ throw new Error('TURN access key rejected (401)');
181
+ if (response.status === 403)
182
+ throw new Error('TURN broker rejected this origin (403)');
183
+ throw new Error(`TURN broker failed with HTTP ${response.status}`);
184
+ }
185
+ const rawText = await readBoundedText(response);
186
+ let parsed;
187
+ try {
188
+ parsed = JSON.parse(rawText);
189
+ }
190
+ catch {
191
+ throw new Error('TURN broker returned invalid JSON');
192
+ }
193
+ const servers = sanitizeIceServers(parsed && typeof parsed === 'object' ? parsed.iceServers : null);
194
+ if (servers.length === 0) {
195
+ throw new Error('TURN broker returned no valid ICE servers');
196
+ }
197
+ return servers;
198
+ }
199
+ catch (error) {
200
+ if (timedOut) {
201
+ throw new DOMException('TURN credential request timed out', 'TimeoutError');
202
+ }
203
+ if (externalSignal?.aborted) {
204
+ throw externalSignal.reason ?? new DOMException('The operation was aborted.', 'AbortError');
205
+ }
206
+ throw error;
207
+ }
208
+ finally {
209
+ if (timer !== undefined)
210
+ clearTimeout(timer);
211
+ externalSignal?.removeEventListener('abort', onExternalAbort);
212
+ }
213
+ }
@@ -0,0 +1,108 @@
1
+ import { type ListenOptions, type Room } from './room.js';
2
+ /** Current state of the local microphone managed by `createVoice()`. */
3
+ export type MicStatus = 'off' | 'requesting' | 'live' | 'muted' | 'error';
4
+ /** Structured error codes describing why local microphone capture failed. */
5
+ export type MicErrorCode = 'permission-denied' | 'not-found' | 'in-use' | 'insecure-context' | 'room-closed' | 'unknown';
6
+ /** Structured microphone capture error exposed on `voice.micError`. */
7
+ export interface MicError {
8
+ readonly code: MicErrorCode;
9
+ readonly message: string;
10
+ }
11
+ /** Immutable state snapshot emitted by `voice.getSnapshot()` and `voice.onChange()`. */
12
+ export interface VoiceSnapshot {
13
+ readonly micStatus: MicStatus;
14
+ readonly micError: MicError | null;
15
+ readonly deviceId: string | null;
16
+ readonly autoplayBlocked: boolean;
17
+ readonly deafened: boolean;
18
+ readonly volume: number;
19
+ readonly selfSpeaking: boolean;
20
+ readonly remotePeers: readonly string[];
21
+ readonly speakingPeers: readonly string[];
22
+ readonly mutedPeers: readonly string[];
23
+ }
24
+ /** Configuration options for `createVoice()`. */
25
+ export interface VoiceOptions {
26
+ /** Initial playback volume for incoming peer audio (`0` to `1`). @default 1 */
27
+ volume?: number;
28
+ /** Start with incoming peer audio muted locally (`audio.muted = true`). @default false */
29
+ deafened?: boolean;
30
+ /**
31
+ * Custom audio track constraints passed to `getUserMedia`.
32
+ * @default { echoCancellation: true, noiseSuppression: true, autoGainControl: true }
33
+ */
34
+ audioConstraints?: MediaTrackConstraints | true;
35
+ /** Automatically attach global capture-phase gesture & visibility listeners to unlock blocked playback. @default true */
36
+ autoUnlock?: boolean;
37
+ /** Enable shared lazy AudioContext + AnalyserNode speaking detection (`selfSpeaking` & `speakingPeers`). @default true */
38
+ speakingDetection?: boolean;
39
+ /** RMS amplitude threshold (`0` to `1`) for speaking detection. @default 0.03 */
40
+ speakingThreshold?: number;
41
+ /** Polling interval in milliseconds (`50` to `60000`) for speaking detection. @default 180 */
42
+ speakingIntervalMs?: number;
43
+ /** Optional target peer ID scoping outgoing microphone audio only (`room.addStream(stream, { to })`). Incoming audio from all peers still plays. */
44
+ to?: string;
45
+ /**
46
+ * Stream tag attached to outgoing microphone streams and matched on incoming streams.
47
+ * Incoming audio streams whose `meta.tag` equals `streamTag` (or is `undefined` when
48
+ * `strictStreamTag` is `false`) are played; streams tagged with another value (e.g. `'screen'`) are ignored.
49
+ * @default 'voice'
50
+ */
51
+ streamTag?: string;
52
+ /**
53
+ * When `true`, ignore untagged (`meta.tag === undefined`) incoming audio streams as well.
54
+ * @default false
55
+ */
56
+ strictStreamTag?: boolean;
57
+ }
58
+ /** Headless P2P voice chat controller built on top of a `Room`. */
59
+ export interface Voice extends VoiceSnapshot {
60
+ /** Return an immutable snapshot of all current voice states. */
61
+ getSnapshot(): VoiceSnapshot;
62
+ /**
63
+ * Acquire microphone on first call (`'off' | 'error'` -> `'requesting'` -> `'live'`),
64
+ * or toggle instant soft-mute (`track.enabled`) without WebRTC renegotiation (`'live'` <-> `'muted'`).
65
+ * Concurrent calls while `'requesting'` coalesce onto the in-flight request. Resolves to `'off'` if closed.
66
+ */
67
+ toggleMic(): Promise<MicStatus>;
68
+ /**
69
+ * Acquire microphone if not active, or unmute if currently soft-muted.
70
+ * Concurrent calls while `'requesting'` coalesce onto the in-flight request. Resolves to `'off'` if closed.
71
+ */
72
+ startMic(): Promise<MicStatus>;
73
+ /** Soft-mute (`true`) or unmute (`false`) an already-acquired local microphone (`'live' | 'muted'`). No-op otherwise. */
74
+ setMuted(muted: boolean): void;
75
+ /** Detach local stream from the room (`room.removeStream`), cancel any in-flight `getUserMedia`, and stop hardware microphone tracks (`track.stop()`). */
76
+ stopMic(): void;
77
+ /**
78
+ * Select or hot-swap the local microphone input device (`deviceId`, or `null`/`undefined`/`''` for system default).
79
+ * When `'live'` or `'muted'`, swaps the active track via `room.replaceStreamTrack()` without SDP renegotiation.
80
+ */
81
+ switchDevice(deviceId?: string | null): Promise<MicStatus>;
82
+ /** Set playback volume (`0` to `1`, clamped) on all current and future remote `<audio>` elements. */
83
+ setVolume(volume: number): void;
84
+ /** Set local playback volume (`0` to `1`, clamped, scaled by master `voice.volume`) for a specific peer. */
85
+ setPeerVolume(peerId: string, volume: number): void;
86
+ /** Read local playback volume (`0` to `1`, default `1`) configured for a specific peer. */
87
+ getPeerVolume(peerId: string): number;
88
+ /** Mute (`true`) or unmute (`false`) all incoming remote `<audio>` elements locally. Unmuting also triggers `unlockAudio()`. */
89
+ setDeafened(deafened: boolean): void;
90
+ /** Locally mute (`true`) or unmute (`false`) incoming audio from a specific peer (independent of `deafened`). */
91
+ setPeerMuted(peerId: string, muted: boolean): void;
92
+ /** Check whether a specific peer is locally muted via `setPeerMuted()`. */
93
+ isPeerMuted(peerId: string): boolean;
94
+ /** Manually trigger synchronous `AudioContext.resume()` + `audio.play()` retry. */
95
+ unlockAudio(): void;
96
+ /** Subscribe to any state change in `VoiceSnapshot`. Supports `ListenOptions` (`{ once, signal }`). */
97
+ onChange(fn: (snapshot: VoiceSnapshot) => void, options?: ListenOptions): () => void;
98
+ /** Release microphone tracks, remove hidden `<audio>` elements, close `AudioContext`, restore `audioSession`, and detach all listeners. */
99
+ close(): void;
100
+ }
101
+ /**
102
+ * Create a headless P2P voice chat controller attached to a `Room`.
103
+ *
104
+ * Automatically plays incoming peer audio streams, manages local microphone capture with instant
105
+ * soft-mute (`track.enabled`) vs full hardware release, tracks speaking peers via a shared lazy
106
+ * `AudioContext`, and handles browser Autoplay Policy & iOS Safari audio unlocking.
107
+ */
108
+ export declare function createVoice(room: Room, options?: VoiceOptions): Voice;