@dimchansky/meshpost 0.1.0 → 0.3.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 +169 -33
- package/dist/blob.d.ts +45 -0
- package/dist/blob.js +364 -0
- package/dist/channel.d.ts +2 -2
- package/dist/channel.js +11 -3
- package/dist/combine.d.ts +18 -0
- package/dist/combine.js +340 -0
- package/dist/index.d.ts +11 -2
- package/dist/index.js +5 -0
- package/dist/mqtt.js +33 -5
- package/dist/room.d.ts +38 -7
- package/dist/room.js +656 -57
- package/dist/signaling.d.ts +25 -1
- package/dist/signaling.js +49 -1
- package/dist/tabs.js +9 -1
- package/dist/turn.d.ts +13 -0
- package/dist/turn.js +213 -0
- package/dist/voice.d.ts +81 -0
- package/dist/voice.js +838 -0
- package/dist/ws.d.ts +14 -0
- package/dist/ws.js +272 -0
- package/docs/behavior.md +86 -14
- package/package.json +1 -1
package/dist/signaling.d.ts
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
/** Individual ICE candidate entry carried inside a Trickle ICE `'ice'` signal. */
|
|
2
|
+
export interface IceCandidatePayload {
|
|
3
|
+
/** SDP candidate attribute string (`''` signals end-of-candidates). */
|
|
4
|
+
readonly candidate: string;
|
|
5
|
+
/** Optional media stream identification tag. */
|
|
6
|
+
readonly sdpMid?: string | null;
|
|
7
|
+
/** Optional zero-based media description index. */
|
|
8
|
+
readonly sdpMLineIndex?: number | null;
|
|
9
|
+
}
|
|
1
10
|
/** Discovery supplies peer IDs. Only the two endpoints interpret the signal payload. */
|
|
2
11
|
export type Signal = {
|
|
3
12
|
kind: 'need';
|
|
@@ -6,9 +15,15 @@ export type Signal = {
|
|
|
6
15
|
kind: 'offer' | 'answer';
|
|
7
16
|
attempt: number;
|
|
8
17
|
sdp: string;
|
|
18
|
+
} | {
|
|
19
|
+
kind: 'ice';
|
|
20
|
+
attempt: number;
|
|
21
|
+
candidates: readonly IceCandidatePayload[];
|
|
9
22
|
};
|
|
10
23
|
/** Connection state reported by a signaling adapter. */
|
|
11
24
|
export type SignalingState = 'connecting' | 'online' | 'offline' | 'closed';
|
|
25
|
+
/** Structured error codes that a signaling adapter may report via `Discovery.error`. */
|
|
26
|
+
export type SignalingErrorCode = 'decrypt-failed' | 'signaling-error';
|
|
12
27
|
/** Callbacks and room metadata passed by `joinRoom()` into a `Signaling` adapter factory. */
|
|
13
28
|
export interface Discovery {
|
|
14
29
|
/** Application namespace isolating rooms across apps. */
|
|
@@ -25,9 +40,18 @@ export interface Discovery {
|
|
|
25
40
|
receive(from: string, signal: Signal): void;
|
|
26
41
|
/** Report a signaling state transition (with an optional human-readable reason). */
|
|
27
42
|
status(state: SignalingState, reason?: string): void;
|
|
43
|
+
/** Optional: report a structured signaling error (e.g. `'decrypt-failed'` or `'signaling-error'`). */
|
|
44
|
+
error?(code: SignalingErrorCode, message?: string): void;
|
|
28
45
|
}
|
|
29
46
|
/** Active signaling handle returned by a `Signaling` adapter factory. */
|
|
30
47
|
export interface SignalingSession {
|
|
48
|
+
/** Set `true` if this adapter supports incremental Trickle ICE (`{ kind: 'ice' }`) messages. */
|
|
49
|
+
readonly trickle?: boolean;
|
|
50
|
+
/**
|
|
51
|
+
* Optional per-peer reachability check for composite adapters (such as `withLocalTabs`) whose
|
|
52
|
+
* outer `SignalingState` reflects a primary transport while secondary local transports remain online.
|
|
53
|
+
*/
|
|
54
|
+
canReach?(peerId: string): boolean;
|
|
31
55
|
/** Send a signal to a peer. Return `true` if accepted, or `false` if signaling is unavailable. */
|
|
32
56
|
send(to: string, signal: Signal): boolean;
|
|
33
57
|
/** Shut down the signaling adapter and release all sockets/timers. */
|
|
@@ -43,7 +67,7 @@ export declare function isUuid(value: unknown): value is string;
|
|
|
43
67
|
export declare function randomUuid(): string;
|
|
44
68
|
/** Deterministic 64-bit hex hash (works even in non-secure contexts such as file://). */
|
|
45
69
|
export declare function namespaceHash(input: string): string;
|
|
46
|
-
/** Type guard validating a parsed signaling payload (`need`, `offer`, or `
|
|
70
|
+
/** Type guard validating a parsed signaling payload (`need`, `offer`, `answer`, or `ice`). */
|
|
47
71
|
export declare function isSignal(value: unknown): value is Signal;
|
|
48
72
|
/** Add a fallback for co-located endpoints when multicast DNS is unavailable.
|
|
49
73
|
* Preserve the original candidate and its priority. Never transmit this local hint.
|
package/dist/signaling.js
CHANGED
|
@@ -27,7 +27,26 @@ export function namespaceHash(input) {
|
|
|
27
27
|
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
28
28
|
return (h2 >>> 0).toString(16).padStart(8, '0') + (h1 >>> 0).toString(16).padStart(8, '0');
|
|
29
29
|
}
|
|
30
|
-
|
|
30
|
+
function isIceCandidatePayload(value) {
|
|
31
|
+
if (!value || typeof value !== 'object')
|
|
32
|
+
return false;
|
|
33
|
+
const c = value;
|
|
34
|
+
if (typeof c.candidate !== 'string' || c.candidate.length > 1024)
|
|
35
|
+
return false;
|
|
36
|
+
if (c.sdpMid !== undefined &&
|
|
37
|
+
c.sdpMid !== null &&
|
|
38
|
+
(typeof c.sdpMid !== 'string' || c.sdpMid.length > 64))
|
|
39
|
+
return false;
|
|
40
|
+
if (c.sdpMLineIndex !== undefined &&
|
|
41
|
+
c.sdpMLineIndex !== null &&
|
|
42
|
+
(typeof c.sdpMLineIndex !== 'number' ||
|
|
43
|
+
!Number.isSafeInteger(c.sdpMLineIndex) ||
|
|
44
|
+
c.sdpMLineIndex < 0 ||
|
|
45
|
+
c.sdpMLineIndex > 65535))
|
|
46
|
+
return false;
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
/** Type guard validating a parsed signaling payload (`need`, `offer`, `answer`, or `ice`). */
|
|
31
50
|
export function isSignal(value) {
|
|
32
51
|
if (!value || typeof value !== 'object')
|
|
33
52
|
return false;
|
|
@@ -41,6 +60,18 @@ export function isSignal(value) {
|
|
|
41
60
|
value.previous > 0 &&
|
|
42
61
|
value.previous <= maxAttemptNumber)));
|
|
43
62
|
}
|
|
63
|
+
if (value.kind === 'ice') {
|
|
64
|
+
return ('attempt' in value &&
|
|
65
|
+
typeof value.attempt === 'number' &&
|
|
66
|
+
Number.isSafeInteger(value.attempt) &&
|
|
67
|
+
value.attempt > 0 &&
|
|
68
|
+
value.attempt <= maxAttemptNumber &&
|
|
69
|
+
'candidates' in value &&
|
|
70
|
+
Array.isArray(value.candidates) &&
|
|
71
|
+
value.candidates.length > 0 &&
|
|
72
|
+
value.candidates.length <= 32 &&
|
|
73
|
+
value.candidates.every(isIceCandidatePayload));
|
|
74
|
+
}
|
|
44
75
|
return ((value.kind === 'offer' || value.kind === 'answer') &&
|
|
45
76
|
'attempt' in value &&
|
|
46
77
|
typeof value.attempt === 'number' &&
|
|
@@ -51,12 +82,29 @@ export function isSignal(value) {
|
|
|
51
82
|
typeof value.sdp === 'string' &&
|
|
52
83
|
value.sdp.length <= 64 * 1024);
|
|
53
84
|
}
|
|
85
|
+
const localMdnsCandidatePattern = /^(?:a=)?candidate:\S+ (\d+) udp \d+ [a-z0-9.-]+\.local (\d+) typ host(?: |$)/i;
|
|
54
86
|
/** Add a fallback for co-located endpoints when multicast DNS is unavailable.
|
|
55
87
|
* Preserve the original candidate and its priority. Never transmit this local hint.
|
|
56
88
|
*/
|
|
57
89
|
export function withLoopbackFallback(signal) {
|
|
58
90
|
if (signal.kind === 'need')
|
|
59
91
|
return signal;
|
|
92
|
+
if (signal.kind === 'ice') {
|
|
93
|
+
let index = 0;
|
|
94
|
+
const out = [];
|
|
95
|
+
for (const item of signal.candidates) {
|
|
96
|
+
out.push(item);
|
|
97
|
+
const match = localMdnsCandidatePattern.exec(item.candidate);
|
|
98
|
+
if (match) {
|
|
99
|
+
out.push({
|
|
100
|
+
candidate: `candidate:mp${++index} ${match[1]} udp 1 127.0.0.1 ${match[2]} typ host`,
|
|
101
|
+
...(item.sdpMid !== undefined ? { sdpMid: item.sdpMid } : {}),
|
|
102
|
+
...(item.sdpMLineIndex !== undefined ? { sdpMLineIndex: item.sdpMLineIndex } : {})
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return index ? { ...signal, candidates: out } : signal;
|
|
107
|
+
}
|
|
60
108
|
const eol = signal.sdp.includes('\r\n') ? '\r\n' : '\n';
|
|
61
109
|
let index = 0;
|
|
62
110
|
const lines = [];
|
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) =>
|
|
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);
|
|
@@ -74,6 +81,7 @@ export function tabSignaling() {
|
|
|
74
81
|
post({ type: 'hello' });
|
|
75
82
|
});
|
|
76
83
|
return {
|
|
84
|
+
trickle: true,
|
|
77
85
|
send(to, signal) {
|
|
78
86
|
if (closed)
|
|
79
87
|
return false;
|
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
|
+
}
|
package/dist/voice.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
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 autoplayBlocked: boolean;
|
|
16
|
+
readonly deafened: boolean;
|
|
17
|
+
readonly volume: number;
|
|
18
|
+
readonly selfSpeaking: boolean;
|
|
19
|
+
readonly remotePeers: readonly string[];
|
|
20
|
+
readonly speakingPeers: readonly string[];
|
|
21
|
+
}
|
|
22
|
+
/** Configuration options for `createVoice()`. */
|
|
23
|
+
export interface VoiceOptions {
|
|
24
|
+
/** Initial playback volume for incoming peer audio (`0` to `1`). @default 1 */
|
|
25
|
+
volume?: number;
|
|
26
|
+
/** Start with incoming peer audio muted locally (`audio.muted = true`). @default false */
|
|
27
|
+
deafened?: boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Custom audio track constraints passed to `getUserMedia`.
|
|
30
|
+
* @default { echoCancellation: true, noiseSuppression: true, autoGainControl: true }
|
|
31
|
+
*/
|
|
32
|
+
audioConstraints?: MediaTrackConstraints | true;
|
|
33
|
+
/** Automatically attach global capture-phase gesture & visibility listeners to unlock blocked playback. @default true */
|
|
34
|
+
autoUnlock?: boolean;
|
|
35
|
+
/** Enable shared lazy AudioContext + AnalyserNode speaking detection (`selfSpeaking` & `speakingPeers`). @default true */
|
|
36
|
+
speakingDetection?: boolean;
|
|
37
|
+
/** RMS amplitude threshold (`0` to `1`) for speaking detection. @default 0.03 */
|
|
38
|
+
speakingThreshold?: number;
|
|
39
|
+
/** Polling interval in milliseconds (`50` to `60000`) for speaking detection. @default 180 */
|
|
40
|
+
speakingIntervalMs?: number;
|
|
41
|
+
/** Optional target peer ID scoping outgoing microphone audio only (`room.addStream(stream, to)`). Incoming audio from all peers still plays. */
|
|
42
|
+
to?: string;
|
|
43
|
+
}
|
|
44
|
+
/** Headless P2P voice chat controller built on top of a `Room`. */
|
|
45
|
+
export interface Voice extends VoiceSnapshot {
|
|
46
|
+
/** Return an immutable snapshot of all current voice states. */
|
|
47
|
+
getSnapshot(): VoiceSnapshot;
|
|
48
|
+
/**
|
|
49
|
+
* Acquire microphone on first call (`'off' | 'error'` -> `'requesting'` -> `'live'`),
|
|
50
|
+
* or toggle instant soft-mute (`track.enabled`) without WebRTC renegotiation (`'live'` <-> `'muted'`).
|
|
51
|
+
* Concurrent calls while `'requesting'` coalesce onto the in-flight request. Resolves to `'off'` if closed.
|
|
52
|
+
*/
|
|
53
|
+
toggleMic(): Promise<MicStatus>;
|
|
54
|
+
/**
|
|
55
|
+
* Acquire microphone if not active, or unmute if currently soft-muted.
|
|
56
|
+
* Concurrent calls while `'requesting'` coalesce onto the in-flight request. Resolves to `'off'` if closed.
|
|
57
|
+
*/
|
|
58
|
+
startMic(): Promise<MicStatus>;
|
|
59
|
+
/** Soft-mute (`true`) or unmute (`false`) an already-acquired local microphone (`'live' | 'muted'`). No-op otherwise. */
|
|
60
|
+
setMuted(muted: boolean): void;
|
|
61
|
+
/** Detach local stream from the room (`room.removeStream`), cancel any in-flight `getUserMedia`, and stop hardware microphone tracks (`track.stop()`). */
|
|
62
|
+
stopMic(): void;
|
|
63
|
+
/** Set playback volume (`0` to `1`, clamped) on all current and future remote `<audio>` elements. */
|
|
64
|
+
setVolume(volume: number): void;
|
|
65
|
+
/** Mute (`true`) or unmute (`false`) all incoming remote `<audio>` elements locally. Unmuting also triggers `unlockAudio()`. */
|
|
66
|
+
setDeafened(deafened: boolean): void;
|
|
67
|
+
/** Manually trigger synchronous `AudioContext.resume()` + `audio.play()` retry. */
|
|
68
|
+
unlockAudio(): void;
|
|
69
|
+
/** Subscribe to any state change in `VoiceSnapshot`. Supports `ListenOptions` (`{ once, signal }`). */
|
|
70
|
+
onChange(fn: (snapshot: VoiceSnapshot) => void, options?: ListenOptions): () => void;
|
|
71
|
+
/** Release microphone tracks, remove hidden `<audio>` elements, close `AudioContext`, restore `audioSession`, and detach all listeners. */
|
|
72
|
+
close(): void;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Create a headless P2P voice chat controller attached to a `Room`.
|
|
76
|
+
*
|
|
77
|
+
* Automatically plays incoming peer audio streams, manages local microphone capture with instant
|
|
78
|
+
* soft-mute (`track.enabled`) vs full hardware release, tracks speaking peers via a shared lazy
|
|
79
|
+
* `AudioContext`, and handles browser Autoplay Policy & iOS Safari audio unlocking.
|
|
80
|
+
*/
|
|
81
|
+
export declare function createVoice(room: Room, options?: VoiceOptions): Voice;
|