@lavitre/apps 1.49.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.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +121 -0
  3. package/dist/Common/AiChannel.d.ts +59 -0
  4. package/dist/Common/AiChannel.js +97 -0
  5. package/dist/Common/AiChannel.js.map +1 -0
  6. package/dist/Common/BlobStore.d.ts +44 -0
  7. package/dist/Common/BlobStore.js +186 -0
  8. package/dist/Common/BlobStore.js.map +1 -0
  9. package/dist/Common/Common.Model.d.ts +1020 -0
  10. package/dist/Common/Common.Model.js +21 -0
  11. package/dist/Common/Common.Model.js.map +1 -0
  12. package/dist/Common/CrdtChannel.d.ts +198 -0
  13. package/dist/Common/CrdtChannel.js +659 -0
  14. package/dist/Common/CrdtChannel.js.map +1 -0
  15. package/dist/Common/Version.d.ts +21 -0
  16. package/dist/Common/Version.js +62 -0
  17. package/dist/Common/Version.js.map +1 -0
  18. package/dist/Common/index.d.ts +6 -0
  19. package/dist/Common/index.js +32 -0
  20. package/dist/Common/index.js.map +1 -0
  21. package/dist/CompanionConnector/CompanionConnector.Model.d.ts +85 -0
  22. package/dist/CompanionConnector/CompanionConnector.Model.js +17 -0
  23. package/dist/CompanionConnector/CompanionConnector.Model.js.map +1 -0
  24. package/dist/CompanionConnector/CompanionConnector.d.ts +28 -0
  25. package/dist/CompanionConnector/CompanionConnector.js +385 -0
  26. package/dist/CompanionConnector/CompanionConnector.js.map +1 -0
  27. package/dist/CompanionConnector/index.d.ts +2 -0
  28. package/dist/CompanionConnector/index.js +3 -0
  29. package/dist/CompanionConnector/index.js.map +1 -0
  30. package/dist/CompanionFrame/CompanionFrame.d.ts +103 -0
  31. package/dist/CompanionFrame/CompanionFrame.js +100 -0
  32. package/dist/CompanionFrame/CompanionFrame.js.map +1 -0
  33. package/dist/CompanionFrame/index.d.ts +1 -0
  34. package/dist/CompanionFrame/index.js +2 -0
  35. package/dist/CompanionFrame/index.js.map +1 -0
  36. package/dist/Connector/Connector.Model.d.ts +567 -0
  37. package/dist/Connector/Connector.Model.js +2 -0
  38. package/dist/Connector/Connector.Model.js.map +1 -0
  39. package/dist/Connector/Connector.d.ts +227 -0
  40. package/dist/Connector/Connector.js +1337 -0
  41. package/dist/Connector/Connector.js.map +1 -0
  42. package/dist/Connector/index.d.ts +2 -0
  43. package/dist/Connector/index.js +3 -0
  44. package/dist/Connector/index.js.map +1 -0
  45. package/dist/Frame/Frame.Model.d.ts +533 -0
  46. package/dist/Frame/Frame.Model.js +2 -0
  47. package/dist/Frame/Frame.Model.js.map +1 -0
  48. package/dist/Frame/Frame.d.ts +309 -0
  49. package/dist/Frame/Frame.js +1408 -0
  50. package/dist/Frame/Frame.js.map +1 -0
  51. package/dist/Frame/SyncAdapter.d.ts +75 -0
  52. package/dist/Frame/SyncAdapter.js +134 -0
  53. package/dist/Frame/SyncAdapter.js.map +1 -0
  54. package/dist/Frame/index.d.ts +3 -0
  55. package/dist/Frame/index.js +4 -0
  56. package/dist/Frame/index.js.map +1 -0
  57. package/dist/MediaLink/MediaLink.d.ts +178 -0
  58. package/dist/MediaLink/MediaLink.js +1432 -0
  59. package/dist/MediaLink/MediaLink.js.map +1 -0
  60. package/dist/MediaLink/index.d.ts +1 -0
  61. package/dist/MediaLink/index.js +2 -0
  62. package/dist/MediaLink/index.js.map +1 -0
  63. package/dist/Native/index.d.ts +170 -0
  64. package/dist/Native/index.js +19 -0
  65. package/dist/Native/index.js.map +1 -0
  66. package/dist/Version.d.ts +1 -0
  67. package/dist/Version.js +2 -0
  68. package/dist/Version.js.map +1 -0
  69. package/package.json +76 -0
@@ -0,0 +1,1432 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Internal CRDT key names — use a namespace prefix to avoid collisions with
3
+ // app-level CRDT keys.
4
+ // ---------------------------------------------------------------------------
5
+ const PREFIX = 'mediaLink:';
6
+ const KEY_SIGNAL = `${PREFIX}signal`;
7
+ const KEY_ICE_OFFERER = `${PREFIX}iceOfferer`;
8
+ const KEY_ICE_ANSWERER = `${PREFIX}iceAnswerer`;
9
+ const KEY_CONTROL = `${PREFIX}control`;
10
+ /**
11
+ * Answerer-owned map key holding the Vitre's full ICE server list (including
12
+ * TURN credentials). Written by the answerer once per session, consumed by the
13
+ * offerer before building its RTCPeerConnection. The key is a Yjs map so the
14
+ * value is overwritten atomically per session; validation uses `entry.s ===
15
+ * sessionId` so a stale entry from a previous session is never consumed.
16
+ */
17
+ const KEY_ICE_SERVERS = `${PREFIX}iceServers`;
18
+ /**
19
+ * Fallback when getIceServers() returns empty or times out. INTENTIONALLY EMPTY:
20
+ * la Vitre must never depend on an external STUN/TURN (e.g. Google) — all ICE
21
+ * servers come from getIceServers() (the la Vitre relay). An empty list means
22
+ * host-candidates only; the real fix for "no servers" is server-side, not a public
23
+ * STUN leak.
24
+ */
25
+ const STUN_FALLBACK = [];
26
+ /** ICE restart config: re-offer with iceRestart to create a new ICE session. */
27
+ const ICE_RESTART_OFFER_OPTIONS = { iceRestart: true };
28
+ async function resolveIceServers(frame) {
29
+ let servers = [];
30
+ try {
31
+ servers = await Promise.race([
32
+ frame.getIceServers(),
33
+ new Promise((resolve) => setTimeout(() => resolve([]), 3000)),
34
+ ]);
35
+ }
36
+ catch {
37
+ servers = [];
38
+ }
39
+ const list = servers.length > 0 ? servers : STUN_FALLBACK.map((s) => ({
40
+ urls: Array.isArray(s.urls) ? s.urls : [s.urls],
41
+ }));
42
+ return list.map((s) => ({
43
+ urls: s.urls,
44
+ username: s.username,
45
+ credential: s.credential,
46
+ }));
47
+ }
48
+ // ---------------------------------------------------------------------------
49
+ // CRDT accessor helpers
50
+ // ---------------------------------------------------------------------------
51
+ function getDoc(frame) {
52
+ return frame.crdt.doc;
53
+ }
54
+ function getSignalMap(frame) {
55
+ return getDoc(frame).getMap(KEY_SIGNAL);
56
+ }
57
+ function getIceOffererArray(frame) {
58
+ return getDoc(frame).getArray(KEY_ICE_OFFERER);
59
+ }
60
+ function getIceAnswererArray(frame) {
61
+ return getDoc(frame).getArray(KEY_ICE_ANSWERER);
62
+ }
63
+ function getControlArray(frame) {
64
+ return getDoc(frame).getArray(KEY_CONTROL);
65
+ }
66
+ function getIceServersMap(frame) {
67
+ return getDoc(frame).getMap(KEY_ICE_SERVERS);
68
+ }
69
+ // Iterate new ICE entries from `from`, return updated count.
70
+ function drainIce(arr, from, sessionId, onCandidate) {
71
+ const len = arr.length;
72
+ for (let i = from; i < len; i++) {
73
+ try {
74
+ const entry = JSON.parse(arr.get(i));
75
+ if (entry.s === sessionId)
76
+ onCandidate(entry.c);
77
+ }
78
+ catch {
79
+ /* ignore malformed entry */
80
+ }
81
+ }
82
+ return len;
83
+ }
84
+ // Check the control array for a voluntary-stop entry for this session.
85
+ function checkVoluntaryStop(frame, sessionId) {
86
+ const arr = getControlArray(frame);
87
+ for (let i = 0; i < arr.length; i++) {
88
+ try {
89
+ const e = JSON.parse(arr.get(i));
90
+ if (e.sessionId === sessionId)
91
+ return e.ended;
92
+ }
93
+ catch {
94
+ /* ignore */
95
+ }
96
+ }
97
+ return null;
98
+ }
99
+ // Write a voluntary-stop entry.
100
+ function writeControlStop(frame, sessionId, reason) {
101
+ const entry = { sessionId, ended: reason };
102
+ getControlArray(frame).push([JSON.stringify(entry)]);
103
+ }
104
+ // ---------------------------------------------------------------------------
105
+ // Offerer implementation
106
+ // ---------------------------------------------------------------------------
107
+ class MediaLinkImpl {
108
+ constructor(sessionId,
109
+ // Companion side: the offerer originates the link from a companion frame and
110
+ // signals the Vitre connector via `frame.sendMessageToVitreConnector`.
111
+ frame, stream, options, openAnswererFrame, receiverDisplay, metadata, vitreIceTimeoutMs) {
112
+ Object.defineProperty(this, "sessionId", {
113
+ enumerable: true,
114
+ configurable: true,
115
+ writable: true,
116
+ value: sessionId
117
+ });
118
+ Object.defineProperty(this, "frame", {
119
+ enumerable: true,
120
+ configurable: true,
121
+ writable: true,
122
+ value: frame
123
+ });
124
+ Object.defineProperty(this, "stream", {
125
+ enumerable: true,
126
+ configurable: true,
127
+ writable: true,
128
+ value: stream
129
+ });
130
+ Object.defineProperty(this, "options", {
131
+ enumerable: true,
132
+ configurable: true,
133
+ writable: true,
134
+ value: options
135
+ });
136
+ Object.defineProperty(this, "openAnswererFrame", {
137
+ enumerable: true,
138
+ configurable: true,
139
+ writable: true,
140
+ value: openAnswererFrame
141
+ });
142
+ Object.defineProperty(this, "receiverDisplay", {
143
+ enumerable: true,
144
+ configurable: true,
145
+ writable: true,
146
+ value: receiverDisplay
147
+ });
148
+ Object.defineProperty(this, "metadata", {
149
+ enumerable: true,
150
+ configurable: true,
151
+ writable: true,
152
+ value: metadata
153
+ });
154
+ Object.defineProperty(this, "vitreIceTimeoutMs", {
155
+ enumerable: true,
156
+ configurable: true,
157
+ writable: true,
158
+ value: vitreIceTimeoutMs
159
+ });
160
+ Object.defineProperty(this, "state", {
161
+ enumerable: true,
162
+ configurable: true,
163
+ writable: true,
164
+ value: 'connecting'
165
+ });
166
+ Object.defineProperty(this, "onStateChange", {
167
+ enumerable: true,
168
+ configurable: true,
169
+ writable: true,
170
+ value: void 0
171
+ });
172
+ Object.defineProperty(this, "onEnded", {
173
+ enumerable: true,
174
+ configurable: true,
175
+ writable: true,
176
+ value: void 0
177
+ });
178
+ Object.defineProperty(this, "pc", {
179
+ enumerable: true,
180
+ configurable: true,
181
+ writable: true,
182
+ value: null
183
+ });
184
+ Object.defineProperty(this, "senders", {
185
+ enumerable: true,
186
+ configurable: true,
187
+ writable: true,
188
+ value: []
189
+ });
190
+ Object.defineProperty(this, "remoteSet", {
191
+ enumerable: true,
192
+ configurable: true,
193
+ writable: true,
194
+ value: false
195
+ });
196
+ Object.defineProperty(this, "pendingRemote", {
197
+ enumerable: true,
198
+ configurable: true,
199
+ writable: true,
200
+ value: []
201
+ });
202
+ Object.defineProperty(this, "processedIce", {
203
+ enumerable: true,
204
+ configurable: true,
205
+ writable: true,
206
+ value: 0
207
+ });
208
+ Object.defineProperty(this, "stopped", {
209
+ enumerable: true,
210
+ configurable: true,
211
+ writable: true,
212
+ value: false
213
+ });
214
+ // FIX 3: separate flag so teardown() cleanup runs exactly once regardless
215
+ // of whether the call came from stop() (after stopped=true) or externally.
216
+ Object.defineProperty(this, "tornDown", {
217
+ enumerable: true,
218
+ configurable: true,
219
+ writable: true,
220
+ value: false
221
+ });
222
+ // Retry state
223
+ Object.defineProperty(this, "retryCount", {
224
+ enumerable: true,
225
+ configurable: true,
226
+ writable: true,
227
+ value: 0
228
+ });
229
+ Object.defineProperty(this, "graceTimer", {
230
+ enumerable: true,
231
+ configurable: true,
232
+ writable: true,
233
+ value: null
234
+ });
235
+ Object.defineProperty(this, "retryTimer", {
236
+ enumerable: true,
237
+ configurable: true,
238
+ writable: true,
239
+ value: null
240
+ });
241
+ // CRDT observer references so we can unobserve
242
+ Object.defineProperty(this, "signalObserver", {
243
+ enumerable: true,
244
+ configurable: true,
245
+ writable: true,
246
+ value: null
247
+ });
248
+ Object.defineProperty(this, "iceObserver", {
249
+ enumerable: true,
250
+ configurable: true,
251
+ writable: true,
252
+ value: null
253
+ });
254
+ Object.defineProperty(this, "controlObserver", {
255
+ enumerable: true,
256
+ configurable: true,
257
+ writable: true,
258
+ value: null
259
+ });
260
+ Object.defineProperty(this, "pagehideHandler", {
261
+ enumerable: true,
262
+ configurable: true,
263
+ writable: true,
264
+ value: null
265
+ });
266
+ /**
267
+ * Resolved ICE server list shared across all ICE restarts of this session.
268
+ * Set once during start() (after waiting for the Vitre-published list) and
269
+ * reused by every subsequent initPeerConnection(iceRestart=true) call.
270
+ */
271
+ Object.defineProperty(this, "resolvedIceServers", {
272
+ enumerable: true,
273
+ configurable: true,
274
+ writable: true,
275
+ value: null
276
+ });
277
+ }
278
+ async start() {
279
+ // Register pagehide handler (best-effort voluntary signal on tab close).
280
+ this.pagehideHandler = () => { this.stop(); };
281
+ window.addEventListener('pagehide', this.pagehideHandler);
282
+ // IMPROVEMENT 7: prune stale CRDT entries from any previous session.
283
+ // The design is single-active-session per frame doc: only one 'session'
284
+ // key in the signal map, and growing ICE/control arrays. At the start of
285
+ // each new offerer session we delete all entries in both ICE arrays and
286
+ // the control array whose sessionId differs from our new sessionId. This
287
+ // bounds CRDT growth to O(1 session) rather than O(lifetime of the frame).
288
+ // Also clear a stale 'iceServers' map entry from a previous session so the
289
+ // offerer cannot accidentally consume it (the answerer overwrites per session
290
+ // anyway, but an extra guard here makes stale-entry reasoning explicit).
291
+ const doc = this.frame.crdt.doc;
292
+ doc.transact(() => {
293
+ const iceOfferer = getIceOffererArray(this.frame);
294
+ const iceAnswerer = getIceAnswererArray(this.frame);
295
+ const controlArr = getControlArray(this.frame);
296
+ const iceServersMap = getIceServersMap(this.frame);
297
+ // Delete indices in reverse so removal does not shift subsequent indices.
298
+ const pruneArray = (arr) => {
299
+ const toDelete = [];
300
+ for (let i = 0; i < arr.length; i++) {
301
+ try {
302
+ const e = JSON.parse(arr.get(i));
303
+ if (e.s !== this.sessionId)
304
+ toDelete.push(i);
305
+ }
306
+ catch {
307
+ toDelete.push(i);
308
+ }
309
+ }
310
+ for (let i = toDelete.length - 1; i >= 0; i--) {
311
+ arr.delete(toDelete[i], 1);
312
+ }
313
+ };
314
+ pruneArray(iceOfferer);
315
+ pruneArray(iceAnswerer);
316
+ pruneArray(controlArr);
317
+ // Clear a stale iceServers entry from a prior session.
318
+ const rawIce = iceServersMap.get('servers');
319
+ if (rawIce) {
320
+ try {
321
+ const existing = JSON.parse(rawIce);
322
+ if (existing.s !== this.sessionId)
323
+ iceServersMap.delete('servers');
324
+ }
325
+ catch {
326
+ iceServersMap.delete('servers');
327
+ }
328
+ }
329
+ });
330
+ // Step 1: publish a session-request (no offer yet) so a late-joining
331
+ // answerer frame sees this session after CRDT sync and can start resolving
332
+ // its ICE servers immediately.
333
+ const sessionRequest = {
334
+ sessionId: this.sessionId,
335
+ receiverDisplay: this.receiverDisplay,
336
+ metadata: this.metadata,
337
+ // offer is intentionally absent — this is a session-request only.
338
+ };
339
+ doc.transact(() => {
340
+ getSignalMap(this.frame).set('session', JSON.stringify(sessionRequest));
341
+ });
342
+ // Step 2: send the open-answerer message AFTER writing the session-request
343
+ // so the answerer frame (if it opens late) finds the session-request in the
344
+ // CRDT on first sync.
345
+ if (this.openAnswererFrame) {
346
+ const msg = {
347
+ type: 'lavitre-media-link',
348
+ action: 'open-answerer',
349
+ frameConnectorId: this.frame.id,
350
+ sessionId: this.sessionId,
351
+ };
352
+ this.frame.sendMessageToVitreConnector(JSON.stringify(msg));
353
+ }
354
+ // Step 3: race the vitre ICE list against the companion fallback and the
355
+ // timeout. Start the companion-side resolve immediately in parallel.
356
+ const companionIcePromise = resolveIceServers(this.frame);
357
+ const vitreIcePromise = new Promise((resolve) => {
358
+ const iceServersMap = getIceServersMap(this.frame);
359
+ const timeout = setTimeout(() => {
360
+ iceServersMap.unobserve(observer);
361
+ resolve(null);
362
+ }, this.vitreIceTimeoutMs);
363
+ const tryRead = () => {
364
+ const raw = iceServersMap.get('servers');
365
+ if (!raw)
366
+ return false;
367
+ try {
368
+ const entry = JSON.parse(raw);
369
+ if (entry.s !== this.sessionId)
370
+ return false;
371
+ if (!Array.isArray(entry.servers) || entry.servers.length === 0)
372
+ return false;
373
+ clearTimeout(timeout);
374
+ iceServersMap.unobserve(observer);
375
+ resolve(entry.servers);
376
+ return true;
377
+ }
378
+ catch {
379
+ return false;
380
+ }
381
+ };
382
+ const observer = () => { tryRead(); };
383
+ iceServersMap.observe(observer);
384
+ // Check for an entry that was already present before we subscribed.
385
+ tryRead();
386
+ });
387
+ // Pick the best available ICE servers: vitre > companion > public STUN.
388
+ const vitreServers = await vitreIcePromise;
389
+ let iceServers;
390
+ if (vitreServers !== null && vitreServers.length > 0) {
391
+ iceServers = vitreServers.map((s) => ({
392
+ urls: s.urls,
393
+ username: s.username,
394
+ credential: s.credential,
395
+ }));
396
+ }
397
+ else {
398
+ // Fall back to companion-side result (already resolving in parallel).
399
+ iceServers = await companionIcePromise;
400
+ }
401
+ // stop() may have torn the link down while we awaited the ICE servers
402
+ // (up to vitreIceTimeoutMs) — do not build a PC that nobody would close.
403
+ if (this.tornDown)
404
+ return;
405
+ // Store for reuse across ICE restarts of this session.
406
+ this.resolvedIceServers = iceServers;
407
+ await this.initPeerConnection();
408
+ }
409
+ async initPeerConnection(iceRestart = false) {
410
+ // Reuse the ICE server list resolved during start() for all restarts of
411
+ // this session. On the first call (iceRestart=false) resolvedIceServers is
412
+ // already set by start(); on subsequent calls it is the stored value.
413
+ const iceServers = this.resolvedIceServers ?? STUN_FALLBACK;
414
+ const pc = new RTCPeerConnection({ iceServers });
415
+ this.pc = pc;
416
+ // --- ICE/TURN diagnostics (offerer). Reveals whether TURN servers were handed
417
+ // out, ICE negotiation progress, and TURN auth failures (errorCode 401/403 =
418
+ // expired/invalid credentials — the classic cause of an intermittent black frame).
419
+ const turnCount = iceServers.filter((s) => {
420
+ const urls = Array.isArray(s.urls) ? s.urls : [s.urls];
421
+ return urls.some((u) => typeof u === 'string' && u.startsWith('turn'));
422
+ }).length;
423
+ console.log('[lavitre-apps][MediaLink] pc-init offerer ' + JSON.stringify({ servers: iceServers.length, turn: turnCount, iceRestart }));
424
+ pc.oniceconnectionstatechange = () => {
425
+ if (this.pc === pc)
426
+ console.log('[lavitre-apps][MediaLink] iceState offerer', pc.iceConnectionState);
427
+ };
428
+ pc.onicecandidateerror = (ev) => {
429
+ console.warn('[lavitre-apps][MediaLink] ice-error offerer ' + JSON.stringify({ code: ev.errorCode, url: ev.url, text: ev.errorText }));
430
+ };
431
+ this.senders = [];
432
+ this.remoteSet = false;
433
+ this.pendingRemote = [];
434
+ // Keep the ice processed index across ICE restarts so we don't re-add old
435
+ // candidates. For a full new session (first call) it starts at 0; for a
436
+ // restart the CRDT arrays keep growing, so we advance from the current tip.
437
+ if (!iceRestart) {
438
+ this.processedIce = 0;
439
+ }
440
+ for (const track of this.stream.getTracks()) {
441
+ this.senders.push(pc.addTrack(track, this.stream));
442
+ }
443
+ pc.onicecandidate = (e) => {
444
+ if (e.candidate && this.pc === pc) {
445
+ const tagged = { s: this.sessionId, c: e.candidate.toJSON() };
446
+ getIceOffererArray(this.frame).push([JSON.stringify(tagged)]);
447
+ }
448
+ };
449
+ pc.onconnectionstatechange = () => {
450
+ if (this.stopped || this.pc !== pc)
451
+ return;
452
+ const cs = pc.connectionState;
453
+ console.log('[lavitre-apps][MediaLink] connState offerer', cs);
454
+ if (cs === 'connected') {
455
+ this.clearTimers();
456
+ this.retryCount = 0;
457
+ this.setState('connected');
458
+ }
459
+ else if (cs === 'disconnected') {
460
+ this.setState('reconnecting');
461
+ this.graceTimer = setTimeout(() => {
462
+ this.graceTimer = null;
463
+ if (!this.stopped && this.pc === pc)
464
+ this.attemptRestart();
465
+ }, this.options.graceMs);
466
+ }
467
+ else if (cs === 'failed') {
468
+ this.clearTimers();
469
+ this.attemptRestart();
470
+ }
471
+ };
472
+ const signalMap = getSignalMap(this.frame);
473
+ const vitreIce = getIceAnswererArray(this.frame);
474
+ const controlArr = getControlArray(this.frame);
475
+ // Drain remote ICE from the answerer array.
476
+ const drainRemote = () => {
477
+ if (!this.pc || this.pc !== pc)
478
+ return;
479
+ this.processedIce = drainIce(vitreIce, this.processedIce, this.sessionId, (c) => {
480
+ if (this.remoteSet)
481
+ void pc.addIceCandidate(c).catch(() => { });
482
+ else
483
+ this.pendingRemote.push(c);
484
+ });
485
+ };
486
+ // Handle the answer arriving in the signal map.
487
+ const onSignal = () => {
488
+ if (this.remoteSet || !this.pc || this.pc !== pc)
489
+ return;
490
+ const raw = signalMap.get('session');
491
+ if (!raw)
492
+ return;
493
+ let entry;
494
+ try {
495
+ entry = JSON.parse(raw);
496
+ }
497
+ catch {
498
+ return;
499
+ }
500
+ if (entry.sessionId !== this.sessionId)
501
+ return;
502
+ const answer = entry.answer;
503
+ if (!answer)
504
+ return;
505
+ void pc.setRemoteDescription({ type: 'answer', sdp: answer })
506
+ .then(() => {
507
+ if (this.pc !== pc)
508
+ return;
509
+ this.remoteSet = true;
510
+ for (const c of this.pendingRemote.splice(0)) {
511
+ void pc.addIceCandidate(c).catch(() => { });
512
+ }
513
+ drainRemote();
514
+ })
515
+ .catch((err) => console.error('[lavitre-apps] MediaLink setRemoteDescription(answer)', err));
516
+ };
517
+ // Watch for voluntary stop from the answerer side.
518
+ const onControl = () => {
519
+ if (this.stopped)
520
+ return;
521
+ const reason = checkVoluntaryStop(this.frame, this.sessionId);
522
+ if (reason != null)
523
+ this.teardown('remote-user');
524
+ };
525
+ if (this.signalObserver)
526
+ signalMap.unobserve(this.signalObserver);
527
+ if (this.iceObserver)
528
+ vitreIce.unobserve(this.iceObserver);
529
+ if (this.controlObserver)
530
+ controlArr.unobserve(this.controlObserver);
531
+ this.signalObserver = onSignal;
532
+ this.iceObserver = drainRemote;
533
+ this.controlObserver = onControl;
534
+ signalMap.observe(onSignal);
535
+ vitreIce.observe(drainRemote);
536
+ controlArr.observe(onControl);
537
+ // Create and publish the offer, merging into the existing session-request
538
+ // entry (written by start()) to preserve sessionId/receiverDisplay/metadata.
539
+ const offerOptions = iceRestart ? ICE_RESTART_OFFER_OPTIONS : undefined;
540
+ const offer = await pc.createOffer(offerOptions);
541
+ await pc.setLocalDescription(offer);
542
+ const doc = this.frame.crdt.doc;
543
+ doc.transact(() => {
544
+ const existing = (() => {
545
+ const raw = signalMap.get('session');
546
+ if (!raw)
547
+ return null;
548
+ try {
549
+ return JSON.parse(raw);
550
+ }
551
+ catch {
552
+ return null;
553
+ }
554
+ })();
555
+ const entry = {
556
+ ...(existing ?? {}),
557
+ sessionId: this.sessionId,
558
+ offer: offer.sdp ?? '',
559
+ receiverDisplay: this.receiverDisplay,
560
+ metadata: this.metadata,
561
+ };
562
+ signalMap.set('session', JSON.stringify(entry));
563
+ });
564
+ // Catch state that synced before observers attached.
565
+ onSignal();
566
+ drainRemote();
567
+ onControl();
568
+ }
569
+ async attemptRestart() {
570
+ if (this.stopped)
571
+ return;
572
+ if (this.retryCount >= this.options.attempts) {
573
+ this.teardown('failure');
574
+ return;
575
+ }
576
+ const delayMs = this.options.backoffMs[Math.min(this.retryCount, this.options.backoffMs.length - 1)] ?? 0;
577
+ this.retryCount++;
578
+ this.setState('reconnecting');
579
+ this.retryTimer = setTimeout(async () => {
580
+ this.retryTimer = null;
581
+ if (this.stopped)
582
+ return;
583
+ // Close old PC before creating new one.
584
+ const oldPc = this.pc;
585
+ this.pc = null;
586
+ if (oldPc) {
587
+ oldPc.onicecandidate = null;
588
+ oldPc.onconnectionstatechange = null;
589
+ oldPc.close();
590
+ }
591
+ try {
592
+ await this.initPeerConnection(true);
593
+ }
594
+ catch (err) {
595
+ console.error('[lavitre-apps] MediaLink ICE restart failed', err);
596
+ this.attemptRestart();
597
+ }
598
+ }, delayMs);
599
+ }
600
+ async replaceStream(stream) {
601
+ // FIX 4: no-op if torn down or PC is gone.
602
+ if (this.tornDown || !this.pc)
603
+ return;
604
+ this.stream = stream;
605
+ const tracks = stream.getTracks();
606
+ const replacePromises = [];
607
+ for (const sender of this.senders) {
608
+ // FIX 4: skip senders whose track is null (e.g. ended track removed by browser).
609
+ if (!sender.track)
610
+ continue;
611
+ const newTrack = tracks.find((t) => t.kind === sender.track?.kind);
612
+ if (newTrack)
613
+ replacePromises.push(sender.replaceTrack(newTrack));
614
+ }
615
+ await Promise.all(replacePromises);
616
+ }
617
+ stop() {
618
+ if (this.stopped)
619
+ return;
620
+ // FIX 3: set stopped=true BEFORE writing the control entry. The CRDT write
621
+ // triggers the local onControl observer synchronously, which calls
622
+ // teardown('remote-user'). With stopped=true set, that re-entrant call hits
623
+ // the tornDown guard and returns early; then teardown('user') below runs
624
+ // the actual cleanup.
625
+ this.stopped = true;
626
+ writeControlStop(this.frame, this.sessionId, 'user');
627
+ // Reliable close signal to the Vitre answerer via the host channel — more
628
+ // likely to flush on companion-frame unmount/back than the P2P CRDT control,
629
+ // so the answerer frame closes promptly. Mirrors the open-answerer send.
630
+ if (this.openAnswererFrame) {
631
+ try {
632
+ const closeMsg = {
633
+ type: 'lavitre-media-link',
634
+ action: 'close-answerer',
635
+ frameConnectorId: this.frame.id,
636
+ sessionId: this.sessionId,
637
+ };
638
+ this.frame.sendMessageToVitreConnector(JSON.stringify(closeMsg));
639
+ }
640
+ catch {
641
+ /* best-effort */
642
+ }
643
+ }
644
+ this.teardown('user');
645
+ }
646
+ /** Internal teardown. Guards on tornDown so the cleanup body runs exactly once. */
647
+ teardown(reason) {
648
+ // FIX 3: guard on tornDown (not stopped) — stop() sets stopped=true before
649
+ // writing the control entry, whose synchronous observer fires teardown
650
+ // ('remote-user'); that hits this guard and exits; then stop() calls
651
+ // teardown('user') which performs the cleanup exactly once.
652
+ if (this.tornDown)
653
+ return;
654
+ this.tornDown = true;
655
+ this.stopped = true;
656
+ // Remove pagehide listener.
657
+ if (this.pagehideHandler) {
658
+ window.removeEventListener('pagehide', this.pagehideHandler);
659
+ this.pagehideHandler = null;
660
+ }
661
+ this.clearTimers();
662
+ // Unsubscribe CRDT observers.
663
+ const signalMap = getSignalMap(this.frame);
664
+ const vitreIce = getIceAnswererArray(this.frame);
665
+ const controlArr = getControlArray(this.frame);
666
+ if (this.signalObserver) {
667
+ signalMap.unobserve(this.signalObserver);
668
+ this.signalObserver = null;
669
+ }
670
+ if (this.iceObserver) {
671
+ vitreIce.unobserve(this.iceObserver);
672
+ this.iceObserver = null;
673
+ }
674
+ if (this.controlObserver) {
675
+ controlArr.unobserve(this.controlObserver);
676
+ this.controlObserver = null;
677
+ }
678
+ // Close the PC.
679
+ if (this.pc) {
680
+ this.pc.onicecandidate = null;
681
+ this.pc.onconnectionstatechange = null;
682
+ this.pc.close();
683
+ this.pc = null;
684
+ }
685
+ this.setState('ended');
686
+ this.onEnded?.(reason);
687
+ }
688
+ setState(s) {
689
+ if (this.state === s)
690
+ return;
691
+ this.state = s;
692
+ this.onStateChange?.(s);
693
+ }
694
+ clearTimers() {
695
+ if (this.graceTimer != null) {
696
+ clearTimeout(this.graceTimer);
697
+ this.graceTimer = null;
698
+ }
699
+ if (this.retryTimer != null) {
700
+ clearTimeout(this.retryTimer);
701
+ this.retryTimer = null;
702
+ }
703
+ }
704
+ }
705
+ // ---------------------------------------------------------------------------
706
+ // Answerer implementation
707
+ // ---------------------------------------------------------------------------
708
+ // The answerer does not drive ICE recovery (the offerer does). If the offerer
709
+ // vanishes WITHOUT a clean control-stop (e.g. the companion frame is closed and
710
+ // its CRDT 'ended' write never flushes), the connection goes disconnected/failed
711
+ // and nothing would ever end the session — so closeOnEnd and the app's onEnded
712
+ // would hang forever. After this grace window with no recovery, the answerer
713
+ // ends the session itself. Longer than the offerer's ICE-restart cycle so a real
714
+ // reconnection wins first.
715
+ const ANSWERER_DISCONNECT_GRACE_MS = 10000;
716
+ class AnsweredMediaLinkImpl {
717
+ constructor(sessionId, frame, receiverDisplay, metadata, onStreamReady) {
718
+ Object.defineProperty(this, "sessionId", {
719
+ enumerable: true,
720
+ configurable: true,
721
+ writable: true,
722
+ value: sessionId
723
+ });
724
+ Object.defineProperty(this, "frame", {
725
+ enumerable: true,
726
+ configurable: true,
727
+ writable: true,
728
+ value: frame
729
+ });
730
+ Object.defineProperty(this, "receiverDisplay", {
731
+ enumerable: true,
732
+ configurable: true,
733
+ writable: true,
734
+ value: receiverDisplay
735
+ });
736
+ Object.defineProperty(this, "metadata", {
737
+ enumerable: true,
738
+ configurable: true,
739
+ writable: true,
740
+ value: metadata
741
+ });
742
+ Object.defineProperty(this, "onStreamReady", {
743
+ enumerable: true,
744
+ configurable: true,
745
+ writable: true,
746
+ value: onStreamReady
747
+ });
748
+ Object.defineProperty(this, "onStreamChanged", {
749
+ enumerable: true,
750
+ configurable: true,
751
+ writable: true,
752
+ value: void 0
753
+ });
754
+ Object.defineProperty(this, "onStateChange", {
755
+ enumerable: true,
756
+ configurable: true,
757
+ writable: true,
758
+ value: void 0
759
+ });
760
+ Object.defineProperty(this, "onEnded", {
761
+ enumerable: true,
762
+ configurable: true,
763
+ writable: true,
764
+ value: void 0
765
+ });
766
+ Object.defineProperty(this, "pc", {
767
+ enumerable: true,
768
+ configurable: true,
769
+ writable: true,
770
+ value: null
771
+ });
772
+ Object.defineProperty(this, "_stream", {
773
+ enumerable: true,
774
+ configurable: true,
775
+ writable: true,
776
+ value: null
777
+ });
778
+ Object.defineProperty(this, "remoteSet", {
779
+ enumerable: true,
780
+ configurable: true,
781
+ writable: true,
782
+ value: false
783
+ });
784
+ Object.defineProperty(this, "pendingRemote", {
785
+ enumerable: true,
786
+ configurable: true,
787
+ writable: true,
788
+ value: []
789
+ });
790
+ Object.defineProperty(this, "processedIce", {
791
+ enumerable: true,
792
+ configurable: true,
793
+ writable: true,
794
+ value: 0
795
+ });
796
+ Object.defineProperty(this, "stopped", {
797
+ enumerable: true,
798
+ configurable: true,
799
+ writable: true,
800
+ value: false
801
+ });
802
+ // Separate flag used by teardown so that teardown()'s cleanup body runs
803
+ // exactly once regardless of the call path (stop() vs. external teardown()).
804
+ Object.defineProperty(this, "tornDown", {
805
+ enumerable: true,
806
+ configurable: true,
807
+ writable: true,
808
+ value: false
809
+ });
810
+ // FIX 2: track the last offer SDP we processed to avoid re-triggering
811
+ // handleOffer when the answerer itself writes its answer into the session
812
+ // entry (the CRDT observer fires again with the same offer still present).
813
+ Object.defineProperty(this, "lastProcessedOfferSdp", {
814
+ enumerable: true,
815
+ configurable: true,
816
+ writable: true,
817
+ value: null
818
+ });
819
+ // Backstop timer: armed on a sustained disconnect with no offerer recovery,
820
+ // it ends the session so closeOnEnd / onEnded don't hang (see the const above).
821
+ Object.defineProperty(this, "endTimer", {
822
+ enumerable: true,
823
+ configurable: true,
824
+ writable: true,
825
+ value: null
826
+ });
827
+ // CRDT observer references
828
+ Object.defineProperty(this, "signalObserver", {
829
+ enumerable: true,
830
+ configurable: true,
831
+ writable: true,
832
+ value: null
833
+ });
834
+ Object.defineProperty(this, "iceObserver", {
835
+ enumerable: true,
836
+ configurable: true,
837
+ writable: true,
838
+ value: null
839
+ });
840
+ Object.defineProperty(this, "controlObserver", {
841
+ enumerable: true,
842
+ configurable: true,
843
+ writable: true,
844
+ value: null
845
+ });
846
+ }
847
+ get stream() {
848
+ if (!this._stream)
849
+ throw new Error('[lavitre-apps] AnsweredMediaLink: stream not yet available');
850
+ return this._stream;
851
+ }
852
+ async initiate(offerSdp, currentIceOffererTip) {
853
+ const iceServers = await resolveIceServers(this.frame);
854
+ const pc = new RTCPeerConnection({ iceServers });
855
+ this.pc = pc;
856
+ // --- ICE/TURN diagnostics (answerer = the Vitre that reshares). Same signals as
857
+ // the offerer: TURN handed out?, ICE progress, TURN auth failures (401/403).
858
+ const turnCount = iceServers.filter((s) => {
859
+ const urls = Array.isArray(s.urls) ? s.urls : [s.urls];
860
+ return urls.some((u) => typeof u === 'string' && u.startsWith('turn'));
861
+ }).length;
862
+ console.log('[lavitre-apps][MediaLink] pc-init answerer ' + JSON.stringify({ servers: iceServers.length, turn: turnCount }));
863
+ pc.oniceconnectionstatechange = () => {
864
+ if (this.pc === pc)
865
+ console.log('[lavitre-apps][MediaLink] iceState answerer', pc.iceConnectionState);
866
+ };
867
+ pc.onicecandidateerror = (ev) => {
868
+ console.warn('[lavitre-apps][MediaLink] ice-error answerer ' + JSON.stringify({ code: ev.errorCode, url: ev.url, text: ev.errorText }));
869
+ };
870
+ this.remoteSet = false;
871
+ this.pendingRemote = [];
872
+ this.processedIce = currentIceOffererTip;
873
+ pc.ontrack = (e) => {
874
+ if (this.pc !== pc)
875
+ return;
876
+ const incoming = e.streams[0] ?? new MediaStream([e.track]);
877
+ if (!this._stream) {
878
+ this._stream = incoming;
879
+ // Notify the handler: the link is ready for the app.
880
+ this.onStreamReady(this);
881
+ }
882
+ else {
883
+ // Subsequent tracks (e.g. audio added after video).
884
+ this._stream = incoming;
885
+ this.onStreamChanged?.(this._stream);
886
+ }
887
+ };
888
+ // FIX 1: answerer trickle ICE — publish answerer candidates so the offerer
889
+ // can drain them from getIceAnswererArray. Guard this.pc === pc to discard
890
+ // stale events after an ICE restart replaces the peer connection.
891
+ pc.onicecandidate = (e) => {
892
+ if (e.candidate && this.pc === pc) {
893
+ const tagged = { s: this.sessionId, c: e.candidate.toJSON() };
894
+ getIceAnswererArray(this.frame).push([JSON.stringify(tagged)]);
895
+ }
896
+ };
897
+ pc.onconnectionstatechange = () => {
898
+ if (this.stopped || this.pc !== pc)
899
+ return;
900
+ const cs = pc.connectionState;
901
+ console.log('[lavitre-apps][MediaLink] connState answerer', cs);
902
+ if (cs === 'connected') {
903
+ if (this.endTimer) {
904
+ clearTimeout(this.endTimer);
905
+ this.endTimer = null;
906
+ }
907
+ this.emitState('connected');
908
+ }
909
+ else if (cs === 'failed' || cs === 'disconnected') {
910
+ // Answerer does not retry; recovery is offerer-driven (ICE restart).
911
+ // Reflect 'reconnecting' so the app can react. A clean stop still ends
912
+ // the session sooner via the control observer. But if the offerer is
913
+ // GONE (e.g. companion frame closed without flushing its 'ended' write),
914
+ // no restart will come — so arm a grace timer to end the session
915
+ // ourselves; otherwise the answerer (and closeOnEnd) would hang forever.
916
+ this.emitState('reconnecting');
917
+ if (!this.endTimer) {
918
+ this.endTimer = setTimeout(() => {
919
+ this.endTimer = null;
920
+ if (!this.stopped && this.pc === pc && pc.connectionState !== 'connected') {
921
+ this.teardown('failure');
922
+ }
923
+ }, ANSWERER_DISCONNECT_GRACE_MS);
924
+ }
925
+ }
926
+ };
927
+ const offererIce = getIceOffererArray(this.frame);
928
+ const signalMap = getSignalMap(this.frame);
929
+ const controlArr = getControlArray(this.frame);
930
+ const drainOffererIce = () => {
931
+ if (!this.pc || this.pc !== pc)
932
+ return;
933
+ this.processedIce = drainIce(offererIce, this.processedIce, this.sessionId, (c) => {
934
+ if (this.remoteSet)
935
+ void pc.addIceCandidate(c).catch(() => { });
936
+ else
937
+ this.pendingRemote.push(c);
938
+ });
939
+ };
940
+ // Watch for a re-offer (ICE restart from the offerer side).
941
+ // FIX 2: guard against the answerer's own answer-write re-triggering this
942
+ // handler. When the answerer writes its answer into the 'session' entry the
943
+ // CRDT observer fires again — the entry still carries .offer so without
944
+ // the guard handleOffer would run again on a stable PC, creating an
945
+ // unbounded loop. We skip if the offer SDP has not changed since we last
946
+ // processed it; ICE-restart offers carry a different SDP and still pass.
947
+ const onSignal = () => {
948
+ if (!this.pc || this.pc !== pc || this.stopped)
949
+ return;
950
+ const raw = signalMap.get('session');
951
+ if (!raw)
952
+ return;
953
+ let entry;
954
+ try {
955
+ entry = JSON.parse(raw);
956
+ }
957
+ catch {
958
+ return;
959
+ }
960
+ if (entry.sessionId !== this.sessionId || !entry.offer)
961
+ return;
962
+ if (entry.offer === this.lastProcessedOfferSdp)
963
+ return;
964
+ // Re-offer arrived: re-answer (ICE restart or first answer).
965
+ void this.handleOffer(entry.offer);
966
+ };
967
+ const onControl = () => {
968
+ if (this.stopped)
969
+ return;
970
+ const reason = checkVoluntaryStop(this.frame, this.sessionId);
971
+ if (reason != null)
972
+ this.teardown('remote-user');
973
+ };
974
+ if (this.signalObserver)
975
+ signalMap.unobserve(this.signalObserver);
976
+ if (this.iceObserver)
977
+ offererIce.unobserve(this.iceObserver);
978
+ if (this.controlObserver)
979
+ controlArr.unobserve(this.controlObserver);
980
+ this.signalObserver = onSignal;
981
+ this.iceObserver = drainOffererIce;
982
+ this.controlObserver = onControl;
983
+ signalMap.observe(onSignal);
984
+ offererIce.observe(drainOffererIce);
985
+ controlArr.observe(onControl);
986
+ // FIX 2: record the initial offer SDP before processing so that the CRDT
987
+ // observer fired by our own answer-write below sees it and returns early.
988
+ this.lastProcessedOfferSdp = offerSdp;
989
+ await pc.setRemoteDescription({ type: 'offer', sdp: offerSdp });
990
+ this.remoteSet = true;
991
+ for (const c of this.pendingRemote.splice(0)) {
992
+ void pc.addIceCandidate(c).catch(() => { });
993
+ }
994
+ const answer = await pc.createAnswer();
995
+ await pc.setLocalDescription(answer);
996
+ // Publish the answer into the existing session entry.
997
+ const raw = signalMap.get('session');
998
+ if (raw) {
999
+ try {
1000
+ const existing = JSON.parse(raw);
1001
+ const updated = { ...existing, answer: answer.sdp ?? '' };
1002
+ signalMap.set('session', JSON.stringify(updated));
1003
+ }
1004
+ catch {
1005
+ signalMap.set('session', JSON.stringify({ sessionId: this.sessionId, answer: answer.sdp ?? '' }));
1006
+ }
1007
+ }
1008
+ drainOffererIce();
1009
+ onControl();
1010
+ }
1011
+ /** Handle a re-offer (ICE restart) from the offerer. */
1012
+ async handleOffer(offerSdp) {
1013
+ if (!this.pc || this.stopped)
1014
+ return;
1015
+ // FIX 2: record the SDP we are about to process BEFORE any async work so
1016
+ // that the synchronous CRDT observer fired by our own answer-write below
1017
+ // sees it and returns early (same SDP = already handled).
1018
+ this.lastProcessedOfferSdp = offerSdp;
1019
+ const pc = this.pc;
1020
+ try {
1021
+ await pc.setRemoteDescription({ type: 'offer', sdp: offerSdp });
1022
+ this.remoteSet = true;
1023
+ const answer = await pc.createAnswer();
1024
+ await pc.setLocalDescription(answer);
1025
+ const signalMap = getSignalMap(this.frame);
1026
+ const raw = signalMap.get('session');
1027
+ if (raw) {
1028
+ try {
1029
+ const existing = JSON.parse(raw);
1030
+ const updated = { ...existing, answer: answer.sdp ?? '' };
1031
+ signalMap.set('session', JSON.stringify(updated));
1032
+ }
1033
+ catch {
1034
+ signalMap.set('session', JSON.stringify({ sessionId: this.sessionId, answer: answer.sdp ?? '' }));
1035
+ }
1036
+ }
1037
+ }
1038
+ catch (err) {
1039
+ console.error('[lavitre-apps] AnsweredMediaLink handleOffer', err);
1040
+ }
1041
+ }
1042
+ stop() {
1043
+ if (this.stopped)
1044
+ return;
1045
+ // FIX 3: set stopped=true BEFORE writing the control entry. The CRDT write
1046
+ // triggers the local onControl observer synchronously, which calls
1047
+ // teardown('remote-user'). With stopped=true already set, that call is a
1048
+ // no-op on the stopped guard, but teardown('user') below must still run
1049
+ // the cleanup — so teardown guards on the separate tornDown flag, not on
1050
+ // stopped.
1051
+ this.stopped = true;
1052
+ writeControlStop(this.frame, this.sessionId, 'user');
1053
+ this.teardown('user');
1054
+ }
1055
+ teardown(reason) {
1056
+ // FIX 3: guard on tornDown (not stopped) so that the cleanup body runs
1057
+ // exactly once regardless of path — stop() sets stopped=true before writing
1058
+ // the control entry, which fires onControl→teardown('remote-user')
1059
+ // synchronously; that call hits this guard and returns early; then
1060
+ // stop() continues and calls teardown('user') which runs the cleanup.
1061
+ if (this.tornDown)
1062
+ return;
1063
+ this.tornDown = true;
1064
+ this.stopped = true;
1065
+ if (this.endTimer) {
1066
+ clearTimeout(this.endTimer);
1067
+ this.endTimer = null;
1068
+ }
1069
+ // FIX 2: reset lastProcessedOfferSdp on teardown.
1070
+ this.lastProcessedOfferSdp = null;
1071
+ const signalMap = getSignalMap(this.frame);
1072
+ const offererIce = getIceOffererArray(this.frame);
1073
+ const controlArr = getControlArray(this.frame);
1074
+ if (this.signalObserver) {
1075
+ signalMap.unobserve(this.signalObserver);
1076
+ this.signalObserver = null;
1077
+ }
1078
+ if (this.iceObserver) {
1079
+ offererIce.unobserve(this.iceObserver);
1080
+ this.iceObserver = null;
1081
+ }
1082
+ if (this.controlObserver) {
1083
+ controlArr.unobserve(this.controlObserver);
1084
+ this.controlObserver = null;
1085
+ }
1086
+ if (this.pc) {
1087
+ this.pc.ontrack = null;
1088
+ this.pc.onicecandidate = null;
1089
+ this.pc.onconnectionstatechange = null;
1090
+ this.pc.close();
1091
+ this.pc = null;
1092
+ }
1093
+ this.emitState('ended');
1094
+ this.onEnded?.(reason);
1095
+ }
1096
+ emitState(s) {
1097
+ this.onStateChange?.(s);
1098
+ }
1099
+ }
1100
+ // ---------------------------------------------------------------------------
1101
+ // Public API entry points
1102
+ // ---------------------------------------------------------------------------
1103
+ /**
1104
+ * Companion-frame side — the offerer.
1105
+ *
1106
+ * Acquires ICE servers, creates an `RTCPeerConnection` with the given stream,
1107
+ * publishes the offer over the frame CRDT doc, and optionally requests that
1108
+ * the answerer frame be opened on the Vitre via
1109
+ * `frame.sendMessageToVitreConnector`. Resolves with a {@link MediaLink}
1110
+ * handle once the local description is set (i.e. signalling is in flight).
1111
+ *
1112
+ * Call `connector.openFrame(frameConnectorId, ...)` on the Vitre side (or use
1113
+ * {@link enableMediaLinkAnswerer}) BEFORE calling this so the answerer frame
1114
+ * is ready to receive the offer when the CRDT syncs. If `requestAnswererFrame`
1115
+ * is true (default) the SDK sends the control message automatically.
1116
+ *
1117
+ * @param frame The companion frame (`CompanionFrame`, from `initializeCompanionFrame`).
1118
+ * @param stream The `MediaStream` to send to the Vitre frame.
1119
+ * @param options Optional configuration (retry, metadata, display mode…).
1120
+ */
1121
+ export async function startMediaLink(frame, stream, options) {
1122
+ const sessionId = crypto.randomUUID();
1123
+ const retryOpts = {
1124
+ graceMs: options?.retry?.graceMs ?? 3000,
1125
+ attempts: options?.retry?.attempts ?? 3,
1126
+ backoffMs: options?.retry?.backoffMs ?? [2000, 4000, 8000],
1127
+ };
1128
+ const link = new MediaLinkImpl(sessionId, frame, stream, retryOpts, options?.requestAnswererFrame !== false, options?.receiverDisplay, options?.metadata, options?.vitreIceTimeoutMs ?? 8000);
1129
+ // Attach the callbacks BEFORE start() so no state transition can be missed
1130
+ // (start() awaits ICE resolution; a fast answer could otherwise fire
1131
+ // 'connected' before the caller had a chance to assign the handlers).
1132
+ if (options?.onStateChange)
1133
+ link.onStateChange = options.onStateChange;
1134
+ if (options?.onEnded)
1135
+ link.onEnded = options.onEnded;
1136
+ await link.start();
1137
+ return link;
1138
+ }
1139
+ /**
1140
+ * Vitre-frame side — subscribe to incoming media link sessions.
1141
+ *
1142
+ * The handler fires once per session (including sessions already present in
1143
+ * the CRDT doc at the time of subscription — late-join). Each invocation
1144
+ * provides an {@link AnsweredMediaLink} with the remote stream and teardown
1145
+ * handle. The caller is responsible for calling `frame.shareStream(link.stream)`
1146
+ * (or equivalent) to route the stream to the space.
1147
+ *
1148
+ * Returns an unsubscribe function that stops watching for new sessions. Existing
1149
+ * {@link AnsweredMediaLink} handles are NOT torn down by unsubscribing — each
1150
+ * must be ended explicitly via `link.stop()` or via the offerer's `stop()`.
1151
+ *
1152
+ * @param frame The Vitre-side frame (`Frame`).
1153
+ * @param handler Called for every new (or already-present) incoming session.
1154
+ * @returns Unsubscribe function.
1155
+ */
1156
+ export function onMediaLink(frame, handler) {
1157
+ const signalMap = getSignalMap(frame);
1158
+ // Track sessions already handled so the CRDT observer doesn't re-fire them.
1159
+ const seen = new Set();
1160
+ // Track sessions for which we have published our ICE servers but the offer
1161
+ // has not yet arrived — prevents re-publishing on every CRDT tick.
1162
+ const icePublished = new Set();
1163
+ // Cleared by the unsubscribe function: stops in-flight async ICE publishes
1164
+ // from writing to the CRDT after the caller unsubscribed, and lets a later
1165
+ // re-subscribe publish again for fresh sessions.
1166
+ let active = true;
1167
+ const processSignal = () => {
1168
+ const raw = signalMap.get('session');
1169
+ if (!raw)
1170
+ return;
1171
+ let entry;
1172
+ try {
1173
+ entry = JSON.parse(raw);
1174
+ }
1175
+ catch {
1176
+ return;
1177
+ }
1178
+ const { sessionId, offer, receiverDisplay, metadata } = entry;
1179
+ if (!sessionId)
1180
+ return;
1181
+ if (!seen.has(sessionId)) {
1182
+ // A new session (with or without an offer) has appeared. The answerer
1183
+ // must resolve the Vitre's ICE servers and publish them exactly once for
1184
+ // this session so the offerer can consume them before building its PC.
1185
+ if (!icePublished.has(sessionId)) {
1186
+ icePublished.add(sessionId);
1187
+ void (async () => {
1188
+ let servers = [];
1189
+ try {
1190
+ servers = await frame.getIceServers();
1191
+ }
1192
+ catch {
1193
+ servers = [];
1194
+ }
1195
+ if (!active)
1196
+ return; // unsubscribed while resolving — do not write
1197
+ if (!servers.length)
1198
+ return; // nothing useful to publish; offerer falls back naturally
1199
+ const iceEntry = { s: sessionId, servers };
1200
+ getIceServersMap(frame).set('servers', JSON.stringify(iceEntry));
1201
+ })();
1202
+ }
1203
+ }
1204
+ // Wait until the offer arrives before creating the answerer impl.
1205
+ if (!offer)
1206
+ return;
1207
+ if (seen.has(sessionId))
1208
+ return;
1209
+ seen.add(sessionId);
1210
+ // Snapshot the current tip of the offerer ICE array so the answerer
1211
+ // doesn't try to process offerer candidates that were published before
1212
+ // this session's offer.
1213
+ const iceOffererTip = getIceOffererArray(frame).length;
1214
+ const link = new AnsweredMediaLinkImpl(sessionId, frame, receiverDisplay, metadata, handler);
1215
+ void link.initiate(offer, iceOffererTip).catch((err) => {
1216
+ console.error('[lavitre-apps] AnsweredMediaLink initiate', err);
1217
+ });
1218
+ };
1219
+ signalMap.observe(processSignal);
1220
+ // Catch a session that was already in the CRDT when this observer attached.
1221
+ processSignal();
1222
+ return () => {
1223
+ active = false;
1224
+ signalMap.unobserve(processSignal);
1225
+ };
1226
+ }
1227
+ /**
1228
+ * Vitre CONNECTOR helper — automatically opens the answerer frame when a
1229
+ * companion frame requests it via the `lavitre-media-link` control message,
1230
+ * and closes it again when the last link of that frame ends (configurable).
1231
+ *
1232
+ * Wire this in the Connector's `onMessageFromCompanionFrame` on the Vitre side:
1233
+ * ```ts
1234
+ * const unsub = enableMediaLinkAnswerer(connector, {
1235
+ * url: 'https://my-app.apps.lavit.re/frame.html',
1236
+ * name: 'My App',
1237
+ * })
1238
+ * // Later:
1239
+ * unsub()
1240
+ * ```
1241
+ *
1242
+ * **Frame id matching**: the companion mints a per-session id of the form
1243
+ * `<appId>-<uuid>` and sends it in the `open-answerer` message. This helper
1244
+ * matches incoming messages by prefix:
1245
+ * - exact match: `msgFrameConnectorId === prefix`
1246
+ * - prefix match: `msgFrameConnectorId.startsWith(prefix + '-')`
1247
+ *
1248
+ * `frameConnectorId` (optional): the match prefix. Defaults to `connector.appId`
1249
+ * so apps that omit it work without any configuration. An app can still pass a
1250
+ * fixed string for backward compatibility — it matches via the `===` arm.
1251
+ *
1252
+ * The answerer frame is opened with the **companion-minted id** received in the
1253
+ * message (not a fixed constant), so re-share / concurrent sessions each get a
1254
+ * distinct frame and SharedContentId — stale state never leaks across sessions.
1255
+ *
1256
+ * `closeOnEnd` (default `true`): when the last active session for this frame
1257
+ * ends, the connector calls `connector.closeFrame(currentFrameId)`.
1258
+ *
1259
+ * @returns Unsubscribe function.
1260
+ */
1261
+ export function enableMediaLinkAnswerer(connector, opts) {
1262
+ const { url, name, closeOnEnd = true, size } = opts;
1263
+ // Default the match prefix to the connector's appId so callers that omit
1264
+ // frameConnectorId work without any extra configuration.
1265
+ const prefix = opts.frameConnectorId ?? connector.appId;
1266
+ let isOpen = false;
1267
+ let activeSessions = 0;
1268
+ // The companion-minted frame id of the currently-open answerer frame.
1269
+ // Set on the first matching open-answerer; reset to null on frame unload.
1270
+ let currentFrameId = null;
1271
+ // Sessions whose open-answerer arrived before the answerer frame finished
1272
+ // loading (getFrameConnector returns undefined until then). Drained when
1273
+ // openFrame resolves; cleared on frame unload.
1274
+ const pendingSessions = new Set();
1275
+ // IMPROVEMENT 6: per-session CRDT control observers, keyed by sessionId.
1276
+ // Kept here (outside the message handler) so that the frameUnloaded handler
1277
+ // installed ONCE below can unobserve all of them on frame close.
1278
+ const sessionControlObservers = new Map();
1279
+ const previousHandler = connector.onMessageFromCompanionFrame;
1280
+ const previousUnloadedHandler = connector.onFrameUnloaded;
1281
+ // IMPROVEMENT 6: register onFrameUnloaded ONCE at setup time (not per session).
1282
+ // Capture the previous handler and call it first (same chain pattern used for
1283
+ // onMessageFromCompanionFrame). Restore-on-unsubscribe only if our closure is
1284
+ // still installed.
1285
+ const unloadedHandler = (unloadedId) => {
1286
+ previousUnloadedHandler?.(unloadedId);
1287
+ if (unloadedId === currentFrameId) {
1288
+ isOpen = false;
1289
+ activeSessions = 0;
1290
+ pendingSessions.clear();
1291
+ currentFrameId = null;
1292
+ // Unobserve all per-session CRDT observers accumulated so far.
1293
+ for (const { arr, obs } of sessionControlObservers.values()) {
1294
+ arr.unobserve(obs);
1295
+ }
1296
+ sessionControlObservers.clear();
1297
+ }
1298
+ };
1299
+ connector.onFrameUnloaded = unloadedHandler;
1300
+ const handler = (fromCompanionId, msgFrameConnectorId, message) => {
1301
+ // Forward to any previously-registered handler first.
1302
+ previousHandler?.(fromCompanionId, msgFrameConnectorId, message);
1303
+ // Accept messages whose frame id matches the prefix exactly (backward-compat
1304
+ // with a fixed id) OR starts with `<prefix>-` (UUID-suffixed per-session id).
1305
+ if (msgFrameConnectorId !== prefix && !msgFrameConnectorId.startsWith(prefix + '-'))
1306
+ return;
1307
+ let parsed;
1308
+ try {
1309
+ parsed = JSON.parse(message);
1310
+ }
1311
+ catch {
1312
+ return;
1313
+ }
1314
+ if (!isMediaLinkOpenAnswererMessage(parsed))
1315
+ return;
1316
+ // Explicit close from the companion frame (sent on its stop/unmount). This is
1317
+ // the reliable, prompt close path — it does not depend on the P2P CRDT control
1318
+ // flushing during teardown. Drop that session and close the frame if it was
1319
+ // the last one.
1320
+ if (parsed.action === 'close-answerer') {
1321
+ const sid = parsed.sessionId;
1322
+ const entry = sessionControlObservers.get(sid);
1323
+ if (entry) {
1324
+ entry.arr.unobserve(entry.obs);
1325
+ sessionControlObservers.delete(sid);
1326
+ }
1327
+ pendingSessions.delete(sid);
1328
+ activeSessions = Math.max(0, activeSessions - 1);
1329
+ if (activeSessions === 0 && isOpen && currentFrameId) {
1330
+ const frameToClose = currentFrameId;
1331
+ isOpen = false;
1332
+ currentFrameId = null;
1333
+ connector.closeFrame(frameToClose);
1334
+ }
1335
+ return;
1336
+ }
1337
+ if (parsed.action !== 'open-answerer')
1338
+ return;
1339
+ activeSessions++;
1340
+ const sessionId = parsed.sessionId;
1341
+ // Register the per-session CRDT control observer that detects a voluntary
1342
+ // stop. `getFrameConnector` only returns once the answerer frame is LOADED,
1343
+ // so if it isn't yet — the first session triggers openFrame, or another
1344
+ // session arrives during that load — the sessionId is queued (see
1345
+ // pendingSessions) and wired when openFrame resolves below. The observer is
1346
+ // stored in sessionControlObservers (keyed by sessionId) so the single
1347
+ // onFrameUnloaded handler above can clean them all up on frame close.
1348
+ const registerSessionObserver = (sid) => {
1349
+ if (!closeOnEnd)
1350
+ return;
1351
+ if (sessionControlObservers.has(sid))
1352
+ return;
1353
+ if (!currentFrameId) {
1354
+ pendingSessions.add(sid);
1355
+ return;
1356
+ }
1357
+ const frameConnector = connector.getFrameConnector(currentFrameId);
1358
+ if (!frameConnector) {
1359
+ pendingSessions.add(sid);
1360
+ return;
1361
+ }
1362
+ const controlArr = getControlArray(frameConnector);
1363
+ const onControl = () => {
1364
+ if (!currentFrameId)
1365
+ return;
1366
+ const reason = checkVoluntaryStop(frameConnector, sid);
1367
+ if (reason != null) {
1368
+ controlArr.unobserve(onControl);
1369
+ sessionControlObservers.delete(sid);
1370
+ activeSessions = Math.max(0, activeSessions - 1);
1371
+ if (activeSessions === 0 && isOpen && currentFrameId) {
1372
+ const frameToClose = currentFrameId;
1373
+ isOpen = false;
1374
+ currentFrameId = null;
1375
+ connector.closeFrame(frameToClose);
1376
+ }
1377
+ }
1378
+ };
1379
+ controlArr.observe(onControl);
1380
+ sessionControlObservers.set(sid, { arr: controlArr, obs: onControl });
1381
+ };
1382
+ if (!isOpen) {
1383
+ isOpen = true;
1384
+ // The answerer frame is opened with the companion-minted id so each
1385
+ // re-share / concurrent session gets a distinct frame and SharedContentId.
1386
+ currentFrameId = msgFrameConnectorId;
1387
+ const frameOptions = {
1388
+ frameConnectorId: currentFrameId,
1389
+ url,
1390
+ name: name ?? 'MediaLink',
1391
+ ...(size ? { size } : {}),
1392
+ };
1393
+ // openFrame resolves when the frame connector is LOADED — only then can
1394
+ // getFrameConnector return it, so wire any queued sessions on resolution.
1395
+ connector
1396
+ .openFrame(frameOptions)
1397
+ .then(() => {
1398
+ for (const sid of pendingSessions)
1399
+ registerSessionObserver(sid);
1400
+ pendingSessions.clear();
1401
+ })
1402
+ .catch((err) => {
1403
+ console.error('[lavitre-apps] enableMediaLinkAnswerer openFrame', err);
1404
+ });
1405
+ }
1406
+ // Register now if the frame is already loaded; otherwise this queues the
1407
+ // sessionId for the openFrame resolution above.
1408
+ registerSessionObserver(sessionId);
1409
+ };
1410
+ connector.onMessageFromCompanionFrame = handler;
1411
+ return () => {
1412
+ if (connector.onMessageFromCompanionFrame === handler) {
1413
+ connector.onMessageFromCompanionFrame = previousHandler;
1414
+ }
1415
+ // Restore onFrameUnloaded only if our closure is still installed.
1416
+ if (connector.onFrameUnloaded === unloadedHandler) {
1417
+ connector.onFrameUnloaded = previousUnloadedHandler;
1418
+ }
1419
+ };
1420
+ }
1421
+ // ---------------------------------------------------------------------------
1422
+ // Type guard
1423
+ // ---------------------------------------------------------------------------
1424
+ function isMediaLinkOpenAnswererMessage(v) {
1425
+ return (typeof v === 'object' &&
1426
+ v !== null &&
1427
+ v['type'] === 'lavitre-media-link' &&
1428
+ typeof v['action'] === 'string' &&
1429
+ typeof v['frameConnectorId'] === 'string' &&
1430
+ typeof v['sessionId'] === 'string');
1431
+ }
1432
+ //# sourceMappingURL=MediaLink.js.map