@dimchansky/meshpost 0.0.0-stage → 0.2.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/blob.js ADDED
@@ -0,0 +1,364 @@
1
+ import { createChannel } from './channel.js';
2
+ const opStart = 0x01;
3
+ const opData = 0x02;
4
+ const opAbort = 0x03;
5
+ const startHeaderBytes = 9;
6
+ const dataHeaderBytes = 5;
7
+ const abortFrameBytes = 5;
8
+ const maxPacketBytes = 16 * 1024;
9
+ const maxUint32 = 0xffff_ffff;
10
+ const defaultMaxReceiveBytes = 4 * 1024 * 1024;
11
+ const defaultChunkSize = 15 * 1024;
12
+ const defaultReceiveTimeoutMs = 30_000;
13
+ const defaultMaxConcurrentPerPeer = 4;
14
+ const encoder = new TextEncoder();
15
+ function listeners() {
16
+ const entries = new Set();
17
+ let closed = false;
18
+ return {
19
+ add(fn, options) {
20
+ const signal = options?.signal;
21
+ if (closed || signal?.aborted)
22
+ return () => { };
23
+ const entry = {
24
+ fn,
25
+ once: Boolean(options?.once),
26
+ off() {
27
+ if (!entries.delete(entry))
28
+ return;
29
+ signal?.removeEventListener('abort', entry.off);
30
+ }
31
+ };
32
+ entries.add(entry);
33
+ signal?.addEventListener('abort', entry.off, { once: true });
34
+ return entry.off;
35
+ },
36
+ fire(...args) {
37
+ for (const entry of [...entries]) {
38
+ if (!entries.has(entry))
39
+ continue;
40
+ if (entry.once)
41
+ entry.off();
42
+ try {
43
+ entry.fn(...args);
44
+ }
45
+ catch (error) {
46
+ globalThis.reportError?.(error);
47
+ }
48
+ }
49
+ },
50
+ clear() {
51
+ closed = true;
52
+ for (const entry of [...entries])
53
+ entry.off();
54
+ }
55
+ };
56
+ }
57
+ /**
58
+ * Create a chunked reliable binary channel for payloads larger than Meshpost's 16 KiB packet limit.
59
+ * Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
60
+ */
61
+ export function createBlobChannel(room, name, options = {}) {
62
+ const channel = createChannel(room, name, { delivery: 'reliable' });
63
+ const nameBytesLen = encoder.encode(name).length;
64
+ const maxAllowedChunk = maxPacketBytes - (1 + nameBytesLen) - startHeaderBytes;
65
+ const maxReceiveBytes = options.maxReceiveBytes ?? defaultMaxReceiveBytes;
66
+ if (!Number.isSafeInteger(maxReceiveBytes) || maxReceiveBytes < 0 || maxReceiveBytes > maxUint32)
67
+ throw new RangeError('Invalid maxReceiveBytes');
68
+ const chunkSize = options.chunkSize ?? Math.min(defaultChunkSize, maxAllowedChunk);
69
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0 || chunkSize > maxAllowedChunk)
70
+ throw new RangeError(`chunkSize must be 1..${maxAllowedChunk}`);
71
+ const receiveTimeoutMs = options.receiveTimeoutMs ?? defaultReceiveTimeoutMs;
72
+ if (!Number.isSafeInteger(receiveTimeoutMs) ||
73
+ receiveTimeoutMs <= 0 ||
74
+ receiveTimeoutMs > 2_147_483_647)
75
+ throw new RangeError('Invalid receiveTimeoutMs');
76
+ const maxConcurrentPerPeer = options.maxConcurrentPerPeer ?? defaultMaxConcurrentPerPeer;
77
+ if (!Number.isSafeInteger(maxConcurrentPerPeer) ||
78
+ maxConcurrentPerPeer <= 0 ||
79
+ maxConcurrentPerPeer > 64)
80
+ throw new RangeError('Invalid maxConcurrentPerPeer');
81
+ const blobs = listeners();
82
+ const progresses = listeners();
83
+ const incoming = new Map();
84
+ const closeWaiters = new Set();
85
+ const internalAbort = new AbortController();
86
+ let nextTransferId = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x7fff_ffff) + 1;
87
+ const isRoomClosed = () => room.signalingState === 'closed';
88
+ let closed = isRoomClosed();
89
+ const dropTransfer = (peerId, transferId) => {
90
+ const byPeer = incoming.get(peerId);
91
+ const entry = byPeer?.get(transferId);
92
+ if (!entry)
93
+ return;
94
+ clearTimeout(entry.timer);
95
+ byPeer.delete(transferId);
96
+ if (byPeer.size === 0)
97
+ incoming.delete(peerId);
98
+ };
99
+ const dropPeerTransfers = (peerId) => {
100
+ const byPeer = incoming.get(peerId);
101
+ if (!byPeer)
102
+ return;
103
+ for (const entry of byPeer.values())
104
+ clearTimeout(entry.timer);
105
+ incoming.delete(peerId);
106
+ };
107
+ const shutdown = () => {
108
+ if (closed)
109
+ return;
110
+ closed = true;
111
+ internalAbort.abort();
112
+ for (const byPeer of incoming.values()) {
113
+ for (const entry of byPeer.values())
114
+ clearTimeout(entry.timer);
115
+ }
116
+ incoming.clear();
117
+ for (const wake of [...closeWaiters])
118
+ wake();
119
+ closeWaiters.clear();
120
+ blobs.clear();
121
+ progresses.clear();
122
+ };
123
+ const sendAbort = (peerId, transferId) => {
124
+ if (isRoomClosed())
125
+ return;
126
+ const frame = new Uint8Array(abortFrameBytes);
127
+ const view = new DataView(frame.buffer);
128
+ frame[0] = opAbort;
129
+ view.setUint32(1, transferId);
130
+ try {
131
+ channel.send(frame, { to: peerId });
132
+ }
133
+ catch {
134
+ // Ignore errors if room closed concurrently.
135
+ }
136
+ };
137
+ const waitForDrain = (peerId, signal) => new Promise((resolve) => {
138
+ if (closed || signal?.aborted) {
139
+ resolve('abort');
140
+ return;
141
+ }
142
+ if (isRoomClosed()) {
143
+ resolve('unavailable');
144
+ return;
145
+ }
146
+ const ctrl = new AbortController();
147
+ let settled = false;
148
+ const done = (outcome) => {
149
+ if (settled)
150
+ return;
151
+ settled = true;
152
+ ctrl.abort();
153
+ closeWaiters.delete(onClose);
154
+ signal?.removeEventListener('abort', onAbort);
155
+ resolve(outcome);
156
+ };
157
+ const onClose = () => done('abort');
158
+ const onAbort = () => done('abort');
159
+ closeWaiters.add(onClose);
160
+ signal?.addEventListener('abort', onAbort, { once: true });
161
+ room.onDrain((id, delivery) => {
162
+ if (id === peerId && delivery === 'reliable')
163
+ done('drain');
164
+ }, { signal: ctrl.signal });
165
+ room.onPeerLeave((id) => {
166
+ if (id === peerId)
167
+ done('unavailable');
168
+ }, { signal: ctrl.signal });
169
+ });
170
+ const sendToPeer = async (peerId, bytes, options) => {
171
+ const { onProgress, signal } = options;
172
+ if (closed || signal?.aborted)
173
+ return 'aborted';
174
+ if (isRoomClosed())
175
+ return 'unavailable';
176
+ if (bytes.byteLength > maxUint32)
177
+ return 'too-large';
178
+ const transferId = ++nextTransferId >>> 0;
179
+ const totalBytes = bytes.byteLength;
180
+ let offset = 0;
181
+ let started = false;
182
+ while (true) {
183
+ if (closed || signal?.aborted) {
184
+ if (started)
185
+ sendAbort(peerId, transferId);
186
+ return 'aborted';
187
+ }
188
+ if (isRoomClosed())
189
+ return 'unavailable';
190
+ const isStart = !started;
191
+ const sliceEnd = Math.min(totalBytes, offset + chunkSize);
192
+ const slice = bytes.subarray(offset, sliceEnd);
193
+ const headerLen = isStart ? startHeaderBytes : dataHeaderBytes;
194
+ const frame = new Uint8Array(headerLen + slice.byteLength);
195
+ const view = new DataView(frame.buffer);
196
+ frame[0] = isStart ? opStart : opData;
197
+ view.setUint32(1, transferId);
198
+ if (isStart)
199
+ view.setUint32(5, totalBytes);
200
+ frame.set(slice, headerLen);
201
+ let result;
202
+ try {
203
+ result = channel.send(frame, { to: peerId });
204
+ }
205
+ catch {
206
+ return 'unavailable';
207
+ }
208
+ const status = result.get(peerId);
209
+ if (status === 'accepted') {
210
+ started = true;
211
+ offset = sliceEnd;
212
+ try {
213
+ onProgress?.(peerId, offset, totalBytes);
214
+ }
215
+ catch (error) {
216
+ globalThis.reportError?.(error);
217
+ }
218
+ if (offset >= totalBytes)
219
+ return 'sent';
220
+ }
221
+ else if (status === 'busy') {
222
+ const outcome = await waitForDrain(peerId, signal);
223
+ if (outcome === 'abort') {
224
+ if (started)
225
+ sendAbort(peerId, transferId);
226
+ return 'aborted';
227
+ }
228
+ if (outcome === 'unavailable')
229
+ return 'unavailable';
230
+ }
231
+ else if (status === 'too-large') {
232
+ if (started)
233
+ sendAbort(peerId, transferId);
234
+ return 'too-large';
235
+ }
236
+ else {
237
+ return 'unavailable';
238
+ }
239
+ }
240
+ };
241
+ if (!closed) {
242
+ const internalListen = { signal: internalAbort.signal };
243
+ room.onPeerLeave((peerId) => dropPeerTransfers(peerId), internalListen);
244
+ room.onSignalingChange((state) => {
245
+ if (state === 'closed')
246
+ shutdown();
247
+ }, internalListen);
248
+ channel.onPacket((from, bytes) => {
249
+ if (closed || bytes.byteLength < abortFrameBytes)
250
+ return;
251
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
252
+ const op = bytes[0];
253
+ const transferId = view.getUint32(1);
254
+ if (op === opAbort) {
255
+ dropTransfer(from, transferId);
256
+ return;
257
+ }
258
+ if (op === opStart) {
259
+ if (bytes.byteLength < startHeaderBytes)
260
+ return;
261
+ const totalBytes = view.getUint32(5);
262
+ const payload = bytes.subarray(startHeaderBytes);
263
+ if (totalBytes > maxReceiveBytes || payload.byteLength > totalBytes)
264
+ return;
265
+ const existingByPeer = incoming.get(from);
266
+ if (existingByPeer?.has(transferId))
267
+ return;
268
+ if (payload.byteLength === totalBytes) {
269
+ if (totalBytes > 0) {
270
+ progresses.fire(from, { transferId, receivedBytes: totalBytes, totalBytes });
271
+ }
272
+ blobs.fire(from, payload.slice());
273
+ return;
274
+ }
275
+ if (existingByPeer && existingByPeer.size >= maxConcurrentPerPeer)
276
+ return;
277
+ const initialCap = Math.min(totalBytes, Math.max(payload.byteLength, 16 * 1024));
278
+ const buffer = new Uint8Array(initialCap);
279
+ if (payload.byteLength > 0)
280
+ buffer.set(payload, 0);
281
+ const timer = setTimeout(() => dropTransfer(from, transferId), receiveTimeoutMs);
282
+ const entry = {
283
+ totalBytes,
284
+ maxFrames: Math.ceil(totalBytes / 256) + 64,
285
+ receivedBytes: payload.byteLength,
286
+ frames: 1,
287
+ buffer,
288
+ timer
289
+ };
290
+ let byPeer = existingByPeer;
291
+ if (!byPeer) {
292
+ byPeer = new Map();
293
+ incoming.set(from, byPeer);
294
+ }
295
+ byPeer.set(transferId, entry);
296
+ if (entry.receivedBytes > 0) {
297
+ progresses.fire(from, { transferId, receivedBytes: entry.receivedBytes, totalBytes });
298
+ }
299
+ return;
300
+ }
301
+ if (op === opData) {
302
+ if (bytes.byteLength <= dataHeaderBytes)
303
+ return;
304
+ const byPeer = incoming.get(from);
305
+ const entry = byPeer?.get(transferId);
306
+ if (!entry)
307
+ return;
308
+ const payload = bytes.subarray(dataHeaderBytes);
309
+ entry.frames++;
310
+ if (entry.frames > entry.maxFrames ||
311
+ entry.receivedBytes + payload.byteLength > entry.totalBytes) {
312
+ dropTransfer(from, transferId);
313
+ return;
314
+ }
315
+ const needed = entry.receivedBytes + payload.byteLength;
316
+ if (needed > entry.buffer.byteLength) {
317
+ let nextCap = entry.buffer.byteLength;
318
+ while (nextCap < needed)
319
+ nextCap = Math.min(entry.totalBytes, nextCap * 2);
320
+ const grown = new Uint8Array(nextCap);
321
+ grown.set(entry.buffer.subarray(0, entry.receivedBytes), 0);
322
+ entry.buffer = grown;
323
+ }
324
+ entry.buffer.set(payload, entry.receivedBytes);
325
+ entry.receivedBytes = needed;
326
+ clearTimeout(entry.timer);
327
+ progresses.fire(from, {
328
+ transferId,
329
+ receivedBytes: entry.receivedBytes,
330
+ totalBytes: entry.totalBytes
331
+ });
332
+ if (closed || byPeer?.get(transferId) !== entry)
333
+ return;
334
+ if (entry.receivedBytes === entry.totalBytes) {
335
+ dropTransfer(from, transferId);
336
+ blobs.fire(from, entry.buffer);
337
+ }
338
+ else {
339
+ entry.timer = setTimeout(() => dropTransfer(from, transferId), receiveTimeoutMs);
340
+ }
341
+ }
342
+ }, internalListen);
343
+ }
344
+ return {
345
+ name,
346
+ async send(bytes, sendOptions = {}) {
347
+ if (closed || isRoomClosed())
348
+ throw new Error('BlobChannel is closed');
349
+ if (!(bytes instanceof Uint8Array))
350
+ throw new TypeError('Expected a Uint8Array');
351
+ const targets = sendOptions.to === undefined ? [...room.peers] : [sendOptions.to];
352
+ const results = new Map();
353
+ if (targets.length === 0)
354
+ return results;
355
+ await Promise.all(targets.map(async (peerId) => {
356
+ results.set(peerId, await sendToPeer(peerId, bytes, sendOptions));
357
+ }));
358
+ return results;
359
+ },
360
+ onBlob: blobs.add,
361
+ onProgress: progresses.add,
362
+ close: shutdown
363
+ };
364
+ }
@@ -0,0 +1,26 @@
1
+ import type { Delivery, ListenOptions, Room, SendResult } from './room.js';
2
+ export interface ChannelOptions {
3
+ /** Delivery mode for this logical channel. @default 'unreliable' */
4
+ delivery?: Delivery;
5
+ }
6
+ export interface ChannelSendOptions {
7
+ /** Optional target peer ID. Omit to broadcast to all connected peers. */
8
+ to?: string;
9
+ }
10
+ /** Named logical message stream multiplexed over a Room's existing data channels. */
11
+ export interface Channel {
12
+ /** Logical channel name (1-64 UTF-8 bytes). */
13
+ readonly name: string;
14
+ /** Delivery mode configured for this channel. */
15
+ readonly delivery: Delivery;
16
+ /** Send a binary packet on this named channel synchronously. Returns a per-recipient result map. */
17
+ send(bytes: Uint8Array, options?: ChannelSendOptions): ReadonlyMap<string, SendResult>;
18
+ /** Subscribe to packets sent to this channel name. Returns an unsubscribe function. */
19
+ onPacket(fn: (from: string, bytes: Uint8Array) => void, options?: ListenOptions): () => void;
20
+ }
21
+ /**
22
+ * Create a named logical channel multiplexed over a Room's existing data channels.
23
+ * Adds a compact length-prefixed UTF-8 header (`[len, ...nameBytes, ...payload]`)
24
+ * without opening additional WebRTC RTCDataChannels.
25
+ */
26
+ export declare function createChannel(room: Room, name: string, options?: ChannelOptions): Channel;
@@ -0,0 +1,51 @@
1
+ const encoder = new TextEncoder();
2
+ const maxNameBytes = 64;
3
+ /**
4
+ * Create a named logical channel multiplexed over a Room's existing data channels.
5
+ * Adds a compact length-prefixed UTF-8 header (`[len, ...nameBytes, ...payload]`)
6
+ * without opening additional WebRTC RTCDataChannels.
7
+ */
8
+ export function createChannel(room, name, options = {}) {
9
+ if (typeof name !== 'string' || name.length === 0)
10
+ throw new TypeError('Invalid channel name');
11
+ const nameBytes = encoder.encode(name);
12
+ if (nameBytes.length === 0 || nameBytes.length > maxNameBytes)
13
+ throw new RangeError('Channel name must be 1-64 UTF-8 bytes');
14
+ const delivery = options.delivery ?? 'unreliable';
15
+ if (delivery !== 'unreliable' && delivery !== 'reliable')
16
+ throw new TypeError('Invalid delivery mode');
17
+ const prefix = new Uint8Array(1 + nameBytes.length);
18
+ prefix[0] = nameBytes.length;
19
+ prefix.set(nameBytes, 1);
20
+ return {
21
+ name,
22
+ delivery,
23
+ send(bytes, sendOptions = {}) {
24
+ if (!(bytes instanceof Uint8Array))
25
+ throw new TypeError('Expected a Uint8Array');
26
+ const framed = new Uint8Array(prefix.length + bytes.byteLength);
27
+ framed.set(prefix, 0);
28
+ framed.set(bytes, prefix.length);
29
+ return room.send(framed, sendOptions.to === undefined ? { delivery } : { to: sendOptions.to, delivery });
30
+ },
31
+ onPacket(fn, options) {
32
+ if (options?.signal?.aborted)
33
+ return () => { };
34
+ const once = Boolean(options?.once);
35
+ const roomOptions = options?.signal ? { signal: options.signal } : undefined;
36
+ let off = () => { };
37
+ off = room.onPacket((from, bytes, mode) => {
38
+ if (mode !== delivery || bytes.byteLength < prefix.length)
39
+ return;
40
+ for (let i = 0; i < prefix.length; i++) {
41
+ if (bytes[i] !== prefix[i])
42
+ return;
43
+ }
44
+ if (once)
45
+ off();
46
+ fn(from, bytes.subarray(prefix.length));
47
+ }, roomOptions);
48
+ return off;
49
+ }
50
+ };
51
+ }
@@ -0,0 +1,7 @@
1
+ import type { Signaling } from './signaling.js';
2
+ /**
3
+ * Combine multiple signaling adapters into one composite adapter.
4
+ * Merges peer rosters across all children, routes signals to online children that advertise the target peer,
5
+ * and stays `'online'` as long as at least one child adapter is `'online'`.
6
+ */
7
+ export declare function combineSignaling(...adapters: readonly Signaling[]): Signaling;
@@ -0,0 +1,249 @@
1
+ const maxSeenIcePeers = 256;
2
+ const maxSeenIceAttemptsPerPeer = 4;
3
+ const maxSeenIceKeysPerAttempt = 64;
4
+ function iceCandidateKey(item) {
5
+ return item.candidate + '\0' + (item.sdpMid ?? '') + '\0' + (item.sdpMLineIndex ?? '');
6
+ }
7
+ function setsEqual(a, b) {
8
+ if (a.size !== b.size)
9
+ return false;
10
+ for (const item of a) {
11
+ if (!b.has(item))
12
+ return false;
13
+ }
14
+ return true;
15
+ }
16
+ /**
17
+ * Combine multiple signaling adapters into one composite adapter.
18
+ * Merges peer rosters across all children, routes signals to online children that advertise the target peer,
19
+ * and stays `'online'` as long as at least one child adapter is `'online'`.
20
+ */
21
+ export function combineSignaling(...adapters) {
22
+ if (adapters.length === 0)
23
+ throw new RangeError('At least one signaling adapter is required');
24
+ for (const adapter of adapters) {
25
+ if (typeof adapter !== 'function') {
26
+ throw new TypeError('All signaling adapters must be functions');
27
+ }
28
+ }
29
+ if (adapters.length === 1)
30
+ return adapters[0];
31
+ const list = [...adapters];
32
+ return (discovery) => {
33
+ const children = list.map(() => ({
34
+ state: 'connecting',
35
+ peers: new Set()
36
+ }));
37
+ const buffered = [];
38
+ const seenIce = new Map();
39
+ let initializing = true;
40
+ let closed = false;
41
+ let aggState = 'connecting';
42
+ let lastReason;
43
+ let publishedRoster = new Set();
44
+ let rosterDirty = false;
45
+ const computeAggregateState = () => {
46
+ let hasConnecting = false;
47
+ let hasOffline = false;
48
+ for (const child of children) {
49
+ if (child.state === 'online')
50
+ return 'online';
51
+ if (child.state === 'connecting')
52
+ hasConnecting = true;
53
+ else if (child.state === 'offline')
54
+ hasOffline = true;
55
+ }
56
+ if (hasConnecting)
57
+ return 'connecting';
58
+ if (hasOffline)
59
+ return 'offline';
60
+ return 'closed';
61
+ };
62
+ const syncState = (reason) => {
63
+ if (closed)
64
+ return;
65
+ const next = computeAggregateState();
66
+ if (next === aggState)
67
+ return;
68
+ aggState = next;
69
+ lastReason = reason;
70
+ if (!initializing)
71
+ discovery.status(next, reason);
72
+ };
73
+ const computeUnion = () => {
74
+ const union = new Set();
75
+ for (const child of children) {
76
+ for (const id of child.peers)
77
+ union.add(id);
78
+ }
79
+ return union;
80
+ };
81
+ const syncRoster = () => {
82
+ if (closed)
83
+ return;
84
+ if (initializing) {
85
+ rosterDirty = true;
86
+ return;
87
+ }
88
+ const union = computeUnion();
89
+ if (setsEqual(union, publishedRoster))
90
+ return;
91
+ publishedRoster = union;
92
+ discovery.roster([...union]);
93
+ };
94
+ const dedupeIceSignal = (from, signal) => {
95
+ if (signal.kind !== 'ice')
96
+ return signal;
97
+ let byAttempt = seenIce.get(from);
98
+ if (!byAttempt) {
99
+ if (seenIce.size >= maxSeenIcePeers) {
100
+ const oldestPeer = seenIce.keys().next().value;
101
+ if (oldestPeer !== undefined)
102
+ seenIce.delete(oldestPeer);
103
+ }
104
+ byAttempt = new Map();
105
+ }
106
+ // Refresh peer LRU order on hit/insert.
107
+ seenIce.delete(from);
108
+ seenIce.set(from, byAttempt);
109
+ let keys = byAttempt.get(signal.attempt);
110
+ if (!keys) {
111
+ if (byAttempt.size >= maxSeenIceAttemptsPerPeer) {
112
+ const oldestAttempt = byAttempt.keys().next().value;
113
+ if (oldestAttempt !== undefined)
114
+ byAttempt.delete(oldestAttempt);
115
+ }
116
+ keys = new Set();
117
+ }
118
+ // Refresh attempt LRU order so active legitimate attempts stay hot.
119
+ byAttempt.delete(signal.attempt);
120
+ byAttempt.set(signal.attempt, keys);
121
+ const fresh = [];
122
+ for (const item of signal.candidates) {
123
+ const key = iceCandidateKey(item);
124
+ if (keys.has(key))
125
+ continue;
126
+ if (keys.size < maxSeenIceKeysPerAttempt)
127
+ keys.add(key);
128
+ fresh.push(item);
129
+ }
130
+ return fresh.length > 0 ? { ...signal, candidates: fresh } : null;
131
+ };
132
+ const closeAll = () => {
133
+ seenIce.clear();
134
+ for (const child of children) {
135
+ try {
136
+ child.session?.close();
137
+ }
138
+ catch {
139
+ // Ensure one failing child close does not leak sibling sessions.
140
+ }
141
+ delete child.session;
142
+ }
143
+ };
144
+ try {
145
+ for (let i = 0; i < list.length; i++) {
146
+ const child = children[i];
147
+ const adapter = list[i];
148
+ child.session = adapter({
149
+ appId: discovery.appId,
150
+ room: discovery.room,
151
+ self: discovery.self,
152
+ ...(discovery.password !== undefined ? { password: discovery.password } : {}),
153
+ status(next, reason) {
154
+ if (closed || next === child.state)
155
+ return;
156
+ child.state = next;
157
+ if (next === 'offline' || next === 'closed') {
158
+ if (child.peers.size > 0) {
159
+ child.peers.clear();
160
+ syncRoster();
161
+ }
162
+ }
163
+ syncState(reason);
164
+ },
165
+ roster(ids) {
166
+ if (closed)
167
+ return;
168
+ child.peers = new Set(ids);
169
+ syncRoster();
170
+ },
171
+ receive(from, signal) {
172
+ if (closed)
173
+ return;
174
+ if (!child.peers.has(from)) {
175
+ child.peers.add(from);
176
+ syncRoster();
177
+ }
178
+ const deduped = dedupeIceSignal(from, signal);
179
+ if (!deduped)
180
+ return;
181
+ if (initializing) {
182
+ buffered.push({ kind: 'receive', from, signal: deduped });
183
+ return;
184
+ }
185
+ discovery.receive(from, deduped);
186
+ },
187
+ error(code, message) {
188
+ if (closed)
189
+ return;
190
+ if (initializing) {
191
+ buffered.push({ kind: 'error', code, message });
192
+ return;
193
+ }
194
+ discovery.error?.(code, message);
195
+ }
196
+ });
197
+ }
198
+ }
199
+ catch (error) {
200
+ closed = true;
201
+ closeAll();
202
+ throw error;
203
+ }
204
+ initializing = false;
205
+ if (!closed) {
206
+ if (aggState !== 'connecting')
207
+ discovery.status(aggState, lastReason);
208
+ if (rosterDirty) {
209
+ rosterDirty = false;
210
+ const union = computeUnion();
211
+ if (union.size > 0) {
212
+ publishedRoster = union;
213
+ discovery.roster([...union]);
214
+ }
215
+ }
216
+ for (const ev of buffered) {
217
+ if (closed)
218
+ break;
219
+ if (ev.kind === 'receive')
220
+ discovery.receive(ev.from, ev.signal);
221
+ else
222
+ discovery.error?.(ev.code, ev.message);
223
+ }
224
+ buffered.length = 0;
225
+ }
226
+ const trickle = children.every((child) => child.session?.trickle === true);
227
+ return {
228
+ trickle,
229
+ send(to, signal) {
230
+ if (closed)
231
+ return false;
232
+ let accepted = false;
233
+ for (const child of children) {
234
+ if (child.state === 'online' && child.peers.has(to) && child.session) {
235
+ if (child.session.send(to, signal))
236
+ accepted = true;
237
+ }
238
+ }
239
+ return accepted;
240
+ },
241
+ close() {
242
+ if (closed)
243
+ return;
244
+ closed = true;
245
+ closeAll();
246
+ }
247
+ };
248
+ };
249
+ }