@dimchansky/meshpost 0.2.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/combine.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { tabSignaling } from './tabs.js';
1
2
  const maxSeenIcePeers = 256;
2
3
  const maxSeenIceAttemptsPerPeer = 4;
3
4
  const maxSeenIceKeysPerAttempt = 64;
@@ -13,237 +14,327 @@ function setsEqual(a, b) {
13
14
  }
14
15
  return true;
15
16
  }
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
- }
17
+ function childCanReach(child, peerId) {
18
+ if (!child.peers.has(peerId) || !child.session)
19
+ return false;
20
+ if (typeof child.session.canReach === 'function') {
21
+ return child.session.canReach(peerId);
28
22
  }
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;
23
+ return child.state === 'online';
24
+ }
25
+ function createCompositeSession(discovery, list, primaryIndex) {
26
+ const children = list.map(() => ({
27
+ state: 'connecting',
28
+ peers: new Set()
29
+ }));
30
+ const buffered = [];
31
+ const seenIce = new Map();
32
+ let initializing = true;
33
+ let closed = false;
34
+ let aggState = 'connecting';
35
+ let lastReason;
36
+ let publishedRoster = new Set();
37
+ let rosterDirty = false;
38
+ const computeAggregateState = () => {
39
+ if (primaryIndex !== null) {
40
+ return children[primaryIndex].state;
41
+ }
42
+ let hasConnecting = false;
43
+ let hasOffline = false;
44
+ for (const child of children) {
45
+ if (child.state === 'online')
46
+ return 'online';
47
+ if (child.state === 'connecting')
48
+ hasConnecting = true;
49
+ else if (child.state === 'offline')
50
+ hasOffline = true;
51
+ }
52
+ if (hasConnecting)
53
+ return 'connecting';
54
+ if (hasOffline)
55
+ return 'offline';
56
+ return 'closed';
57
+ };
58
+ const syncState = (reason) => {
59
+ if (closed)
60
+ return;
61
+ const next = computeAggregateState();
62
+ if (next === aggState)
63
+ return;
64
+ aggState = next;
65
+ lastReason = reason;
66
+ if (!initializing)
67
+ discovery.status(next, reason);
68
+ };
69
+ const computeUnion = () => {
70
+ const union = new Set();
71
+ for (const child of children) {
72
+ for (const id of child.peers) {
73
+ if (child.session ? childCanReach(child, id) : child.state === 'online') {
74
+ union.add(id);
75
+ }
76
+ }
77
+ }
78
+ return union;
79
+ };
80
+ const syncRoster = () => {
81
+ if (closed)
82
+ return;
83
+ if (initializing) {
84
+ rosterDirty = true;
85
+ return;
86
+ }
87
+ const union = computeUnion();
88
+ if (setsEqual(union, publishedRoster))
89
+ return;
90
+ publishedRoster = union;
91
+ discovery.roster([...union]);
92
+ };
93
+ const dedupeIceSignal = (from, signal) => {
94
+ if (signal.kind !== 'ice')
95
+ return signal;
96
+ let byAttempt = seenIce.get(from);
97
+ if (!byAttempt) {
98
+ if (seenIce.size >= maxSeenIcePeers) {
99
+ const oldestPeer = seenIce.keys().next().value;
100
+ if (oldestPeer !== undefined)
101
+ seenIce.delete(oldestPeer);
102
+ }
103
+ byAttempt = new Map();
104
+ }
105
+ seenIce.delete(from);
106
+ seenIce.set(from, byAttempt);
107
+ let keys = byAttempt.get(signal.attempt);
108
+ if (!keys) {
109
+ if (byAttempt.size >= maxSeenIceAttemptsPerPeer) {
110
+ const oldestAttempt = byAttempt.keys().next().value;
111
+ if (oldestAttempt !== undefined)
112
+ byAttempt.delete(oldestAttempt);
55
113
  }
56
- if (hasConnecting)
57
- return 'connecting';
58
- if (hasOffline)
59
- return 'offline';
60
- return 'closed';
61
- };
62
- const syncState = (reason) => {
114
+ keys = new Set();
115
+ }
116
+ byAttempt.delete(signal.attempt);
117
+ byAttempt.set(signal.attempt, keys);
118
+ const fresh = [];
119
+ for (const item of signal.candidates) {
120
+ const key = iceCandidateKey(item);
121
+ if (keys.has(key))
122
+ continue;
123
+ if (keys.size < maxSeenIceKeysPerAttempt)
124
+ keys.add(key);
125
+ fresh.push(item);
126
+ }
127
+ return fresh.length > 0 ? { ...signal, candidates: fresh } : null;
128
+ };
129
+ const closeAll = () => {
130
+ seenIce.clear();
131
+ for (const child of children) {
132
+ try {
133
+ child.session?.close();
134
+ }
135
+ catch {
136
+ // Ensure one failing child close does not leak sibling sessions.
137
+ }
138
+ delete child.session;
139
+ }
140
+ };
141
+ const makeChildDiscovery = (index, child) => ({
142
+ appId: discovery.appId,
143
+ room: discovery.room,
144
+ self: discovery.self,
145
+ ...(discovery.password !== undefined ? { password: discovery.password } : {}),
146
+ status(next, reason) {
147
+ if (closed || next === child.state)
148
+ return;
149
+ child.state = next;
150
+ if (next === 'closed') {
151
+ if (child.peers.size > 0) {
152
+ child.peers.clear();
153
+ syncRoster();
154
+ }
155
+ }
156
+ else if (next === 'offline') {
157
+ if (typeof child.session?.canReach === 'function') {
158
+ let removed = false;
159
+ for (const id of [...child.peers]) {
160
+ if (!child.session.canReach(id)) {
161
+ child.peers.delete(id);
162
+ removed = true;
163
+ }
164
+ }
165
+ if (removed)
166
+ syncRoster();
167
+ }
168
+ else if (child.peers.size > 0) {
169
+ child.peers.clear();
170
+ syncRoster();
171
+ }
172
+ }
173
+ else if (next === 'online' && child.peers.size > 0) {
174
+ syncRoster();
175
+ }
176
+ if (primaryIndex === null || index === primaryIndex) {
177
+ syncState(reason);
178
+ }
179
+ },
180
+ roster(ids) {
63
181
  if (closed)
64
182
  return;
65
- const next = computeAggregateState();
66
- if (next === aggState)
183
+ child.peers = new Set(ids);
184
+ syncRoster();
185
+ },
186
+ receive(from, signal) {
187
+ if (closed)
67
188
  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);
189
+ if (!child.peers.has(from)) {
190
+ child.peers.add(from);
191
+ syncRoster();
78
192
  }
79
- return union;
80
- };
81
- const syncRoster = () => {
82
- if (closed)
193
+ const deduped = dedupeIceSignal(from, signal);
194
+ if (!deduped)
83
195
  return;
84
196
  if (initializing) {
85
- rosterDirty = true;
197
+ buffered.push({ kind: 'receive', from, signal: deduped });
86
198
  return;
87
199
  }
88
- const union = computeUnion();
89
- if (setsEqual(union, publishedRoster))
200
+ discovery.receive(from, deduped);
201
+ },
202
+ error(code, message) {
203
+ if (closed)
204
+ return;
205
+ if (primaryIndex !== null && index !== primaryIndex)
206
+ return;
207
+ if (initializing) {
208
+ buffered.push({ kind: 'error', code, message });
90
209
  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
210
  }
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();
211
+ discovery.error?.(code, message);
212
+ }
213
+ });
214
+ try {
215
+ for (let i = 0; i < list.length; i++) {
216
+ const child = children[i];
217
+ const adapter = list[i];
218
+ child.session = adapter(makeChildDiscovery(i, child));
219
+ if (child.peers.size > 0)
220
+ rosterDirty = true;
221
+ }
222
+ }
223
+ catch (error) {
224
+ closed = true;
225
+ closeAll();
226
+ throw error;
227
+ }
228
+ initializing = false;
229
+ if (!closed) {
230
+ const nextState = computeAggregateState();
231
+ aggState = nextState;
232
+ if (nextState !== 'connecting')
233
+ discovery.status(nextState, lastReason);
234
+ if (rosterDirty) {
235
+ rosterDirty = false;
236
+ const union = computeUnion();
237
+ if (union.size > 0) {
238
+ publishedRoster = union;
239
+ discovery.roster([...union]);
117
240
  }
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);
241
+ }
242
+ for (const ev of buffered) {
243
+ if (closed)
244
+ break;
245
+ if (ev.kind === 'receive')
246
+ discovery.receive(ev.from, ev.signal);
247
+ else
248
+ discovery.error?.(ev.code, ev.message);
249
+ }
250
+ buffered.length = 0;
251
+ }
252
+ const trickle = children.every((child) => child.session?.trickle === true);
253
+ return {
254
+ trickle,
255
+ canReach(peerId) {
256
+ if (closed)
257
+ return false;
258
+ for (const child of children) {
259
+ if (childCanReach(child, peerId))
260
+ return true;
129
261
  }
130
- return fresh.length > 0 ? { ...signal, candidates: fresh } : null;
131
- };
132
- const closeAll = () => {
133
- seenIce.clear();
262
+ return false;
263
+ },
264
+ send(to, signal) {
265
+ if (closed)
266
+ return false;
267
+ let accepted = false;
134
268
  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.
269
+ if (childCanReach(child, to) && child.session) {
270
+ if (child.session.send(to, signal))
271
+ accepted = true;
140
272
  }
141
- delete child.session;
142
273
  }
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) {
274
+ return accepted;
275
+ },
276
+ close() {
277
+ if (closed)
278
+ return;
200
279
  closed = true;
201
280
  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
- };
281
+ }
282
+ };
283
+ }
284
+ /**
285
+ * Combine multiple signaling adapters into one composite adapter.
286
+ * Merges peer rosters across all children, routes signals to reachable children that advertise the target peer,
287
+ * and stays `'online'` as long as at least one child adapter is `'online'`.
288
+ */
289
+ export function combineSignaling(...adapters) {
290
+ if (adapters.length === 0)
291
+ throw new RangeError('At least one signaling adapter is required');
292
+ for (const adapter of adapters) {
293
+ if (typeof adapter !== 'function') {
294
+ throw new TypeError('All signaling adapters must be functions');
295
+ }
296
+ }
297
+ if (adapters.length === 1)
298
+ return adapters[0];
299
+ const list = [...adapters];
300
+ return (discovery) => createCompositeSession(discovery, list, null);
301
+ }
302
+ function canUseLocalTabs() {
303
+ if (typeof BroadcastChannel !== 'function')
304
+ return false;
305
+ if (typeof location !== 'undefined') {
306
+ if (location.protocol === 'file:' || location.origin === 'null')
307
+ return false;
308
+ }
309
+ return true;
310
+ }
311
+ /**
312
+ * Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
313
+ * same-browser `BroadcastChannel` discovery (`tabSignaling()`).
314
+ *
315
+ * - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
316
+ * (avoiding a permanently `'online'` indicator when network connectivity is lost).
317
+ * - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
318
+ * - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
319
+ * origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
320
+ */
321
+ export function withLocalTabs(primary) {
322
+ if (typeof primary !== 'function') {
323
+ throw new TypeError('Expected a signaling adapter function');
324
+ }
325
+ return (discovery) => {
326
+ if (!canUseLocalTabs())
327
+ return primary(discovery);
328
+ // Probe BroadcastChannel construction before starting anything so a synchronous SecurityError
329
+ // falls back cleanly to `primary(discovery)` without creating duplicate sessions.
330
+ try {
331
+ const probe = new BroadcastChannel('meshpost/probe');
332
+ probe.close();
333
+ }
334
+ catch {
335
+ return primary(discovery);
336
+ }
337
+ const tabs = tabSignaling();
338
+ return createCompositeSession(discovery, [tabs, primary], 1);
248
339
  };
249
340
  }
package/dist/index.d.ts CHANGED
@@ -4,6 +4,10 @@ export { createChannel } from './channel.js';
4
4
  export type { Channel, ChannelOptions, ChannelSendOptions } from './channel.js';
5
5
  export { createBlobChannel } from './blob.js';
6
6
  export type { BlobChannel, BlobChannelOptions, BlobProgress, BlobSendOptions, BlobSendStatus } from './blob.js';
7
+ export { createVoice } from './voice.js';
8
+ export type { MicError, MicErrorCode, MicStatus, Voice, VoiceOptions, VoiceSnapshot } from './voice.js';
9
+ export { fetchTurnCredentials } from './turn.js';
10
+ export type { FetchTurnOptions } from './turn.js';
7
11
  export { tabSignaling } from './tabs.js';
8
12
  export { manualSignaling } from './manual.js';
9
13
  export type { ManualSignaling } from './manual.js';
@@ -11,6 +15,6 @@ export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
11
15
  export type { MqttSignalingOptions } from './mqtt.js';
12
16
  export { wsSignaling } from './ws.js';
13
17
  export type { WsSignalingOptions } from './ws.js';
14
- export { combineSignaling } from './combine.js';
18
+ export { combineSignaling, withLocalTabs } from './combine.js';
15
19
  export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
16
20
  export type { Discovery, IceCandidatePayload, Signal, Signaling, SignalingErrorCode, SignalingSession, SignalingState } from './signaling.js';
package/dist/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  export { defaultIceServers, joinRoom } from './room.js';
2
2
  export { createChannel } from './channel.js';
3
3
  export { createBlobChannel } from './blob.js';
4
+ export { createVoice } from './voice.js';
5
+ export { fetchTurnCredentials } from './turn.js';
4
6
  export { tabSignaling } from './tabs.js';
5
7
  export { manualSignaling } from './manual.js';
6
8
  export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
7
9
  export { wsSignaling } from './ws.js';
8
- export { combineSignaling } from './combine.js';
10
+ export { combineSignaling, withLocalTabs } from './combine.js';
9
11
  export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
package/dist/room.d.ts CHANGED
@@ -1,4 +1,10 @@
1
1
  import { type Signaling, type SignalingErrorCode, type SignalingState } from './signaling.js';
2
+ /** @internal */
3
+ export declare function isRoomClosed(room: Room): boolean;
4
+ /** @internal */
5
+ export declare function onRoomClose(room: Room, fn: () => void): () => void;
6
+ /** @internal */
7
+ export declare function getRoomRemoteStreams(room: Room): Array<[string, MediaStream]>;
2
8
  /** Built-in Cloudflare and Google public STUN servers used by default. */
3
9
  export declare const defaultIceServers: readonly RTCIceServer[];
4
10
  /** Delivery guarantee for a packet: fast unordered (`'unreliable'`) or ordered reliable (`'reliable'`). */