@reactor-team/js-sdk 3.0.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -317,16 +317,53 @@ function extractFileRefs(data) {
317
317
  let uploads;
318
318
  let scalars;
319
319
  for (const [key, value] of Object.entries(data)) {
320
- if (!isFileRef(value)) {
320
+ if (isFileRef(value)) {
321
+ uploads ??= {};
322
+ scalars ??= { ...data };
323
+ uploads[key] = toWireFileRef(value);
324
+ delete scalars[key];
321
325
  continue;
322
326
  }
323
- uploads ??= {};
324
- scalars ??= { ...data };
325
- uploads[key] = toWireFileRef(value);
326
- delete scalars[key];
327
+ const rewritten = rewriteNestedFileRefs(value);
328
+ if (rewritten !== value) {
329
+ scalars ??= { ...data };
330
+ scalars[key] = rewritten;
331
+ }
327
332
  }
328
333
  return { data: scalars ?? data, uploads };
329
334
  }
335
+ function rewriteNestedFileRefs(value) {
336
+ if (isFileRef(value)) {
337
+ return toWireFileRef(value);
338
+ }
339
+ if (Array.isArray(value)) {
340
+ const elements = value;
341
+ let copy;
342
+ elements.forEach((element, index) => {
343
+ const rewritten = rewriteNestedFileRefs(element);
344
+ if (rewritten !== element) {
345
+ copy ??= [...elements];
346
+ copy[index] = rewritten;
347
+ }
348
+ });
349
+ return copy ?? elements;
350
+ }
351
+ if (isSerializedAsObject(value)) {
352
+ let copy;
353
+ for (const [key, element] of Object.entries(value)) {
354
+ const rewritten = rewriteNestedFileRefs(element);
355
+ if (rewritten !== element) {
356
+ copy ??= { ...value };
357
+ copy[key] = rewritten;
358
+ }
359
+ }
360
+ return copy ?? value;
361
+ }
362
+ return value;
363
+ }
364
+ function isSerializedAsObject(value) {
365
+ return typeof value === "object" && value !== null && !ArrayBuffer.isView(value);
366
+ }
330
367
 
331
368
  // src/internal/recording.ts
332
369
  function toPublicClip(clip) {
@@ -342,14 +379,185 @@ function toPublicClip(clip) {
342
379
  }
343
380
 
344
381
  // src/internal/stats.ts
345
- var STATS_INTERVAL_MS = 2e3;
346
- function createRTCStatsExtractor() {
382
+ var LOCAL_STATS_INTERVAL_MS = 2e3;
383
+ var RUNTIME_REPORT_INTERVAL_MS = 5e3;
384
+ function pollPeerStats(client, intervalMs, onReport) {
385
+ let stopped = false;
386
+ let reading = false;
387
+ const handle = setInterval(() => {
388
+ if (reading) {
389
+ return;
390
+ }
391
+ const peerConnection = client.getPeerConnection();
392
+ if (!peerConnection) {
393
+ return;
394
+ }
395
+ reading = true;
396
+ void peerConnection.getStats().then(
397
+ (report) => {
398
+ if (stopped) {
399
+ return;
400
+ }
401
+ try {
402
+ onReport(report);
403
+ } catch (error) {
404
+ console.error("[Reactor] stats report handler threw:", error);
405
+ }
406
+ },
407
+ () => {
408
+ }
409
+ ).finally(() => {
410
+ reading = false;
411
+ });
412
+ }, intervalMs);
413
+ return () => {
414
+ stopped = true;
415
+ clearInterval(handle);
416
+ };
417
+ }
418
+ function roundMs(ms) {
419
+ return Math.round(ms * 1e3) / 1e3;
420
+ }
421
+ function secondsToMs(seconds) {
422
+ return roundMs(seconds * 1e3);
423
+ }
424
+ var WIRE_CODECS = {
425
+ video: /* @__PURE__ */ new Set(["vp8", "vp9", "av1", "h264", "h265"]),
426
+ audio: /* @__PURE__ */ new Set(["opus"])
427
+ };
428
+ function createTrackStatsExtractor() {
429
+ const lastBytes = /* @__PURE__ */ new Map();
430
+ return (report, tracks, pausedTracks) => {
431
+ const reportWithLookup = report;
432
+ const stats = [];
433
+ const seenStreams = /* @__PURE__ */ new Set();
434
+ const remoteInbound = /* @__PURE__ */ new Map();
435
+ report.forEach((stat) => {
436
+ if (stat.type === "remote-inbound-rtp" && stat.localId !== void 0) {
437
+ remoteInbound.set(stat.localId, stat);
438
+ }
439
+ });
440
+ report.forEach((stat) => {
441
+ const inbound = stat.type === "inbound-rtp";
442
+ if (!inbound && stat.type !== "outbound-rtp" || stat.mid === void 0) {
443
+ return;
444
+ }
445
+ const direction = inbound ? "recvonly" : "sendonly";
446
+ const streamKey = `${direction}:${stat.mid}`;
447
+ if (seenStreams.has(streamKey)) {
448
+ return;
449
+ }
450
+ const track = tracks.find((entry) => entry.mid === stat.mid && entry.direction === direction);
451
+ const codecStat = stat.codecId !== void 0 ? reportWithLookup.get(stat.codecId) : void 0;
452
+ const codec = codecStat?.mimeType?.split("/")[1]?.toLowerCase();
453
+ if (track === void 0 || codec === void 0 || !WIRE_CODECS[track.kind].has(codec)) {
454
+ return;
455
+ }
456
+ seenStreams.add(streamKey);
457
+ const metrics = {};
458
+ const put = (key, value) => {
459
+ if (value !== void 0) {
460
+ metrics[key] = value;
461
+ }
462
+ };
463
+ const bytes = inbound ? stat.bytesReceived : stat.bytesSent;
464
+ if (bytes !== void 0) {
465
+ const previous = lastBytes.get(stat.id);
466
+ if (previous !== void 0 && stat.timestamp > previous.timestamp && bytes >= previous.bytes) {
467
+ put("bitrate_bps", Math.round((bytes - previous.bytes) * 8 * 1e3 / (stat.timestamp - previous.timestamp)));
468
+ }
469
+ lastBytes.set(stat.id, { bytes, timestamp: stat.timestamp });
470
+ }
471
+ const keyframeRequests = stat.firCount !== void 0 || stat.pliCount !== void 0 ? (stat.firCount ?? 0) + (stat.pliCount ?? 0) : void 0;
472
+ if (inbound) {
473
+ put("packets_received", stat.packetsReceived);
474
+ put("packets_lost", stat.packetsLost);
475
+ put("jitter_ms", stat.jitter !== void 0 ? secondsToMs(stat.jitter) : void 0);
476
+ put("nack_count", stat.nackCount);
477
+ if (track.kind === "video") {
478
+ put("frames_per_second", stat.framesPerSecond);
479
+ put("frames_decoded", stat.framesDecoded);
480
+ put("frames_dropped", stat.framesDropped);
481
+ put("frame_width", stat.frameWidth);
482
+ put("frame_height", stat.frameHeight);
483
+ put("keyframe_requests", keyframeRequests);
484
+ } else {
485
+ put("concealed_samples", stat.concealedSamples);
486
+ put("total_samples_received", stat.totalSamplesReceived);
487
+ }
488
+ } else {
489
+ const remote = remoteInbound.get(stat.id);
490
+ put("packets_sent", stat.packetsSent);
491
+ put("retransmitted_packets_sent", stat.retransmittedPacketsSent);
492
+ put("nack_count", stat.nackCount);
493
+ put("packets_lost", remote?.packetsLost);
494
+ put("jitter_ms", remote?.jitter !== void 0 ? secondsToMs(remote.jitter) : void 0);
495
+ put("round_trip_time_ms", remote?.roundTripTime !== void 0 ? secondsToMs(remote.roundTripTime) : void 0);
496
+ if (track.kind === "video") {
497
+ put("frames_per_second", stat.framesPerSecond);
498
+ put("frames_encoded", stat.framesEncoded);
499
+ put("frame_width", stat.frameWidth);
500
+ put("frame_height", stat.frameHeight);
501
+ put("keyframe_requests", keyframeRequests);
502
+ }
503
+ }
504
+ stats.push({
505
+ timestamp: Date.now(),
506
+ trackName: track.name,
507
+ kind: track.kind,
508
+ direction,
509
+ codec,
510
+ paused: pausedTracks.includes(track.name),
511
+ metrics
512
+ });
513
+ });
514
+ return stats;
515
+ };
516
+ }
517
+ function toClientConnectionStat(report, timeToConnectMs) {
518
+ const pair = activeCandidatePair(report);
519
+ const metrics = {};
520
+ if (pair?.availableOutgoingBitrate !== void 0) {
521
+ metrics.available_outgoing_bitrate_bps = pair.availableOutgoingBitrate;
522
+ }
523
+ if (pair?.availableIncomingBitrate !== void 0) {
524
+ metrics.available_incoming_bitrate_bps = pair.availableIncomingBitrate;
525
+ }
526
+ if (pair?.currentRoundTripTime !== void 0) {
527
+ metrics.connection_rtt_ms = secondsToMs(pair.currentRoundTripTime);
528
+ }
529
+ if (timeToConnectMs !== void 0) {
530
+ metrics.time_to_connect_ms = roundMs(timeToConnectMs);
531
+ }
532
+ return { timestamp: Date.now(), metrics };
533
+ }
534
+ function activeCandidatePair(report) {
535
+ let namedByTransport;
536
+ let flaggedSelected;
537
+ let firstNominated;
538
+ report.forEach((stat) => {
539
+ if (stat.type === "transport" && stat.selectedCandidatePairId) {
540
+ namedByTransport ??= stat.selectedCandidatePairId;
541
+ }
542
+ if (stat.type === "candidate-pair" && stat.state === "succeeded") {
543
+ if (stat.selected) {
544
+ flaggedSelected ??= stat;
545
+ }
546
+ if (stat.nominated) {
547
+ firstNominated ??= stat;
548
+ }
549
+ }
550
+ });
551
+ const named = namedByTransport !== void 0 ? report.get(namedByTransport) : void 0;
552
+ const namedSucceeded = named?.state === "succeeded" ? named : void 0;
553
+ return namedSucceeded ?? flaggedSelected ?? firstNominated;
554
+ }
555
+ function createConnectionStatsExtractor() {
347
556
  let lastBytesReceived;
348
557
  let lastBytesSent;
349
558
  let lastCandPairTimestamp;
350
559
  let lastCandPairId;
351
560
  return (report) => {
352
- let candPairId;
353
561
  let rtt;
354
562
  let availableOutgoingBitrate;
355
563
  let availableIncomingBitrate;
@@ -360,40 +568,35 @@ function createRTCStatsExtractor() {
360
568
  let jitter;
361
569
  let packetLossRatio;
362
570
  let candidateType;
363
- const reportWithLookup = report;
364
- report.forEach((stat) => {
365
- if (candPairId === void 0 && stat.type === "candidate-pair" && stat.state === "succeeded" && stat.nominated) {
366
- candPairId = stat.id;
367
- if (stat.currentRoundTripTime !== void 0) {
368
- rtt = stat.currentRoundTripTime * 1e3;
369
- }
370
- if (stat.availableOutgoingBitrate !== void 0) {
371
- availableOutgoingBitrate = stat.availableOutgoingBitrate;
372
- }
373
- if (stat.availableIncomingBitrate !== void 0) {
374
- availableIncomingBitrate = stat.availableIncomingBitrate;
375
- }
376
- const localCandidate = stat.localCandidateId !== void 0 ? reportWithLookup.get(stat.localCandidateId) : void 0;
377
- if (localCandidate?.candidateType) {
378
- candidateType = localCandidate.candidateType;
379
- }
380
- const samePair = lastCandPairId === candPairId;
381
- const timeDiff = samePair && lastCandPairTimestamp !== void 0 ? stat.timestamp - lastCandPairTimestamp : 0;
382
- if (stat.bytesReceived !== void 0) {
383
- if (samePair && lastBytesReceived !== void 0 && timeDiff > 0) {
384
- incomingBitrate = (stat.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
385
- }
386
- lastBytesReceived = stat.bytesReceived;
571
+ const pair = activeCandidatePair(report);
572
+ if (pair !== void 0) {
573
+ if (pair.currentRoundTripTime !== void 0) {
574
+ rtt = pair.currentRoundTripTime * 1e3;
575
+ }
576
+ availableOutgoingBitrate = pair.availableOutgoingBitrate;
577
+ availableIncomingBitrate = pair.availableIncomingBitrate;
578
+ const localCandidate = pair.localCandidateId !== void 0 ? report.get(pair.localCandidateId) : void 0;
579
+ if (localCandidate?.candidateType) {
580
+ candidateType = localCandidate.candidateType;
581
+ }
582
+ const samePair = lastCandPairId === pair.id;
583
+ const timeDiff = samePair && lastCandPairTimestamp !== void 0 ? pair.timestamp - lastCandPairTimestamp : 0;
584
+ if (pair.bytesReceived !== void 0) {
585
+ if (samePair && lastBytesReceived !== void 0 && timeDiff > 0) {
586
+ incomingBitrate = (pair.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
387
587
  }
388
- if (stat.bytesSent !== void 0) {
389
- if (samePair && lastBytesSent !== void 0 && timeDiff > 0) {
390
- outgoingBitrate = (stat.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
391
- }
392
- lastBytesSent = stat.bytesSent;
588
+ lastBytesReceived = pair.bytesReceived;
589
+ }
590
+ if (pair.bytesSent !== void 0) {
591
+ if (samePair && lastBytesSent !== void 0 && timeDiff > 0) {
592
+ outgoingBitrate = (pair.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
393
593
  }
394
- lastCandPairTimestamp = stat.timestamp;
395
- lastCandPairId = candPairId;
594
+ lastBytesSent = pair.bytesSent;
396
595
  }
596
+ lastCandPairTimestamp = pair.timestamp;
597
+ lastCandPairId = pair.id;
598
+ }
599
+ report.forEach((stat) => {
397
600
  if (videoInboundRtpId === void 0 && stat.type === "inbound-rtp" && stat.kind === "video") {
398
601
  videoInboundRtpId = stat.id;
399
602
  if (stat.framesPerSecond !== void 0) {
@@ -448,7 +651,7 @@ async function importWasmModule() {
448
651
  // package.json
449
652
  var package_default = {
450
653
  name: "@reactor-team/js-sdk",
451
- version: "3.0.1",
654
+ version: "3.1.0",
452
655
  description: "Connect your JavaScript/TypeScript app to a live Reactor model in the browser.",
453
656
  license: "Apache-2.0",
454
657
  repository: {
@@ -924,11 +1127,14 @@ var Reactor = class {
924
1127
  capabilities;
925
1128
  stats;
926
1129
  connectionTimings;
927
- statsPollHandle;
928
- /** Bumped on every `startStatsPolling()`/`stopStatsPolling()` call — lets an
929
- * in-flight `getStats()` recognize it's stale once it resolves, even if
930
- * `this.client` hasn't changed in the meantime. */
931
- statsPollGeneration = 0;
1130
+ /** The stop functions of the running stats pollers — see `pollPeerStats()`. */
1131
+ stopStatsPollers = [];
1132
+ /** Whether this connection has already reported its time to connect —
1133
+ * a one-time fact, sent on the first client-stats report that carries it
1134
+ * and omitted on every one after. Set only once a batch actually went out
1135
+ * with it, so a batch sent before the timings exist doesn't use it up.
1136
+ * Reset per `startStatsPolling()` call, i.e. per connect()/reconnect(). */
1137
+ hasSentConnectTime = false;
932
1138
  /** Set on the "connecting" status transition, cleared once `connectionTimings`
933
1139
  * is finalized on "ready" — see `handleStatusChanged()`. */
934
1140
  connectStartTime;
@@ -941,6 +1147,70 @@ var Reactor = class {
941
1147
  * take ownership of Rust value while it was borrowed") or corrupt it
942
1148
  * outright. */
943
1149
  queue = new import_awaitqueue.AwaitQueue();
1150
+ /** In-flight calls to `withReaderAccess()` — a "reply" `.catch(() => {})`
1151
+ * copy of each, never the caller's own promise, so one rejecting can't
1152
+ * make `Promise.all()` in `withWriterAccess()` reject and skip waiting
1153
+ * for the rest. See `withReaderAccess()`/`withWriterAccess()`. */
1154
+ activeReads = /* @__PURE__ */ new Set();
1155
+ /** True for the span of a `withWriterAccess()` call — after it has waited
1156
+ * out every read active when it started, before it releases the ones
1157
+ * that arrived while it ran. */
1158
+ writerActive = false;
1159
+ /** Readers parked in `withReaderAccess()`'s wait loop, woken once
1160
+ * `withWriterAccess()` finishes; each re-checks `writerActive` rather
1161
+ * than assuming its turn, since another writer already queued behind the
1162
+ * first one may have claimed it first. */
1163
+ writerIdleWaiters = [];
1164
+ /**
1165
+ * Runs a read — sendCommand()/requestSchema()/requestClip()/
1166
+ * requestRecording() — excluded from a lifecycle op (`withWriterAccess()`)
1167
+ * but not from other reads: unlike `queue`, concurrent reads run
1168
+ * concurrently. Queuing them the same way `queue` serializes writes would
1169
+ * head-of-line block an unrelated command, or even disconnect() itself,
1170
+ * behind one slow reply (the binding correlates replies independently, so
1171
+ * nothing requires this to be serial).
1172
+ *
1173
+ * Race-free the same way the wasm binding's own `readyState` check is: the
1174
+ * `writerActive` check and this call's registration in `activeReads` both
1175
+ * happen before the first `await` inside *fn*, so nothing can run between
1176
+ * them on a single-threaded JS event loop.
1177
+ */
1178
+ async withReaderAccess(fn) {
1179
+ while (this.writerActive) {
1180
+ await new Promise((resolve) => this.writerIdleWaiters.push(resolve));
1181
+ }
1182
+ const result = fn();
1183
+ const tracked = result.catch(() => void 0);
1184
+ this.activeReads.add(tracked);
1185
+ try {
1186
+ return await result;
1187
+ } finally {
1188
+ this.activeReads.delete(tracked);
1189
+ }
1190
+ }
1191
+ /**
1192
+ * Runs a lifecycle op's client-touching body exclusively: waits out every
1193
+ * read already in flight, then blocks new ones (`writerActive`) until it
1194
+ * finishes. Only ever called from inside a `queue`-serialized task, so at
1195
+ * most one writer runs this at a time — it doesn't serialize against
1196
+ * itself, only against `activeReads`.
1197
+ */
1198
+ async withWriterAccess(fn) {
1199
+ this.writerActive = true;
1200
+ if (this.activeReads.size > 0) {
1201
+ await Promise.all(this.activeReads);
1202
+ }
1203
+ try {
1204
+ return await fn();
1205
+ } finally {
1206
+ this.writerActive = false;
1207
+ const waiters = this.writerIdleWaiters;
1208
+ this.writerIdleWaiters = [];
1209
+ for (const wake of waiters) {
1210
+ wake();
1211
+ }
1212
+ }
1213
+ }
944
1214
  constructor(options) {
945
1215
  const { jwt, ...clientOptions } = options;
946
1216
  this.clientOptions = { sdkVersion: package_default.version, ...clientOptions };
@@ -964,10 +1234,13 @@ var Reactor = class {
964
1234
  this.jwt = jwt;
965
1235
  this.client?.setJwt(jwt);
966
1236
  }
967
- await this.queue.push(async () => {
968
- const client = await this.getOrCreateClient();
969
- await client.connect(options);
970
- }, "connect");
1237
+ await this.queue.push(
1238
+ () => this.withWriterAccess(async () => {
1239
+ const client = await this.getOrCreateClient();
1240
+ await client.connect(options);
1241
+ }),
1242
+ "connect"
1243
+ );
971
1244
  } catch (cause) {
972
1245
  throw this.captureError(cause);
973
1246
  }
@@ -990,15 +1263,18 @@ var Reactor = class {
990
1263
  async disconnect(recoverable = false) {
991
1264
  this.assertNotDisposed();
992
1265
  try {
993
- await this.queue.push(async () => {
994
- if (this.client) {
995
- await this.client.disconnect();
996
- }
997
- this.resetConnectionState();
998
- if (!recoverable) {
999
- this.freeClient();
1000
- }
1001
- }, "disconnect");
1266
+ await this.queue.push(
1267
+ () => this.withWriterAccess(async () => {
1268
+ if (this.client) {
1269
+ await this.client.disconnect();
1270
+ }
1271
+ this.resetConnectionState();
1272
+ if (!recoverable) {
1273
+ this.freeClient();
1274
+ }
1275
+ }),
1276
+ "disconnect"
1277
+ );
1002
1278
  } catch (cause) {
1003
1279
  throw this.captureError(cause);
1004
1280
  }
@@ -1012,10 +1288,13 @@ var Reactor = class {
1012
1288
  async reconnect(options) {
1013
1289
  this.assertNotDisposed();
1014
1290
  try {
1015
- await this.queue.push(async () => {
1016
- const client = await this.getOrCreateClient();
1017
- await client.reconnect(options);
1018
- }, "reconnect");
1291
+ await this.queue.push(
1292
+ () => this.withWriterAccess(async () => {
1293
+ const client = await this.getOrCreateClient();
1294
+ await client.reconnect(options);
1295
+ }),
1296
+ "reconnect"
1297
+ );
1019
1298
  } catch (cause) {
1020
1299
  throw this.captureError(cause);
1021
1300
  }
@@ -1030,9 +1309,11 @@ var Reactor = class {
1030
1309
  * mode) actually hands back `null` — normalized here so callers can rely
1031
1310
  * on the documented type instead of the binding's serialization quirk.
1032
1311
  *
1033
- * A `FileRef` (from `uploadFile`) may be passed as a top-level value in
1034
- * `data` alongside regular parameters — it is extracted and sent as a
1035
- * separate upload reference rather than embedded in the JSON payload.
1312
+ * A `FileRef` (from `uploadFile`) may be passed in `data` wherever the
1313
+ * model's schema declares a file. As a top-level value it is extracted and
1314
+ * sent as a separate upload reference rather than embedded in the JSON
1315
+ * payload; inside an array or object (a parameter that takes several files,
1316
+ * say) it is serialized as an upload reference in place.
1036
1317
  *
1037
1318
  * Unlike every other method here, this never rejects — a failure (the
1038
1319
  * session isn't `"ready"`, the send itself fails, …) is reported through
@@ -1054,9 +1335,11 @@ var Reactor = class {
1054
1335
  }
1055
1336
  try {
1056
1337
  this.assertNotDisposed();
1057
- const client = await this.getOrCreateClient();
1058
1338
  const extracted = extractFileRefs(data);
1059
- const reply = await client.sendCommand(command, extracted.data, extracted.uploads);
1339
+ const reply = await this.withReaderAccess(async () => {
1340
+ const client = await this.getOrCreateClient();
1341
+ return client.sendCommand(command, extracted.data, extracted.uploads);
1342
+ });
1060
1343
  return reply ?? void 0;
1061
1344
  } catch (cause) {
1062
1345
  this.emitError(cause);
@@ -1083,8 +1366,10 @@ var Reactor = class {
1083
1366
  switch (command) {
1084
1367
  case "requestSchema":
1085
1368
  try {
1086
- const client = await this.getOrCreateClient();
1087
- await this.refreshSchema(client);
1369
+ await this.withReaderAccess(async () => {
1370
+ const client = await this.getOrCreateClient();
1371
+ await this.refreshSchema(client);
1372
+ });
1088
1373
  } catch (cause) {
1089
1374
  this.emitError(cause);
1090
1375
  }
@@ -1106,8 +1391,10 @@ var Reactor = class {
1106
1391
  async requestSchema() {
1107
1392
  this.assertNotDisposed();
1108
1393
  try {
1109
- const client = await this.getOrCreateClient();
1110
- return this.normalizeSchema(await client.requestSchema());
1394
+ return await this.withReaderAccess(async () => {
1395
+ const client = await this.getOrCreateClient();
1396
+ return this.normalizeSchema(await client.requestSchema());
1397
+ });
1111
1398
  } catch (cause) {
1112
1399
  throw this.captureError(cause);
1113
1400
  }
@@ -1247,8 +1534,10 @@ var Reactor = class {
1247
1534
  async requestClip(durationSeconds) {
1248
1535
  this.assertNotDisposed();
1249
1536
  try {
1250
- const client = await this.getOrCreateClient();
1251
- return toPublicClip(await client.requestClip(durationSeconds));
1537
+ return await this.withReaderAccess(async () => {
1538
+ const client = await this.getOrCreateClient();
1539
+ return toPublicClip(await client.requestClip(durationSeconds));
1540
+ });
1252
1541
  } catch (cause) {
1253
1542
  throw this.captureError(cause);
1254
1543
  }
@@ -1257,8 +1546,10 @@ var Reactor = class {
1257
1546
  async requestRecording() {
1258
1547
  this.assertNotDisposed();
1259
1548
  try {
1260
- const client = await this.getOrCreateClient();
1261
- return toPublicClip(await client.requestRecording());
1549
+ return await this.withReaderAccess(async () => {
1550
+ const client = await this.getOrCreateClient();
1551
+ return toPublicClip(await client.requestRecording());
1552
+ });
1262
1553
  } catch (cause) {
1263
1554
  throw this.captureError(cause);
1264
1555
  }
@@ -1270,8 +1561,9 @@ var Reactor = class {
1270
1561
  // ── Uploads ─────────────────────────────────────────────────────────────
1271
1562
  /**
1272
1563
  * Uploads a file to the session's object store, resolving with a
1273
- * `FileRef` to pass as a top-level value in a `sendCommand()`'s `data`
1274
- * (see `extractFileRefs`). The binding itself takes `(file, name?)`
1564
+ * `FileRef` to pass in a `sendCommand()`'s `data`, at the top level or
1565
+ * inside an array or object (see `extractFileRefs`). The binding itself
1566
+ * takes `(file, name?)`
1275
1567
  * positionally and already applies the right defaulting — a bare
1276
1568
  * `Blob`'s name falls back to `"upload"`, and an empty/missing mime type
1277
1569
  * to `"application/octet-stream"` — so there's nothing to wrap here.
@@ -1345,7 +1637,7 @@ var Reactor = class {
1345
1637
  this.resetConnectionState();
1346
1638
  this.emitter.clear();
1347
1639
  if (client) {
1348
- void this.queue.push(() => client.free(), "dispose").catch(() => {
1640
+ void this.queue.push(() => this.withWriterAccess(() => Promise.resolve(client.free())), "dispose").catch(() => {
1349
1641
  });
1350
1642
  }
1351
1643
  }
@@ -1371,7 +1663,7 @@ var Reactor = class {
1371
1663
  getLastError() {
1372
1664
  return this._lastError;
1373
1665
  }
1374
- /** The most recent WebRTC connection stats, polled every `STATS_INTERVAL_MS`
1666
+ /** The most recent WebRTC connection stats, polled every `LOCAL_STATS_INTERVAL_MS`
1375
1667
  * while "ready" — see `statsUpdate`. `undefined` before the first sample. */
1376
1668
  getStats() {
1377
1669
  return this.stats;
@@ -1521,31 +1813,57 @@ var Reactor = class {
1521
1813
  this.stopStatsPolling();
1522
1814
  }
1523
1815
  }
1816
+ /** Starts both stats pollers: the local one updates `getStats()` and emits
1817
+ * `statsUpdate`, the runtime one sends a client-stats batch. Each owns the
1818
+ * extractor it computes bitrates with, so a bitrate covers its own
1819
+ * poller's interval. */
1524
1820
  startStatsPolling(client) {
1525
1821
  this.stopStatsPolling();
1526
- const generation = ++this.statsPollGeneration;
1527
- const extractStats = createRTCStatsExtractor();
1528
- this.statsPollHandle = setInterval(() => {
1529
- const peerConnection = client.getPeerConnection();
1530
- if (!peerConnection) {
1531
- return;
1532
- }
1533
- peerConnection.getStats().then((report) => {
1534
- if (generation !== this.statsPollGeneration) {
1535
- return;
1536
- }
1537
- this.stats = { ...extractStats(report), connectionTimings: this.connectionTimings };
1822
+ const extractConnectionStats = createConnectionStatsExtractor();
1823
+ const extractTrackStats = createTrackStatsExtractor();
1824
+ this.hasSentConnectTime = false;
1825
+ this.stopStatsPollers = [
1826
+ pollPeerStats(client, LOCAL_STATS_INTERVAL_MS, (report) => {
1827
+ this.stats = { ...extractConnectionStats(report), connectionTimings: this.connectionTimings };
1538
1828
  this.emitter.emit("statsUpdate", this.stats);
1539
- }).catch(() => {
1540
- });
1541
- }, STATS_INTERVAL_MS);
1829
+ }),
1830
+ pollPeerStats(client, RUNTIME_REPORT_INTERVAL_MS, (report) => {
1831
+ this.reportClientStats(client, report, extractTrackStats);
1832
+ })
1833
+ ];
1834
+ }
1835
+ /** Report one quality batch to the runtime: a reading per negotiated
1836
+ * track — audio and video, sent and received — see
1837
+ * `createTrackStatsExtractor`, and the connection-wide reading — see
1838
+ * `toClientConnectionStat`. The connection reading goes even while no
1839
+ * track has one yet (none negotiated onto a named track, or no codec
1840
+ * reported yet), so the runtime gets the bandwidth estimate, the
1841
+ * round-trip time and the time to connect without waiting on the tracks.
1842
+ * Skipped only when there is nothing at all to say; one is due again in
1843
+ * `RUNTIME_REPORT_INTERVAL_MS`. The time to connect goes on the first batch
1844
+ * actually sent for this connection — see `hasSentConnectTime`.
1845
+ * `sendClientStats` throws synchronously on a closing connection; caught
1846
+ * here for the same reason `getStats()`'s rejection is above. */
1847
+ reportClientStats(client, report, extractTrackStats) {
1848
+ const trackStats = extractTrackStats(report, this.trackMapping(), this.pausedTracks());
1849
+ const timeToConnectMs = this.hasSentConnectTime ? void 0 : this.connectionTimings?.totalMs;
1850
+ const connectionStat = toClientConnectionStat(report, timeToConnectMs);
1851
+ if (trackStats.length === 0 && Object.keys(connectionStat.metrics).length === 0) {
1852
+ return;
1853
+ }
1854
+ try {
1855
+ client.sendClientStats(trackStats, connectionStat);
1856
+ if (timeToConnectMs !== void 0) {
1857
+ this.hasSentConnectTime = true;
1858
+ }
1859
+ } catch {
1860
+ }
1542
1861
  }
1543
1862
  stopStatsPolling() {
1544
- this.statsPollGeneration += 1;
1545
- if (this.statsPollHandle !== void 0) {
1546
- clearInterval(this.statsPollHandle);
1547
- this.statsPollHandle = void 0;
1863
+ for (const stop of this.stopStatsPollers) {
1864
+ stop();
1548
1865
  }
1866
+ this.stopStatsPollers = [];
1549
1867
  this.stats = void 0;
1550
1868
  }
1551
1869
  /** Called on every `disconnect()` and on `[Symbol.dispose]`. Leaves