@dimchansky/meshpost 0.4.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -550
- package/dist/bip340.d.ts +1 -0
- package/dist/bip340.js +346 -0
- package/dist/blob.d.ts +1 -1
- package/dist/blob.js +15 -16
- package/dist/channel.js +15 -44
- package/dist/combine.js +25 -39
- package/dist/crypto.js +10 -9
- package/dist/identity.d.ts +45 -0
- package/dist/identity.js +188 -28
- package/dist/index.d.ts +6 -6
- package/dist/index.js +3 -3
- package/dist/listeners.js +18 -3
- package/dist/mqtt.js +193 -408
- package/dist/nostr.js +163 -745
- package/dist/public.d.ts +19 -1
- package/dist/public.js +26 -9
- package/dist/relay-core.d.ts +1 -0
- package/dist/relay-core.js +323 -0
- package/dist/room-hello.d.ts +1 -0
- package/dist/room-hello.js +129 -0
- package/dist/room-ice.d.ts +1 -0
- package/dist/room-ice.js +115 -0
- package/dist/room-media.d.ts +1 -0
- package/dist/room-media.js +477 -0
- package/dist/room-reclaim.d.ts +1 -0
- package/dist/room-reclaim.js +111 -0
- package/dist/room-stats.d.ts +1 -0
- package/dist/room-stats.js +75 -0
- package/dist/room.js +109 -919
- package/dist/signaling.d.ts +8 -0
- package/dist/signaling.js +64 -0
- package/dist/state.js +1 -2
- package/dist/voice-helpers.d.ts +1 -0
- package/dist/voice-helpers.js +100 -0
- package/dist/voice-meter.d.ts +1 -0
- package/dist/voice-meter.js +79 -0
- package/dist/voice.d.ts +41 -0
- package/dist/voice.js +205 -273
- package/dist/ws.js +60 -146
- package/docs/api.md +217 -0
- package/docs/behavior.md +16 -9
- package/docs/guide.md +404 -0
- package/docs/signaling-and-production.md +312 -0
- package/docs/voice-and-media.md +193 -0
- package/package.json +3 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
/** @internal */
|
|
2
|
+
export const rtcControlPrefix = 'meshpost/1/rtc:';
|
|
3
|
+
/** @internal */
|
|
4
|
+
export const maxRtcControlBytes = 64 * 1024;
|
|
5
|
+
/** @internal */
|
|
6
|
+
export const maxRemoteStreamsPerPeer = 32;
|
|
7
|
+
const maxRtcQueueDepth = 16;
|
|
8
|
+
const maxRemoteStreamTags = 64;
|
|
9
|
+
const streamTagPattern = /^[a-zA-Z0-9._-]{1,32}$/;
|
|
10
|
+
const emptyStreamMeta = Object.freeze({});
|
|
11
|
+
/** @internal */
|
|
12
|
+
export function buildStreamMeta(tag) {
|
|
13
|
+
return tag !== undefined ? Object.freeze({ tag }) : emptyStreamMeta;
|
|
14
|
+
}
|
|
15
|
+
/** @internal */
|
|
16
|
+
export function parseIncomingStreamTags(raw) {
|
|
17
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
18
|
+
return null;
|
|
19
|
+
const entries = Object.entries(raw);
|
|
20
|
+
if (entries.length > maxRemoteStreamsPerPeer)
|
|
21
|
+
return null;
|
|
22
|
+
const out = [];
|
|
23
|
+
for (const [id, tag] of entries) {
|
|
24
|
+
if (id.length === 0 ||
|
|
25
|
+
id.length > 128 ||
|
|
26
|
+
id === '__proto__' ||
|
|
27
|
+
id === 'constructor' ||
|
|
28
|
+
id === 'prototype' ||
|
|
29
|
+
typeof tag !== 'string' ||
|
|
30
|
+
!streamTagPattern.test(tag)) {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
out.push([id, tag]);
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
function parseStreamTarget(toOrOptions, allowTag) {
|
|
38
|
+
if (typeof toOrOptions === 'string')
|
|
39
|
+
return { to: toOrOptions };
|
|
40
|
+
if (toOrOptions === undefined)
|
|
41
|
+
return {};
|
|
42
|
+
if (!toOrOptions || typeof toOrOptions !== 'object' || Array.isArray(toOrOptions)) {
|
|
43
|
+
throw new TypeError(allowTag ? 'Invalid addStream options' : 'Invalid removeStream options');
|
|
44
|
+
}
|
|
45
|
+
if (toOrOptions.to !== undefined && typeof toOrOptions.to !== 'string') {
|
|
46
|
+
throw new TypeError('Invalid target peer ID');
|
|
47
|
+
}
|
|
48
|
+
const tag = allowTag ? toOrOptions.tag : undefined;
|
|
49
|
+
if (tag !== undefined && (typeof tag !== 'string' || !streamTagPattern.test(tag))) {
|
|
50
|
+
throw new TypeError('Invalid stream tag');
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
...(toOrOptions.to !== undefined ? { to: toOrOptions.to } : {}),
|
|
54
|
+
...(tag !== undefined ? { tag } : {})
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** @internal */
|
|
58
|
+
export function createRoomMedia(params) {
|
|
59
|
+
const { self, isStopped, peers, onError, onStreamEnd } = params;
|
|
60
|
+
const broadcastStreams = new Set();
|
|
61
|
+
const peerStreams = new Map();
|
|
62
|
+
const localStreamTags = new Map();
|
|
63
|
+
const desiredStreamsFor = (peerId) => {
|
|
64
|
+
const set = new Set(broadcastStreams);
|
|
65
|
+
const targeted = peerStreams.get(peerId);
|
|
66
|
+
if (targeted) {
|
|
67
|
+
for (const s of targeted)
|
|
68
|
+
set.add(s);
|
|
69
|
+
}
|
|
70
|
+
return set;
|
|
71
|
+
};
|
|
72
|
+
const isStreamRegistered = (stream) => {
|
|
73
|
+
if (broadcastStreams.has(stream))
|
|
74
|
+
return true;
|
|
75
|
+
for (const set of peerStreams.values()) {
|
|
76
|
+
if (set.has(stream))
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
return false;
|
|
80
|
+
};
|
|
81
|
+
const collectLinkStreamTags = (link) => {
|
|
82
|
+
let out;
|
|
83
|
+
for (const stream of link.senders.keys()) {
|
|
84
|
+
const tag = localStreamTags.get(stream);
|
|
85
|
+
if (tag !== undefined) {
|
|
86
|
+
out ??= {};
|
|
87
|
+
out[stream.id] = tag;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
};
|
|
92
|
+
const mergeRemoteStreamTags = (link, entries) => {
|
|
93
|
+
for (const [id, tag] of entries) {
|
|
94
|
+
if (link.remoteStreamTags.has(id)) {
|
|
95
|
+
link.remoteStreamTags.delete(id);
|
|
96
|
+
link.remoteStreamTags.set(id, tag);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (link.remoteStreamTags.size >= maxRemoteStreamTags) {
|
|
100
|
+
let evicted = false;
|
|
101
|
+
for (const existingId of link.remoteStreamTags.keys()) {
|
|
102
|
+
if (!link.remoteStreams.has(existingId)) {
|
|
103
|
+
link.remoteStreamTags.delete(existingId);
|
|
104
|
+
evicted = true;
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (!evicted)
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
link.remoteStreamTags.set(id, tag);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const remoteMetaFor = (link, streamId) => buildStreamMeta(link.remoteStreamTags.get(streamId));
|
|
115
|
+
const sendRtcControl = (link, payload) => {
|
|
116
|
+
const reliable = link.channels.reliable;
|
|
117
|
+
if (reliable.readyState !== 'open')
|
|
118
|
+
return false;
|
|
119
|
+
try {
|
|
120
|
+
reliable.send(rtcControlPrefix + JSON.stringify(payload));
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
const attachStreamToLink = (link, stream) => {
|
|
128
|
+
if (link.senders.has(stream))
|
|
129
|
+
return false;
|
|
130
|
+
const tracks = stream.getTracks();
|
|
131
|
+
if (tracks.length === 0)
|
|
132
|
+
return false;
|
|
133
|
+
const added = [];
|
|
134
|
+
for (const track of tracks) {
|
|
135
|
+
added.push(link.pc.addTrack(track, stream));
|
|
136
|
+
}
|
|
137
|
+
link.senders.set(stream, added);
|
|
138
|
+
link.pendingStreamEnds.delete(stream.id);
|
|
139
|
+
return true;
|
|
140
|
+
};
|
|
141
|
+
const detachStreamFromLink = (link, stream) => {
|
|
142
|
+
const added = link.senders.get(stream);
|
|
143
|
+
if (!added)
|
|
144
|
+
return false;
|
|
145
|
+
link.senders.delete(stream);
|
|
146
|
+
for (const sender of added) {
|
|
147
|
+
try {
|
|
148
|
+
link.pc.removeTrack(sender);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
// Ignore if connection is closing.
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
link.pendingStreamEnds.add(stream.id);
|
|
155
|
+
return true;
|
|
156
|
+
};
|
|
157
|
+
const enqueueRenegotiate = (peer, link) => {
|
|
158
|
+
link.renegotiateQueued = true;
|
|
159
|
+
link.rtcQueue = link.rtcQueue.then(async () => {
|
|
160
|
+
if (isStopped() ||
|
|
161
|
+
peer.link !== link ||
|
|
162
|
+
!link.ready ||
|
|
163
|
+
!link.renegotiateQueued ||
|
|
164
|
+
link.channels.reliable.readyState !== 'open')
|
|
165
|
+
return;
|
|
166
|
+
if (link.pc.signalingState !== 'stable')
|
|
167
|
+
return;
|
|
168
|
+
link.renegotiateQueued = false;
|
|
169
|
+
try {
|
|
170
|
+
const offer = await link.pc.createOffer();
|
|
171
|
+
if (isStopped() || peer.link !== link)
|
|
172
|
+
return;
|
|
173
|
+
await link.pc.setLocalDescription(offer);
|
|
174
|
+
if (isStopped() || peer.link !== link || !link.pc.localDescription)
|
|
175
|
+
return;
|
|
176
|
+
const tags = collectLinkStreamTags(link);
|
|
177
|
+
if (sendRtcControl(link, {
|
|
178
|
+
kind: 'offer',
|
|
179
|
+
sdp: link.pc.localDescription.sdp,
|
|
180
|
+
...(tags ? { tags } : {})
|
|
181
|
+
})) {
|
|
182
|
+
for (const id of link.pendingStreamEnds) {
|
|
183
|
+
sendRtcControl(link, { kind: 'stream-end', id });
|
|
184
|
+
}
|
|
185
|
+
link.pendingStreamEnds.clear();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
if (!isStopped() && peer.link === link) {
|
|
190
|
+
onError({
|
|
191
|
+
code: 'media-error',
|
|
192
|
+
peerId: peer.id,
|
|
193
|
+
message: 'Failed to negotiate media tracks'
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
};
|
|
199
|
+
const handleRtcControl = (peer, link, raw) => {
|
|
200
|
+
if (raw.length > maxRtcControlBytes || link.rtcPending >= maxRtcQueueDepth)
|
|
201
|
+
return;
|
|
202
|
+
let msg;
|
|
203
|
+
try {
|
|
204
|
+
const parsed = JSON.parse(raw.slice(rtcControlPrefix.length));
|
|
205
|
+
msg = parsed && typeof parsed === 'object' ? parsed : null;
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (!msg || typeof msg.kind !== 'string')
|
|
211
|
+
return;
|
|
212
|
+
if (msg.kind === 'stream-end' && typeof msg.id === 'string') {
|
|
213
|
+
const streamId = msg.id;
|
|
214
|
+
link.rtcPending++;
|
|
215
|
+
link.rtcQueue = link.rtcQueue.then(() => {
|
|
216
|
+
link.rtcPending--;
|
|
217
|
+
if (isStopped() || peer.link !== link || !link.ready)
|
|
218
|
+
return;
|
|
219
|
+
const stream = link.remoteStreams.get(streamId);
|
|
220
|
+
const meta = remoteMetaFor(link, streamId);
|
|
221
|
+
link.remoteStreamTags.delete(streamId);
|
|
222
|
+
if (stream) {
|
|
223
|
+
link.remoteStreams.delete(streamId);
|
|
224
|
+
onStreamEnd(peer.id, stream, meta);
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if ((msg.kind !== 'offer' && msg.kind !== 'answer') || typeof msg.sdp !== 'string')
|
|
230
|
+
return;
|
|
231
|
+
let incomingTags = null;
|
|
232
|
+
if (msg.tags !== undefined) {
|
|
233
|
+
incomingTags = parseIncomingStreamTags(msg.tags);
|
|
234
|
+
if (!incomingTags)
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const kind = msg.kind;
|
|
238
|
+
const sdp = msg.sdp;
|
|
239
|
+
const polite = self > peer.id;
|
|
240
|
+
link.rtcPending++;
|
|
241
|
+
link.rtcQueue = link.rtcQueue.then(async () => {
|
|
242
|
+
try {
|
|
243
|
+
if (isStopped() || peer.link !== link || !link.ready)
|
|
244
|
+
return;
|
|
245
|
+
if (kind === 'offer') {
|
|
246
|
+
const collision = link.pc.signalingState !== 'stable';
|
|
247
|
+
if (!polite && collision)
|
|
248
|
+
return;
|
|
249
|
+
try {
|
|
250
|
+
if (polite && collision) {
|
|
251
|
+
await link.pc.setLocalDescription({ type: 'rollback' });
|
|
252
|
+
link.renegotiateQueued = true;
|
|
253
|
+
}
|
|
254
|
+
if (incomingTags)
|
|
255
|
+
mergeRemoteStreamTags(link, incomingTags);
|
|
256
|
+
await link.pc.setRemoteDescription({ type: 'offer', sdp });
|
|
257
|
+
if (isStopped() || peer.link !== link)
|
|
258
|
+
return;
|
|
259
|
+
const answer = await link.pc.createAnswer();
|
|
260
|
+
if (isStopped() || peer.link !== link)
|
|
261
|
+
return;
|
|
262
|
+
await link.pc.setLocalDescription(answer);
|
|
263
|
+
if (isStopped() || peer.link !== link || !link.pc.localDescription)
|
|
264
|
+
return;
|
|
265
|
+
const answerTags = collectLinkStreamTags(link);
|
|
266
|
+
sendRtcControl(link, {
|
|
267
|
+
kind: 'answer',
|
|
268
|
+
sdp: link.pc.localDescription.sdp,
|
|
269
|
+
...(answerTags ? { tags: answerTags } : {})
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
if (!isStopped() && peer.link === link) {
|
|
274
|
+
onError({
|
|
275
|
+
code: 'media-error',
|
|
276
|
+
peerId: peer.id,
|
|
277
|
+
message: 'Failed to apply media offer'
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (!isStopped() && peer.link === link && link.renegotiateQueued) {
|
|
282
|
+
enqueueRenegotiate(peer, link);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
if (link.pc.signalingState !== 'have-local-offer')
|
|
287
|
+
return;
|
|
288
|
+
try {
|
|
289
|
+
if (incomingTags)
|
|
290
|
+
mergeRemoteStreamTags(link, incomingTags);
|
|
291
|
+
await link.pc.setRemoteDescription({ type: 'answer', sdp });
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
if (!isStopped() && peer.link === link) {
|
|
295
|
+
onError({
|
|
296
|
+
code: 'media-error',
|
|
297
|
+
peerId: peer.id,
|
|
298
|
+
message: 'Failed to apply media answer'
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (!isStopped() && peer.link === link && link.renegotiateQueued) {
|
|
303
|
+
enqueueRenegotiate(peer, link);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
finally {
|
|
308
|
+
link.rtcPending--;
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
};
|
|
312
|
+
return {
|
|
313
|
+
desiredStreamsFor,
|
|
314
|
+
collectLinkStreamTags,
|
|
315
|
+
mergeRemoteStreamTags,
|
|
316
|
+
remoteMetaFor,
|
|
317
|
+
attachStreamToLink,
|
|
318
|
+
handleRtcControl,
|
|
319
|
+
reconcileLinkStreams(peer, link) {
|
|
320
|
+
const desired = desiredStreamsFor(peer.id);
|
|
321
|
+
let needsRenegotiate = false;
|
|
322
|
+
for (const stream of desired) {
|
|
323
|
+
if (attachStreamToLink(link, stream))
|
|
324
|
+
needsRenegotiate = true;
|
|
325
|
+
}
|
|
326
|
+
for (const stream of [...link.senders.keys()]) {
|
|
327
|
+
if (!desired.has(stream) && detachStreamFromLink(link, stream)) {
|
|
328
|
+
needsRenegotiate = true;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
if (needsRenegotiate)
|
|
332
|
+
enqueueRenegotiate(peer, link);
|
|
333
|
+
},
|
|
334
|
+
clearLinkMedia(link) {
|
|
335
|
+
link.remoteStreams.clear();
|
|
336
|
+
link.remoteStreamTags.clear();
|
|
337
|
+
link.senders.clear();
|
|
338
|
+
link.pendingStreamEnds.clear();
|
|
339
|
+
},
|
|
340
|
+
addStream(stream, toOrOptions) {
|
|
341
|
+
if (isStopped())
|
|
342
|
+
throw new Error('Room is closed');
|
|
343
|
+
if (!stream || typeof stream.getTracks !== 'function')
|
|
344
|
+
throw new TypeError('Expected a MediaStream');
|
|
345
|
+
const { to, tag } = parseStreamTarget(toOrOptions, true);
|
|
346
|
+
if (tag !== undefined)
|
|
347
|
+
localStreamTags.set(stream, tag);
|
|
348
|
+
if (to === undefined) {
|
|
349
|
+
broadcastStreams.add(stream);
|
|
350
|
+
for (const peer of peers.values()) {
|
|
351
|
+
const link = peer.link;
|
|
352
|
+
if (link?.ready && attachStreamToLink(link, stream)) {
|
|
353
|
+
enqueueRenegotiate(peer, link);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
if (to === self) {
|
|
359
|
+
if (!isStreamRegistered(stream))
|
|
360
|
+
localStreamTags.delete(stream);
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
let set = peerStreams.get(to);
|
|
364
|
+
if (!set) {
|
|
365
|
+
set = new Set();
|
|
366
|
+
peerStreams.set(to, set);
|
|
367
|
+
}
|
|
368
|
+
set.add(stream);
|
|
369
|
+
const peer = peers.get(to);
|
|
370
|
+
const link = peer?.link;
|
|
371
|
+
if (peer && link?.ready && attachStreamToLink(link, stream)) {
|
|
372
|
+
enqueueRenegotiate(peer, link);
|
|
373
|
+
}
|
|
374
|
+
},
|
|
375
|
+
removeStream(stream, toOrOptions) {
|
|
376
|
+
const { to } = parseStreamTarget(toOrOptions, false);
|
|
377
|
+
if (isStopped() || !stream)
|
|
378
|
+
return;
|
|
379
|
+
if (to === undefined) {
|
|
380
|
+
if (!broadcastStreams.delete(stream))
|
|
381
|
+
return;
|
|
382
|
+
if (!isStreamRegistered(stream))
|
|
383
|
+
localStreamTags.delete(stream);
|
|
384
|
+
for (const peer of peers.values()) {
|
|
385
|
+
if (peerStreams.get(peer.id)?.has(stream))
|
|
386
|
+
continue;
|
|
387
|
+
const link = peer.link;
|
|
388
|
+
if (link?.ready && detachStreamFromLink(link, stream)) {
|
|
389
|
+
enqueueRenegotiate(peer, link);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
const set = peerStreams.get(to);
|
|
395
|
+
if (!set?.delete(stream))
|
|
396
|
+
return;
|
|
397
|
+
if (set.size === 0)
|
|
398
|
+
peerStreams.delete(to);
|
|
399
|
+
if (!isStreamRegistered(stream))
|
|
400
|
+
localStreamTags.delete(stream);
|
|
401
|
+
if (broadcastStreams.has(stream))
|
|
402
|
+
return;
|
|
403
|
+
const peer = peers.get(to);
|
|
404
|
+
const link = peer?.link;
|
|
405
|
+
if (peer && link?.ready && detachStreamFromLink(link, stream)) {
|
|
406
|
+
enqueueRenegotiate(peer, link);
|
|
407
|
+
}
|
|
408
|
+
},
|
|
409
|
+
async replaceStreamTrack(stream, oldTrack, newTrack) {
|
|
410
|
+
if (isStopped())
|
|
411
|
+
throw new Error('Room is closed');
|
|
412
|
+
if (!stream || typeof stream.getTracks !== 'function')
|
|
413
|
+
throw new TypeError('Expected a MediaStream');
|
|
414
|
+
if (!oldTrack ||
|
|
415
|
+
typeof oldTrack.kind !== 'string' ||
|
|
416
|
+
!newTrack ||
|
|
417
|
+
typeof newTrack.kind !== 'string' ||
|
|
418
|
+
oldTrack.kind !== newTrack.kind) {
|
|
419
|
+
throw new TypeError('Expected matching-kind MediaStreamTrack instances');
|
|
420
|
+
}
|
|
421
|
+
if (!isStreamRegistered(stream)) {
|
|
422
|
+
throw new Error('Stream is not attached to this room');
|
|
423
|
+
}
|
|
424
|
+
if (oldTrack === newTrack)
|
|
425
|
+
return;
|
|
426
|
+
if (stream.getTracks().includes(oldTrack))
|
|
427
|
+
stream.removeTrack(oldTrack);
|
|
428
|
+
if (!stream.getTracks().includes(newTrack))
|
|
429
|
+
stream.addTrack(newTrack);
|
|
430
|
+
const ops = [];
|
|
431
|
+
for (const peer of peers.values()) {
|
|
432
|
+
const link = peer.link;
|
|
433
|
+
const senderList = link?.senders.get(stream);
|
|
434
|
+
if (!peer || !link || !senderList)
|
|
435
|
+
continue;
|
|
436
|
+
let targetSender = senderList.find((s) => s.track === oldTrack);
|
|
437
|
+
if (!targetSender) {
|
|
438
|
+
const sameKind = senderList.filter((s) => s.track?.kind === newTrack.kind);
|
|
439
|
+
if (sameKind.length === 1)
|
|
440
|
+
targetSender = sameKind[0];
|
|
441
|
+
}
|
|
442
|
+
if (!targetSender)
|
|
443
|
+
continue;
|
|
444
|
+
ops.push(targetSender.replaceTrack(newTrack).catch(() => {
|
|
445
|
+
if (!isStopped() && peer.link === link && link.ready) {
|
|
446
|
+
onError({
|
|
447
|
+
code: 'media-error',
|
|
448
|
+
peerId: peer.id,
|
|
449
|
+
message: 'Failed to replace media track'
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
}));
|
|
453
|
+
}
|
|
454
|
+
if (ops.length > 0)
|
|
455
|
+
await Promise.all(ops);
|
|
456
|
+
},
|
|
457
|
+
getRemoteStreams() {
|
|
458
|
+
const out = [];
|
|
459
|
+
if (isStopped())
|
|
460
|
+
return out;
|
|
461
|
+
for (const peer of peers.values()) {
|
|
462
|
+
const link = peer.link;
|
|
463
|
+
if (!link?.ready)
|
|
464
|
+
continue;
|
|
465
|
+
for (const stream of link.remoteStreams.values()) {
|
|
466
|
+
out.push([peer.id, stream, remoteMetaFor(link, stream.id)]);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
return out;
|
|
470
|
+
},
|
|
471
|
+
clearAll() {
|
|
472
|
+
broadcastStreams.clear();
|
|
473
|
+
peerStreams.clear();
|
|
474
|
+
localStreamTags.clear();
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { toBase64Url } from './crypto.js';
|
|
2
|
+
import { decodeCanonicalBase64Url, sha256Base64Url } from './identity.js';
|
|
3
|
+
import { isUuid } from './signaling.js';
|
|
4
|
+
const reclaimTtlMs = 60_000;
|
|
5
|
+
const maxSupersededPeers = 128;
|
|
6
|
+
/** @internal */
|
|
7
|
+
export function createSessionReclaim(params) {
|
|
8
|
+
const { appId, roomName, self, isStopped, sendUnloadLeaveNotices } = params;
|
|
9
|
+
const supersededPeers = new Set();
|
|
10
|
+
const storageKey = `meshpost/1/reclaim:${appId}:${roomName}`;
|
|
11
|
+
let pendingReclaim = null;
|
|
12
|
+
try {
|
|
13
|
+
const raw = globalThis.sessionStorage?.getItem(storageKey);
|
|
14
|
+
if (raw) {
|
|
15
|
+
globalThis.sessionStorage?.removeItem(storageKey);
|
|
16
|
+
const parsed = JSON.parse(raw);
|
|
17
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
18
|
+
const rec = parsed;
|
|
19
|
+
if (typeof rec.id === 'string' &&
|
|
20
|
+
isUuid(rec.id) &&
|
|
21
|
+
rec.id !== self &&
|
|
22
|
+
decodeCanonicalBase64Url(rec.secret, 22, 16) !== null &&
|
|
23
|
+
typeof rec.ts === 'number' &&
|
|
24
|
+
Number.isFinite(rec.ts) &&
|
|
25
|
+
Math.abs(Date.now() - rec.ts) <= reclaimTtlMs) {
|
|
26
|
+
pendingReclaim = { id: rec.id, secret: rec.secret, ts: rec.ts };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
// Ignore storage restrictions on opaque origins or non-browser runtimes.
|
|
33
|
+
}
|
|
34
|
+
const localSecret = globalThis.crypto?.subtle
|
|
35
|
+
? toBase64Url(crypto.getRandomValues(new Uint8Array(16)))
|
|
36
|
+
: null;
|
|
37
|
+
const localCommitPromise = localSecret
|
|
38
|
+
? sha256Base64Url(`meshpost/1/reclaim:${self}:${localSecret}`)
|
|
39
|
+
: Promise.resolve(null);
|
|
40
|
+
const hasWindowEvents = typeof window !== 'undefined' &&
|
|
41
|
+
typeof window.addEventListener === 'function' &&
|
|
42
|
+
typeof window.removeEventListener === 'function';
|
|
43
|
+
const onPageHide = (event) => {
|
|
44
|
+
if (isStopped())
|
|
45
|
+
return;
|
|
46
|
+
if (!event.persisted)
|
|
47
|
+
sendUnloadLeaveNotices();
|
|
48
|
+
if (localSecret) {
|
|
49
|
+
try {
|
|
50
|
+
globalThis.sessionStorage?.setItem(storageKey, JSON.stringify({ id: self, secret: localSecret, ts: Date.now() }));
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// Ignore storage quota or security errors.
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const onPageShow = () => {
|
|
58
|
+
if (isStopped())
|
|
59
|
+
return;
|
|
60
|
+
try {
|
|
61
|
+
globalThis.sessionStorage?.removeItem(storageKey);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
// Ignore storage errors.
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
let attached = false;
|
|
68
|
+
return {
|
|
69
|
+
localCommitPromise,
|
|
70
|
+
getPendingReclaim() {
|
|
71
|
+
if (!pendingReclaim)
|
|
72
|
+
return null;
|
|
73
|
+
if (Math.abs(Date.now() - pendingReclaim.ts) <= reclaimTtlMs) {
|
|
74
|
+
return { id: pendingReclaim.id, secret: pendingReclaim.secret };
|
|
75
|
+
}
|
|
76
|
+
pendingReclaim = null;
|
|
77
|
+
return null;
|
|
78
|
+
},
|
|
79
|
+
isSuperseded: (id) => supersededPeers.has(id),
|
|
80
|
+
markSuperseded(id) {
|
|
81
|
+
supersededPeers.delete(id);
|
|
82
|
+
supersededPeers.add(id);
|
|
83
|
+
if (supersededPeers.size > maxSupersededPeers) {
|
|
84
|
+
const oldest = supersededPeers.values().next().value;
|
|
85
|
+
if (oldest !== undefined)
|
|
86
|
+
supersededPeers.delete(oldest);
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
attachWindowListeners() {
|
|
90
|
+
if (hasWindowEvents && !attached) {
|
|
91
|
+
attached = true;
|
|
92
|
+
window.addEventListener('pagehide', onPageHide);
|
|
93
|
+
window.addEventListener('pageshow', onPageShow);
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
cleanup() {
|
|
97
|
+
if (hasWindowEvents && attached) {
|
|
98
|
+
attached = false;
|
|
99
|
+
window.removeEventListener('pagehide', onPageHide);
|
|
100
|
+
window.removeEventListener('pageshow', onPageShow);
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
globalThis.sessionStorage?.removeItem(storageKey);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
// Ignore storage errors.
|
|
107
|
+
}
|
|
108
|
+
supersededPeers.clear();
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
function asStat(value) {
|
|
2
|
+
return value && typeof value === 'object' ? value : undefined;
|
|
3
|
+
}
|
|
4
|
+
function nonNegativeNumber(value) {
|
|
5
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
|
|
6
|
+
}
|
|
7
|
+
/** @internal */
|
|
8
|
+
export function parsePeerStats(report, bufferedUnreliable, bufferedReliable) {
|
|
9
|
+
const byId = new Map();
|
|
10
|
+
let bytesSent = 0;
|
|
11
|
+
let bytesReceived = 0;
|
|
12
|
+
let selectedId;
|
|
13
|
+
let selectedPair;
|
|
14
|
+
let nominatedPair;
|
|
15
|
+
let succeededPair;
|
|
16
|
+
report.forEach((raw, id) => {
|
|
17
|
+
const stat = asStat(raw);
|
|
18
|
+
if (!stat)
|
|
19
|
+
return;
|
|
20
|
+
byId.set(id, stat);
|
|
21
|
+
if (stat.type === 'data-channel') {
|
|
22
|
+
bytesSent += nonNegativeNumber(stat.bytesSent) ?? 0;
|
|
23
|
+
bytesReceived += nonNegativeNumber(stat.bytesReceived) ?? 0;
|
|
24
|
+
}
|
|
25
|
+
else if (stat.type === 'transport' && typeof stat.selectedCandidatePairId === 'string') {
|
|
26
|
+
selectedId = stat.selectedCandidatePairId;
|
|
27
|
+
}
|
|
28
|
+
else if (stat.type === 'candidate-pair') {
|
|
29
|
+
if (stat.selected === true && !selectedPair)
|
|
30
|
+
selectedPair = stat;
|
|
31
|
+
if (stat.state === 'succeeded') {
|
|
32
|
+
if (stat.nominated === true && !nominatedPair)
|
|
33
|
+
nominatedPair = stat;
|
|
34
|
+
if (!succeededPair)
|
|
35
|
+
succeededPair = stat;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
let activePair;
|
|
40
|
+
if (selectedId) {
|
|
41
|
+
const pair = byId.get(selectedId);
|
|
42
|
+
if (pair?.type === 'candidate-pair')
|
|
43
|
+
activePair = pair;
|
|
44
|
+
}
|
|
45
|
+
activePair ??= selectedPair ?? nominatedPair ?? succeededPair;
|
|
46
|
+
const rttSec = activePair ? nonNegativeNumber(activePair.currentRoundTripTime) : null;
|
|
47
|
+
const rttMs = rttSec !== null ? Math.round(rttSec * 1000) : null;
|
|
48
|
+
let route = 'unknown';
|
|
49
|
+
if (activePair) {
|
|
50
|
+
const local = typeof activePair.localCandidateId === 'string'
|
|
51
|
+
? byId.get(activePair.localCandidateId)
|
|
52
|
+
: undefined;
|
|
53
|
+
const remote = typeof activePair.remoteCandidateId === 'string'
|
|
54
|
+
? byId.get(activePair.remoteCandidateId)
|
|
55
|
+
: undefined;
|
|
56
|
+
const localType = local?.type === 'local-candidate' && typeof local.candidateType === 'string'
|
|
57
|
+
? local.candidateType
|
|
58
|
+
: undefined;
|
|
59
|
+
const remoteType = remote?.type === 'remote-candidate' && typeof remote.candidateType === 'string'
|
|
60
|
+
? remote.candidateType
|
|
61
|
+
: undefined;
|
|
62
|
+
if (localType === 'relay' || remoteType === 'relay')
|
|
63
|
+
route = 'relay';
|
|
64
|
+
else if (localType && remoteType)
|
|
65
|
+
route = 'direct';
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
rttMs,
|
|
69
|
+
route,
|
|
70
|
+
bytesSent,
|
|
71
|
+
bytesReceived,
|
|
72
|
+
bufferedUnreliable,
|
|
73
|
+
bufferedReliable
|
|
74
|
+
};
|
|
75
|
+
}
|