@furious.luke/argus-js 0.3.0 → 0.3.1
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 +22 -0
- package/dist/index.cjs +129 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +49 -1
- package/dist/index.d.ts +49 -1
- package/dist/index.js +129 -10
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -44,6 +44,10 @@ const publisher = new Publisher({
|
|
|
44
44
|
callbacks: {
|
|
45
45
|
onConnected: () => console.log("streaming live"),
|
|
46
46
|
onConnectionStateChange: (state) => console.log("state:", state),
|
|
47
|
+
onRecoveryStateChange: (event) => console.log("media recovery:", event),
|
|
48
|
+
// Show a button or prompt. From its click handler, call captureScreen()
|
|
49
|
+
// and then publisher.replaceStream(newStream).
|
|
50
|
+
onRecoveryRequired: (event) => console.warn("screen share must be restarted", event),
|
|
47
51
|
onError: (err) => console.error("publish error:", err),
|
|
48
52
|
},
|
|
49
53
|
});
|
|
@@ -113,6 +117,8 @@ publisher.stop(); // stops all tracks and tears down the peer connection
|
|
|
113
117
|
| --- | --- |
|
|
114
118
|
| `onConnected()` | The peer connection reached `"connected"` — media is flowing. |
|
|
115
119
|
| `onConnectionStateChange(state)` | The `RTCPeerConnectionState` changed. |
|
|
120
|
+
| `onRecoveryStateChange(event)` | Argus detected stalled media and the publisher started, escalated, completed, or failed automatic recovery. |
|
|
121
|
+
| `onRecoveryRequired(event)` | Automatic recovery could not restore media, or capture ended and the host must ask the user for a new screen share. |
|
|
116
122
|
| `onError(error)` | A fatal error occurred (signaling error, initial gateway failure, or signaling resume timed out). |
|
|
117
123
|
|
|
118
124
|
## How `start()` works
|
|
@@ -127,6 +133,22 @@ one-hour read token and waits for `resumed`; it does not race regions, rebuild
|
|
|
127
133
|
the peer connection, or repeat the `ready` handshake. If the retry deadline
|
|
128
134
|
expires, the publisher closes the stream and calls `onError`.
|
|
129
135
|
|
|
136
|
+
## Automatic media recovery
|
|
137
|
+
|
|
138
|
+
Argus measures freshness from complete encoded samples received by the media
|
|
139
|
+
server, not from pixel changes. An unchanged screen therefore remains healthy.
|
|
140
|
+
If samples stop for 15 seconds, the media server tells the publisher that the
|
|
141
|
+
track has stalled and stops serving its retained frame as current. The publisher
|
|
142
|
+
first detaches and reattaches the live sender and renegotiates. If samples do not
|
|
143
|
+
resume within four seconds, it performs an ICE restart and waits another eight
|
|
144
|
+
seconds. These fixed timings deliberately are not application configuration.
|
|
145
|
+
|
|
146
|
+
`onRecoveryStateChange` reports the recovery transitions. If both automatic
|
|
147
|
+
steps fail, `onRecoveryRequired` is called and the host can acquire a replacement
|
|
148
|
+
stream and pass it to `replaceStream`. A browser cannot silently reacquire a
|
|
149
|
+
screen share after the user or operating system ends it, so `capture_ended`
|
|
150
|
+
always requires host UI and a fresh `captureScreen()` call.
|
|
151
|
+
|
|
130
152
|
## Browser support
|
|
131
153
|
|
|
132
154
|
Requires a browser with WebRTC (`RTCPeerConnection`) and `WebSocket` — all current evergreen browsers. There is no Node.js runtime support; this is a browser-only package.
|
package/dist/index.cjs
CHANGED
|
@@ -76,6 +76,9 @@ function parseSignal(data) {
|
|
|
76
76
|
var defaultSignalingReconnectTimeoutMs = 2e4;
|
|
77
77
|
var signalingResumeAttemptTimeoutMs = 3e3;
|
|
78
78
|
var signalingResumeMaxBackoffMs = 3e3;
|
|
79
|
+
var senderRestartPauseMs = 100;
|
|
80
|
+
var senderRecoveryWaitMs = 4e3;
|
|
81
|
+
var iceRecoveryWaitMs = 8e3;
|
|
79
82
|
var Publisher = class {
|
|
80
83
|
opts;
|
|
81
84
|
sig = null;
|
|
@@ -89,6 +92,11 @@ var Publisher = class {
|
|
|
89
92
|
reconnecting = false;
|
|
90
93
|
reconnectGeneration = 0;
|
|
91
94
|
resumeSocket = null;
|
|
95
|
+
recoveryGeneration = 0;
|
|
96
|
+
recoveringMedia = false;
|
|
97
|
+
recoveryRequired = false;
|
|
98
|
+
recoveryAction = null;
|
|
99
|
+
trackEndHandlers = /* @__PURE__ */ new Map();
|
|
92
100
|
constructor(opts) {
|
|
93
101
|
this.opts = opts;
|
|
94
102
|
}
|
|
@@ -104,7 +112,9 @@ var Publisher = class {
|
|
|
104
112
|
*/
|
|
105
113
|
async start(stream) {
|
|
106
114
|
this.stopped = false;
|
|
115
|
+
this.recoveryRequired = false;
|
|
107
116
|
this.localStream = stream;
|
|
117
|
+
this.watchStreamTracks(stream);
|
|
108
118
|
const { ws, readyInfo, gatewayURL } = await this.raceGateways();
|
|
109
119
|
this.selectedGatewayURL = gatewayURL;
|
|
110
120
|
if (readyInfo.read_token) {
|
|
@@ -149,6 +159,9 @@ var Publisher = class {
|
|
|
149
159
|
/** Replaces the currently published stream with a new one. */
|
|
150
160
|
async replaceStream(stream) {
|
|
151
161
|
if (!this.pc) throw new Error("publisher not started");
|
|
162
|
+
this.cancelMediaRecovery();
|
|
163
|
+
this.recoveryRequired = false;
|
|
164
|
+
this.unwatchStreamTracks();
|
|
152
165
|
const senders = this.pc.getSenders();
|
|
153
166
|
for (const sender of senders) {
|
|
154
167
|
if (sender.track) {
|
|
@@ -159,26 +172,20 @@ var Publisher = class {
|
|
|
159
172
|
this.pc.addTrack(track, stream);
|
|
160
173
|
}
|
|
161
174
|
this.localStream = stream;
|
|
162
|
-
|
|
163
|
-
await this.
|
|
164
|
-
await this.gatherComplete();
|
|
165
|
-
const local = this.pc.localDescription;
|
|
166
|
-
if (!local) throw new Error("local description missing");
|
|
167
|
-
this.sig?.send({
|
|
168
|
-
type: "offer",
|
|
169
|
-
sdp: local.sdp,
|
|
170
|
-
sdp_type: "offer"
|
|
171
|
-
});
|
|
175
|
+
this.watchStreamTracks(stream);
|
|
176
|
+
await this.renegotiate(false);
|
|
172
177
|
}
|
|
173
178
|
/** Stops publishing and tears down the peer connection. */
|
|
174
179
|
stop() {
|
|
175
180
|
this.stopped = true;
|
|
181
|
+
this.cancelMediaRecovery();
|
|
176
182
|
this.reconnectGeneration++;
|
|
177
183
|
this.reconnecting = false;
|
|
178
184
|
this.resumeSocket?.close();
|
|
179
185
|
this.resumeSocket = null;
|
|
180
186
|
this.sig?.close();
|
|
181
187
|
this.sig = null;
|
|
188
|
+
this.unwatchStreamTracks();
|
|
182
189
|
this.localStream?.getTracks().forEach((t) => t.stop());
|
|
183
190
|
this.localStream = null;
|
|
184
191
|
this.pc?.close();
|
|
@@ -341,6 +348,7 @@ var Publisher = class {
|
|
|
341
348
|
}
|
|
342
349
|
terminateWithError(err) {
|
|
343
350
|
this.stopped = true;
|
|
351
|
+
this.cancelMediaRecovery();
|
|
344
352
|
this.reconnectGeneration++;
|
|
345
353
|
this.resumeSocket?.close();
|
|
346
354
|
this.resumeSocket = null;
|
|
@@ -348,6 +356,7 @@ var Publisher = class {
|
|
|
348
356
|
this.sig = null;
|
|
349
357
|
this.pc?.close();
|
|
350
358
|
this.pc = null;
|
|
359
|
+
this.unwatchStreamTracks();
|
|
351
360
|
this.localStream?.getTracks().forEach((track) => track.stop());
|
|
352
361
|
this.localStream = null;
|
|
353
362
|
this.hasAnswer = false;
|
|
@@ -395,6 +404,15 @@ var Publisher = class {
|
|
|
395
404
|
case "connection_state": {
|
|
396
405
|
break;
|
|
397
406
|
}
|
|
407
|
+
case "media_stall":
|
|
408
|
+
case "media_track_ended": {
|
|
409
|
+
void this.beginMediaRecovery(msg.track);
|
|
410
|
+
break;
|
|
411
|
+
}
|
|
412
|
+
case "media_resumed": {
|
|
413
|
+
this.completeMediaRecovery(msg.track);
|
|
414
|
+
break;
|
|
415
|
+
}
|
|
398
416
|
case "error": {
|
|
399
417
|
this.opts.callbacks?.onError?.(new Error(msg.error));
|
|
400
418
|
break;
|
|
@@ -403,6 +421,107 @@ var Publisher = class {
|
|
|
403
421
|
break;
|
|
404
422
|
}
|
|
405
423
|
}
|
|
424
|
+
async beginMediaRecovery(trackType) {
|
|
425
|
+
if (this.stopped || this.recoveringMedia || this.recoveryRequired) return;
|
|
426
|
+
const tracks = this.localStream?.getVideoTracks() ?? [];
|
|
427
|
+
const liveTracks = tracks.filter((track) => track.readyState !== "ended");
|
|
428
|
+
if (liveTracks.length === 0) {
|
|
429
|
+
this.failMediaRecovery(trackType, "capture_ended");
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
this.recoveringMedia = true;
|
|
433
|
+
const generation = ++this.recoveryGeneration;
|
|
434
|
+
this.recoveryAction = "sender_restart";
|
|
435
|
+
this.emitRecoveryTransition({ state: "recovering", track: trackType, action: "sender_restart" });
|
|
436
|
+
this.sendRecoveryDiagnostic("recovery_started", trackType, "sender_restart");
|
|
437
|
+
await this.restartSenders(liveTracks, generation);
|
|
438
|
+
if (!this.isCurrentRecovery(generation)) return;
|
|
439
|
+
await this.wait(senderRecoveryWaitMs);
|
|
440
|
+
if (!this.isCurrentRecovery(generation)) return;
|
|
441
|
+
this.recoveryAction = "ice_restart";
|
|
442
|
+
this.emitRecoveryTransition({ state: "recovering", track: trackType, action: "ice_restart" });
|
|
443
|
+
this.sendRecoveryDiagnostic("recovery_retry", trackType, "ice_restart");
|
|
444
|
+
try {
|
|
445
|
+
await this.renegotiate(true);
|
|
446
|
+
} catch {
|
|
447
|
+
}
|
|
448
|
+
await this.wait(iceRecoveryWaitMs);
|
|
449
|
+
if (!this.isCurrentRecovery(generation)) return;
|
|
450
|
+
this.failMediaRecovery(trackType, "automatic_recovery_failed");
|
|
451
|
+
}
|
|
452
|
+
async restartSenders(tracks, generation) {
|
|
453
|
+
const live = new Set(tracks);
|
|
454
|
+
const senders = this.pc?.getSenders().filter(
|
|
455
|
+
(sender) => sender.track && live.has(sender.track)
|
|
456
|
+
) ?? [];
|
|
457
|
+
if (senders.length === 0) return;
|
|
458
|
+
const originals = senders.map((sender) => ({ sender, track: sender.track }));
|
|
459
|
+
try {
|
|
460
|
+
await Promise.all(originals.map(({ sender }) => sender.replaceTrack(null)));
|
|
461
|
+
await this.wait(senderRestartPauseMs);
|
|
462
|
+
if (!this.isCurrentRecovery(generation)) return;
|
|
463
|
+
await Promise.all(originals.map(({ sender, track }) => sender.replaceTrack(track)));
|
|
464
|
+
await this.renegotiate(false);
|
|
465
|
+
} catch {
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
async renegotiate(iceRestart) {
|
|
469
|
+
const pc = this.pc;
|
|
470
|
+
const signaling = this.sig;
|
|
471
|
+
if (!pc || !signaling) throw new Error("publisher signaling is unavailable");
|
|
472
|
+
if (iceRestart) pc.restartIce?.();
|
|
473
|
+
const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : void 0);
|
|
474
|
+
await pc.setLocalDescription(offer);
|
|
475
|
+
await this.gatherComplete();
|
|
476
|
+
const local = pc.localDescription;
|
|
477
|
+
if (!local) throw new Error("local description missing");
|
|
478
|
+
this.hasAnswer = false;
|
|
479
|
+
this.pendingRemoteCandidates = [];
|
|
480
|
+
signaling.send({ type: "offer", sdp: local.sdp, sdp_type: "offer" });
|
|
481
|
+
}
|
|
482
|
+
completeMediaRecovery(trackType) {
|
|
483
|
+
if (!this.recoveringMedia) return;
|
|
484
|
+
const action = this.recoveryAction ?? void 0;
|
|
485
|
+
this.cancelMediaRecovery();
|
|
486
|
+
this.emitRecoveryTransition({ state: "recovered", track: trackType, action });
|
|
487
|
+
}
|
|
488
|
+
failMediaRecovery(trackType, reason) {
|
|
489
|
+
if (this.stopped || this.recoveryRequired) return;
|
|
490
|
+
this.recoveryRequired = true;
|
|
491
|
+
const action = this.recoveryAction ?? void 0;
|
|
492
|
+
this.cancelMediaRecovery();
|
|
493
|
+
const event = { state: "failed", track: trackType, action, reason };
|
|
494
|
+
this.emitRecoveryTransition(event);
|
|
495
|
+
this.opts.callbacks?.onRecoveryRequired?.(event);
|
|
496
|
+
this.sendRecoveryDiagnostic("recovery_failed", trackType, action, reason);
|
|
497
|
+
}
|
|
498
|
+
cancelMediaRecovery() {
|
|
499
|
+
this.recoveryGeneration++;
|
|
500
|
+
this.recoveringMedia = false;
|
|
501
|
+
this.recoveryAction = null;
|
|
502
|
+
}
|
|
503
|
+
isCurrentRecovery(generation) {
|
|
504
|
+
return !this.stopped && this.recoveringMedia && generation === this.recoveryGeneration;
|
|
505
|
+
}
|
|
506
|
+
emitRecoveryTransition(event) {
|
|
507
|
+
this.opts.callbacks?.onRecoveryStateChange?.(event);
|
|
508
|
+
}
|
|
509
|
+
sendRecoveryDiagnostic(event, track, action, reason) {
|
|
510
|
+
this.sig?.send({ type: "recovery_event", event, track, action, reason });
|
|
511
|
+
}
|
|
512
|
+
watchStreamTracks(stream) {
|
|
513
|
+
for (const track of stream.getVideoTracks()) {
|
|
514
|
+
const handler = () => this.failMediaRecovery("screen", "capture_ended");
|
|
515
|
+
track.addEventListener("ended", handler);
|
|
516
|
+
this.trackEndHandlers.set(track, handler);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
unwatchStreamTracks() {
|
|
520
|
+
for (const [track, handler] of this.trackEndHandlers) {
|
|
521
|
+
track.removeEventListener("ended", handler);
|
|
522
|
+
}
|
|
523
|
+
this.trackEndHandlers.clear();
|
|
524
|
+
}
|
|
406
525
|
/** Waits for ICE gathering to reach the "complete" state. */
|
|
407
526
|
gatherComplete() {
|
|
408
527
|
return new Promise((resolve) => {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/signaling.ts","../src/publisher.ts","../src/capture.ts"],"sourcesContent":["export { Publisher } from \"./publisher\";\nexport type {\n SignalMessage,\n PublisherCallbacks,\n PublisherOptions,\n GatewayReadyInfo,\n} from \"./types\";\nexport { captureCamera, captureScreen } from \"./capture\";\nexport type {\n CaptureCameraOptions,\n CaptureScreenOptions,\n} from \"./capture\";\n","import type { SignalMessage } from \"./types\";\n\n/**\n * Wraps an open WebSocket to the Argus gateway and handles the JSON message\n * envelope: incoming text frames are parsed into {@link SignalMessage}s and\n * outgoing messages are serialised.\n *\n * This is an internal helper. The {@link Publisher} opens the socket itself\n * (racing all candidate gateways) and hands the winner here, so this class only\n * ever adopts an already-open socket rather than dialing one.\n *\n * @internal\n */\nexport class SignalingChannel {\n private ws: WebSocket;\n\n /** Fired for every incoming JSON message. */\n onMessage: ((msg: SignalMessage) => void) | null = null;\n /** Fired when the underlying WebSocket closes. */\n onClose: (() => void) | null = null;\n /** Fired when an error occurs on the WebSocket. */\n onError: ((err: Error) => void) | null = null;\n\n private constructor(ws: WebSocket) {\n this.ws = ws;\n }\n\n /**\n * Adopts an already-open WebSocket (e.g. the winner of a gateway race),\n * routing its events through the channel's callbacks. Any handlers previously\n * attached to the socket are replaced.\n */\n static wrap(ws: WebSocket): SignalingChannel {\n const ch = new SignalingChannel(ws);\n ws.onmessage = (ev: MessageEvent) => {\n const msg = parseSignal(ev.data);\n if (msg) ch.onMessage?.(msg);\n };\n ws.onerror = () => ch.onError?.(new Error(\"WebSocket error\"));\n ws.onclose = () => ch.onClose?.();\n return ch;\n }\n\n /** Sends a JSON message if the socket is open; a no-op otherwise. */\n send(msg: SignalMessage): void {\n if (this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /** Closes the underlying WebSocket. */\n close(): void {\n this.ws.close();\n }\n}\n\n/** Parses a WebSocket text frame into a SignalMessage, or null if malformed. */\nfunction parseSignal(data: unknown): SignalMessage | null {\n try {\n return JSON.parse(data as string) as SignalMessage;\n } catch {\n return null;\n }\n}\n","import { SignalingChannel } from \"./signaling\";\nimport type { GatewayReadyInfo, PublisherOptions, SignalMessage } from \"./types\";\n\nconst defaultSignalingReconnectTimeoutMs = 20_000;\nconst signalingResumeAttemptTimeoutMs = 3_000;\nconst signalingResumeMaxBackoffMs = 3_000;\n\n/**\n * Publisher streams a browser {@link MediaStream} to an Argus media server over\n * WebRTC. Given the `gateway_urls` and `token` from a join-token response, it\n * races the candidate gateways to the fastest one, completes the two-phase\n * signaling handshake, and manages the peer connection — offer/answer exchange,\n * ICE candidate trickling, and track (re)negotiation.\n *\n * After {@link Publisher.start} resolves, {@link Publisher.frameReadToken} holds\n * the token your application server needs to fetch frames for this stream.\n *\n * @example Publish the default camera:\n * ```ts\n * const pub = new Publisher({\n * gatewayURLs: joinResp.gateway_urls,\n * token: joinResp.token,\n * callbacks: { onConnected: () => console.log(\"live!\") },\n * });\n *\n * const stream = await navigator.mediaDevices.getUserMedia({ video: true });\n * await pub.start(stream);\n * ```\n */\nexport class Publisher {\n private opts: PublisherOptions;\n private sig: SignalingChannel | null = null;\n private pc: RTCPeerConnection | null = null;\n private hasAnswer = false;\n private pendingRemoteCandidates: RTCIceCandidateInit[] = [];\n private localStream: MediaStream | null = null;\n private readToken: string | null = null;\n private selectedGatewayURL: string | null = null;\n private stopped = true;\n private reconnecting = false;\n private reconnectGeneration = 0;\n private resumeSocket: WebSocket | null = null;\n\n constructor(opts: PublisherOptions) {\n this.opts = opts;\n }\n\n /** The read token used for frame fetches and signaling resume in the selected region. */\n get frameReadToken(): string | null { return this.readToken; }\n\n /**\n * Starts the publisher: races all gateways to find the fastest, completes\n * the two-phase handshake, creates the peer connection, and sends the SDP\n * offer. Resolves when the offer has been sent (not when ICE completes —\n * use onConnected for that).\n */\n async start(stream: MediaStream): Promise<void> {\n this.stopped = false;\n this.localStream = stream;\n\n // Race all gateways; returns winning WebSocket + TURN/read-token info\n const { ws, readyInfo, gatewayURL } = await this.raceGateways();\n this.selectedGatewayURL = gatewayURL;\n\n // Store read token for caller\n if (readyInfo.read_token) {\n this.readToken = readyInfo.read_token;\n }\n\n // Build ICE servers: extra servers from opts + TURN from gateway. The\n // gateway supplies multi-transport turn_urls (UDP + TCP) so relay can fall\n // back to TCP on UDP-blocking networks. A single credential is valid for\n // every transport.\n const iceServers: RTCIceServer[] = [...(this.opts.iceServers ?? [])];\n if (readyInfo.turn_urls && readyInfo.turn_urls.length > 0) {\n iceServers.push({\n urls: readyInfo.turn_urls,\n username: readyInfo.turn_username,\n credential: readyInfo.turn_credential,\n });\n }\n\n this.pc = new RTCPeerConnection({ iceServers });\n\n this.pc.onicecandidate = (ev) => {\n if (!ev.candidate || !this.sig) return;\n const c = ev.candidate;\n this.sig.send({\n type: \"ice_candidate\",\n candidate: c.candidate,\n sdp_mid: c.sdpMid ?? undefined,\n sdp_mline_index: c.sdpMLineIndex ?? undefined,\n username_fragment: c.usernameFragment ?? undefined,\n });\n };\n\n this.pc.onconnectionstatechange = () => {\n const state = this.pc?.connectionState;\n if (state) this.opts.callbacks?.onConnectionStateChange?.(state);\n if (state === \"connected\") this.opts.callbacks?.onConnected?.();\n };\n\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n // Wrap winning WebSocket in SignalingChannel\n const signaling = this.installSignaling(ws);\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing after gather\");\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n /** Replaces the currently published stream with a new one. */\n async replaceStream(stream: MediaStream): Promise<void> {\n if (!this.pc) throw new Error(\"publisher not started\");\n\n // Remove old tracks.\n const senders = this.pc.getSenders();\n for (const sender of senders) {\n if (sender.track) {\n this.pc.removeTrack(sender);\n }\n }\n\n // Add new tracks.\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n this.localStream = stream;\n\n // Renegotiate.\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing\");\n this.sig?.send({\n type: \"offer\",\n sdp: local.sdp,\n sdp_type: \"offer\",\n });\n }\n\n /** Stops publishing and tears down the peer connection. */\n stop(): void {\n this.stopped = true;\n this.reconnectGeneration++;\n this.reconnecting = false;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n\n this.localStream?.getTracks().forEach((t) => t.stop());\n this.localStream = null;\n\n this.pc?.close();\n this.pc = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n }\n\n /** Returns the current RTCPeerConnection, or null if not started. */\n get peerConnection(): RTCPeerConnection | null {\n return this.pc;\n }\n\n /** Returns true if the peer connection is in the \"connected\" state. */\n get isConnected(): boolean {\n return this.pc?.connectionState === \"connected\";\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n private raceGateways(): Promise<{ ws: WebSocket; readyInfo: GatewayReadyInfo; gatewayURL: string }> {\n return new Promise((resolve, reject) => {\n const { gatewayURLs, token } = this.opts;\n if (gatewayURLs.length === 0) {\n reject(new Error(\"no gateway URLs provided\"));\n return;\n }\n\n const sockets: WebSocket[] = [];\n let settled = false;\n\n const closeAll = (except?: WebSocket) => {\n for (const s of sockets) {\n if (s !== except) {\n s.onmessage = null;\n s.onerror = null;\n s.onclose = null;\n s.close();\n }\n }\n };\n\n const checkAllFailed = () => {\n if (settled) return;\n if (sockets.every(s => s.readyState === WebSocket.CLOSED || s.readyState === WebSocket.CLOSING)) {\n settled = true;\n reject(new Error(\"all gateways failed to connect\"));\n }\n };\n\n for (const gatewayURL of gatewayURLs) {\n const u = new URL(gatewayURL);\n u.searchParams.set(\"token\", token);\n const ws = new WebSocket(u.toString());\n sockets.push(ws);\n\n let accepted = false;\n\n ws.onmessage = (ev: MessageEvent) => {\n if (settled) return;\n try {\n const msg = JSON.parse(ev.data as string);\n if (!accepted && msg.type === \"accepted\") {\n accepted = true;\n ws.send(JSON.stringify({ type: \"proceed\" }));\n } else if (accepted && msg.type === \"ready\") {\n settled = true;\n closeAll(ws);\n resolve({ ws, readyInfo: msg as GatewayReadyInfo, gatewayURL });\n }\n } catch {\n /* ignore malformed */\n }\n };\n\n ws.onerror = () => checkAllFailed();\n ws.onclose = () => checkAllFailed();\n }\n });\n }\n\n private installSignaling(ws: WebSocket): SignalingChannel {\n const channel = SignalingChannel.wrap(ws);\n this.sig = channel;\n channel.onMessage = (msg) => this.handleSignal(msg);\n channel.onClose = () => {\n if (this.sig !== channel || this.stopped) return;\n this.sig = null;\n void this.resumeSignaling();\n };\n // Browsers normally follow an error event with close. Recovery begins from\n // close so a single transport failure cannot start two retry loops.\n channel.onError = () => {};\n return channel;\n }\n\n private async resumeSignaling(): Promise<void> {\n if (this.reconnecting || this.stopped) return;\n if (!this.selectedGatewayURL || !this.readToken) {\n this.terminateWithError(new Error(\"signaling closed and cannot be resumed\"));\n return;\n }\n\n this.reconnecting = true;\n const generation = ++this.reconnectGeneration;\n const timeout = this.opts.signalingReconnectTimeoutMs ?? defaultSignalingReconnectTimeoutMs;\n const deadline = Date.now() + Math.max(0, timeout);\n let backoffMs = 0;\n\n while (!this.stopped && generation === this.reconnectGeneration && Date.now() <= deadline) {\n if (backoffMs > 0) {\n const waitMs = Math.min(backoffMs, Math.max(0, deadline - Date.now()));\n if (waitMs === 0) break;\n await this.wait(waitMs);\n if (this.stopped || generation !== this.reconnectGeneration) return;\n }\n\n const remaining = deadline - Date.now();\n if (remaining < 0) break;\n try {\n const ws = await this.openResumeSocket(Math.min(signalingResumeAttemptTimeoutMs, Math.max(1, remaining)));\n if (this.stopped || generation !== this.reconnectGeneration) {\n ws.close();\n return;\n }\n this.resumeSocket = null;\n this.reconnecting = false;\n this.installSignaling(ws);\n return;\n } catch {\n backoffMs = backoffMs === 0 ? 250 : Math.min(backoffMs * 2, signalingResumeMaxBackoffMs);\n }\n }\n\n if (!this.stopped && generation === this.reconnectGeneration) {\n this.reconnecting = false;\n this.terminateWithError(new Error(\"unable to resume signaling with the selected gateway\"));\n }\n }\n\n private openResumeSocket(timeoutMs: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const u = new URL(this.selectedGatewayURL!);\n u.searchParams.set(\"token\", this.readToken!);\n const ws = new WebSocket(u.toString());\n this.resumeSocket = ws;\n let settled = false;\n const timer = setTimeout(() => fail(), timeoutMs);\n\n const fail = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n if (this.resumeSocket === ws) this.resumeSocket = null;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n ws.close();\n reject(new Error(\"signaling resume attempt failed\"));\n };\n\n ws.onmessage = (ev: MessageEvent) => {\n try {\n const msg = JSON.parse(ev.data as string);\n if (msg.type !== \"resumed\" || settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(ws);\n } catch {\n // Ignore malformed messages while waiting for the resume acknowledgement.\n }\n };\n ws.onerror = fail;\n ws.onclose = fail;\n });\n }\n\n private wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private terminateWithError(err: Error): void {\n this.stopped = true;\n this.reconnectGeneration++;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n this.pc?.close();\n this.pc = null;\n this.localStream?.getTracks().forEach((track) => track.stop());\n this.localStream = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n this.opts.callbacks?.onError?.(err);\n }\n\n private handleSignal(msg: SignalMessage): void {\n switch (msg.type) {\n case \"answer\": {\n if (!this.pc) return;\n this.pc\n .setRemoteDescription(\n new RTCSessionDescription({ type: \"answer\", sdp: msg.sdp }),\n )\n .then(() => {\n this.hasAnswer = true;\n // Flush any ICE candidates that arrived before the answer.\n for (const init of this.pendingRemoteCandidates) {\n this.pc?.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n }\n this.pendingRemoteCandidates = [];\n })\n .catch((err) => {\n this.opts.callbacks?.onError?.(\n new Error(`failed to set remote description: ${err}`),\n );\n });\n break;\n }\n\n case \"ice_candidate\": {\n if (!this.pc) return;\n const init: RTCIceCandidateInit = {\n candidate: msg.candidate,\n sdpMid: msg.sdp_mid ?? null,\n sdpMLineIndex: msg.sdp_mline_index ?? null,\n usernameFragment: msg.username_fragment ?? null,\n };\n if (this.hasAnswer) {\n this.pc.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n } else {\n this.pendingRemoteCandidates.push(init);\n }\n break;\n }\n\n case \"connection_state\": {\n // The server echoes the peer connection state; the onconnectionstatechange\n // handler above already covers this, but callers can also react via\n // onConnectionStateChange.\n break;\n }\n\n case \"error\": {\n this.opts.callbacks?.onError?.(new Error(msg.error));\n break;\n }\n\n case \"resumed\":\n break;\n }\n }\n\n /** Waits for ICE gathering to reach the \"complete\" state. */\n private gatherComplete(): Promise<void> {\n return new Promise((resolve) => {\n const pc = this.pc;\n if (!pc) {\n resolve();\n return;\n }\n if (pc.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n const handler = () => {\n if (pc.iceGatheringState === \"complete\") {\n pc.removeEventListener(\"icegatheringstatechange\", handler);\n resolve();\n }\n };\n pc.addEventListener(\"icegatheringstatechange\", handler);\n });\n }\n}\n","/**\n * Options for {@link captureCamera}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely (e.g. passing `video` overrides\n * the default video constraints rather than merging into them). Omit a field to\n * keep its default.\n */\nexport interface CaptureCameraOptions {\n /**\n * Video constraints, or `true`/`false`. Defaults to a modest resolution and\n * frame rate (see {@link captureCamera}). Set `false` to disable video.\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — Argus is a\n * video-frame streaming system, so audio is off unless you ask for it.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the browser's permission\n * prompt and transient-activation check are anchored to that window rather\n * than the one holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Options for {@link captureScreen}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely. Omit a field to keep its\n * default.\n */\nexport interface CaptureScreenOptions {\n /**\n * Video constraints, or `true`. Defaults to a capped width and a low frame\n * rate (see {@link captureScreen}).\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — screen shares\n * rarely need audio for a video-frame streaming system.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the screen picker and its\n * transient-activation check are anchored to that window rather than the one\n * holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Captures the user's camera via `navigator.mediaDevices.getUserMedia`,\n * applying sensible defaults for a video-frame streaming system.\n *\n * Defaults:\n * - `video`: `{ width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }`\n * — a modest resolution that keeps upload bandwidth reasonable. Cameras are\n * rarely the 4k bandwidth problem that screen capture is, so this is an\n * `ideal` (a hint) rather than a hard cap.\n * - `audio`: `false` — this is a video-frame streaming system.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureCamera();\n * await publisher.start(stream);\n * ```\n *\n * @example Front camera with audio:\n * ```ts\n * const stream = await captureCamera({\n * video: { facingMode: \"user\" },\n * audio: true,\n * });\n * ```\n */\nexport async function captureCamera(\n opts: CaptureCameraOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n frameRate: { ideal: 30 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getUserMedia(constraints);\n}\n\n/**\n * Captures a screen / window / tab via\n * `navigator.mediaDevices.getDisplayMedia`, applying sensible defaults tuned to\n * avoid the HiDPI/Retina bandwidth trap.\n *\n * Defaults:\n * - `video`: `{ width: { max: 1920 }, frameRate: { ideal: 5, max: 10 } }`.\n * The `width` is a **`max`, not an `ideal`**: on a 2x-Retina display the\n * browser would otherwise capture at native resolution (often 3456px+ /\n * effectively 4k), wasting upload bandwidth and downstream decode cost for no\n * visible benefit. Capping the max roughly halves a 2x-Retina share while\n * leaving smaller displays untouched. Screen content is mostly static, so the\n * low frame rate saves further bandwidth.\n * - `audio`: `false`.\n *\n * IMPORTANT — do NOT add `resizeMode: \"none\"` here. That value forbids the\n * browser from downscaling the source, which turns the `width: { max: 1920 }`\n * cap into a no-op on exactly the Retina displays it targets. By omitting\n * `resizeMode` we let the user agent scale to satisfy the constraint (its\n * default behaviour), which is the entire point of this helper. It is tempting\n * to add `resizeMode: \"none\"` back for \"sharpness\" — don't.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureScreen();\n * await publisher.start(stream);\n * ```\n */\nexport async function captureScreen(\n opts: CaptureScreenOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { max: 1920 },\n frameRate: { ideal: 5, max: 10 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getDisplayMedia(constraints);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,mBAAN,MAAM,kBAAiB;AAAA,EACpB;AAAA;AAAA,EAGR,YAAmD;AAAA;AAAA,EAEnD,UAA+B;AAAA;AAAA,EAE/B,UAAyC;AAAA,EAEjC,YAAY,IAAe;AACjC,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,KAAK,IAAiC;AAC3C,UAAM,KAAK,IAAI,kBAAiB,EAAE;AAClC,OAAG,YAAY,CAAC,OAAqB;AACnC,YAAM,MAAM,YAAY,GAAG,IAAI;AAC/B,UAAI,IAAK,IAAG,YAAY,GAAG;AAAA,IAC7B;AACA,OAAG,UAAU,MAAM,GAAG,UA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AAA,MACF;AAAA,MAEA,KAAK;AACH;AAAA,IACJ;AAAA,EACF;AAAA;AAAA,EAGQ,iBAAgC;AACtC,WAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,YAAM,KAAK,KAAK;AAChB,UAAI,CAAC,IAAI;AACP,gBAAQ;AACR;AAAA,MACF;AACA,UAAI,GAAG,sBAAsB,YAAY;AACvC,gBAAQ;AACR;AAAA,MACF;AACA,YAAM,UAAU,MAAM;AACpB,YAAI,GAAG,sBAAsB,YAAY;AACvC,aAAG,oBAAoB,2BAA2B,OAAO;AACzD,kBAAQ;AAAA,QACV;AAAA,MACF;AACA,SAAG,iBAAiB,2BAA2B,OAAO;AAAA,IACxD,CAAC;AAAA,EACH;AACF;;;ACzWA,eAAsB,cACpB,OAA6B,CAAC,GACR;AACtB,QAAM,cAAsC;AAAA,IAC1C,OAAO,KAAK,SAAS;AAAA,MACnB,OAAO,EAAE,OAAO,KAAK;AAAA,MACrB,QAAQ,EAAE,OAAO,IAAI;AAAA,MACrB,WAAW,EAAE,OAAO,GAAG;AAAA,IACzB;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,aAAa,WAAW;AAC9C;AAiCA,eAAsB,cACpB,OAA6B,CAAC,GACR;AACtB,QAAM,cAAsC;AAAA,IAC1C,OAAO,KAAK,SAAS;AAAA,MACnB,OAAO,EAAE,KAAK,KAAK;AAAA,MACnB,WAAW,EAAE,OAAO,GAAG,KAAK,GAAG;AAAA,IACjC;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,gBAAgB,WAAW;AACjD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/signaling.ts","../src/publisher.ts","../src/capture.ts"],"sourcesContent":["export { Publisher } from \"./publisher\";\nexport type {\n SignalMessage,\n PublisherCallbacks,\n PublisherOptions,\n GatewayReadyInfo,\n PublisherRecoveryEvent,\n PublisherRecoveryState,\n PublisherRecoveryAction,\n PublisherRecoveryFailureReason,\n} from \"./types\";\nexport { captureCamera, captureScreen } from \"./capture\";\nexport type {\n CaptureCameraOptions,\n CaptureScreenOptions,\n} from \"./capture\";\n","import type { SignalMessage } from \"./types\";\n\n/**\n * Wraps an open WebSocket to the Argus gateway and handles the JSON message\n * envelope: incoming text frames are parsed into {@link SignalMessage}s and\n * outgoing messages are serialised.\n *\n * This is an internal helper. The {@link Publisher} opens the socket itself\n * (racing all candidate gateways) and hands the winner here, so this class only\n * ever adopts an already-open socket rather than dialing one.\n *\n * @internal\n */\nexport class SignalingChannel {\n private ws: WebSocket;\n\n /** Fired for every incoming JSON message. */\n onMessage: ((msg: SignalMessage) => void) | null = null;\n /** Fired when the underlying WebSocket closes. */\n onClose: (() => void) | null = null;\n /** Fired when an error occurs on the WebSocket. */\n onError: ((err: Error) => void) | null = null;\n\n private constructor(ws: WebSocket) {\n this.ws = ws;\n }\n\n /**\n * Adopts an already-open WebSocket (e.g. the winner of a gateway race),\n * routing its events through the channel's callbacks. Any handlers previously\n * attached to the socket are replaced.\n */\n static wrap(ws: WebSocket): SignalingChannel {\n const ch = new SignalingChannel(ws);\n ws.onmessage = (ev: MessageEvent) => {\n const msg = parseSignal(ev.data);\n if (msg) ch.onMessage?.(msg);\n };\n ws.onerror = () => ch.onError?.(new Error(\"WebSocket error\"));\n ws.onclose = () => ch.onClose?.();\n return ch;\n }\n\n /** Sends a JSON message if the socket is open; a no-op otherwise. */\n send(msg: SignalMessage): void {\n if (this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /** Closes the underlying WebSocket. */\n close(): void {\n this.ws.close();\n }\n}\n\n/** Parses a WebSocket text frame into a SignalMessage, or null if malformed. */\nfunction parseSignal(data: unknown): SignalMessage | null {\n try {\n return JSON.parse(data as string) as SignalMessage;\n } catch {\n return null;\n }\n}\n","import { SignalingChannel } from \"./signaling\";\nimport type {\n GatewayReadyInfo,\n PublisherOptions,\n PublisherRecoveryAction,\n PublisherRecoveryEvent,\n SignalMessage,\n} from \"./types\";\n\nconst defaultSignalingReconnectTimeoutMs = 20_000;\nconst signalingResumeAttemptTimeoutMs = 3_000;\nconst signalingResumeMaxBackoffMs = 3_000;\nconst senderRestartPauseMs = 100;\nconst senderRecoveryWaitMs = 4_000;\nconst iceRecoveryWaitMs = 8_000;\n\n/**\n * Publisher streams a browser {@link MediaStream} to an Argus media server over\n * WebRTC. Given the `gateway_urls` and `token` from a join-token response, it\n * races the candidate gateways to the fastest one, completes the two-phase\n * signaling handshake, and manages the peer connection — offer/answer exchange,\n * ICE candidate trickling, and track (re)negotiation.\n *\n * After {@link Publisher.start} resolves, {@link Publisher.frameReadToken} holds\n * the token your application server needs to fetch frames for this stream.\n *\n * @example Publish the default camera:\n * ```ts\n * const pub = new Publisher({\n * gatewayURLs: joinResp.gateway_urls,\n * token: joinResp.token,\n * callbacks: { onConnected: () => console.log(\"live!\") },\n * });\n *\n * const stream = await navigator.mediaDevices.getUserMedia({ video: true });\n * await pub.start(stream);\n * ```\n */\nexport class Publisher {\n private opts: PublisherOptions;\n private sig: SignalingChannel | null = null;\n private pc: RTCPeerConnection | null = null;\n private hasAnswer = false;\n private pendingRemoteCandidates: RTCIceCandidateInit[] = [];\n private localStream: MediaStream | null = null;\n private readToken: string | null = null;\n private selectedGatewayURL: string | null = null;\n private stopped = true;\n private reconnecting = false;\n private reconnectGeneration = 0;\n private resumeSocket: WebSocket | null = null;\n private recoveryGeneration = 0;\n private recoveringMedia = false;\n private recoveryRequired = false;\n private recoveryAction: PublisherRecoveryAction | null = null;\n private trackEndHandlers = new Map<MediaStreamTrack, EventListener>();\n\n constructor(opts: PublisherOptions) {\n this.opts = opts;\n }\n\n /** The read token used for frame fetches and signaling resume in the selected region. */\n get frameReadToken(): string | null { return this.readToken; }\n\n /**\n * Starts the publisher: races all gateways to find the fastest, completes\n * the two-phase handshake, creates the peer connection, and sends the SDP\n * offer. Resolves when the offer has been sent (not when ICE completes —\n * use onConnected for that).\n */\n async start(stream: MediaStream): Promise<void> {\n this.stopped = false;\n this.recoveryRequired = false;\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n // Race all gateways; returns winning WebSocket + TURN/read-token info\n const { ws, readyInfo, gatewayURL } = await this.raceGateways();\n this.selectedGatewayURL = gatewayURL;\n\n // Store read token for caller\n if (readyInfo.read_token) {\n this.readToken = readyInfo.read_token;\n }\n\n // Build ICE servers: extra servers from opts + TURN from gateway. The\n // gateway supplies multi-transport turn_urls (UDP + TCP) so relay can fall\n // back to TCP on UDP-blocking networks. A single credential is valid for\n // every transport.\n const iceServers: RTCIceServer[] = [...(this.opts.iceServers ?? [])];\n if (readyInfo.turn_urls && readyInfo.turn_urls.length > 0) {\n iceServers.push({\n urls: readyInfo.turn_urls,\n username: readyInfo.turn_username,\n credential: readyInfo.turn_credential,\n });\n }\n\n this.pc = new RTCPeerConnection({ iceServers });\n\n this.pc.onicecandidate = (ev) => {\n if (!ev.candidate || !this.sig) return;\n const c = ev.candidate;\n this.sig.send({\n type: \"ice_candidate\",\n candidate: c.candidate,\n sdp_mid: c.sdpMid ?? undefined,\n sdp_mline_index: c.sdpMLineIndex ?? undefined,\n username_fragment: c.usernameFragment ?? undefined,\n });\n };\n\n this.pc.onconnectionstatechange = () => {\n const state = this.pc?.connectionState;\n if (state) this.opts.callbacks?.onConnectionStateChange?.(state);\n if (state === \"connected\") this.opts.callbacks?.onConnected?.();\n };\n\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n // Wrap winning WebSocket in SignalingChannel\n const signaling = this.installSignaling(ws);\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing after gather\");\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n /** Replaces the currently published stream with a new one. */\n async replaceStream(stream: MediaStream): Promise<void> {\n if (!this.pc) throw new Error(\"publisher not started\");\n\n this.cancelMediaRecovery();\n this.recoveryRequired = false;\n this.unwatchStreamTracks();\n\n // Remove old tracks.\n const senders = this.pc.getSenders();\n for (const sender of senders) {\n if (sender.track) {\n this.pc.removeTrack(sender);\n }\n }\n\n // Add new tracks.\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n await this.renegotiate(false);\n }\n\n /** Stops publishing and tears down the peer connection. */\n stop(): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.reconnecting = false;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((t) => t.stop());\n this.localStream = null;\n\n this.pc?.close();\n this.pc = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n }\n\n /** Returns the current RTCPeerConnection, or null if not started. */\n get peerConnection(): RTCPeerConnection | null {\n return this.pc;\n }\n\n /** Returns true if the peer connection is in the \"connected\" state. */\n get isConnected(): boolean {\n return this.pc?.connectionState === \"connected\";\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n private raceGateways(): Promise<{ ws: WebSocket; readyInfo: GatewayReadyInfo; gatewayURL: string }> {\n return new Promise((resolve, reject) => {\n const { gatewayURLs, token } = this.opts;\n if (gatewayURLs.length === 0) {\n reject(new Error(\"no gateway URLs provided\"));\n return;\n }\n\n const sockets: WebSocket[] = [];\n let settled = false;\n\n const closeAll = (except?: WebSocket) => {\n for (const s of sockets) {\n if (s !== except) {\n s.onmessage = null;\n s.onerror = null;\n s.onclose = null;\n s.close();\n }\n }\n };\n\n const checkAllFailed = () => {\n if (settled) return;\n if (sockets.every(s => s.readyState === WebSocket.CLOSED || s.readyState === WebSocket.CLOSING)) {\n settled = true;\n reject(new Error(\"all gateways failed to connect\"));\n }\n };\n\n for (const gatewayURL of gatewayURLs) {\n const u = new URL(gatewayURL);\n u.searchParams.set(\"token\", token);\n const ws = new WebSocket(u.toString());\n sockets.push(ws);\n\n let accepted = false;\n\n ws.onmessage = (ev: MessageEvent) => {\n if (settled) return;\n try {\n const msg = JSON.parse(ev.data as string);\n if (!accepted && msg.type === \"accepted\") {\n accepted = true;\n ws.send(JSON.stringify({ type: \"proceed\" }));\n } else if (accepted && msg.type === \"ready\") {\n settled = true;\n closeAll(ws);\n resolve({ ws, readyInfo: msg as GatewayReadyInfo, gatewayURL });\n }\n } catch {\n /* ignore malformed */\n }\n };\n\n ws.onerror = () => checkAllFailed();\n ws.onclose = () => checkAllFailed();\n }\n });\n }\n\n private installSignaling(ws: WebSocket): SignalingChannel {\n const channel = SignalingChannel.wrap(ws);\n this.sig = channel;\n channel.onMessage = (msg) => this.handleSignal(msg);\n channel.onClose = () => {\n if (this.sig !== channel || this.stopped) return;\n this.sig = null;\n void this.resumeSignaling();\n };\n // Browsers normally follow an error event with close. Recovery begins from\n // close so a single transport failure cannot start two retry loops.\n channel.onError = () => {};\n return channel;\n }\n\n private async resumeSignaling(): Promise<void> {\n if (this.reconnecting || this.stopped) return;\n if (!this.selectedGatewayURL || !this.readToken) {\n this.terminateWithError(new Error(\"signaling closed and cannot be resumed\"));\n return;\n }\n\n this.reconnecting = true;\n const generation = ++this.reconnectGeneration;\n const timeout = this.opts.signalingReconnectTimeoutMs ?? defaultSignalingReconnectTimeoutMs;\n const deadline = Date.now() + Math.max(0, timeout);\n let backoffMs = 0;\n\n while (!this.stopped && generation === this.reconnectGeneration && Date.now() <= deadline) {\n if (backoffMs > 0) {\n const waitMs = Math.min(backoffMs, Math.max(0, deadline - Date.now()));\n if (waitMs === 0) break;\n await this.wait(waitMs);\n if (this.stopped || generation !== this.reconnectGeneration) return;\n }\n\n const remaining = deadline - Date.now();\n if (remaining < 0) break;\n try {\n const ws = await this.openResumeSocket(Math.min(signalingResumeAttemptTimeoutMs, Math.max(1, remaining)));\n if (this.stopped || generation !== this.reconnectGeneration) {\n ws.close();\n return;\n }\n this.resumeSocket = null;\n this.reconnecting = false;\n this.installSignaling(ws);\n return;\n } catch {\n backoffMs = backoffMs === 0 ? 250 : Math.min(backoffMs * 2, signalingResumeMaxBackoffMs);\n }\n }\n\n if (!this.stopped && generation === this.reconnectGeneration) {\n this.reconnecting = false;\n this.terminateWithError(new Error(\"unable to resume signaling with the selected gateway\"));\n }\n }\n\n private openResumeSocket(timeoutMs: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const u = new URL(this.selectedGatewayURL!);\n u.searchParams.set(\"token\", this.readToken!);\n const ws = new WebSocket(u.toString());\n this.resumeSocket = ws;\n let settled = false;\n const timer = setTimeout(() => fail(), timeoutMs);\n\n const fail = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n if (this.resumeSocket === ws) this.resumeSocket = null;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n ws.close();\n reject(new Error(\"signaling resume attempt failed\"));\n };\n\n ws.onmessage = (ev: MessageEvent) => {\n try {\n const msg = JSON.parse(ev.data as string);\n if (msg.type !== \"resumed\" || settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(ws);\n } catch {\n // Ignore malformed messages while waiting for the resume acknowledgement.\n }\n };\n ws.onerror = fail;\n ws.onclose = fail;\n });\n }\n\n private wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private terminateWithError(err: Error): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n this.pc?.close();\n this.pc = null;\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((track) => track.stop());\n this.localStream = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n this.opts.callbacks?.onError?.(err);\n }\n\n private handleSignal(msg: SignalMessage): void {\n switch (msg.type) {\n case \"answer\": {\n if (!this.pc) return;\n this.pc\n .setRemoteDescription(\n new RTCSessionDescription({ type: \"answer\", sdp: msg.sdp }),\n )\n .then(() => {\n this.hasAnswer = true;\n // Flush any ICE candidates that arrived before the answer.\n for (const init of this.pendingRemoteCandidates) {\n this.pc?.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n }\n this.pendingRemoteCandidates = [];\n })\n .catch((err) => {\n this.opts.callbacks?.onError?.(\n new Error(`failed to set remote description: ${err}`),\n );\n });\n break;\n }\n\n case \"ice_candidate\": {\n if (!this.pc) return;\n const init: RTCIceCandidateInit = {\n candidate: msg.candidate,\n sdpMid: msg.sdp_mid ?? null,\n sdpMLineIndex: msg.sdp_mline_index ?? null,\n usernameFragment: msg.username_fragment ?? null,\n };\n if (this.hasAnswer) {\n this.pc.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n } else {\n this.pendingRemoteCandidates.push(init);\n }\n break;\n }\n\n case \"connection_state\": {\n // The server echoes the peer connection state; the onconnectionstatechange\n // handler above already covers this, but callers can also react via\n // onConnectionStateChange.\n break;\n }\n\n case \"media_stall\":\n case \"media_track_ended\": {\n void this.beginMediaRecovery(msg.track);\n break;\n }\n\n case \"media_resumed\": {\n this.completeMediaRecovery(msg.track);\n break;\n }\n\n case \"error\": {\n this.opts.callbacks?.onError?.(new Error(msg.error));\n break;\n }\n\n case \"resumed\":\n break;\n }\n }\n\n private async beginMediaRecovery(trackType: string): Promise<void> {\n if (this.stopped || this.recoveringMedia || this.recoveryRequired) return;\n\n const tracks = this.localStream?.getVideoTracks() ?? [];\n const liveTracks = tracks.filter((track) => track.readyState !== \"ended\");\n if (liveTracks.length === 0) {\n this.failMediaRecovery(trackType, \"capture_ended\");\n return;\n }\n\n this.recoveringMedia = true;\n const generation = ++this.recoveryGeneration;\n this.recoveryAction = \"sender_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"sender_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_started\", trackType, \"sender_restart\");\n\n await this.restartSenders(liveTracks, generation);\n if (!this.isCurrentRecovery(generation)) return;\n\n await this.wait(senderRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n\n this.recoveryAction = \"ice_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"ice_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_retry\", trackType, \"ice_restart\");\n try {\n await this.renegotiate(true);\n } catch {\n // The fixed recovery window below still gives signaling-resume a chance.\n // If media does not recover, the host receives onRecoveryRequired.\n }\n\n await this.wait(iceRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n this.failMediaRecovery(trackType, \"automatic_recovery_failed\");\n }\n\n private async restartSenders(tracks: MediaStreamTrack[], generation: number): Promise<void> {\n const live = new Set(tracks);\n const senders = this.pc?.getSenders().filter(\n (sender) => sender.track && live.has(sender.track),\n ) ?? [];\n if (senders.length === 0) return;\n\n const originals = senders.map((sender) => ({ sender, track: sender.track! }));\n try {\n await Promise.all(originals.map(({ sender }) => sender.replaceTrack(null)));\n await this.wait(senderRestartPauseMs);\n if (!this.isCurrentRecovery(generation)) return;\n await Promise.all(originals.map(({ sender, track }) => sender.replaceTrack(track)));\n await this.renegotiate(false);\n } catch {\n // ICE restart is the second stage and may still recover a sender reset or\n // renegotiation failure, so do not fail the stream at this stage.\n }\n }\n\n private async renegotiate(iceRestart: boolean): Promise<void> {\n const pc = this.pc;\n const signaling = this.sig;\n if (!pc || !signaling) throw new Error(\"publisher signaling is unavailable\");\n\n if (iceRestart) pc.restartIce?.();\n const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : undefined);\n await pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n const local = pc.localDescription;\n if (!local) throw new Error(\"local description missing\");\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n private completeMediaRecovery(trackType: string): void {\n if (!this.recoveringMedia) return;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n this.emitRecoveryTransition({ state: \"recovered\", track: trackType, action });\n }\n\n private failMediaRecovery(\n trackType: string,\n reason: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n if (this.stopped || this.recoveryRequired) return;\n this.recoveryRequired = true;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n const event: PublisherRecoveryEvent = { state: \"failed\", track: trackType, action, reason };\n this.emitRecoveryTransition(event);\n this.opts.callbacks?.onRecoveryRequired?.(event);\n this.sendRecoveryDiagnostic(\"recovery_failed\", trackType, action, reason);\n }\n\n private cancelMediaRecovery(): void {\n this.recoveryGeneration++;\n this.recoveringMedia = false;\n this.recoveryAction = null;\n }\n\n private isCurrentRecovery(generation: number): boolean {\n return !this.stopped && this.recoveringMedia && generation === this.recoveryGeneration;\n }\n\n private emitRecoveryTransition(event: PublisherRecoveryEvent): void {\n this.opts.callbacks?.onRecoveryStateChange?.(event);\n }\n\n private sendRecoveryDiagnostic(\n event: \"recovery_started\" | \"recovery_retry\" | \"recovery_failed\",\n track: string,\n action?: PublisherRecoveryAction,\n reason?: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n this.sig?.send({ type: \"recovery_event\", event, track, action, reason });\n }\n\n private watchStreamTracks(stream: MediaStream): void {\n for (const track of stream.getVideoTracks()) {\n const handler: EventListener = () => this.failMediaRecovery(\"screen\", \"capture_ended\");\n track.addEventListener(\"ended\", handler);\n this.trackEndHandlers.set(track, handler);\n }\n }\n\n private unwatchStreamTracks(): void {\n for (const [track, handler] of this.trackEndHandlers) {\n track.removeEventListener(\"ended\", handler);\n }\n this.trackEndHandlers.clear();\n }\n\n /** Waits for ICE gathering to reach the \"complete\" state. */\n private gatherComplete(): Promise<void> {\n return new Promise((resolve) => {\n const pc = this.pc;\n if (!pc) {\n resolve();\n return;\n }\n if (pc.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n const handler = () => {\n if (pc.iceGatheringState === \"complete\") {\n pc.removeEventListener(\"icegatheringstatechange\", handler);\n resolve();\n }\n };\n pc.addEventListener(\"icegatheringstatechange\", handler);\n });\n }\n}\n","/**\n * Options for {@link captureCamera}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely (e.g. passing `video` overrides\n * the default video constraints rather than merging into them). Omit a field to\n * keep its default.\n */\nexport interface CaptureCameraOptions {\n /**\n * Video constraints, or `true`/`false`. Defaults to a modest resolution and\n * frame rate (see {@link captureCamera}). Set `false` to disable video.\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — Argus is a\n * video-frame streaming system, so audio is off unless you ask for it.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the browser's permission\n * prompt and transient-activation check are anchored to that window rather\n * than the one holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Options for {@link captureScreen}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely. Omit a field to keep its\n * default.\n */\nexport interface CaptureScreenOptions {\n /**\n * Video constraints, or `true`. Defaults to a capped width and a low frame\n * rate (see {@link captureScreen}).\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — screen shares\n * rarely need audio for a video-frame streaming system.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the screen picker and its\n * transient-activation check are anchored to that window rather than the one\n * holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Captures the user's camera via `navigator.mediaDevices.getUserMedia`,\n * applying sensible defaults for a video-frame streaming system.\n *\n * Defaults:\n * - `video`: `{ width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }`\n * — a modest resolution that keeps upload bandwidth reasonable. Cameras are\n * rarely the 4k bandwidth problem that screen capture is, so this is an\n * `ideal` (a hint) rather than a hard cap.\n * - `audio`: `false` — this is a video-frame streaming system.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureCamera();\n * await publisher.start(stream);\n * ```\n *\n * @example Front camera with audio:\n * ```ts\n * const stream = await captureCamera({\n * video: { facingMode: \"user\" },\n * audio: true,\n * });\n * ```\n */\nexport async function captureCamera(\n opts: CaptureCameraOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n frameRate: { ideal: 30 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getUserMedia(constraints);\n}\n\n/**\n * Captures a screen / window / tab via\n * `navigator.mediaDevices.getDisplayMedia`, applying sensible defaults tuned to\n * avoid the HiDPI/Retina bandwidth trap.\n *\n * Defaults:\n * - `video`: `{ width: { max: 1920 }, frameRate: { ideal: 5, max: 10 } }`.\n * The `width` is a **`max`, not an `ideal`**: on a 2x-Retina display the\n * browser would otherwise capture at native resolution (often 3456px+ /\n * effectively 4k), wasting upload bandwidth and downstream decode cost for no\n * visible benefit. Capping the max roughly halves a 2x-Retina share while\n * leaving smaller displays untouched. Screen content is mostly static, so the\n * low frame rate saves further bandwidth.\n * - `audio`: `false`.\n *\n * IMPORTANT — do NOT add `resizeMode: \"none\"` here. That value forbids the\n * browser from downscaling the source, which turns the `width: { max: 1920 }`\n * cap into a no-op on exactly the Retina displays it targets. By omitting\n * `resizeMode` we let the user agent scale to satisfy the constraint (its\n * default behaviour), which is the entire point of this helper. It is tempting\n * to add `resizeMode: \"none\"` back for \"sharpness\" — don't.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureScreen();\n * await publisher.start(stream);\n * ```\n */\nexport async function captureScreen(\n opts: CaptureScreenOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { max: 1920 },\n frameRate: { ideal: 5, max: 10 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getDisplayMedia(constraints);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,mBAAN,MAAM,kBAAiB;AAAA,EACpB;AAAA;AAAA,EAGR,YAAmD;AAAA;AAAA,EAEnD,UAA+B;AAAA;AAAA,EAE/B,UAAyC;AAAA,EAEjC,YAAY,IAAe;AACjC,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,KAAK,IAAiC;AAC3C,UAAM,KAAK,IAAI,kBAAiB,EAAE;AAClC,OAAG,YAAY,CAAC,OAAqB;AACnC,YAAM,MAAM,YAAY,GAAG,IAAI;AAC/B,UAAI,IAAK,IAAG,YAAY,GAAG;AAAA,IAC7B;AACA,OAAG,UAAU,MAAM,GAAG,UAAU,IAAI,MAAM,iBAAiB,CAAC;AAC5D,OAAG,UAAU,MAAM,GAAG,UAAU;AAChC,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,KAAK,KAA0B;AAC7B,QAAI,KAAK,GAAG,eAAe,UAAU,MAAM;AACzC,WAAK,GAAG,KAAK,KAAK,UAAU,GAAG,CAAC;AAAA,IAClC;AAAA,EACF;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,GAAG,MAAM;AAAA,EAChB;AACF;AAGA,SAAS,YAAY,MAAqC;A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YAAI,GAAG,sBAAsB,YAAY;AACvC,aAAG,oBAAoB,2BAA2B,OAAO;AACzD,kBAAQ;AAAA,QACV;AAAA,MACF;AACA,SAAG,iBAAiB,2BAA2B,OAAO;AAAA,IACxD,CAAC;AAAA,EACH;AACF;;;ACvgBA,eAAsB,cACpB,OAA6B,CAAC,GACR;AACtB,QAAM,cAAsC;AAAA,IAC1C,OAAO,KAAK,SAAS;AAAA,MACnB,OAAO,EAAE,OAAO,KAAK;AAAA,MACrB,QAAQ,EAAE,OAAO,IAAI;AAAA,MACrB,WAAW,EAAE,OAAO,GAAG;AAAA,IACzB;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,aAAa,WAAW;AAC9C;AAiCA,eAAsB,cACpB,OAA6B,CAAC,GACR;AACtB,QAAM,cAAsC;AAAA,IAC1C,OAAO,KAAK,SAAS;AAAA,MACnB,OAAO,EAAE,KAAK,KAAK;AAAA,MACnB,WAAW,EAAE,OAAO,GAAG,KAAK,GAAG;AAAA,IACjC;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,gBAAgB,WAAW;AACjD;","names":[]}
|
package/dist/index.d.cts
CHANGED
|
@@ -18,6 +18,24 @@ type SignalMessage = {
|
|
|
18
18
|
} | {
|
|
19
19
|
type: "connection_state";
|
|
20
20
|
state: string;
|
|
21
|
+
} | {
|
|
22
|
+
type: "media_stall";
|
|
23
|
+
track: string;
|
|
24
|
+
frame_age_ms: number;
|
|
25
|
+
} | {
|
|
26
|
+
type: "media_resumed";
|
|
27
|
+
track: string;
|
|
28
|
+
duration_ms: number;
|
|
29
|
+
} | {
|
|
30
|
+
type: "media_track_ended";
|
|
31
|
+
track: string;
|
|
32
|
+
reason?: string;
|
|
33
|
+
} | {
|
|
34
|
+
type: "recovery_event";
|
|
35
|
+
event: "recovery_started" | "recovery_retry" | "recovery_failed";
|
|
36
|
+
track: string;
|
|
37
|
+
action?: "sender_restart" | "ice_restart";
|
|
38
|
+
reason?: "capture_ended" | "automatic_recovery_failed";
|
|
21
39
|
} | {
|
|
22
40
|
type: "error";
|
|
23
41
|
error: string;
|
|
@@ -44,6 +62,20 @@ interface PublisherCallbacks {
|
|
|
44
62
|
onError?: (error: Error) => void;
|
|
45
63
|
/** Called when the browser has successfully connected to the media server. */
|
|
46
64
|
onConnected?: () => void;
|
|
65
|
+
/** Called for each transition in automatic media recovery. */
|
|
66
|
+
onRecoveryStateChange?: (event: PublisherRecoveryEvent) => void;
|
|
67
|
+
/** Called when recovery requires the host application to obtain a new screen share. */
|
|
68
|
+
onRecoveryRequired?: (event: PublisherRecoveryEvent) => void;
|
|
69
|
+
}
|
|
70
|
+
type PublisherRecoveryState = "recovering" | "recovered" | "failed";
|
|
71
|
+
type PublisherRecoveryAction = "sender_restart" | "ice_restart";
|
|
72
|
+
type PublisherRecoveryFailureReason = "capture_ended" | "automatic_recovery_failed";
|
|
73
|
+
/** A transition in the publisher's fixed automatic media-recovery ladder. */
|
|
74
|
+
interface PublisherRecoveryEvent {
|
|
75
|
+
state: PublisherRecoveryState;
|
|
76
|
+
track: string;
|
|
77
|
+
action?: PublisherRecoveryAction;
|
|
78
|
+
reason?: PublisherRecoveryFailureReason;
|
|
47
79
|
}
|
|
48
80
|
/**
|
|
49
81
|
* TURN and read-token info delivered in the gateway `ready` message.
|
|
@@ -107,6 +139,11 @@ declare class Publisher {
|
|
|
107
139
|
private reconnecting;
|
|
108
140
|
private reconnectGeneration;
|
|
109
141
|
private resumeSocket;
|
|
142
|
+
private recoveryGeneration;
|
|
143
|
+
private recoveringMedia;
|
|
144
|
+
private recoveryRequired;
|
|
145
|
+
private recoveryAction;
|
|
146
|
+
private trackEndHandlers;
|
|
110
147
|
constructor(opts: PublisherOptions);
|
|
111
148
|
/** The read token used for frame fetches and signaling resume in the selected region. */
|
|
112
149
|
get frameReadToken(): string | null;
|
|
@@ -132,6 +169,17 @@ declare class Publisher {
|
|
|
132
169
|
private wait;
|
|
133
170
|
private terminateWithError;
|
|
134
171
|
private handleSignal;
|
|
172
|
+
private beginMediaRecovery;
|
|
173
|
+
private restartSenders;
|
|
174
|
+
private renegotiate;
|
|
175
|
+
private completeMediaRecovery;
|
|
176
|
+
private failMediaRecovery;
|
|
177
|
+
private cancelMediaRecovery;
|
|
178
|
+
private isCurrentRecovery;
|
|
179
|
+
private emitRecoveryTransition;
|
|
180
|
+
private sendRecoveryDiagnostic;
|
|
181
|
+
private watchStreamTracks;
|
|
182
|
+
private unwatchStreamTracks;
|
|
135
183
|
/** Waits for ICE gathering to reach the "complete" state. */
|
|
136
184
|
private gatherComplete;
|
|
137
185
|
}
|
|
@@ -253,4 +301,4 @@ declare function captureCamera(opts?: CaptureCameraOptions): Promise<MediaStream
|
|
|
253
301
|
*/
|
|
254
302
|
declare function captureScreen(opts?: CaptureScreenOptions): Promise<MediaStream>;
|
|
255
303
|
|
|
256
|
-
export { type CaptureCameraOptions, type CaptureScreenOptions, type GatewayReadyInfo, Publisher, type PublisherCallbacks, type PublisherOptions, type SignalMessage, captureCamera, captureScreen };
|
|
304
|
+
export { type CaptureCameraOptions, type CaptureScreenOptions, type GatewayReadyInfo, Publisher, type PublisherCallbacks, type PublisherOptions, type PublisherRecoveryAction, type PublisherRecoveryEvent, type PublisherRecoveryFailureReason, type PublisherRecoveryState, type SignalMessage, captureCamera, captureScreen };
|
package/dist/index.d.ts
CHANGED
|
@@ -18,6 +18,24 @@ type SignalMessage = {
|
|
|
18
18
|
} | {
|
|
19
19
|
type: "connection_state";
|
|
20
20
|
state: string;
|
|
21
|
+
} | {
|
|
22
|
+
type: "media_stall";
|
|
23
|
+
track: string;
|
|
24
|
+
frame_age_ms: number;
|
|
25
|
+
} | {
|
|
26
|
+
type: "media_resumed";
|
|
27
|
+
track: string;
|
|
28
|
+
duration_ms: number;
|
|
29
|
+
} | {
|
|
30
|
+
type: "media_track_ended";
|
|
31
|
+
track: string;
|
|
32
|
+
reason?: string;
|
|
33
|
+
} | {
|
|
34
|
+
type: "recovery_event";
|
|
35
|
+
event: "recovery_started" | "recovery_retry" | "recovery_failed";
|
|
36
|
+
track: string;
|
|
37
|
+
action?: "sender_restart" | "ice_restart";
|
|
38
|
+
reason?: "capture_ended" | "automatic_recovery_failed";
|
|
21
39
|
} | {
|
|
22
40
|
type: "error";
|
|
23
41
|
error: string;
|
|
@@ -44,6 +62,20 @@ interface PublisherCallbacks {
|
|
|
44
62
|
onError?: (error: Error) => void;
|
|
45
63
|
/** Called when the browser has successfully connected to the media server. */
|
|
46
64
|
onConnected?: () => void;
|
|
65
|
+
/** Called for each transition in automatic media recovery. */
|
|
66
|
+
onRecoveryStateChange?: (event: PublisherRecoveryEvent) => void;
|
|
67
|
+
/** Called when recovery requires the host application to obtain a new screen share. */
|
|
68
|
+
onRecoveryRequired?: (event: PublisherRecoveryEvent) => void;
|
|
69
|
+
}
|
|
70
|
+
type PublisherRecoveryState = "recovering" | "recovered" | "failed";
|
|
71
|
+
type PublisherRecoveryAction = "sender_restart" | "ice_restart";
|
|
72
|
+
type PublisherRecoveryFailureReason = "capture_ended" | "automatic_recovery_failed";
|
|
73
|
+
/** A transition in the publisher's fixed automatic media-recovery ladder. */
|
|
74
|
+
interface PublisherRecoveryEvent {
|
|
75
|
+
state: PublisherRecoveryState;
|
|
76
|
+
track: string;
|
|
77
|
+
action?: PublisherRecoveryAction;
|
|
78
|
+
reason?: PublisherRecoveryFailureReason;
|
|
47
79
|
}
|
|
48
80
|
/**
|
|
49
81
|
* TURN and read-token info delivered in the gateway `ready` message.
|
|
@@ -107,6 +139,11 @@ declare class Publisher {
|
|
|
107
139
|
private reconnecting;
|
|
108
140
|
private reconnectGeneration;
|
|
109
141
|
private resumeSocket;
|
|
142
|
+
private recoveryGeneration;
|
|
143
|
+
private recoveringMedia;
|
|
144
|
+
private recoveryRequired;
|
|
145
|
+
private recoveryAction;
|
|
146
|
+
private trackEndHandlers;
|
|
110
147
|
constructor(opts: PublisherOptions);
|
|
111
148
|
/** The read token used for frame fetches and signaling resume in the selected region. */
|
|
112
149
|
get frameReadToken(): string | null;
|
|
@@ -132,6 +169,17 @@ declare class Publisher {
|
|
|
132
169
|
private wait;
|
|
133
170
|
private terminateWithError;
|
|
134
171
|
private handleSignal;
|
|
172
|
+
private beginMediaRecovery;
|
|
173
|
+
private restartSenders;
|
|
174
|
+
private renegotiate;
|
|
175
|
+
private completeMediaRecovery;
|
|
176
|
+
private failMediaRecovery;
|
|
177
|
+
private cancelMediaRecovery;
|
|
178
|
+
private isCurrentRecovery;
|
|
179
|
+
private emitRecoveryTransition;
|
|
180
|
+
private sendRecoveryDiagnostic;
|
|
181
|
+
private watchStreamTracks;
|
|
182
|
+
private unwatchStreamTracks;
|
|
135
183
|
/** Waits for ICE gathering to reach the "complete" state. */
|
|
136
184
|
private gatherComplete;
|
|
137
185
|
}
|
|
@@ -253,4 +301,4 @@ declare function captureCamera(opts?: CaptureCameraOptions): Promise<MediaStream
|
|
|
253
301
|
*/
|
|
254
302
|
declare function captureScreen(opts?: CaptureScreenOptions): Promise<MediaStream>;
|
|
255
303
|
|
|
256
|
-
export { type CaptureCameraOptions, type CaptureScreenOptions, type GatewayReadyInfo, Publisher, type PublisherCallbacks, type PublisherOptions, type SignalMessage, captureCamera, captureScreen };
|
|
304
|
+
export { type CaptureCameraOptions, type CaptureScreenOptions, type GatewayReadyInfo, Publisher, type PublisherCallbacks, type PublisherOptions, type PublisherRecoveryAction, type PublisherRecoveryEvent, type PublisherRecoveryFailureReason, type PublisherRecoveryState, type SignalMessage, captureCamera, captureScreen };
|
package/dist/index.js
CHANGED
|
@@ -48,6 +48,9 @@ function parseSignal(data) {
|
|
|
48
48
|
var defaultSignalingReconnectTimeoutMs = 2e4;
|
|
49
49
|
var signalingResumeAttemptTimeoutMs = 3e3;
|
|
50
50
|
var signalingResumeMaxBackoffMs = 3e3;
|
|
51
|
+
var senderRestartPauseMs = 100;
|
|
52
|
+
var senderRecoveryWaitMs = 4e3;
|
|
53
|
+
var iceRecoveryWaitMs = 8e3;
|
|
51
54
|
var Publisher = class {
|
|
52
55
|
opts;
|
|
53
56
|
sig = null;
|
|
@@ -61,6 +64,11 @@ var Publisher = class {
|
|
|
61
64
|
reconnecting = false;
|
|
62
65
|
reconnectGeneration = 0;
|
|
63
66
|
resumeSocket = null;
|
|
67
|
+
recoveryGeneration = 0;
|
|
68
|
+
recoveringMedia = false;
|
|
69
|
+
recoveryRequired = false;
|
|
70
|
+
recoveryAction = null;
|
|
71
|
+
trackEndHandlers = /* @__PURE__ */ new Map();
|
|
64
72
|
constructor(opts) {
|
|
65
73
|
this.opts = opts;
|
|
66
74
|
}
|
|
@@ -76,7 +84,9 @@ var Publisher = class {
|
|
|
76
84
|
*/
|
|
77
85
|
async start(stream) {
|
|
78
86
|
this.stopped = false;
|
|
87
|
+
this.recoveryRequired = false;
|
|
79
88
|
this.localStream = stream;
|
|
89
|
+
this.watchStreamTracks(stream);
|
|
80
90
|
const { ws, readyInfo, gatewayURL } = await this.raceGateways();
|
|
81
91
|
this.selectedGatewayURL = gatewayURL;
|
|
82
92
|
if (readyInfo.read_token) {
|
|
@@ -121,6 +131,9 @@ var Publisher = class {
|
|
|
121
131
|
/** Replaces the currently published stream with a new one. */
|
|
122
132
|
async replaceStream(stream) {
|
|
123
133
|
if (!this.pc) throw new Error("publisher not started");
|
|
134
|
+
this.cancelMediaRecovery();
|
|
135
|
+
this.recoveryRequired = false;
|
|
136
|
+
this.unwatchStreamTracks();
|
|
124
137
|
const senders = this.pc.getSenders();
|
|
125
138
|
for (const sender of senders) {
|
|
126
139
|
if (sender.track) {
|
|
@@ -131,26 +144,20 @@ var Publisher = class {
|
|
|
131
144
|
this.pc.addTrack(track, stream);
|
|
132
145
|
}
|
|
133
146
|
this.localStream = stream;
|
|
134
|
-
|
|
135
|
-
await this.
|
|
136
|
-
await this.gatherComplete();
|
|
137
|
-
const local = this.pc.localDescription;
|
|
138
|
-
if (!local) throw new Error("local description missing");
|
|
139
|
-
this.sig?.send({
|
|
140
|
-
type: "offer",
|
|
141
|
-
sdp: local.sdp,
|
|
142
|
-
sdp_type: "offer"
|
|
143
|
-
});
|
|
147
|
+
this.watchStreamTracks(stream);
|
|
148
|
+
await this.renegotiate(false);
|
|
144
149
|
}
|
|
145
150
|
/** Stops publishing and tears down the peer connection. */
|
|
146
151
|
stop() {
|
|
147
152
|
this.stopped = true;
|
|
153
|
+
this.cancelMediaRecovery();
|
|
148
154
|
this.reconnectGeneration++;
|
|
149
155
|
this.reconnecting = false;
|
|
150
156
|
this.resumeSocket?.close();
|
|
151
157
|
this.resumeSocket = null;
|
|
152
158
|
this.sig?.close();
|
|
153
159
|
this.sig = null;
|
|
160
|
+
this.unwatchStreamTracks();
|
|
154
161
|
this.localStream?.getTracks().forEach((t) => t.stop());
|
|
155
162
|
this.localStream = null;
|
|
156
163
|
this.pc?.close();
|
|
@@ -313,6 +320,7 @@ var Publisher = class {
|
|
|
313
320
|
}
|
|
314
321
|
terminateWithError(err) {
|
|
315
322
|
this.stopped = true;
|
|
323
|
+
this.cancelMediaRecovery();
|
|
316
324
|
this.reconnectGeneration++;
|
|
317
325
|
this.resumeSocket?.close();
|
|
318
326
|
this.resumeSocket = null;
|
|
@@ -320,6 +328,7 @@ var Publisher = class {
|
|
|
320
328
|
this.sig = null;
|
|
321
329
|
this.pc?.close();
|
|
322
330
|
this.pc = null;
|
|
331
|
+
this.unwatchStreamTracks();
|
|
323
332
|
this.localStream?.getTracks().forEach((track) => track.stop());
|
|
324
333
|
this.localStream = null;
|
|
325
334
|
this.hasAnswer = false;
|
|
@@ -367,6 +376,15 @@ var Publisher = class {
|
|
|
367
376
|
case "connection_state": {
|
|
368
377
|
break;
|
|
369
378
|
}
|
|
379
|
+
case "media_stall":
|
|
380
|
+
case "media_track_ended": {
|
|
381
|
+
void this.beginMediaRecovery(msg.track);
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
case "media_resumed": {
|
|
385
|
+
this.completeMediaRecovery(msg.track);
|
|
386
|
+
break;
|
|
387
|
+
}
|
|
370
388
|
case "error": {
|
|
371
389
|
this.opts.callbacks?.onError?.(new Error(msg.error));
|
|
372
390
|
break;
|
|
@@ -375,6 +393,107 @@ var Publisher = class {
|
|
|
375
393
|
break;
|
|
376
394
|
}
|
|
377
395
|
}
|
|
396
|
+
async beginMediaRecovery(trackType) {
|
|
397
|
+
if (this.stopped || this.recoveringMedia || this.recoveryRequired) return;
|
|
398
|
+
const tracks = this.localStream?.getVideoTracks() ?? [];
|
|
399
|
+
const liveTracks = tracks.filter((track) => track.readyState !== "ended");
|
|
400
|
+
if (liveTracks.length === 0) {
|
|
401
|
+
this.failMediaRecovery(trackType, "capture_ended");
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
this.recoveringMedia = true;
|
|
405
|
+
const generation = ++this.recoveryGeneration;
|
|
406
|
+
this.recoveryAction = "sender_restart";
|
|
407
|
+
this.emitRecoveryTransition({ state: "recovering", track: trackType, action: "sender_restart" });
|
|
408
|
+
this.sendRecoveryDiagnostic("recovery_started", trackType, "sender_restart");
|
|
409
|
+
await this.restartSenders(liveTracks, generation);
|
|
410
|
+
if (!this.isCurrentRecovery(generation)) return;
|
|
411
|
+
await this.wait(senderRecoveryWaitMs);
|
|
412
|
+
if (!this.isCurrentRecovery(generation)) return;
|
|
413
|
+
this.recoveryAction = "ice_restart";
|
|
414
|
+
this.emitRecoveryTransition({ state: "recovering", track: trackType, action: "ice_restart" });
|
|
415
|
+
this.sendRecoveryDiagnostic("recovery_retry", trackType, "ice_restart");
|
|
416
|
+
try {
|
|
417
|
+
await this.renegotiate(true);
|
|
418
|
+
} catch {
|
|
419
|
+
}
|
|
420
|
+
await this.wait(iceRecoveryWaitMs);
|
|
421
|
+
if (!this.isCurrentRecovery(generation)) return;
|
|
422
|
+
this.failMediaRecovery(trackType, "automatic_recovery_failed");
|
|
423
|
+
}
|
|
424
|
+
async restartSenders(tracks, generation) {
|
|
425
|
+
const live = new Set(tracks);
|
|
426
|
+
const senders = this.pc?.getSenders().filter(
|
|
427
|
+
(sender) => sender.track && live.has(sender.track)
|
|
428
|
+
) ?? [];
|
|
429
|
+
if (senders.length === 0) return;
|
|
430
|
+
const originals = senders.map((sender) => ({ sender, track: sender.track }));
|
|
431
|
+
try {
|
|
432
|
+
await Promise.all(originals.map(({ sender }) => sender.replaceTrack(null)));
|
|
433
|
+
await this.wait(senderRestartPauseMs);
|
|
434
|
+
if (!this.isCurrentRecovery(generation)) return;
|
|
435
|
+
await Promise.all(originals.map(({ sender, track }) => sender.replaceTrack(track)));
|
|
436
|
+
await this.renegotiate(false);
|
|
437
|
+
} catch {
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
async renegotiate(iceRestart) {
|
|
441
|
+
const pc = this.pc;
|
|
442
|
+
const signaling = this.sig;
|
|
443
|
+
if (!pc || !signaling) throw new Error("publisher signaling is unavailable");
|
|
444
|
+
if (iceRestart) pc.restartIce?.();
|
|
445
|
+
const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : void 0);
|
|
446
|
+
await pc.setLocalDescription(offer);
|
|
447
|
+
await this.gatherComplete();
|
|
448
|
+
const local = pc.localDescription;
|
|
449
|
+
if (!local) throw new Error("local description missing");
|
|
450
|
+
this.hasAnswer = false;
|
|
451
|
+
this.pendingRemoteCandidates = [];
|
|
452
|
+
signaling.send({ type: "offer", sdp: local.sdp, sdp_type: "offer" });
|
|
453
|
+
}
|
|
454
|
+
completeMediaRecovery(trackType) {
|
|
455
|
+
if (!this.recoveringMedia) return;
|
|
456
|
+
const action = this.recoveryAction ?? void 0;
|
|
457
|
+
this.cancelMediaRecovery();
|
|
458
|
+
this.emitRecoveryTransition({ state: "recovered", track: trackType, action });
|
|
459
|
+
}
|
|
460
|
+
failMediaRecovery(trackType, reason) {
|
|
461
|
+
if (this.stopped || this.recoveryRequired) return;
|
|
462
|
+
this.recoveryRequired = true;
|
|
463
|
+
const action = this.recoveryAction ?? void 0;
|
|
464
|
+
this.cancelMediaRecovery();
|
|
465
|
+
const event = { state: "failed", track: trackType, action, reason };
|
|
466
|
+
this.emitRecoveryTransition(event);
|
|
467
|
+
this.opts.callbacks?.onRecoveryRequired?.(event);
|
|
468
|
+
this.sendRecoveryDiagnostic("recovery_failed", trackType, action, reason);
|
|
469
|
+
}
|
|
470
|
+
cancelMediaRecovery() {
|
|
471
|
+
this.recoveryGeneration++;
|
|
472
|
+
this.recoveringMedia = false;
|
|
473
|
+
this.recoveryAction = null;
|
|
474
|
+
}
|
|
475
|
+
isCurrentRecovery(generation) {
|
|
476
|
+
return !this.stopped && this.recoveringMedia && generation === this.recoveryGeneration;
|
|
477
|
+
}
|
|
478
|
+
emitRecoveryTransition(event) {
|
|
479
|
+
this.opts.callbacks?.onRecoveryStateChange?.(event);
|
|
480
|
+
}
|
|
481
|
+
sendRecoveryDiagnostic(event, track, action, reason) {
|
|
482
|
+
this.sig?.send({ type: "recovery_event", event, track, action, reason });
|
|
483
|
+
}
|
|
484
|
+
watchStreamTracks(stream) {
|
|
485
|
+
for (const track of stream.getVideoTracks()) {
|
|
486
|
+
const handler = () => this.failMediaRecovery("screen", "capture_ended");
|
|
487
|
+
track.addEventListener("ended", handler);
|
|
488
|
+
this.trackEndHandlers.set(track, handler);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
unwatchStreamTracks() {
|
|
492
|
+
for (const [track, handler] of this.trackEndHandlers) {
|
|
493
|
+
track.removeEventListener("ended", handler);
|
|
494
|
+
}
|
|
495
|
+
this.trackEndHandlers.clear();
|
|
496
|
+
}
|
|
378
497
|
/** Waits for ICE gathering to reach the "complete" state. */
|
|
379
498
|
gatherComplete() {
|
|
380
499
|
return new Promise((resolve) => {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/signaling.ts","../src/publisher.ts","../src/capture.ts"],"sourcesContent":["import type { SignalMessage } from \"./types\";\n\n/**\n * Wraps an open WebSocket to the Argus gateway and handles the JSON message\n * envelope: incoming text frames are parsed into {@link SignalMessage}s and\n * outgoing messages are serialised.\n *\n * This is an internal helper. The {@link Publisher} opens the socket itself\n * (racing all candidate gateways) and hands the winner here, so this class only\n * ever adopts an already-open socket rather than dialing one.\n *\n * @internal\n */\nexport class SignalingChannel {\n private ws: WebSocket;\n\n /** Fired for every incoming JSON message. */\n onMessage: ((msg: SignalMessage) => void) | null = null;\n /** Fired when the underlying WebSocket closes. */\n onClose: (() => void) | null = null;\n /** Fired when an error occurs on the WebSocket. */\n onError: ((err: Error) => void) | null = null;\n\n private constructor(ws: WebSocket) {\n this.ws = ws;\n }\n\n /**\n * Adopts an already-open WebSocket (e.g. the winner of a gateway race),\n * routing its events through the channel's callbacks. Any handlers previously\n * attached to the socket are replaced.\n */\n static wrap(ws: WebSocket): SignalingChannel {\n const ch = new SignalingChannel(ws);\n ws.onmessage = (ev: MessageEvent) => {\n const msg = parseSignal(ev.data);\n if (msg) ch.onMessage?.(msg);\n };\n ws.onerror = () => ch.onError?.(new Error(\"WebSocket error\"));\n ws.onclose = () => ch.onClose?.();\n return ch;\n }\n\n /** Sends a JSON message if the socket is open; a no-op otherwise. */\n send(msg: SignalMessage): void {\n if (this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /** Closes the underlying WebSocket. */\n close(): void {\n this.ws.close();\n }\n}\n\n/** Parses a WebSocket text frame into a SignalMessage, or null if malformed. */\nfunction parseSignal(data: unknown): SignalMessage | null {\n try {\n return JSON.parse(data as string) as SignalMessage;\n } catch {\n return null;\n }\n}\n","import { SignalingChannel } from \"./signaling\";\nimport type { GatewayReadyInfo, PublisherOptions, SignalMessage } from \"./types\";\n\nconst defaultSignalingReconnectTimeoutMs = 20_000;\nconst signalingResumeAttemptTimeoutMs = 3_000;\nconst signalingResumeMaxBackoffMs = 3_000;\n\n/**\n * Publisher streams a browser {@link MediaStream} to an Argus media server over\n * WebRTC. Given the `gateway_urls` and `token` from a join-token response, it\n * races the candidate gateways to the fastest one, completes the two-phase\n * signaling handshake, and manages the peer connection — offer/answer exchange,\n * ICE candidate trickling, and track (re)negotiation.\n *\n * After {@link Publisher.start} resolves, {@link Publisher.frameReadToken} holds\n * the token your application server needs to fetch frames for this stream.\n *\n * @example Publish the default camera:\n * ```ts\n * const pub = new Publisher({\n * gatewayURLs: joinResp.gateway_urls,\n * token: joinResp.token,\n * callbacks: { onConnected: () => console.log(\"live!\") },\n * });\n *\n * const stream = await navigator.mediaDevices.getUserMedia({ video: true });\n * await pub.start(stream);\n * ```\n */\nexport class Publisher {\n private opts: PublisherOptions;\n private sig: SignalingChannel | null = null;\n private pc: RTCPeerConnection | null = null;\n private hasAnswer = false;\n private pendingRemoteCandidates: RTCIceCandidateInit[] = [];\n private localStream: MediaStream | null = null;\n private readToken: string | null = null;\n private selectedGatewayURL: string | null = null;\n private stopped = true;\n private reconnecting = false;\n private reconnectGeneration = 0;\n private resumeSocket: WebSocket | null = null;\n\n constructor(opts: PublisherOptions) {\n this.opts = opts;\n }\n\n /** The read token used for frame fetches and signaling resume in the selected region. */\n get frameReadToken(): string | null { return this.readToken; }\n\n /**\n * Starts the publisher: races all gateways to find the fastest, completes\n * the two-phase handshake, creates the peer connection, and sends the SDP\n * offer. Resolves when the offer has been sent (not when ICE completes —\n * use onConnected for that).\n */\n async start(stream: MediaStream): Promise<void> {\n this.stopped = false;\n this.localStream = stream;\n\n // Race all gateways; returns winning WebSocket + TURN/read-token info\n const { ws, readyInfo, gatewayURL } = await this.raceGateways();\n this.selectedGatewayURL = gatewayURL;\n\n // Store read token for caller\n if (readyInfo.read_token) {\n this.readToken = readyInfo.read_token;\n }\n\n // Build ICE servers: extra servers from opts + TURN from gateway. The\n // gateway supplies multi-transport turn_urls (UDP + TCP) so relay can fall\n // back to TCP on UDP-blocking networks. A single credential is valid for\n // every transport.\n const iceServers: RTCIceServer[] = [...(this.opts.iceServers ?? [])];\n if (readyInfo.turn_urls && readyInfo.turn_urls.length > 0) {\n iceServers.push({\n urls: readyInfo.turn_urls,\n username: readyInfo.turn_username,\n credential: readyInfo.turn_credential,\n });\n }\n\n this.pc = new RTCPeerConnection({ iceServers });\n\n this.pc.onicecandidate = (ev) => {\n if (!ev.candidate || !this.sig) return;\n const c = ev.candidate;\n this.sig.send({\n type: \"ice_candidate\",\n candidate: c.candidate,\n sdp_mid: c.sdpMid ?? undefined,\n sdp_mline_index: c.sdpMLineIndex ?? undefined,\n username_fragment: c.usernameFragment ?? undefined,\n });\n };\n\n this.pc.onconnectionstatechange = () => {\n const state = this.pc?.connectionState;\n if (state) this.opts.callbacks?.onConnectionStateChange?.(state);\n if (state === \"connected\") this.opts.callbacks?.onConnected?.();\n };\n\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n // Wrap winning WebSocket in SignalingChannel\n const signaling = this.installSignaling(ws);\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing after gather\");\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n /** Replaces the currently published stream with a new one. */\n async replaceStream(stream: MediaStream): Promise<void> {\n if (!this.pc) throw new Error(\"publisher not started\");\n\n // Remove old tracks.\n const senders = this.pc.getSenders();\n for (const sender of senders) {\n if (sender.track) {\n this.pc.removeTrack(sender);\n }\n }\n\n // Add new tracks.\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n this.localStream = stream;\n\n // Renegotiate.\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing\");\n this.sig?.send({\n type: \"offer\",\n sdp: local.sdp,\n sdp_type: \"offer\",\n });\n }\n\n /** Stops publishing and tears down the peer connection. */\n stop(): void {\n this.stopped = true;\n this.reconnectGeneration++;\n this.reconnecting = false;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n\n this.localStream?.getTracks().forEach((t) => t.stop());\n this.localStream = null;\n\n this.pc?.close();\n this.pc = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n }\n\n /** Returns the current RTCPeerConnection, or null if not started. */\n get peerConnection(): RTCPeerConnection | null {\n return this.pc;\n }\n\n /** Returns true if the peer connection is in the \"connected\" state. */\n get isConnected(): boolean {\n return this.pc?.connectionState === \"connected\";\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n private raceGateways(): Promise<{ ws: WebSocket; readyInfo: GatewayReadyInfo; gatewayURL: string }> {\n return new Promise((resolve, reject) => {\n const { gatewayURLs, token } = this.opts;\n if (gatewayURLs.length === 0) {\n reject(new Error(\"no gateway URLs provided\"));\n return;\n }\n\n const sockets: WebSocket[] = [];\n let settled = false;\n\n const closeAll = (except?: WebSocket) => {\n for (const s of sockets) {\n if (s !== except) {\n s.onmessage = null;\n s.onerror = null;\n s.onclose = null;\n s.close();\n }\n }\n };\n\n const checkAllFailed = () => {\n if (settled) return;\n if (sockets.every(s => s.readyState === WebSocket.CLOSED || s.readyState === WebSocket.CLOSING)) {\n settled = true;\n reject(new Error(\"all gateways failed to connect\"));\n }\n };\n\n for (const gatewayURL of gatewayURLs) {\n const u = new URL(gatewayURL);\n u.searchParams.set(\"token\", token);\n const ws = new WebSocket(u.toString());\n sockets.push(ws);\n\n let accepted = false;\n\n ws.onmessage = (ev: MessageEvent) => {\n if (settled) return;\n try {\n const msg = JSON.parse(ev.data as string);\n if (!accepted && msg.type === \"accepted\") {\n accepted = true;\n ws.send(JSON.stringify({ type: \"proceed\" }));\n } else if (accepted && msg.type === \"ready\") {\n settled = true;\n closeAll(ws);\n resolve({ ws, readyInfo: msg as GatewayReadyInfo, gatewayURL });\n }\n } catch {\n /* ignore malformed */\n }\n };\n\n ws.onerror = () => checkAllFailed();\n ws.onclose = () => checkAllFailed();\n }\n });\n }\n\n private installSignaling(ws: WebSocket): SignalingChannel {\n const channel = SignalingChannel.wrap(ws);\n this.sig = channel;\n channel.onMessage = (msg) => this.handleSignal(msg);\n channel.onClose = () => {\n if (this.sig !== channel || this.stopped) return;\n this.sig = null;\n void this.resumeSignaling();\n };\n // Browsers normally follow an error event with close. Recovery begins from\n // close so a single transport failure cannot start two retry loops.\n channel.onError = () => {};\n return channel;\n }\n\n private async resumeSignaling(): Promise<void> {\n if (this.reconnecting || this.stopped) return;\n if (!this.selectedGatewayURL || !this.readToken) {\n this.terminateWithError(new Error(\"signaling closed and cannot be resumed\"));\n return;\n }\n\n this.reconnecting = true;\n const generation = ++this.reconnectGeneration;\n const timeout = this.opts.signalingReconnectTimeoutMs ?? defaultSignalingReconnectTimeoutMs;\n const deadline = Date.now() + Math.max(0, timeout);\n let backoffMs = 0;\n\n while (!this.stopped && generation === this.reconnectGeneration && Date.now() <= deadline) {\n if (backoffMs > 0) {\n const waitMs = Math.min(backoffMs, Math.max(0, deadline - Date.now()));\n if (waitMs === 0) break;\n await this.wait(waitMs);\n if (this.stopped || generation !== this.reconnectGeneration) return;\n }\n\n const remaining = deadline - Date.now();\n if (remaining < 0) break;\n try {\n const ws = await this.openResumeSocket(Math.min(signalingResumeAttemptTimeoutMs, Math.max(1, remaining)));\n if (this.stopped || generation !== this.reconnectGeneration) {\n ws.close();\n return;\n }\n this.resumeSocket = null;\n this.reconnecting = false;\n this.installSignaling(ws);\n return;\n } catch {\n backoffMs = backoffMs === 0 ? 250 : Math.min(backoffMs * 2, signalingResumeMaxBackoffMs);\n }\n }\n\n if (!this.stopped && generation === this.reconnectGeneration) {\n this.reconnecting = false;\n this.terminateWithError(new Error(\"unable to resume signaling with the selected gateway\"));\n }\n }\n\n private openResumeSocket(timeoutMs: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const u = new URL(this.selectedGatewayURL!);\n u.searchParams.set(\"token\", this.readToken!);\n const ws = new WebSocket(u.toString());\n this.resumeSocket = ws;\n let settled = false;\n const timer = setTimeout(() => fail(), timeoutMs);\n\n const fail = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n if (this.resumeSocket === ws) this.resumeSocket = null;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n ws.close();\n reject(new Error(\"signaling resume attempt failed\"));\n };\n\n ws.onmessage = (ev: MessageEvent) => {\n try {\n const msg = JSON.parse(ev.data as string);\n if (msg.type !== \"resumed\" || settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(ws);\n } catch {\n // Ignore malformed messages while waiting for the resume acknowledgement.\n }\n };\n ws.onerror = fail;\n ws.onclose = fail;\n });\n }\n\n private wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private terminateWithError(err: Error): void {\n this.stopped = true;\n this.reconnectGeneration++;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n this.pc?.close();\n this.pc = null;\n this.localStream?.getTracks().forEach((track) => track.stop());\n this.localStream = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n this.opts.callbacks?.onError?.(err);\n }\n\n private handleSignal(msg: SignalMessage): void {\n switch (msg.type) {\n case \"answer\": {\n if (!this.pc) return;\n this.pc\n .setRemoteDescription(\n new RTCSessionDescription({ type: \"answer\", sdp: msg.sdp }),\n )\n .then(() => {\n this.hasAnswer = true;\n // Flush any ICE candidates that arrived before the answer.\n for (const init of this.pendingRemoteCandidates) {\n this.pc?.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n }\n this.pendingRemoteCandidates = [];\n })\n .catch((err) => {\n this.opts.callbacks?.onError?.(\n new Error(`failed to set remote description: ${err}`),\n );\n });\n break;\n }\n\n case \"ice_candidate\": {\n if (!this.pc) return;\n const init: RTCIceCandidateInit = {\n candidate: msg.candidate,\n sdpMid: msg.sdp_mid ?? null,\n sdpMLineIndex: msg.sdp_mline_index ?? null,\n usernameFragment: msg.username_fragment ?? null,\n };\n if (this.hasAnswer) {\n this.pc.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n } else {\n this.pendingRemoteCandidates.push(init);\n }\n break;\n }\n\n case \"connection_state\": {\n // The server echoes the peer connection state; the onconnectionstatechange\n // handler above already covers this, but callers can also react via\n // onConnectionStateChange.\n break;\n }\n\n case \"error\": {\n this.opts.callbacks?.onError?.(new Error(msg.error));\n break;\n }\n\n case \"resumed\":\n break;\n }\n }\n\n /** Waits for ICE gathering to reach the \"complete\" state. */\n private gatherComplete(): Promise<void> {\n return new Promise((resolve) => {\n const pc = this.pc;\n if (!pc) {\n resolve();\n return;\n }\n if (pc.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n const handler = () => {\n if (pc.iceGatheringState === \"complete\") {\n pc.removeEventListener(\"icegatheringstatechange\", handler);\n resolve();\n }\n };\n pc.addEventListener(\"icegatheringstatechange\", handler);\n });\n }\n}\n","/**\n * Options for {@link captureCamera}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely (e.g. passing `video` overrides\n * the default video constraints rather than merging into them). Omit a field to\n * keep its default.\n */\nexport interface CaptureCameraOptions {\n /**\n * Video constraints, or `true`/`false`. Defaults to a modest resolution and\n * frame rate (see {@link captureCamera}). Set `false` to disable video.\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — Argus is a\n * video-frame streaming system, so audio is off unless you ask for it.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the browser's permission\n * prompt and transient-activation check are anchored to that window rather\n * than the one holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Options for {@link captureScreen}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely. Omit a field to keep its\n * default.\n */\nexport interface CaptureScreenOptions {\n /**\n * Video constraints, or `true`. Defaults to a capped width and a low frame\n * rate (see {@link captureScreen}).\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — screen shares\n * rarely need audio for a video-frame streaming system.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the screen picker and its\n * transient-activation check are anchored to that window rather than the one\n * holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Captures the user's camera via `navigator.mediaDevices.getUserMedia`,\n * applying sensible defaults for a video-frame streaming system.\n *\n * Defaults:\n * - `video`: `{ width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }`\n * — a modest resolution that keeps upload bandwidth reasonable. Cameras are\n * rarely the 4k bandwidth problem that screen capture is, so this is an\n * `ideal` (a hint) rather than a hard cap.\n * - `audio`: `false` — this is a video-frame streaming system.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureCamera();\n * await publisher.start(stream);\n * ```\n *\n * @example Front camera with audio:\n * ```ts\n * const stream = await captureCamera({\n * video: { facingMode: \"user\" },\n * audio: true,\n * });\n * ```\n */\nexport async function captureCamera(\n opts: CaptureCameraOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n frameRate: { ideal: 30 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getUserMedia(constraints);\n}\n\n/**\n * Captures a screen / window / tab via\n * `navigator.mediaDevices.getDisplayMedia`, applying sensible defaults tuned to\n * avoid the HiDPI/Retina bandwidth trap.\n *\n * Defaults:\n * - `video`: `{ width: { max: 1920 }, frameRate: { ideal: 5, max: 10 } }`.\n * The `width` is a **`max`, not an `ideal`**: on a 2x-Retina display the\n * browser would otherwise capture at native resolution (often 3456px+ /\n * effectively 4k), wasting upload bandwidth and downstream decode cost for no\n * visible benefit. Capping the max roughly halves a 2x-Retina share while\n * leaving smaller displays untouched. Screen content is mostly static, so the\n * low frame rate saves further bandwidth.\n * - `audio`: `false`.\n *\n * IMPORTANT — do NOT add `resizeMode: \"none\"` here. That value forbids the\n * browser from downscaling the source, which turns the `width: { max: 1920 }`\n * cap into a no-op on exactly the Retina displays it targets. By omitting\n * `resizeMode` we let the user agent scale to satisfy the constraint (its\n * default behaviour), which is the entire point of this helper. It is tempting\n * to add `resizeMode: \"none\"` back for \"sharpness\" — don't.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureScreen();\n * await publisher.start(stream);\n * ```\n */\nexport async function captureScreen(\n opts: CaptureScreenOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { max: 1920 },\n frameRate: { ideal: 5, max: 10 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getDisplayMedia(constraints);\n}\n"],"mappings":";AAaO,IAAM,mBAAN,MAAM,kBAAiB;AAAA,EACpB;AAAA;AAAA,EAGR,YAAmD;AAAA;AAAA,EAEnD,UAA+B;AAAA;AAAA,EAE/B,UAAyC;AAAA,EAEjC,YAAY,IAAe;AACjC,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,KAAK,IAAiC;AAC3C,UAAM,KAAK,IAAI,kBAAiB,EAAE;AAClC,OAAG,YAAY,CAAC,OAAqB;AACnC,YAAM,MAAM,YAAY,GAAG,IA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ture.ts"],"sourcesContent":["import type { SignalMessage } from \"./types\";\n\n/**\n * Wraps an open WebSocket to the Argus gateway and handles the JSON message\n * envelope: incoming text frames are parsed into {@link SignalMessage}s and\n * outgoing messages are serialised.\n *\n * This is an internal helper. The {@link Publisher} opens the socket itself\n * (racing all candidate gateways) and hands the winner here, so this class only\n * ever adopts an already-open socket rather than dialing one.\n *\n * @internal\n */\nexport class SignalingChannel {\n private ws: WebSocket;\n\n /** Fired for every incoming JSON message. */\n onMessage: ((msg: SignalMessage) => void) | null = null;\n /** Fired when the underlying WebSocket closes. */\n onClose: (() => void) | null = null;\n /** Fired when an error occurs on the WebSocket. */\n onError: ((err: Error) => void) | null = null;\n\n private constructor(ws: WebSocket) {\n this.ws = ws;\n }\n\n /**\n * Adopts an already-open WebSocket (e.g. the winner of a gateway race),\n * routing its events through the channel's callbacks. Any handlers previously\n * attached to the socket are replaced.\n */\n static wrap(ws: WebSocket): SignalingChannel {\n const ch = new SignalingChannel(ws);\n ws.onmessage = (ev: MessageEvent) => {\n const msg = parseSignal(ev.data);\n if (msg) ch.onMessage?.(msg);\n };\n ws.onerror = () => ch.onError?.(new Error(\"WebSocket error\"));\n ws.onclose = () => ch.onClose?.();\n return ch;\n }\n\n /** Sends a JSON message if the socket is open; a no-op otherwise. */\n send(msg: SignalMessage): void {\n if (this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /** Closes the underlying WebSocket. */\n close(): void {\n this.ws.close();\n }\n}\n\n/** Parses a WebSocket text frame into a SignalMessage, or null if malformed. */\nfunction parseSignal(data: unknown): SignalMessage | null {\n try {\n return JSON.parse(data as string) as SignalMessage;\n } catch {\n return null;\n }\n}\n","import { SignalingChannel } from \"./signaling\";\nimport type {\n GatewayReadyInfo,\n PublisherOptions,\n PublisherRecoveryAction,\n PublisherRecoveryEvent,\n SignalMessage,\n} from \"./types\";\n\nconst defaultSignalingReconnectTimeoutMs = 20_000;\nconst signalingResumeAttemptTimeoutMs = 3_000;\nconst signalingResumeMaxBackoffMs = 3_000;\nconst senderRestartPauseMs = 100;\nconst senderRecoveryWaitMs = 4_000;\nconst iceRecoveryWaitMs = 8_000;\n\n/**\n * Publisher streams a browser {@link MediaStream} to an Argus media server over\n * WebRTC. Given the `gateway_urls` and `token` from a join-token response, it\n * races the candidate gateways to the fastest one, completes the two-phase\n * signaling handshake, and manages the peer connection — offer/answer exchange,\n * ICE candidate trickling, and track (re)negotiation.\n *\n * After {@link Publisher.start} resolves, {@link Publisher.frameReadToken} holds\n * the token your application server needs to fetch frames for this stream.\n *\n * @example Publish the default camera:\n * ```ts\n * const pub = new Publisher({\n * gatewayURLs: joinResp.gateway_urls,\n * token: joinResp.token,\n * callbacks: { onConnected: () => console.log(\"live!\") },\n * });\n *\n * const stream = await navigator.mediaDevices.getUserMedia({ video: true });\n * await pub.start(stream);\n * ```\n */\nexport class Publisher {\n private opts: PublisherOptions;\n private sig: SignalingChannel | null = null;\n private pc: RTCPeerConnection | null = null;\n private hasAnswer = false;\n private pendingRemoteCandidates: RTCIceCandidateInit[] = [];\n private localStream: MediaStream | null = null;\n private readToken: string | null = null;\n private selectedGatewayURL: string | null = null;\n private stopped = true;\n private reconnecting = false;\n private reconnectGeneration = 0;\n private resumeSocket: WebSocket | null = null;\n private recoveryGeneration = 0;\n private recoveringMedia = false;\n private recoveryRequired = false;\n private recoveryAction: PublisherRecoveryAction | null = null;\n private trackEndHandlers = new Map<MediaStreamTrack, EventListener>();\n\n constructor(opts: PublisherOptions) {\n this.opts = opts;\n }\n\n /** The read token used for frame fetches and signaling resume in the selected region. */\n get frameReadToken(): string | null { return this.readToken; }\n\n /**\n * Starts the publisher: races all gateways to find the fastest, completes\n * the two-phase handshake, creates the peer connection, and sends the SDP\n * offer. Resolves when the offer has been sent (not when ICE completes —\n * use onConnected for that).\n */\n async start(stream: MediaStream): Promise<void> {\n this.stopped = false;\n this.recoveryRequired = false;\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n // Race all gateways; returns winning WebSocket + TURN/read-token info\n const { ws, readyInfo, gatewayURL } = await this.raceGateways();\n this.selectedGatewayURL = gatewayURL;\n\n // Store read token for caller\n if (readyInfo.read_token) {\n this.readToken = readyInfo.read_token;\n }\n\n // Build ICE servers: extra servers from opts + TURN from gateway. The\n // gateway supplies multi-transport turn_urls (UDP + TCP) so relay can fall\n // back to TCP on UDP-blocking networks. A single credential is valid for\n // every transport.\n const iceServers: RTCIceServer[] = [...(this.opts.iceServers ?? [])];\n if (readyInfo.turn_urls && readyInfo.turn_urls.length > 0) {\n iceServers.push({\n urls: readyInfo.turn_urls,\n username: readyInfo.turn_username,\n credential: readyInfo.turn_credential,\n });\n }\n\n this.pc = new RTCPeerConnection({ iceServers });\n\n this.pc.onicecandidate = (ev) => {\n if (!ev.candidate || !this.sig) return;\n const c = ev.candidate;\n this.sig.send({\n type: \"ice_candidate\",\n candidate: c.candidate,\n sdp_mid: c.sdpMid ?? undefined,\n sdp_mline_index: c.sdpMLineIndex ?? undefined,\n username_fragment: c.usernameFragment ?? undefined,\n });\n };\n\n this.pc.onconnectionstatechange = () => {\n const state = this.pc?.connectionState;\n if (state) this.opts.callbacks?.onConnectionStateChange?.(state);\n if (state === \"connected\") this.opts.callbacks?.onConnected?.();\n };\n\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n // Wrap winning WebSocket in SignalingChannel\n const signaling = this.installSignaling(ws);\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing after gather\");\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n /** Replaces the currently published stream with a new one. */\n async replaceStream(stream: MediaStream): Promise<void> {\n if (!this.pc) throw new Error(\"publisher not started\");\n\n this.cancelMediaRecovery();\n this.recoveryRequired = false;\n this.unwatchStreamTracks();\n\n // Remove old tracks.\n const senders = this.pc.getSenders();\n for (const sender of senders) {\n if (sender.track) {\n this.pc.removeTrack(sender);\n }\n }\n\n // Add new tracks.\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n await this.renegotiate(false);\n }\n\n /** Stops publishing and tears down the peer connection. */\n stop(): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.reconnecting = false;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((t) => t.stop());\n this.localStream = null;\n\n this.pc?.close();\n this.pc = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n }\n\n /** Returns the current RTCPeerConnection, or null if not started. */\n get peerConnection(): RTCPeerConnection | null {\n return this.pc;\n }\n\n /** Returns true if the peer connection is in the \"connected\" state. */\n get isConnected(): boolean {\n return this.pc?.connectionState === \"connected\";\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n private raceGateways(): Promise<{ ws: WebSocket; readyInfo: GatewayReadyInfo; gatewayURL: string }> {\n return new Promise((resolve, reject) => {\n const { gatewayURLs, token } = this.opts;\n if (gatewayURLs.length === 0) {\n reject(new Error(\"no gateway URLs provided\"));\n return;\n }\n\n const sockets: WebSocket[] = [];\n let settled = false;\n\n const closeAll = (except?: WebSocket) => {\n for (const s of sockets) {\n if (s !== except) {\n s.onmessage = null;\n s.onerror = null;\n s.onclose = null;\n s.close();\n }\n }\n };\n\n const checkAllFailed = () => {\n if (settled) return;\n if (sockets.every(s => s.readyState === WebSocket.CLOSED || s.readyState === WebSocket.CLOSING)) {\n settled = true;\n reject(new Error(\"all gateways failed to connect\"));\n }\n };\n\n for (const gatewayURL of gatewayURLs) {\n const u = new URL(gatewayURL);\n u.searchParams.set(\"token\", token);\n const ws = new WebSocket(u.toString());\n sockets.push(ws);\n\n let accepted = false;\n\n ws.onmessage = (ev: MessageEvent) => {\n if (settled) return;\n try {\n const msg = JSON.parse(ev.data as string);\n if (!accepted && msg.type === \"accepted\") {\n accepted = true;\n ws.send(JSON.stringify({ type: \"proceed\" }));\n } else if (accepted && msg.type === \"ready\") {\n settled = true;\n closeAll(ws);\n resolve({ ws, readyInfo: msg as GatewayReadyInfo, gatewayURL });\n }\n } catch {\n /* ignore malformed */\n }\n };\n\n ws.onerror = () => checkAllFailed();\n ws.onclose = () => checkAllFailed();\n }\n });\n }\n\n private installSignaling(ws: WebSocket): SignalingChannel {\n const channel = SignalingChannel.wrap(ws);\n this.sig = channel;\n channel.onMessage = (msg) => this.handleSignal(msg);\n channel.onClose = () => {\n if (this.sig !== channel || this.stopped) return;\n this.sig = null;\n void this.resumeSignaling();\n };\n // Browsers normally follow an error event with close. Recovery begins from\n // close so a single transport failure cannot start two retry loops.\n channel.onError = () => {};\n return channel;\n }\n\n private async resumeSignaling(): Promise<void> {\n if (this.reconnecting || this.stopped) return;\n if (!this.selectedGatewayURL || !this.readToken) {\n this.terminateWithError(new Error(\"signaling closed and cannot be resumed\"));\n return;\n }\n\n this.reconnecting = true;\n const generation = ++this.reconnectGeneration;\n const timeout = this.opts.signalingReconnectTimeoutMs ?? defaultSignalingReconnectTimeoutMs;\n const deadline = Date.now() + Math.max(0, timeout);\n let backoffMs = 0;\n\n while (!this.stopped && generation === this.reconnectGeneration && Date.now() <= deadline) {\n if (backoffMs > 0) {\n const waitMs = Math.min(backoffMs, Math.max(0, deadline - Date.now()));\n if (waitMs === 0) break;\n await this.wait(waitMs);\n if (this.stopped || generation !== this.reconnectGeneration) return;\n }\n\n const remaining = deadline - Date.now();\n if (remaining < 0) break;\n try {\n const ws = await this.openResumeSocket(Math.min(signalingResumeAttemptTimeoutMs, Math.max(1, remaining)));\n if (this.stopped || generation !== this.reconnectGeneration) {\n ws.close();\n return;\n }\n this.resumeSocket = null;\n this.reconnecting = false;\n this.installSignaling(ws);\n return;\n } catch {\n backoffMs = backoffMs === 0 ? 250 : Math.min(backoffMs * 2, signalingResumeMaxBackoffMs);\n }\n }\n\n if (!this.stopped && generation === this.reconnectGeneration) {\n this.reconnecting = false;\n this.terminateWithError(new Error(\"unable to resume signaling with the selected gateway\"));\n }\n }\n\n private openResumeSocket(timeoutMs: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const u = new URL(this.selectedGatewayURL!);\n u.searchParams.set(\"token\", this.readToken!);\n const ws = new WebSocket(u.toString());\n this.resumeSocket = ws;\n let settled = false;\n const timer = setTimeout(() => fail(), timeoutMs);\n\n const fail = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n if (this.resumeSocket === ws) this.resumeSocket = null;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n ws.close();\n reject(new Error(\"signaling resume attempt failed\"));\n };\n\n ws.onmessage = (ev: MessageEvent) => {\n try {\n const msg = JSON.parse(ev.data as string);\n if (msg.type !== \"resumed\" || settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(ws);\n } catch {\n // Ignore malformed messages while waiting for the resume acknowledgement.\n }\n };\n ws.onerror = fail;\n ws.onclose = fail;\n });\n }\n\n private wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private terminateWithError(err: Error): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n this.pc?.close();\n this.pc = null;\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((track) => track.stop());\n this.localStream = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n this.opts.callbacks?.onError?.(err);\n }\n\n private handleSignal(msg: SignalMessage): void {\n switch (msg.type) {\n case \"answer\": {\n if (!this.pc) return;\n this.pc\n .setRemoteDescription(\n new RTCSessionDescription({ type: \"answer\", sdp: msg.sdp }),\n )\n .then(() => {\n this.hasAnswer = true;\n // Flush any ICE candidates that arrived before the answer.\n for (const init of this.pendingRemoteCandidates) {\n this.pc?.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n }\n this.pendingRemoteCandidates = [];\n })\n .catch((err) => {\n this.opts.callbacks?.onError?.(\n new Error(`failed to set remote description: ${err}`),\n );\n });\n break;\n }\n\n case \"ice_candidate\": {\n if (!this.pc) return;\n const init: RTCIceCandidateInit = {\n candidate: msg.candidate,\n sdpMid: msg.sdp_mid ?? null,\n sdpMLineIndex: msg.sdp_mline_index ?? null,\n usernameFragment: msg.username_fragment ?? null,\n };\n if (this.hasAnswer) {\n this.pc.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n } else {\n this.pendingRemoteCandidates.push(init);\n }\n break;\n }\n\n case \"connection_state\": {\n // The server echoes the peer connection state; the onconnectionstatechange\n // handler above already covers this, but callers can also react via\n // onConnectionStateChange.\n break;\n }\n\n case \"media_stall\":\n case \"media_track_ended\": {\n void this.beginMediaRecovery(msg.track);\n break;\n }\n\n case \"media_resumed\": {\n this.completeMediaRecovery(msg.track);\n break;\n }\n\n case \"error\": {\n this.opts.callbacks?.onError?.(new Error(msg.error));\n break;\n }\n\n case \"resumed\":\n break;\n }\n }\n\n private async beginMediaRecovery(trackType: string): Promise<void> {\n if (this.stopped || this.recoveringMedia || this.recoveryRequired) return;\n\n const tracks = this.localStream?.getVideoTracks() ?? [];\n const liveTracks = tracks.filter((track) => track.readyState !== \"ended\");\n if (liveTracks.length === 0) {\n this.failMediaRecovery(trackType, \"capture_ended\");\n return;\n }\n\n this.recoveringMedia = true;\n const generation = ++this.recoveryGeneration;\n this.recoveryAction = \"sender_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"sender_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_started\", trackType, \"sender_restart\");\n\n await this.restartSenders(liveTracks, generation);\n if (!this.isCurrentRecovery(generation)) return;\n\n await this.wait(senderRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n\n this.recoveryAction = \"ice_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"ice_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_retry\", trackType, \"ice_restart\");\n try {\n await this.renegotiate(true);\n } catch {\n // The fixed recovery window below still gives signaling-resume a chance.\n // If media does not recover, the host receives onRecoveryRequired.\n }\n\n await this.wait(iceRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n this.failMediaRecovery(trackType, \"automatic_recovery_failed\");\n }\n\n private async restartSenders(tracks: MediaStreamTrack[], generation: number): Promise<void> {\n const live = new Set(tracks);\n const senders = this.pc?.getSenders().filter(\n (sender) => sender.track && live.has(sender.track),\n ) ?? [];\n if (senders.length === 0) return;\n\n const originals = senders.map((sender) => ({ sender, track: sender.track! }));\n try {\n await Promise.all(originals.map(({ sender }) => sender.replaceTrack(null)));\n await this.wait(senderRestartPauseMs);\n if (!this.isCurrentRecovery(generation)) return;\n await Promise.all(originals.map(({ sender, track }) => sender.replaceTrack(track)));\n await this.renegotiate(false);\n } catch {\n // ICE restart is the second stage and may still recover a sender reset or\n // renegotiation failure, so do not fail the stream at this stage.\n }\n }\n\n private async renegotiate(iceRestart: boolean): Promise<void> {\n const pc = this.pc;\n const signaling = this.sig;\n if (!pc || !signaling) throw new Error(\"publisher signaling is unavailable\");\n\n if (iceRestart) pc.restartIce?.();\n const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : undefined);\n await pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n const local = pc.localDescription;\n if (!local) throw new Error(\"local description missing\");\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n private completeMediaRecovery(trackType: string): void {\n if (!this.recoveringMedia) return;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n this.emitRecoveryTransition({ state: \"recovered\", track: trackType, action });\n }\n\n private failMediaRecovery(\n trackType: string,\n reason: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n if (this.stopped || this.recoveryRequired) return;\n this.recoveryRequired = true;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n const event: PublisherRecoveryEvent = { state: \"failed\", track: trackType, action, reason };\n this.emitRecoveryTransition(event);\n this.opts.callbacks?.onRecoveryRequired?.(event);\n this.sendRecoveryDiagnostic(\"recovery_failed\", trackType, action, reason);\n }\n\n private cancelMediaRecovery(): void {\n this.recoveryGeneration++;\n this.recoveringMedia = false;\n this.recoveryAction = null;\n }\n\n private isCurrentRecovery(generation: number): boolean {\n return !this.stopped && this.recoveringMedia && generation === this.recoveryGeneration;\n }\n\n private emitRecoveryTransition(event: PublisherRecoveryEvent): void {\n this.opts.callbacks?.onRecoveryStateChange?.(event);\n }\n\n private sendRecoveryDiagnostic(\n event: \"recovery_started\" | \"recovery_retry\" | \"recovery_failed\",\n track: string,\n action?: PublisherRecoveryAction,\n reason?: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n this.sig?.send({ type: \"recovery_event\", event, track, action, reason });\n }\n\n private watchStreamTracks(stream: MediaStream): void {\n for (const track of stream.getVideoTracks()) {\n const handler: EventListener = () => this.failMediaRecovery(\"screen\", \"capture_ended\");\n track.addEventListener(\"ended\", handler);\n this.trackEndHandlers.set(track, handler);\n }\n }\n\n private unwatchStreamTracks(): void {\n for (const [track, handler] of this.trackEndHandlers) {\n track.removeEventListener(\"ended\", handler);\n }\n this.trackEndHandlers.clear();\n }\n\n /** Waits for ICE gathering to reach the \"complete\" state. */\n private gatherComplete(): Promise<void> {\n return new Promise((resolve) => {\n const pc = this.pc;\n if (!pc) {\n resolve();\n return;\n }\n if (pc.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n const handler = () => {\n if (pc.iceGatheringState === \"complete\") {\n pc.removeEventListener(\"icegatheringstatechange\", handler);\n resolve();\n }\n };\n pc.addEventListener(\"icegatheringstatechange\", handler);\n });\n }\n}\n","/**\n * Options for {@link captureCamera}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely (e.g. passing `video` overrides\n * the default video constraints rather than merging into them). Omit a field to\n * keep its default.\n */\nexport interface CaptureCameraOptions {\n /**\n * Video constraints, or `true`/`false`. Defaults to a modest resolution and\n * frame rate (see {@link captureCamera}). Set `false` to disable video.\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — Argus is a\n * video-frame streaming system, so audio is off unless you ask for it.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the browser's permission\n * prompt and transient-activation check are anchored to that window rather\n * than the one holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Options for {@link captureScreen}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely. Omit a field to keep its\n * default.\n */\nexport interface CaptureScreenOptions {\n /**\n * Video constraints, or `true`. Defaults to a capped width and a low frame\n * rate (see {@link captureScreen}).\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — screen shares\n * rarely need audio for a video-frame streaming system.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the screen picker and its\n * transient-activation check are anchored to that window rather than the one\n * holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Captures the user's camera via `navigator.mediaDevices.getUserMedia`,\n * applying sensible defaults for a video-frame streaming system.\n *\n * Defaults:\n * - `video`: `{ width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }`\n * — a modest resolution that keeps upload bandwidth reasonable. Cameras are\n * rarely the 4k bandwidth problem that screen capture is, so this is an\n * `ideal` (a hint) rather than a hard cap.\n * - `audio`: `false` — this is a video-frame streaming system.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureCamera();\n * await publisher.start(stream);\n * ```\n *\n * @example Front camera with audio:\n * ```ts\n * const stream = await captureCamera({\n * video: { facingMode: \"user\" },\n * audio: true,\n * });\n * ```\n */\nexport async function captureCamera(\n opts: CaptureCameraOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n frameRate: { ideal: 30 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getUserMedia(constraints);\n}\n\n/**\n * Captures a screen / window / tab via\n * `navigator.mediaDevices.getDisplayMedia`, applying sensible defaults tuned to\n * avoid the HiDPI/Retina bandwidth trap.\n *\n * Defaults:\n * - `video`: `{ width: { max: 1920 }, frameRate: { ideal: 5, max: 10 } }`.\n * The `width` is a **`max`, not an `ideal`**: on a 2x-Retina display the\n * browser would otherwise capture at native resolution (often 3456px+ /\n * effectively 4k), wasting upload bandwidth and downstream decode cost for no\n * visible benefit. Capping the max roughly halves a 2x-Retina share while\n * leaving smaller displays untouched. Screen content is mostly static, so the\n * low frame rate saves further bandwidth.\n * - `audio`: `false`.\n *\n * IMPORTANT — do NOT add `resizeMode: \"none\"` here. That value forbids the\n * browser from downscaling the source, which turns the `width: { max: 1920 }`\n * cap into a no-op on exactly the Retina displays it targets. By omitting\n * `resizeMode` we let the user agent scale to satisfy the constraint (its\n * default behaviour), which is the entire point of this helper. It is tempting\n * to add `resizeMode: \"none\"` back for \"sharpness\" — don't.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureScreen();\n * await publisher.start(stream);\n * ```\n */\nexport async function captureScreen(\n opts: CaptureScreenOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { max: 1920 },\n frameRate: { ideal: 5, max: 10 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getDisplayMedia(constraints);\n}\n"],"mappings":";AAaO,IAAM,mBAAN,MAAM,kBAAiB;AAAA,EACpB;AAAA;AAAA,EAGR,YAAmD;AAAA;AAAA,EAEnD,UAA+B;AAAA;AAAA,EAE/B,UAAyC;AAAA,EAEjC,YAAY,IAAe;AACjC,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,KAAK,IAAiC;AAC3C,UAAM,KAAK,IAAI,kBAAiB,EAAE;AAClC,OAAG,YAAY,CAAC,OAAqB;AACnC,YAAM,MAAM,YAAY,GAAG,IAAI;AAC/B,UAAI,IAAK,IAAG,YAAY,GAAG;AAAA,IAC7B;AACA,OAAG,UAAU,MAAM,GAAG,UAAU,IAAI,MAAM,iBAAiB,CAAC;AAC5D,OAAG,UAAU,MAAM,GAAG,UAAU;AAChC,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,KAAK,KAA0B;AAC7B,QAAI,KAAK,GAAG,eAAe,UAAU,MAAM;AACzC,WAAK,GAAG,KAAK,KAAK,UAAU,GAAG,CAAC;AAAA,IAClC;AAAA,EACF;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,GAAG,MAAM;AAAA,EAChB;AACF;AAGA,SAAS,YAAY,MAAqC;AACxD,MAAI;AACF,WAAO,KAAK,MAAM,IAAc;AAAA,EAClC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACtDA,IAAM,qCAAqC;AAC3C,IAAM,kCAAkC;AACxC,IAAM,8BAA8B;AACpC,IAAM,uBAAuB;AAC7B,IAAM,uBAAuB;AAC7B,IAAM,oBAAoB;AAwBnB,IAAM,YAAN,MAA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