@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/dist/room.js CHANGED
@@ -1,4 +1,24 @@
1
1
  import { isSignal, randomUuid, withLoopbackFallback } from './signaling.js';
2
+ const roomInternals = new WeakMap();
3
+ /** @internal */
4
+ export function isRoomClosed(room) {
5
+ const internal = roomInternals.get(room);
6
+ return internal ? internal.isClosed() : room.signalingState === 'closed';
7
+ }
8
+ /** @internal */
9
+ export function onRoomClose(room, fn) {
10
+ const internal = roomInternals.get(room);
11
+ if (!internal) {
12
+ if (room.signalingState === 'closed')
13
+ fn();
14
+ return () => { };
15
+ }
16
+ return internal.onClose(fn);
17
+ }
18
+ /** @internal */
19
+ export function getRoomRemoteStreams(room) {
20
+ return roomInternals.get(room)?.getRemoteStreams() ?? [];
21
+ }
2
22
  /** Built-in Cloudflare and Google public STUN servers used by default. */
3
23
  export const defaultIceServers = Object.freeze([
4
24
  Object.freeze({ urls: 'stun:stun.cloudflare.com:3478' }),
@@ -6,18 +26,34 @@ export const defaultIceServers = Object.freeze([
6
26
  Object.freeze({ urls: 'stun:stun1.l.google.com:19302' })
7
27
  ]);
8
28
  function listeners() {
9
- const handlers = new Set();
29
+ const entries = new Set();
30
+ let closed = false;
10
31
  return {
11
- add(fn) {
12
- handlers.add(fn);
13
- return () => {
14
- handlers.delete(fn);
32
+ add(fn, options) {
33
+ const signal = options?.signal;
34
+ if (closed || signal?.aborted)
35
+ return () => { };
36
+ const entry = {
37
+ fn,
38
+ once: Boolean(options?.once),
39
+ off() {
40
+ if (!entries.delete(entry))
41
+ return;
42
+ signal?.removeEventListener('abort', entry.off);
43
+ }
15
44
  };
45
+ entries.add(entry);
46
+ signal?.addEventListener('abort', entry.off, { once: true });
47
+ return entry.off;
16
48
  },
17
49
  fire(...args) {
18
- for (const fn of [...handlers]) {
50
+ for (const entry of [...entries]) {
51
+ if (!entries.has(entry))
52
+ continue;
53
+ if (entry.once)
54
+ entry.off();
19
55
  try {
20
- fn(...args);
56
+ entry.fn(...args);
21
57
  }
22
58
  catch (error) {
23
59
  globalThis.reportError?.(error);
@@ -25,7 +61,9 @@ function listeners() {
25
61
  }
26
62
  },
27
63
  clear() {
28
- handlers.clear();
64
+ closed = true;
65
+ for (const entry of [...entries])
66
+ entry.off();
29
67
  }
30
68
  };
31
69
  }
@@ -110,6 +148,13 @@ const gatherTimeoutDefault = 2_500;
110
148
  const maxPeersDefault = 32;
111
149
  const disconnectGrace = 8_000;
112
150
  const leaveNotice = 'meshpost/1/leave';
151
+ const rtcControlPrefix = 'meshpost/1/rtc:';
152
+ const maxRtcControlBytes = 64 * 1024;
153
+ const maxRtcQueueDepth = 16;
154
+ const maxRemoteStreamsPerPeer = 32;
155
+ const trickleBatchMs = 50;
156
+ const trickleBatchSize = 16;
157
+ const maxTrickleCandidates = 64;
113
158
  /** Start discovery immediately. Membership becomes observable as peer links open. */
114
159
  export function joinRoom(name, options) {
115
160
  if (typeof name !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(name))
@@ -144,19 +189,225 @@ export function joinRoom(name, options) {
144
189
  }) ?? false;
145
190
  const self = randomUuid();
146
191
  const peers = new Map();
192
+ const rejectedFull = new Set();
193
+ const broadcastStreams = new Set();
194
+ const peerStreams = new Map();
147
195
  const joins = listeners();
148
196
  const leaves = listeners();
149
197
  const packets = listeners();
150
198
  const drains = listeners();
151
199
  const status = listeners();
200
+ const errors = listeners();
201
+ const peerStreamListeners = listeners();
202
+ const peerStreamEndListeners = listeners();
152
203
  let state = 'connecting';
153
204
  // Start attempt numbers from an unpredictable positive offset so observers cannot guess them.
154
205
  let nextAttempt = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x0fffffff) + 1;
155
206
  let stopped = false;
156
207
  let signaling;
208
+ let useTrickle = false;
157
209
  const prepareRemoteSdp = (signal) => rtcConfig.iceTransportPolicy === 'relay' ? signal.sdp : withLoopbackFallback(signal).sdp;
210
+ const prepareRemoteCandidates = (signal) => rtcConfig.iceTransportPolicy === 'relay'
211
+ ? signal.candidates
212
+ : withLoopbackFallback(signal).candidates;
213
+ const applyRemoteCandidates = (peer, link, candidates) => {
214
+ for (const item of candidates) {
215
+ if (stopped || peer.link !== link)
216
+ return;
217
+ void link.pc.addIceCandidate(item).catch(() => { });
218
+ }
219
+ };
220
+ const desiredStreamsFor = (peerId) => {
221
+ const set = new Set(broadcastStreams);
222
+ const targeted = peerStreams.get(peerId);
223
+ if (targeted) {
224
+ for (const s of targeted)
225
+ set.add(s);
226
+ }
227
+ return set;
228
+ };
229
+ const sendRtcControl = (link, payload) => {
230
+ const reliable = link.channels.reliable;
231
+ if (reliable.readyState !== 'open')
232
+ return false;
233
+ try {
234
+ reliable.send(rtcControlPrefix + JSON.stringify(payload));
235
+ return true;
236
+ }
237
+ catch {
238
+ return false;
239
+ }
240
+ };
241
+ const attachStreamToLink = (link, stream) => {
242
+ if (link.senders.has(stream))
243
+ return false;
244
+ const tracks = stream.getTracks();
245
+ if (tracks.length === 0)
246
+ return false;
247
+ const added = [];
248
+ for (const track of tracks) {
249
+ added.push(link.pc.addTrack(track, stream));
250
+ }
251
+ link.senders.set(stream, added);
252
+ link.pendingStreamEnds.delete(stream.id);
253
+ return true;
254
+ };
255
+ const detachStreamFromLink = (link, stream) => {
256
+ const added = link.senders.get(stream);
257
+ if (!added)
258
+ return false;
259
+ link.senders.delete(stream);
260
+ for (const sender of added) {
261
+ try {
262
+ link.pc.removeTrack(sender);
263
+ }
264
+ catch {
265
+ // Ignore if connection is closing.
266
+ }
267
+ }
268
+ link.pendingStreamEnds.add(stream.id);
269
+ return true;
270
+ };
271
+ const enqueueRenegotiate = (peer, link) => {
272
+ link.renegotiateQueued = true;
273
+ link.rtcQueue = link.rtcQueue.then(async () => {
274
+ if (stopped ||
275
+ peer.link !== link ||
276
+ !link.ready ||
277
+ !link.renegotiateQueued ||
278
+ link.channels.reliable.readyState !== 'open')
279
+ return;
280
+ if (link.pc.signalingState !== 'stable')
281
+ return;
282
+ link.renegotiateQueued = false;
283
+ try {
284
+ const offer = await link.pc.createOffer();
285
+ if (stopped || peer.link !== link)
286
+ return;
287
+ await link.pc.setLocalDescription(offer);
288
+ if (stopped || peer.link !== link || !link.pc.localDescription)
289
+ return;
290
+ if (sendRtcControl(link, { kind: 'offer', sdp: link.pc.localDescription.sdp })) {
291
+ for (const id of link.pendingStreamEnds) {
292
+ sendRtcControl(link, { kind: 'stream-end', id });
293
+ }
294
+ link.pendingStreamEnds.clear();
295
+ }
296
+ }
297
+ catch {
298
+ if (!stopped && peer.link === link) {
299
+ errors.fire({
300
+ code: 'media-error',
301
+ peerId: peer.id,
302
+ message: 'Failed to negotiate media tracks'
303
+ });
304
+ }
305
+ }
306
+ });
307
+ };
308
+ const handleRtcControl = (peer, link, raw) => {
309
+ if (raw.length > maxRtcControlBytes || link.rtcPending >= maxRtcQueueDepth)
310
+ return;
311
+ let msg;
312
+ try {
313
+ const parsed = JSON.parse(raw.slice(rtcControlPrefix.length));
314
+ msg = parsed && typeof parsed === 'object' ? parsed : null;
315
+ }
316
+ catch {
317
+ return;
318
+ }
319
+ if (!msg || typeof msg.kind !== 'string')
320
+ return;
321
+ if (msg.kind === 'stream-end' && typeof msg.id === 'string') {
322
+ const streamId = msg.id;
323
+ link.rtcPending++;
324
+ link.rtcQueue = link.rtcQueue.then(() => {
325
+ link.rtcPending--;
326
+ if (stopped || peer.link !== link || !link.ready)
327
+ return;
328
+ const stream = link.remoteStreams.get(streamId);
329
+ if (stream) {
330
+ link.remoteStreams.delete(streamId);
331
+ peerStreamEndListeners.fire(peer.id, stream);
332
+ }
333
+ });
334
+ return;
335
+ }
336
+ if ((msg.kind !== 'offer' && msg.kind !== 'answer') || typeof msg.sdp !== 'string')
337
+ return;
338
+ const kind = msg.kind;
339
+ const sdp = msg.sdp;
340
+ const polite = self > peer.id;
341
+ link.rtcPending++;
342
+ link.rtcQueue = link.rtcQueue.then(async () => {
343
+ try {
344
+ if (stopped || peer.link !== link || !link.ready)
345
+ return;
346
+ if (kind === 'offer') {
347
+ const collision = link.pc.signalingState !== 'stable';
348
+ if (!polite && collision)
349
+ return;
350
+ try {
351
+ if (polite && collision) {
352
+ await link.pc.setLocalDescription({ type: 'rollback' });
353
+ link.renegotiateQueued = true;
354
+ }
355
+ await link.pc.setRemoteDescription({ type: 'offer', sdp });
356
+ if (stopped || peer.link !== link)
357
+ return;
358
+ const answer = await link.pc.createAnswer();
359
+ if (stopped || peer.link !== link)
360
+ return;
361
+ await link.pc.setLocalDescription(answer);
362
+ if (stopped || peer.link !== link || !link.pc.localDescription)
363
+ return;
364
+ sendRtcControl(link, { kind: 'answer', sdp: link.pc.localDescription.sdp });
365
+ }
366
+ catch {
367
+ if (!stopped && peer.link === link) {
368
+ errors.fire({
369
+ code: 'media-error',
370
+ peerId: peer.id,
371
+ message: 'Failed to apply media offer'
372
+ });
373
+ }
374
+ }
375
+ if (!stopped && peer.link === link && link.renegotiateQueued) {
376
+ enqueueRenegotiate(peer, link);
377
+ }
378
+ }
379
+ else {
380
+ if (link.pc.signalingState !== 'have-local-offer')
381
+ return;
382
+ try {
383
+ await link.pc.setRemoteDescription({ type: 'answer', sdp });
384
+ }
385
+ catch {
386
+ if (!stopped && peer.link === link) {
387
+ errors.fire({
388
+ code: 'media-error',
389
+ peerId: peer.id,
390
+ message: 'Failed to apply media answer'
391
+ });
392
+ }
393
+ }
394
+ if (!stopped && peer.link === link && link.renegotiateQueued) {
395
+ enqueueRenegotiate(peer, link);
396
+ }
397
+ }
398
+ }
399
+ finally {
400
+ link.rtcPending--;
401
+ }
402
+ });
403
+ };
404
+ const canReachPeer = (id) => {
405
+ if (!signaling)
406
+ return false;
407
+ return typeof signaling.canReach === 'function' ? signaling.canReach(id) : state === 'online';
408
+ };
158
409
  function retry(peer) {
159
- if (stopped || state !== 'online' || !peer.advertised || peer.retry || peer.link)
410
+ if (stopped || !canReachPeer(peer.id) || !peer.advertised || peer.retry || peer.link)
160
411
  return;
161
412
  const base = Math.min(8000, 350 * 2 ** Math.min(peer.failures++, 5));
162
413
  const delay = Math.round(base * (0.75 + Math.random() * 0.5));
@@ -171,8 +422,11 @@ export function joinRoom(name, options) {
171
422
  delete peer.link;
172
423
  if (link.accepted)
173
424
  peer.previous = link.attempt;
425
+ if (peer.earlyIce?.attempt === link.attempt)
426
+ delete peer.earlyIce;
174
427
  clearTimeout(link.deadline);
175
428
  clearTimeout(link.gather);
429
+ clearTimeout(link.iceFlush);
176
430
  clearTimeout(link.grace);
177
431
  const reliable = link.channels.reliable;
178
432
  if (flushLeave && reliable.readyState === 'open') {
@@ -195,8 +449,20 @@ export function joinRoom(name, options) {
195
449
  link.pc.close();
196
450
  if (!peer.advertised)
197
451
  peers.delete(peer.id);
198
- if (link.ready)
452
+ if (link.ready) {
453
+ for (const stream of [...link.remoteStreams.values()]) {
454
+ peerStreamEndListeners.fire(peer.id, stream);
455
+ }
456
+ link.remoteStreams.clear();
457
+ link.senders.clear();
458
+ link.pendingStreamEnds.clear();
199
459
  leaves.fire(peer.id);
460
+ }
461
+ else {
462
+ link.remoteStreams.clear();
463
+ link.senders.clear();
464
+ link.pendingStreamEnds.clear();
465
+ }
200
466
  if (shouldRetry)
201
467
  retry(peer);
202
468
  }
@@ -234,14 +500,51 @@ export function joinRoom(name, options) {
234
500
  ready: false,
235
501
  accepted: false,
236
502
  published: false,
237
- answerApplied: false
503
+ answerApplied: false,
504
+ remoteDescApplied: false,
505
+ pendingCandidates: [],
506
+ rtcQueue: Promise.resolve(),
507
+ rtcPending: 0,
508
+ renegotiateQueued: false,
509
+ pendingStreamEnds: new Set(),
510
+ senders: new Map(),
511
+ remoteStreams: new Map()
512
+ };
513
+ // Attach active local streams before initial createOffer() on the offerer for 0-RTT media setup.
514
+ if (self < peer.id) {
515
+ for (const stream of desiredStreamsFor(peer.id)) {
516
+ attachStreamToLink(link, stream);
517
+ }
518
+ }
519
+ const earlyStreams = [];
520
+ pc.ontrack = (event) => {
521
+ if (stopped || peer.link !== link)
522
+ return;
523
+ const stream = event.streams[0] ?? new MediaStream([event.track]);
524
+ if (link.remoteStreams.has(stream.id) || link.remoteStreams.size >= maxRemoteStreamsPerPeer)
525
+ return;
526
+ link.remoteStreams.set(stream.id, stream);
527
+ if (link.ready)
528
+ peerStreamListeners.fire(peer.id, stream);
529
+ else
530
+ earlyStreams.push(stream);
531
+ };
532
+ const reportIceFailed = (message) => {
533
+ const wasReady = link.ready;
534
+ drop(peer, link);
535
+ if (!stopped && !wasReady && !peer.iceFailedReported) {
536
+ peer.iceFailedReported = true;
537
+ errors.fire({ code: 'ice-failed', peerId: peer.id, message });
538
+ }
238
539
  };
239
540
  peer.link = link;
240
- link.deadline = setTimeout(() => drop(peer, link), timeout);
541
+ link.deadline = setTimeout(() => reportIceFailed('Connection handshake timed out'), timeout);
241
542
  pc.onconnectionstatechange = () => {
242
543
  if (peer.link !== link)
243
544
  return;
244
- if (pc.connectionState === 'failed' || pc.connectionState === 'closed')
545
+ if (pc.connectionState === 'failed')
546
+ reportIceFailed('Peer connection failed');
547
+ else if (pc.connectionState === 'closed')
245
548
  drop(peer, link);
246
549
  else if (pc.connectionState === 'disconnected') {
247
550
  link.grace ??= setTimeout(() => drop(peer, link), disconnectGrace);
@@ -252,6 +555,7 @@ export function joinRoom(name, options) {
252
555
  }
253
556
  };
254
557
  const early = [];
558
+ const earlyRtc = [];
255
559
  let earlyBytes = 0;
256
560
  for (const delivery of ['unreliable', 'reliable']) {
257
561
  const channel = channels[delivery];
@@ -268,15 +572,46 @@ export function joinRoom(name, options) {
268
572
  return;
269
573
  if (Object.values(channels).every((c) => c.readyState === 'open')) {
270
574
  clearTimeout(link.deadline);
575
+ clearTimeout(link.iceFlush);
576
+ delete link.iceFlush;
271
577
  link.ready = true;
272
578
  peer.failures = 0;
579
+ peer.iceFailedReported = false;
273
580
  joins.fire(peer.id);
581
+ for (const stream of earlyStreams) {
582
+ if (peer.link !== link || stopped)
583
+ break;
584
+ peerStreamListeners.fire(peer.id, stream);
585
+ }
586
+ earlyStreams.length = 0;
587
+ for (const raw of earlyRtc) {
588
+ if (peer.link !== link || stopped)
589
+ break;
590
+ handleRtcControl(peer, link, raw);
591
+ }
592
+ earlyRtc.length = 0;
274
593
  for (const [bytes, mode] of early) {
275
594
  if (peer.link !== link || stopped)
276
595
  break;
277
596
  packets.fire(peer.id, bytes, mode);
278
597
  }
279
598
  early.length = 0;
599
+ // Reconcile local streams (attach newly desired ones, detach any removed mid-handshake).
600
+ if (!stopped && peer.link === link) {
601
+ const desired = desiredStreamsFor(peer.id);
602
+ let needsRenegotiate = false;
603
+ for (const stream of desired) {
604
+ if (attachStreamToLink(link, stream))
605
+ needsRenegotiate = true;
606
+ }
607
+ for (const stream of [...link.senders.keys()]) {
608
+ if (!desired.has(stream) && detachStreamFromLink(link, stream)) {
609
+ needsRenegotiate = true;
610
+ }
611
+ }
612
+ if (needsRenegotiate)
613
+ enqueueRenegotiate(peer, link);
614
+ }
280
615
  }
281
616
  };
282
617
  channel.onmessage = ({ data }) => {
@@ -287,6 +622,15 @@ export function joinRoom(name, options) {
287
622
  drop(peer, link);
288
623
  return;
289
624
  }
625
+ if (typeof data === 'string' &&
626
+ delivery === 'reliable' &&
627
+ data.startsWith(rtcControlPrefix)) {
628
+ if (link.ready)
629
+ handleRtcControl(peer, link, data);
630
+ else if (earlyRtc.length < 16 && data.length <= maxRtcControlBytes)
631
+ earlyRtc.push(data);
632
+ return;
633
+ }
290
634
  if (!(data instanceof ArrayBuffer))
291
635
  return;
292
636
  if (data.byteLength > maxPacket) {
@@ -320,17 +664,22 @@ export function joinRoom(name, options) {
320
664
  await pc.setRemoteDescription({ type: 'offer', sdp: remoteOffer });
321
665
  if (peer.link !== link)
322
666
  return;
667
+ link.remoteDescApplied = true;
668
+ if (peer.earlyIce?.attempt === attempt) {
669
+ const earlyCandidates = peer.earlyIce.candidates;
670
+ delete peer.earlyIce;
671
+ applyRemoteCandidates(peer, link, earlyCandidates);
672
+ }
673
+ if (link.pendingCandidates.length > 0) {
674
+ const queued = link.pendingCandidates.splice(0);
675
+ applyRemoteCandidates(peer, link, queued);
676
+ }
323
677
  }
324
678
  link.accepted = true;
325
679
  const description = remoteOffer === undefined ? await pc.createOffer() : await pc.createAnswer();
326
680
  if (peer.link !== link)
327
681
  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
682
  const current = link;
331
- let hasRelay = false;
332
- let hasSrflx = false;
333
- let softExpired = false;
334
683
  const publish = (force = false) => {
335
684
  if (current.published || peer.link !== current)
336
685
  return;
@@ -345,41 +694,103 @@ export function joinRoom(name, options) {
345
694
  if (!signaling?.send(peer.id, { kind: local.type, attempt, sdp: local.sdp }))
346
695
  drop(peer, current);
347
696
  };
348
- pc.onicecandidate = (event) => {
349
- if (peer.link !== current || current.published)
350
- return;
351
- if (!event.candidate) {
352
- publish(true);
697
+ if (useTrickle) {
698
+ const outgoing = [];
699
+ let totalQueued = 0;
700
+ let gatheringDone = false;
701
+ const flushIce = () => {
702
+ clearTimeout(current.iceFlush);
703
+ delete current.iceFlush;
704
+ if (!current.published || peer.link !== current || current.ready || stopped)
705
+ return;
706
+ while (outgoing.length > 0) {
707
+ const batch = outgoing.splice(0, trickleBatchSize);
708
+ signaling?.send(peer.id, { kind: 'ice', attempt, candidates: batch });
709
+ }
710
+ };
711
+ const scheduleFlush = (immediate = false) => {
712
+ if (!current.published || peer.link !== current || current.ready || stopped)
713
+ return;
714
+ if (immediate || outgoing.length >= trickleBatchSize) {
715
+ flushIce();
716
+ }
717
+ else if (!current.iceFlush) {
718
+ current.iceFlush = setTimeout(flushIce, trickleBatchMs);
719
+ }
720
+ };
721
+ pc.onicecandidate = (event) => {
722
+ if (peer.link !== current || current.ready || stopped)
723
+ return;
724
+ if (!event.candidate) {
725
+ gatheringDone = true;
726
+ if (totalQueued < maxTrickleCandidates) {
727
+ outgoing.push({ candidate: '' });
728
+ totalQueued++;
729
+ }
730
+ scheduleFlush(true);
731
+ return;
732
+ }
733
+ if (totalQueued >= maxTrickleCandidates)
734
+ return;
735
+ outgoing.push({
736
+ candidate: event.candidate.candidate,
737
+ ...(event.candidate.sdpMid !== null ? { sdpMid: event.candidate.sdpMid } : {}),
738
+ ...(event.candidate.sdpMLineIndex !== null
739
+ ? { sdpMLineIndex: event.candidate.sdpMLineIndex }
740
+ : {})
741
+ });
742
+ totalQueued++;
743
+ scheduleFlush(false);
744
+ };
745
+ await pc.setLocalDescription(description);
746
+ if (peer.link !== current)
353
747
  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);
748
+ publish(true);
749
+ if (outgoing.length > 0)
750
+ scheduleFlush(gatheringDone);
751
+ }
752
+ else {
753
+ // Send one complete SDP. Publish early after gatherTimeout so unreachable STUN never stalls,
754
+ // while allowing extra time when relay/TURN candidates are required or configured.
755
+ let hasRelay = false;
756
+ let hasSrflx = false;
757
+ let softExpired = false;
758
+ pc.onicecandidate = (event) => {
759
+ if (peer.link !== current || current.published)
760
+ return;
761
+ if (!event.candidate) {
762
+ publish(true);
763
+ return;
378
764
  }
379
- else {
765
+ const type = event.candidate.type;
766
+ if (type === 'relay')
767
+ hasRelay = true;
768
+ else if (type === 'srflx')
769
+ hasSrflx = true;
770
+ if (softExpired && (hasRelay || (!needsRelay && hasSrflx))) {
380
771
  publish(true);
381
772
  }
382
- }, gatherTimeout);
773
+ };
774
+ pc.onicegatheringstatechange = () => publish(false);
775
+ await pc.setLocalDescription(description);
776
+ if (peer.link !== current)
777
+ return;
778
+ publish(false);
779
+ if (!current.published) {
780
+ const extendedGather = options.iceGatheringTimeoutMs === undefined
781
+ ? Math.min(10_000, Math.floor(timeout / 2))
782
+ : gatherTimeout;
783
+ current.gather = setTimeout(() => {
784
+ softExpired = true;
785
+ const waitingForRelay = (needsRelay && !hasRelay) || (hasTurn && !hasRelay && !hasSrflx);
786
+ if (waitingForRelay && extendedGather > gatherTimeout) {
787
+ current.gather = setTimeout(() => publish(true), extendedGather - gatherTimeout);
788
+ }
789
+ else {
790
+ publish(true);
791
+ }
792
+ }, gatherTimeout);
793
+ }
383
794
  }
384
795
  }
385
796
  catch {
@@ -390,7 +801,12 @@ export function joinRoom(name, options) {
390
801
  }
391
802
  }
392
803
  function discover(peer) {
393
- if (stopped || !signaling || !peer.advertised || state !== 'online' || peer.link || peer.retry)
804
+ if (stopped ||
805
+ !signaling ||
806
+ !peer.advertised ||
807
+ !canReachPeer(peer.id) ||
808
+ peer.link ||
809
+ peer.retry)
394
810
  return;
395
811
  if (self < peer.id)
396
812
  void negotiate(peer, ++nextAttempt);
@@ -444,7 +860,40 @@ export function joinRoom(name, options) {
444
860
  drop(peer, link, false, false);
445
861
  void negotiate(peer, signal.attempt, prepareRemoteSdp(signal));
446
862
  }
447
- else if (self < id &&
863
+ else if (signal.kind === 'ice') {
864
+ if (link && signal.attempt === link.attempt) {
865
+ const candidates = prepareRemoteCandidates(signal);
866
+ if (link.remoteDescApplied) {
867
+ applyRemoteCandidates(peer, link, candidates);
868
+ }
869
+ else {
870
+ for (const item of candidates) {
871
+ if (link.pendingCandidates.length >= maxTrickleCandidates)
872
+ break;
873
+ link.pendingCandidates.push(item);
874
+ }
875
+ }
876
+ }
877
+ else {
878
+ const baseline = link?.attempt ?? peer.previous ?? 0;
879
+ if (self > id &&
880
+ signal.attempt > baseline &&
881
+ (baseline === 0 || signal.attempt - baseline <= 1024)) {
882
+ if (!peer.earlyIce || signal.attempt > peer.earlyIce.attempt) {
883
+ peer.earlyIce = { attempt: signal.attempt, candidates: [] };
884
+ }
885
+ if (peer.earlyIce.attempt === signal.attempt) {
886
+ for (const item of prepareRemoteCandidates(signal)) {
887
+ if (peer.earlyIce.candidates.length >= maxTrickleCandidates)
888
+ break;
889
+ peer.earlyIce.candidates.push(item);
890
+ }
891
+ }
892
+ }
893
+ }
894
+ }
895
+ else if (signal.kind === 'answer' &&
896
+ self < id &&
448
897
  link &&
449
898
  !link.answerApplied &&
450
899
  link.attempt === signal.attempt &&
@@ -452,6 +901,15 @@ export function joinRoom(name, options) {
452
901
  link.answerApplied = true;
453
902
  void link.pc
454
903
  .setRemoteDescription({ type: 'answer', sdp: prepareRemoteSdp(signal) })
904
+ .then(() => {
905
+ if (stopped || peer.link !== link)
906
+ return;
907
+ link.remoteDescApplied = true;
908
+ if (link.pendingCandidates.length > 0) {
909
+ const queued = link.pendingCandidates.splice(0);
910
+ applyRemoteCandidates(peer, link, queued);
911
+ }
912
+ })
455
913
  .catch(() => drop(peer, link));
456
914
  }
457
915
  }
@@ -467,24 +925,41 @@ export function joinRoom(name, options) {
467
925
  state = next;
468
926
  if (next !== 'online') {
469
927
  for (const peer of peers.values()) {
470
- clearTimeout(peer.retry);
471
- delete peer.retry;
928
+ if (!canReachPeer(peer.id)) {
929
+ clearTimeout(peer.retry);
930
+ delete peer.retry;
931
+ }
472
932
  }
473
933
  }
474
934
  status.fire(next, reason);
475
935
  if (!stopped && state === 'online') {
476
936
  for (const peer of peers.values()) {
477
- if (peer.advertised && !peer.link) {
937
+ if (peer.advertised && !peer.link && !peer.retry) {
478
938
  peer.failures = 0;
479
939
  discover(peer);
480
940
  }
481
941
  }
482
942
  }
483
943
  },
944
+ error(code, message) {
945
+ if (stopped || (code !== 'decrypt-failed' && code !== 'signaling-error'))
946
+ return;
947
+ errors.fire({
948
+ code,
949
+ message: message ??
950
+ (code === 'decrypt-failed'
951
+ ? 'Failed to decrypt signaling message'
952
+ : 'Signaling adapter error')
953
+ });
954
+ },
484
955
  roster(ids) {
485
956
  if (stopped)
486
957
  return;
487
958
  const present = new Set(ids);
959
+ for (const id of [...rejectedFull]) {
960
+ if (!present.has(id) || peers.has(id))
961
+ rejectedFull.delete(id);
962
+ }
488
963
  for (const peer of peers.values()) {
489
964
  peer.advertised = present.has(peer.id);
490
965
  if (!peer.advertised) {
@@ -494,24 +969,37 @@ export function joinRoom(name, options) {
494
969
  peers.delete(peer.id);
495
970
  }
496
971
  }
972
+ const newlyRejected = [];
497
973
  for (const id of present) {
498
974
  if (id === self)
499
975
  continue;
500
976
  let peer = peers.get(id);
501
977
  if (!peer) {
502
- if (peers.size >= maxPeers)
978
+ if (peers.size >= maxPeers) {
979
+ if (!rejectedFull.has(id)) {
980
+ rejectedFull.add(id);
981
+ newlyRejected.push(id);
982
+ }
503
983
  continue;
984
+ }
504
985
  peer = { id, advertised: true, previous: null, failures: 0 };
505
986
  peers.set(id, peer);
506
987
  }
507
988
  discover(peer);
508
989
  }
990
+ for (const id of newlyRejected) {
991
+ if (stopped)
992
+ return;
993
+ errors.fire({ code: 'room-full', peerId: id, message: 'Room reached maxPeers limit' });
994
+ }
509
995
  }
510
996
  });
997
+ useTrickle = signaling.trickle === true;
511
998
  for (const peer of peers.values())
512
999
  discover(peer);
1000
+ const closeHooks = new Set();
513
1001
  const connected = () => [...peers.values()].filter((p) => p.link?.ready).map((p) => p.id);
514
- return {
1002
+ const room = {
515
1003
  id: self,
516
1004
  get peers() {
517
1005
  return connected();
@@ -524,6 +1012,69 @@ export function joinRoom(name, options) {
524
1012
  onPeerJoin: joins.add,
525
1013
  onPeerLeave: leaves.add,
526
1014
  onSignalingChange: status.add,
1015
+ onError: errors.add,
1016
+ onPeerStream: peerStreamListeners.add,
1017
+ onPeerStreamEnd: peerStreamEndListeners.add,
1018
+ addStream(stream, to) {
1019
+ if (stopped)
1020
+ throw new Error('Room is closed');
1021
+ if (!stream || typeof stream.getTracks !== 'function')
1022
+ throw new TypeError('Expected a MediaStream');
1023
+ if (to === undefined) {
1024
+ broadcastStreams.add(stream);
1025
+ for (const peer of peers.values()) {
1026
+ const link = peer.link;
1027
+ if (link?.ready && attachStreamToLink(link, stream)) {
1028
+ enqueueRenegotiate(peer, link);
1029
+ }
1030
+ }
1031
+ }
1032
+ else {
1033
+ if (to === self)
1034
+ return;
1035
+ let set = peerStreams.get(to);
1036
+ if (!set) {
1037
+ set = new Set();
1038
+ peerStreams.set(to, set);
1039
+ }
1040
+ set.add(stream);
1041
+ const peer = peers.get(to);
1042
+ const link = peer?.link;
1043
+ if (peer && link?.ready && attachStreamToLink(link, stream)) {
1044
+ enqueueRenegotiate(peer, link);
1045
+ }
1046
+ }
1047
+ },
1048
+ removeStream(stream, to) {
1049
+ if (stopped || !stream)
1050
+ return;
1051
+ if (to === undefined) {
1052
+ if (!broadcastStreams.delete(stream))
1053
+ return;
1054
+ for (const peer of peers.values()) {
1055
+ if (peerStreams.get(peer.id)?.has(stream))
1056
+ continue;
1057
+ const link = peer.link;
1058
+ if (link?.ready && detachStreamFromLink(link, stream)) {
1059
+ enqueueRenegotiate(peer, link);
1060
+ }
1061
+ }
1062
+ }
1063
+ else {
1064
+ const set = peerStreams.get(to);
1065
+ if (!set?.delete(stream))
1066
+ return;
1067
+ if (set.size === 0)
1068
+ peerStreams.delete(to);
1069
+ if (broadcastStreams.has(stream))
1070
+ return;
1071
+ const peer = peers.get(to);
1072
+ const link = peer?.link;
1073
+ if (peer && link?.ready && detachStreamFromLink(link, stream)) {
1074
+ enqueueRenegotiate(peer, link);
1075
+ }
1076
+ }
1077
+ },
527
1078
  async getStats(peerId) {
528
1079
  if (stopped || peerId === self)
529
1080
  return null;
@@ -582,6 +1133,15 @@ export function joinRoom(name, options) {
582
1133
  stopped = true;
583
1134
  const wasClosed = state === 'closed';
584
1135
  state = 'closed';
1136
+ for (const fn of [...closeHooks]) {
1137
+ closeHooks.delete(fn);
1138
+ try {
1139
+ fn();
1140
+ }
1141
+ catch (error) {
1142
+ globalThis.reportError?.(error);
1143
+ }
1144
+ }
585
1145
  signaling?.close();
586
1146
  for (const peer of peers.values()) {
587
1147
  peer.advertised = false;
@@ -591,10 +1151,49 @@ export function joinRoom(name, options) {
591
1151
  drop(peer, peer.link, true, false);
592
1152
  }
593
1153
  peers.clear();
1154
+ rejectedFull.clear();
1155
+ broadcastStreams.clear();
1156
+ peerStreams.clear();
594
1157
  if (!wasClosed)
595
1158
  status.fire('closed');
596
- for (const group of [joins, leaves, packets, drains, status])
1159
+ for (const group of [
1160
+ joins,
1161
+ leaves,
1162
+ packets,
1163
+ drains,
1164
+ status,
1165
+ errors,
1166
+ peerStreamListeners,
1167
+ peerStreamEndListeners
1168
+ ])
597
1169
  group.clear();
598
1170
  }
599
1171
  };
1172
+ roomInternals.set(room, {
1173
+ isClosed: () => stopped,
1174
+ onClose(fn) {
1175
+ if (stopped) {
1176
+ fn();
1177
+ return () => { };
1178
+ }
1179
+ closeHooks.add(fn);
1180
+ return () => {
1181
+ closeHooks.delete(fn);
1182
+ };
1183
+ },
1184
+ getRemoteStreams() {
1185
+ const out = [];
1186
+ if (stopped)
1187
+ return out;
1188
+ for (const peer of peers.values()) {
1189
+ if (!peer.link?.ready)
1190
+ continue;
1191
+ for (const stream of peer.link.remoteStreams.values()) {
1192
+ out.push([peer.id, stream]);
1193
+ }
1194
+ }
1195
+ return out;
1196
+ }
1197
+ });
1198
+ return room;
600
1199
  }