@dimchansky/meshpost 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +293 -2
- package/dist/channel.d.ts +26 -0
- package/dist/channel.js +43 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +6 -0
- package/dist/manual.d.ts +13 -0
- package/dist/manual.js +109 -0
- package/dist/mqtt.d.ts +20 -0
- package/dist/mqtt.js +582 -0
- package/dist/room.d.ts +74 -0
- package/dist/room.js +600 -0
- package/dist/signaling.d.ts +51 -0
- package/dist/signaling.js +70 -0
- package/dist/tabs.d.ts +3 -0
- package/dist/tabs.js +93 -0
- package/docs/behavior.md +180 -0
- package/package.json +65 -4
package/dist/room.js
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
import { isSignal, randomUuid, withLoopbackFallback } from './signaling.js';
|
|
2
|
+
/** Built-in Cloudflare and Google public STUN servers used by default. */
|
|
3
|
+
export const defaultIceServers = Object.freeze([
|
|
4
|
+
Object.freeze({ urls: 'stun:stun.cloudflare.com:3478' }),
|
|
5
|
+
Object.freeze({ urls: 'stun:stun.l.google.com:19302' }),
|
|
6
|
+
Object.freeze({ urls: 'stun:stun1.l.google.com:19302' })
|
|
7
|
+
]);
|
|
8
|
+
function listeners() {
|
|
9
|
+
const handlers = new Set();
|
|
10
|
+
return {
|
|
11
|
+
add(fn) {
|
|
12
|
+
handlers.add(fn);
|
|
13
|
+
return () => {
|
|
14
|
+
handlers.delete(fn);
|
|
15
|
+
};
|
|
16
|
+
},
|
|
17
|
+
fire(...args) {
|
|
18
|
+
for (const fn of [...handlers]) {
|
|
19
|
+
try {
|
|
20
|
+
fn(...args);
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
globalThis.reportError?.(error);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
clear() {
|
|
28
|
+
handlers.clear();
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const maxPacket = 16 * 1024;
|
|
33
|
+
function asStat(value) {
|
|
34
|
+
return value && typeof value === 'object' ? value : undefined;
|
|
35
|
+
}
|
|
36
|
+
function nonNegativeNumber(value) {
|
|
37
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
|
|
38
|
+
}
|
|
39
|
+
function parsePeerStats(report, bufferedUnreliable, bufferedReliable) {
|
|
40
|
+
const byId = new Map();
|
|
41
|
+
let bytesSent = 0;
|
|
42
|
+
let bytesReceived = 0;
|
|
43
|
+
let selectedId;
|
|
44
|
+
let selectedPair;
|
|
45
|
+
let nominatedPair;
|
|
46
|
+
let succeededPair;
|
|
47
|
+
report.forEach((raw, id) => {
|
|
48
|
+
const stat = asStat(raw);
|
|
49
|
+
if (!stat)
|
|
50
|
+
return;
|
|
51
|
+
byId.set(id, stat);
|
|
52
|
+
if (stat.type === 'data-channel') {
|
|
53
|
+
bytesSent += nonNegativeNumber(stat.bytesSent) ?? 0;
|
|
54
|
+
bytesReceived += nonNegativeNumber(stat.bytesReceived) ?? 0;
|
|
55
|
+
}
|
|
56
|
+
else if (stat.type === 'transport' && typeof stat.selectedCandidatePairId === 'string') {
|
|
57
|
+
selectedId = stat.selectedCandidatePairId;
|
|
58
|
+
}
|
|
59
|
+
else if (stat.type === 'candidate-pair') {
|
|
60
|
+
if (stat.selected === true && !selectedPair)
|
|
61
|
+
selectedPair = stat;
|
|
62
|
+
if (stat.state === 'succeeded') {
|
|
63
|
+
if (stat.nominated === true && !nominatedPair)
|
|
64
|
+
nominatedPair = stat;
|
|
65
|
+
if (!succeededPair)
|
|
66
|
+
succeededPair = stat;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
let activePair;
|
|
71
|
+
if (selectedId) {
|
|
72
|
+
const pair = byId.get(selectedId);
|
|
73
|
+
if (pair?.type === 'candidate-pair')
|
|
74
|
+
activePair = pair;
|
|
75
|
+
}
|
|
76
|
+
activePair ??= selectedPair ?? nominatedPair ?? succeededPair;
|
|
77
|
+
const rttSec = activePair ? nonNegativeNumber(activePair.currentRoundTripTime) : null;
|
|
78
|
+
const rttMs = rttSec !== null ? Math.round(rttSec * 1000) : null;
|
|
79
|
+
let route = 'unknown';
|
|
80
|
+
if (activePair) {
|
|
81
|
+
const local = typeof activePair.localCandidateId === 'string'
|
|
82
|
+
? byId.get(activePair.localCandidateId)
|
|
83
|
+
: undefined;
|
|
84
|
+
const remote = typeof activePair.remoteCandidateId === 'string'
|
|
85
|
+
? byId.get(activePair.remoteCandidateId)
|
|
86
|
+
: undefined;
|
|
87
|
+
const localType = local?.type === 'local-candidate' && typeof local.candidateType === 'string'
|
|
88
|
+
? local.candidateType
|
|
89
|
+
: undefined;
|
|
90
|
+
const remoteType = remote?.type === 'remote-candidate' && typeof remote.candidateType === 'string'
|
|
91
|
+
? remote.candidateType
|
|
92
|
+
: undefined;
|
|
93
|
+
if (localType === 'relay' || remoteType === 'relay')
|
|
94
|
+
route = 'relay';
|
|
95
|
+
else if (localType && remoteType)
|
|
96
|
+
route = 'direct';
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
rttMs,
|
|
100
|
+
route,
|
|
101
|
+
bytesSent,
|
|
102
|
+
bytesReceived,
|
|
103
|
+
bufferedUnreliable,
|
|
104
|
+
bufferedReliable
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
const bufferLimit = { unreliable: 64 * 1024, reliable: 256 * 1024 };
|
|
108
|
+
const establishTimeout = 35_000;
|
|
109
|
+
const gatherTimeoutDefault = 2_500;
|
|
110
|
+
const maxPeersDefault = 32;
|
|
111
|
+
const disconnectGrace = 8_000;
|
|
112
|
+
const leaveNotice = 'meshpost/1/leave';
|
|
113
|
+
/** Start discovery immediately. Membership becomes observable as peer links open. */
|
|
114
|
+
export function joinRoom(name, options) {
|
|
115
|
+
if (typeof name !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(name))
|
|
116
|
+
throw new TypeError('Invalid room name');
|
|
117
|
+
const appId = options.appId ?? 'meshpost';
|
|
118
|
+
if (typeof appId !== 'string' || !/^[a-zA-Z0-9._-]{1,64}$/.test(appId))
|
|
119
|
+
throw new TypeError('Invalid appId');
|
|
120
|
+
const password = options.password;
|
|
121
|
+
if (password !== undefined && (typeof password !== 'string' || password.length === 0))
|
|
122
|
+
throw new TypeError('Invalid password');
|
|
123
|
+
const timeout = options.handshakeTimeoutMs ?? establishTimeout;
|
|
124
|
+
if (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > 2_147_483_647)
|
|
125
|
+
throw new RangeError('Invalid handshake timeout');
|
|
126
|
+
const gatherTimeout = options.iceGatheringTimeoutMs ??
|
|
127
|
+
Math.min(gatherTimeoutDefault, Math.max(1, Math.floor(timeout / 2)));
|
|
128
|
+
if (!Number.isSafeInteger(gatherTimeout) || gatherTimeout <= 0 || gatherTimeout > 2_147_483_647)
|
|
129
|
+
throw new RangeError('Invalid ICE gathering timeout');
|
|
130
|
+
const maxPeers = options.maxPeers ?? maxPeersDefault;
|
|
131
|
+
if (!Number.isSafeInteger(maxPeers) || maxPeers <= 0)
|
|
132
|
+
throw new RangeError('Invalid maxPeers limit');
|
|
133
|
+
const baseIceServers = options.rtcConfig?.iceServers ?? defaultIceServers;
|
|
134
|
+
const rtcConfig = {
|
|
135
|
+
...options.rtcConfig,
|
|
136
|
+
iceServers: [...baseIceServers, ...(options.turnConfig ?? [])]
|
|
137
|
+
};
|
|
138
|
+
// Fail fast on malformed browser RTC configuration instead of retrying silently.
|
|
139
|
+
new RTCPeerConnection(rtcConfig).close();
|
|
140
|
+
const needsRelay = rtcConfig.iceTransportPolicy === 'relay';
|
|
141
|
+
const hasTurn = rtcConfig.iceServers?.some((server) => {
|
|
142
|
+
const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
|
|
143
|
+
return urls.some((u) => /^turns?:/i.test(u));
|
|
144
|
+
}) ?? false;
|
|
145
|
+
const self = randomUuid();
|
|
146
|
+
const peers = new Map();
|
|
147
|
+
const joins = listeners();
|
|
148
|
+
const leaves = listeners();
|
|
149
|
+
const packets = listeners();
|
|
150
|
+
const drains = listeners();
|
|
151
|
+
const status = listeners();
|
|
152
|
+
let state = 'connecting';
|
|
153
|
+
// Start attempt numbers from an unpredictable positive offset so observers cannot guess them.
|
|
154
|
+
let nextAttempt = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x0fffffff) + 1;
|
|
155
|
+
let stopped = false;
|
|
156
|
+
let signaling;
|
|
157
|
+
const prepareRemoteSdp = (signal) => rtcConfig.iceTransportPolicy === 'relay' ? signal.sdp : withLoopbackFallback(signal).sdp;
|
|
158
|
+
function retry(peer) {
|
|
159
|
+
if (stopped || state !== 'online' || !peer.advertised || peer.retry || peer.link)
|
|
160
|
+
return;
|
|
161
|
+
const base = Math.min(8000, 350 * 2 ** Math.min(peer.failures++, 5));
|
|
162
|
+
const delay = Math.round(base * (0.75 + Math.random() * 0.5));
|
|
163
|
+
peer.retry = setTimeout(() => {
|
|
164
|
+
delete peer.retry;
|
|
165
|
+
discover(peer);
|
|
166
|
+
}, delay);
|
|
167
|
+
}
|
|
168
|
+
function drop(peer, link, flushLeave = false, shouldRetry = true) {
|
|
169
|
+
if (peer.link !== link)
|
|
170
|
+
return;
|
|
171
|
+
delete peer.link;
|
|
172
|
+
if (link.accepted)
|
|
173
|
+
peer.previous = link.attempt;
|
|
174
|
+
clearTimeout(link.deadline);
|
|
175
|
+
clearTimeout(link.gather);
|
|
176
|
+
clearTimeout(link.grace);
|
|
177
|
+
const reliable = link.channels.reliable;
|
|
178
|
+
if (flushLeave && reliable.readyState === 'open') {
|
|
179
|
+
// Give SCTP a bounded opportunity to deliver the departure before closing DTLS.
|
|
180
|
+
const closeTimer = setTimeout(() => link.pc.close(), 750);
|
|
181
|
+
reliable.addEventListener('close', () => {
|
|
182
|
+
clearTimeout(closeTimer);
|
|
183
|
+
link.pc.close();
|
|
184
|
+
}, { once: true });
|
|
185
|
+
try {
|
|
186
|
+
reliable.send(leaveNotice);
|
|
187
|
+
reliable.close();
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
clearTimeout(closeTimer);
|
|
191
|
+
link.pc.close();
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
else
|
|
195
|
+
link.pc.close();
|
|
196
|
+
if (!peer.advertised)
|
|
197
|
+
peers.delete(peer.id);
|
|
198
|
+
if (link.ready)
|
|
199
|
+
leaves.fire(peer.id);
|
|
200
|
+
if (shouldRetry)
|
|
201
|
+
retry(peer);
|
|
202
|
+
}
|
|
203
|
+
function createLink(peer, attempt) {
|
|
204
|
+
clearTimeout(peer.retry);
|
|
205
|
+
delete peer.retry;
|
|
206
|
+
const pc = new RTCPeerConnection(rtcConfig);
|
|
207
|
+
// Fixed stream IDs let both endpoints create identical channels without glare.
|
|
208
|
+
let channels;
|
|
209
|
+
try {
|
|
210
|
+
channels = {
|
|
211
|
+
unreliable: pc.createDataChannel('meshpost/1/unreliable', {
|
|
212
|
+
negotiated: true,
|
|
213
|
+
id: 0,
|
|
214
|
+
ordered: false,
|
|
215
|
+
maxRetransmits: 0,
|
|
216
|
+
protocol: appId
|
|
217
|
+
}),
|
|
218
|
+
reliable: pc.createDataChannel('meshpost/1/reliable', {
|
|
219
|
+
negotiated: true,
|
|
220
|
+
id: 1,
|
|
221
|
+
ordered: true,
|
|
222
|
+
protocol: appId
|
|
223
|
+
})
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
pc.close();
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
const link = {
|
|
231
|
+
pc,
|
|
232
|
+
channels,
|
|
233
|
+
attempt,
|
|
234
|
+
ready: false,
|
|
235
|
+
accepted: false,
|
|
236
|
+
published: false,
|
|
237
|
+
answerApplied: false
|
|
238
|
+
};
|
|
239
|
+
peer.link = link;
|
|
240
|
+
link.deadline = setTimeout(() => drop(peer, link), timeout);
|
|
241
|
+
pc.onconnectionstatechange = () => {
|
|
242
|
+
if (peer.link !== link)
|
|
243
|
+
return;
|
|
244
|
+
if (pc.connectionState === 'failed' || pc.connectionState === 'closed')
|
|
245
|
+
drop(peer, link);
|
|
246
|
+
else if (pc.connectionState === 'disconnected') {
|
|
247
|
+
link.grace ??= setTimeout(() => drop(peer, link), disconnectGrace);
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
clearTimeout(link.grace);
|
|
251
|
+
delete link.grace;
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
const early = [];
|
|
255
|
+
let earlyBytes = 0;
|
|
256
|
+
for (const delivery of ['unreliable', 'reliable']) {
|
|
257
|
+
const channel = channels[delivery];
|
|
258
|
+
channel.binaryType = 'arraybuffer';
|
|
259
|
+
channel.bufferedAmountLowThreshold = Math.floor(bufferLimit[delivery] / 2);
|
|
260
|
+
channel.onbufferedamountlow = () => {
|
|
261
|
+
if (!stopped && peer.link === link && link.ready)
|
|
262
|
+
drains.fire(peer.id, delivery);
|
|
263
|
+
};
|
|
264
|
+
channel.onclose = () => drop(peer, link);
|
|
265
|
+
channel.onerror = () => drop(peer, link);
|
|
266
|
+
channel.onopen = () => {
|
|
267
|
+
if (stopped || peer.link !== link || link.ready)
|
|
268
|
+
return;
|
|
269
|
+
if (Object.values(channels).every((c) => c.readyState === 'open')) {
|
|
270
|
+
clearTimeout(link.deadline);
|
|
271
|
+
link.ready = true;
|
|
272
|
+
peer.failures = 0;
|
|
273
|
+
joins.fire(peer.id);
|
|
274
|
+
for (const [bytes, mode] of early) {
|
|
275
|
+
if (peer.link !== link || stopped)
|
|
276
|
+
break;
|
|
277
|
+
packets.fire(peer.id, bytes, mode);
|
|
278
|
+
}
|
|
279
|
+
early.length = 0;
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
channel.onmessage = ({ data }) => {
|
|
283
|
+
if (stopped || peer.link !== link)
|
|
284
|
+
return;
|
|
285
|
+
if (data === leaveNotice && delivery === 'reliable') {
|
|
286
|
+
peer.advertised = false;
|
|
287
|
+
drop(peer, link);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
if (!(data instanceof ArrayBuffer))
|
|
291
|
+
return;
|
|
292
|
+
if (data.byteLength > maxPacket) {
|
|
293
|
+
if (delivery === 'reliable')
|
|
294
|
+
drop(peer, link);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const bytes = new Uint8Array(data);
|
|
298
|
+
if (link.ready)
|
|
299
|
+
packets.fire(peer.id, bytes, delivery);
|
|
300
|
+
else if (early.length >= 64 || earlyBytes + bytes.byteLength > 256 * 1024) {
|
|
301
|
+
if (delivery === 'reliable')
|
|
302
|
+
drop(peer, link);
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
early.push([bytes, delivery]);
|
|
306
|
+
earlyBytes += bytes.byteLength;
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
return link;
|
|
311
|
+
}
|
|
312
|
+
async function negotiate(peer, attempt, remoteOffer) {
|
|
313
|
+
if (stopped || !peer.advertised || !signaling)
|
|
314
|
+
return;
|
|
315
|
+
let link;
|
|
316
|
+
try {
|
|
317
|
+
link = createLink(peer, attempt);
|
|
318
|
+
const { pc } = link;
|
|
319
|
+
if (remoteOffer !== undefined) {
|
|
320
|
+
await pc.setRemoteDescription({ type: 'offer', sdp: remoteOffer });
|
|
321
|
+
if (peer.link !== link)
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
link.accepted = true;
|
|
325
|
+
const description = remoteOffer === undefined ? await pc.createOffer() : await pc.createAnswer();
|
|
326
|
+
if (peer.link !== link)
|
|
327
|
+
return;
|
|
328
|
+
// Send one complete SDP. Publish early after gatherTimeout so unreachable STUN never stalls,
|
|
329
|
+
// while allowing extra time when relay/TURN candidates are required or configured.
|
|
330
|
+
const current = link;
|
|
331
|
+
let hasRelay = false;
|
|
332
|
+
let hasSrflx = false;
|
|
333
|
+
let softExpired = false;
|
|
334
|
+
const publish = (force = false) => {
|
|
335
|
+
if (current.published || peer.link !== current)
|
|
336
|
+
return;
|
|
337
|
+
if (!force && pc.iceGatheringState !== 'complete')
|
|
338
|
+
return;
|
|
339
|
+
const local = pc.localDescription;
|
|
340
|
+
if (!local || (local.type !== 'offer' && local.type !== 'answer'))
|
|
341
|
+
return;
|
|
342
|
+
clearTimeout(current.gather);
|
|
343
|
+
delete current.gather;
|
|
344
|
+
current.published = true;
|
|
345
|
+
if (!signaling?.send(peer.id, { kind: local.type, attempt, sdp: local.sdp }))
|
|
346
|
+
drop(peer, current);
|
|
347
|
+
};
|
|
348
|
+
pc.onicecandidate = (event) => {
|
|
349
|
+
if (peer.link !== current || current.published)
|
|
350
|
+
return;
|
|
351
|
+
if (!event.candidate) {
|
|
352
|
+
publish(true);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
const type = event.candidate.type;
|
|
356
|
+
if (type === 'relay')
|
|
357
|
+
hasRelay = true;
|
|
358
|
+
else if (type === 'srflx')
|
|
359
|
+
hasSrflx = true;
|
|
360
|
+
if (softExpired && (hasRelay || (!needsRelay && hasSrflx))) {
|
|
361
|
+
publish(true);
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
pc.onicegatheringstatechange = () => publish(false);
|
|
365
|
+
await pc.setLocalDescription(description);
|
|
366
|
+
if (peer.link !== current)
|
|
367
|
+
return;
|
|
368
|
+
publish(false);
|
|
369
|
+
if (!current.published) {
|
|
370
|
+
const extendedGather = options.iceGatheringTimeoutMs === undefined
|
|
371
|
+
? Math.min(10_000, Math.floor(timeout / 2))
|
|
372
|
+
: gatherTimeout;
|
|
373
|
+
current.gather = setTimeout(() => {
|
|
374
|
+
softExpired = true;
|
|
375
|
+
const waitingForRelay = (needsRelay && !hasRelay) || (hasTurn && !hasRelay && !hasSrflx);
|
|
376
|
+
if (waitingForRelay && extendedGather > gatherTimeout) {
|
|
377
|
+
current.gather = setTimeout(() => publish(true), extendedGather - gatherTimeout);
|
|
378
|
+
}
|
|
379
|
+
else {
|
|
380
|
+
publish(true);
|
|
381
|
+
}
|
|
382
|
+
}, gatherTimeout);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
catch {
|
|
386
|
+
if (link)
|
|
387
|
+
drop(peer, link);
|
|
388
|
+
else
|
|
389
|
+
retry(peer);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
function discover(peer) {
|
|
393
|
+
if (stopped || !signaling || !peer.advertised || state !== 'online' || peer.link || peer.retry)
|
|
394
|
+
return;
|
|
395
|
+
if (self < peer.id)
|
|
396
|
+
void negotiate(peer, ++nextAttempt);
|
|
397
|
+
else {
|
|
398
|
+
signaling.send(peer.id, { kind: 'need', previous: peer.previous });
|
|
399
|
+
retry(peer);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
function receive(id, signal) {
|
|
403
|
+
if (!isSignal(signal))
|
|
404
|
+
return;
|
|
405
|
+
const peer = peers.get(id);
|
|
406
|
+
if (stopped || !peer?.advertised)
|
|
407
|
+
return;
|
|
408
|
+
const link = peer.link;
|
|
409
|
+
if (signal.kind === 'need') {
|
|
410
|
+
if (self >= id)
|
|
411
|
+
return;
|
|
412
|
+
if (link) {
|
|
413
|
+
if (signal.previous === link.attempt) {
|
|
414
|
+
drop(peer, link, false, false);
|
|
415
|
+
discover(peer);
|
|
416
|
+
}
|
|
417
|
+
else if (!link.ready &&
|
|
418
|
+
!link.answerApplied &&
|
|
419
|
+
link.published &&
|
|
420
|
+
link.pc.signalingState === 'have-local-offer' &&
|
|
421
|
+
link.pc.localDescription?.type === 'offer') {
|
|
422
|
+
if (!signaling?.send(peer.id, {
|
|
423
|
+
kind: 'offer',
|
|
424
|
+
attempt: link.attempt,
|
|
425
|
+
sdp: link.pc.localDescription.sdp
|
|
426
|
+
}))
|
|
427
|
+
drop(peer, link);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
else {
|
|
431
|
+
clearTimeout(peer.retry);
|
|
432
|
+
delete peer.retry;
|
|
433
|
+
discover(peer);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
else if (signal.kind === 'offer') {
|
|
437
|
+
const baseline = link?.attempt ?? peer.previous ?? 0;
|
|
438
|
+
if (self <= id || signal.attempt <= baseline)
|
|
439
|
+
return;
|
|
440
|
+
// Reject extreme attempt jumps once a baseline exists to prevent attempt-space exhaustion DoS.
|
|
441
|
+
if (baseline > 0 && signal.attempt - baseline > 1024)
|
|
442
|
+
return;
|
|
443
|
+
if (link)
|
|
444
|
+
drop(peer, link, false, false);
|
|
445
|
+
void negotiate(peer, signal.attempt, prepareRemoteSdp(signal));
|
|
446
|
+
}
|
|
447
|
+
else if (self < id &&
|
|
448
|
+
link &&
|
|
449
|
+
!link.answerApplied &&
|
|
450
|
+
link.attempt === signal.attempt &&
|
|
451
|
+
link.pc.signalingState === 'have-local-offer') {
|
|
452
|
+
link.answerApplied = true;
|
|
453
|
+
void link.pc
|
|
454
|
+
.setRemoteDescription({ type: 'answer', sdp: prepareRemoteSdp(signal) })
|
|
455
|
+
.catch(() => drop(peer, link));
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
signaling = options.signaling({
|
|
459
|
+
appId,
|
|
460
|
+
room: name,
|
|
461
|
+
self,
|
|
462
|
+
...(password !== undefined ? { password } : {}),
|
|
463
|
+
receive,
|
|
464
|
+
status(next, reason) {
|
|
465
|
+
if (stopped || next === state)
|
|
466
|
+
return;
|
|
467
|
+
state = next;
|
|
468
|
+
if (next !== 'online') {
|
|
469
|
+
for (const peer of peers.values()) {
|
|
470
|
+
clearTimeout(peer.retry);
|
|
471
|
+
delete peer.retry;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
status.fire(next, reason);
|
|
475
|
+
if (!stopped && state === 'online') {
|
|
476
|
+
for (const peer of peers.values()) {
|
|
477
|
+
if (peer.advertised && !peer.link) {
|
|
478
|
+
peer.failures = 0;
|
|
479
|
+
discover(peer);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
},
|
|
484
|
+
roster(ids) {
|
|
485
|
+
if (stopped)
|
|
486
|
+
return;
|
|
487
|
+
const present = new Set(ids);
|
|
488
|
+
for (const peer of peers.values()) {
|
|
489
|
+
peer.advertised = present.has(peer.id);
|
|
490
|
+
if (!peer.advertised) {
|
|
491
|
+
clearTimeout(peer.retry);
|
|
492
|
+
delete peer.retry;
|
|
493
|
+
if (!peer.link)
|
|
494
|
+
peers.delete(peer.id);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
for (const id of present) {
|
|
498
|
+
if (id === self)
|
|
499
|
+
continue;
|
|
500
|
+
let peer = peers.get(id);
|
|
501
|
+
if (!peer) {
|
|
502
|
+
if (peers.size >= maxPeers)
|
|
503
|
+
continue;
|
|
504
|
+
peer = { id, advertised: true, previous: null, failures: 0 };
|
|
505
|
+
peers.set(id, peer);
|
|
506
|
+
}
|
|
507
|
+
discover(peer);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
});
|
|
511
|
+
for (const peer of peers.values())
|
|
512
|
+
discover(peer);
|
|
513
|
+
const connected = () => [...peers.values()].filter((p) => p.link?.ready).map((p) => p.id);
|
|
514
|
+
return {
|
|
515
|
+
id: self,
|
|
516
|
+
get peers() {
|
|
517
|
+
return connected();
|
|
518
|
+
},
|
|
519
|
+
get signalingState() {
|
|
520
|
+
return state;
|
|
521
|
+
},
|
|
522
|
+
onPacket: packets.add,
|
|
523
|
+
onDrain: drains.add,
|
|
524
|
+
onPeerJoin: joins.add,
|
|
525
|
+
onPeerLeave: leaves.add,
|
|
526
|
+
onSignalingChange: status.add,
|
|
527
|
+
async getStats(peerId) {
|
|
528
|
+
if (stopped || peerId === self)
|
|
529
|
+
return null;
|
|
530
|
+
const peer = peers.get(peerId);
|
|
531
|
+
const link = peer?.link;
|
|
532
|
+
if (!peer || !link?.ready)
|
|
533
|
+
return null;
|
|
534
|
+
try {
|
|
535
|
+
const report = await link.pc.getStats();
|
|
536
|
+
if (stopped || peer.link !== link || !link.ready)
|
|
537
|
+
return null;
|
|
538
|
+
return parsePeerStats(report, link.channels.unreliable.bufferedAmount, link.channels.reliable.bufferedAmount);
|
|
539
|
+
}
|
|
540
|
+
catch {
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
},
|
|
544
|
+
send(bytes, { to, delivery = 'unreliable' } = {}) {
|
|
545
|
+
if (stopped)
|
|
546
|
+
throw new Error('Room is closed');
|
|
547
|
+
if (!(bytes instanceof Uint8Array))
|
|
548
|
+
throw new TypeError('Expected a Uint8Array');
|
|
549
|
+
if (delivery !== 'unreliable' && delivery !== 'reliable')
|
|
550
|
+
throw new TypeError('Invalid delivery mode');
|
|
551
|
+
const result = new Map();
|
|
552
|
+
const targets = to === undefined ? connected() : [to];
|
|
553
|
+
for (const id of targets) {
|
|
554
|
+
const link = peers.get(id)?.link;
|
|
555
|
+
const channel = link?.channels[delivery];
|
|
556
|
+
if (!link?.ready || channel?.readyState !== 'open')
|
|
557
|
+
result.set(id, 'unavailable');
|
|
558
|
+
else if (bytes.byteLength > Math.min(maxPacket, link.pc.sctp?.maxMessageSize || Infinity))
|
|
559
|
+
result.set(id, 'too-large');
|
|
560
|
+
else if (channel.bufferedAmount + bytes.byteLength > bufferLimit[delivery])
|
|
561
|
+
result.set(id, 'busy');
|
|
562
|
+
else {
|
|
563
|
+
try {
|
|
564
|
+
// Copy shared memory views to a browser-supported non-shared buffer.
|
|
565
|
+
channel.send(bytes.buffer instanceof ArrayBuffer
|
|
566
|
+
? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
567
|
+
: Uint8Array.from(bytes));
|
|
568
|
+
result.set(id, 'accepted');
|
|
569
|
+
}
|
|
570
|
+
catch (error) {
|
|
571
|
+
result.set(id, error instanceof DOMException && error.name === 'OperationError'
|
|
572
|
+
? 'busy'
|
|
573
|
+
: 'unavailable');
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
return result;
|
|
578
|
+
},
|
|
579
|
+
leave() {
|
|
580
|
+
if (stopped)
|
|
581
|
+
return;
|
|
582
|
+
stopped = true;
|
|
583
|
+
const wasClosed = state === 'closed';
|
|
584
|
+
state = 'closed';
|
|
585
|
+
signaling?.close();
|
|
586
|
+
for (const peer of peers.values()) {
|
|
587
|
+
peer.advertised = false;
|
|
588
|
+
clearTimeout(peer.retry);
|
|
589
|
+
delete peer.retry;
|
|
590
|
+
if (peer.link)
|
|
591
|
+
drop(peer, peer.link, true, false);
|
|
592
|
+
}
|
|
593
|
+
peers.clear();
|
|
594
|
+
if (!wasClosed)
|
|
595
|
+
status.fire('closed');
|
|
596
|
+
for (const group of [joins, leaves, packets, drains, status])
|
|
597
|
+
group.clear();
|
|
598
|
+
}
|
|
599
|
+
};
|
|
600
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** Discovery supplies peer IDs. Only the two endpoints interpret the signal payload. */
|
|
2
|
+
export type Signal = {
|
|
3
|
+
kind: 'need';
|
|
4
|
+
previous: number | null;
|
|
5
|
+
} | {
|
|
6
|
+
kind: 'offer' | 'answer';
|
|
7
|
+
attempt: number;
|
|
8
|
+
sdp: string;
|
|
9
|
+
};
|
|
10
|
+
/** Connection state reported by a signaling adapter. */
|
|
11
|
+
export type SignalingState = 'connecting' | 'online' | 'offline' | 'closed';
|
|
12
|
+
/** Callbacks and room metadata passed by `joinRoom()` into a `Signaling` adapter factory. */
|
|
13
|
+
export interface Discovery {
|
|
14
|
+
/** Application namespace isolating rooms across apps. */
|
|
15
|
+
readonly appId: string;
|
|
16
|
+
/** Room name. */
|
|
17
|
+
readonly room: string;
|
|
18
|
+
/** Local peer ID (UUID v4). */
|
|
19
|
+
readonly self: string;
|
|
20
|
+
/** Optional shared room password, if configured in `joinRoom()`. */
|
|
21
|
+
readonly password?: string;
|
|
22
|
+
/** Publish the current list of remote peer IDs present in the room. */
|
|
23
|
+
roster(ids: readonly string[]): void;
|
|
24
|
+
/** Deliver an incoming signaling message from a peer already in the roster. */
|
|
25
|
+
receive(from: string, signal: Signal): void;
|
|
26
|
+
/** Report a signaling state transition (with an optional human-readable reason). */
|
|
27
|
+
status(state: SignalingState, reason?: string): void;
|
|
28
|
+
}
|
|
29
|
+
/** Active signaling handle returned by a `Signaling` adapter factory. */
|
|
30
|
+
export interface SignalingSession {
|
|
31
|
+
/** Send a signal to a peer. Return `true` if accepted, or `false` if signaling is unavailable. */
|
|
32
|
+
send(to: string, signal: Signal): boolean;
|
|
33
|
+
/** Shut down the signaling adapter and release all sockets/timers. */
|
|
34
|
+
close(): void;
|
|
35
|
+
}
|
|
36
|
+
/** Factory function that connects a room to a discovery and SDP exchange transport. */
|
|
37
|
+
export type Signaling = (discovery: Discovery) => SignalingSession;
|
|
38
|
+
export declare const uuidPattern: RegExp;
|
|
39
|
+
export declare const maxAttemptNumber = 2147483647;
|
|
40
|
+
/** Check whether a value is a lowercase hyphenated UUID string. */
|
|
41
|
+
export declare function isUuid(value: unknown): value is string;
|
|
42
|
+
/** Generate an RFC 4122 v4 UUID even in non-secure contexts (e.g. plain HTTP LAN) where crypto.randomUUID is absent. */
|
|
43
|
+
export declare function randomUuid(): string;
|
|
44
|
+
/** Deterministic 64-bit hex hash (works even in non-secure contexts such as file://). */
|
|
45
|
+
export declare function namespaceHash(input: string): string;
|
|
46
|
+
/** Type guard validating a parsed signaling payload (`need`, `offer`, or `answer`). */
|
|
47
|
+
export declare function isSignal(value: unknown): value is Signal;
|
|
48
|
+
/** Add a fallback for co-located endpoints when multicast DNS is unavailable.
|
|
49
|
+
* Preserve the original candidate and its priority. Never transmit this local hint.
|
|
50
|
+
*/
|
|
51
|
+
export declare function withLoopbackFallback<T extends Signal>(signal: T): T;
|