@reactor-team/js-sdk 2.9.2 → 2.10.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.mjs CHANGED
@@ -83,8 +83,24 @@ import { z } from "zod";
83
83
  // package.json
84
84
  var package_default = {
85
85
  name: "@reactor-team/js-sdk",
86
- version: "2.9.2",
87
- description: "Reactor JavaScript frontend SDK",
86
+ version: "2.10.0",
87
+ description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
88
+ license: "MIT",
89
+ repository: {
90
+ type: "git",
91
+ url: "https://github.com/reactor-team/js-sdk.git"
92
+ },
93
+ keywords: [
94
+ "reactor",
95
+ "sdk",
96
+ "frontend",
97
+ "react",
98
+ "webrtc",
99
+ "real-time",
100
+ "video",
101
+ "ai"
102
+ ],
103
+ author: "Reactor Technologies, Inc.",
88
104
  main: "dist/index.js",
89
105
  module: "dist/index.mjs",
90
106
  types: "dist/index.d.ts",
@@ -95,6 +111,10 @@ var package_default = {
95
111
  require: "./dist/index.js"
96
112
  }
97
113
  },
114
+ sideEffects: false,
115
+ engines: {
116
+ node: ">=18"
117
+ },
98
118
  files: [
99
119
  "dist",
100
120
  "README.md"
@@ -109,44 +129,34 @@ var package_default = {
109
129
  format: "prettier --write .",
110
130
  "format:check": "prettier --check ."
111
131
  },
112
- keywords: [
113
- "reactor",
114
- "frontend",
115
- "sdk"
116
- ],
117
- author: "Reactor Technologies, Inc.",
118
132
  reactor: {
119
133
  apiVersion: 1,
120
134
  webrtcVersion: "1.0"
121
135
  },
122
- license: "MIT",
123
- repository: {
124
- type: "git",
125
- url: "https://github.com/reactor-team/js-sdk.git"
126
- },
127
136
  packageManager: "pnpm@10.12.1",
137
+ dependencies: {
138
+ "sdp-transform": "^3.0.0",
139
+ zod: "^4.0.5"
140
+ },
141
+ peerDependencies: {
142
+ "hls.js": "^1.6.0",
143
+ react: "^17.0.0 || ^18.0.0 || ^19.0.0",
144
+ zustand: "^5.0.6"
145
+ },
146
+ peerDependenciesMeta: {
147
+ "hls.js": {
148
+ optional: true
149
+ }
150
+ },
128
151
  devDependencies: {
129
152
  "@roamhq/wrtc": "^0.8.0",
130
- "@types/inquirer": "^9.0.9",
131
153
  "@types/node": "^20",
132
154
  "@types/react": "^18.2.8",
133
- "@types/ws": "^8.18.1",
155
+ "hls.js": "^1.6.0",
134
156
  prettier: "^3.6.2",
135
157
  tsup: "^8.5.0",
136
158
  typescript: "^5.8.3",
137
159
  vitest: "^3.0.0"
138
- },
139
- dependencies: {
140
- "@bufbuild/protobuf": "^2.0.0",
141
- chalk: "^5.3.0",
142
- inquirer: "^9.3.0",
143
- "simple-git": "^3.24.0",
144
- ws: "^8.18.3",
145
- zod: "^4.0.5"
146
- },
147
- peerDependencies: {
148
- react: "^17.0.0 || ^18.0.0 || ^19.0.0",
149
- zustand: "^5.0.6"
150
160
  }
151
161
  };
152
162
 
@@ -691,6 +701,377 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
691
701
  }
692
702
  };
693
703
 
704
+ // src/utils/sdp.ts
705
+ import { parse, parsePayloads } from "sdp-transform";
706
+ function sdpLineSeparator(sdp) {
707
+ return sdp.includes("\r\n") ? "\r\n" : "\n";
708
+ }
709
+ function splitSdpLines(sdp) {
710
+ return sdp.split(/\r?\n/);
711
+ }
712
+ function joinSdpLines(lines, sep) {
713
+ return lines.join(sep);
714
+ }
715
+ var DYNAMIC_PT_MIN = 96;
716
+ var DYNAMIC_PT_MAX = 127;
717
+ function isSanitizedVideoCodecRtpmapEncoding(name) {
718
+ const u = name.toUpperCase();
719
+ if (/^(H265|HEVC|HEV1|HVC1)/.test(u)) return true;
720
+ if (/^VP8(\/|$)/.test(u)) return true;
721
+ if (/^VP9(\/|$)/.test(u)) return true;
722
+ if (/^H264(\/|$)/.test(u)) return true;
723
+ return false;
724
+ }
725
+ function isOpusRtpmapEncoding(name) {
726
+ return /^OPUS(\/|$)/i.test(name);
727
+ }
728
+ function mediaMLinePayloadTypes(media) {
729
+ var _a;
730
+ return parsePayloads(String((_a = media.payloads) != null ? _a : ""));
731
+ }
732
+ function collectRtpmap(media) {
733
+ var _a;
734
+ const rtpmap = /* @__PURE__ */ new Map();
735
+ for (const r of (_a = media.rtp) != null ? _a : []) {
736
+ rtpmap.set(Number(r.payload), String(r.codec));
737
+ }
738
+ return rtpmap;
739
+ }
740
+ function collectSanitizedCodecPayloadSet(media) {
741
+ const rtpmap = collectRtpmap(media);
742
+ const tracked = /* @__PURE__ */ new Set();
743
+ if (media.type === "video") {
744
+ for (const [pt, enc] of rtpmap) {
745
+ if (isSanitizedVideoCodecRtpmapEncoding(enc)) tracked.add(pt);
746
+ }
747
+ } else if (media.type === "audio") {
748
+ for (const [pt, enc] of rtpmap) {
749
+ if (isOpusRtpmapEncoding(enc)) tracked.add(pt);
750
+ }
751
+ }
752
+ return tracked.size > 0 ? tracked : null;
753
+ }
754
+ function mediaSectionNeedsSanitizedPtRelocate(media) {
755
+ const pts = collectSanitizedCodecPayloadSet(media);
756
+ if (!pts) {
757
+ return false;
758
+ }
759
+ return [...pts].some((p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX);
760
+ }
761
+ function codecRelocationPriority(enc) {
762
+ const u = (enc != null ? enc : "").toUpperCase();
763
+ if (/^(H265|HEVC|HEV1|HVC1)/.test(u)) return 0;
764
+ if (/^H264(\/|$)/.test(u)) return 1;
765
+ if (/^VP9(\/|$)/.test(u)) return 2;
766
+ if (/^VP8(\/|$)/.test(u)) return 3;
767
+ if (/^OPUS(\/|$)/.test(u)) return 4;
768
+ return 5;
769
+ }
770
+ function sortedRelocate(relocate, rtpmap) {
771
+ return [...relocate].sort(
772
+ (a, b) => codecRelocationPriority(rtpmap.get(a)) - codecRelocationPriority(rtpmap.get(b))
773
+ );
774
+ }
775
+ function remapFmtpConfigForPayloadMap(config, remap) {
776
+ let s = config;
777
+ const pairs = [...remap.entries()].sort((a, b) => b[0] - a[0]);
778
+ for (const [oldP, newP] of pairs) {
779
+ if (oldP === newP) continue;
780
+ s = s.replace(new RegExp(`apt=${oldP}([^0-9]|$)`, "g"), `apt=${newP}$1`);
781
+ }
782
+ return s;
783
+ }
784
+ function computeCodecRemapForMedia(media, forbidden) {
785
+ const remap = /* @__PURE__ */ new Map();
786
+ if (media.type !== "video" && media.type !== "audio") {
787
+ return remap;
788
+ }
789
+ const tracked = collectSanitizedCodecPayloadSet(media);
790
+ if (!tracked) {
791
+ return remap;
792
+ }
793
+ const relocate = [...tracked].filter(
794
+ (p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX
795
+ );
796
+ if (relocate.length === 0) {
797
+ return remap;
798
+ }
799
+ const rtpmap = collectRtpmap(media);
800
+ const ordered = sortedRelocate(relocate, rtpmap);
801
+ const usedPts = new Set(forbidden);
802
+ for (const p of mediaMLinePayloadTypes(media)) {
803
+ if (p >= DYNAMIC_PT_MIN && p <= DYNAMIC_PT_MAX) usedPts.add(p);
804
+ }
805
+ let candidate = DYNAMIC_PT_MIN;
806
+ for (const oldPt of ordered) {
807
+ while (candidate <= DYNAMIC_PT_MAX && usedPts.has(candidate)) candidate++;
808
+ if (candidate > DYNAMIC_PT_MAX) break;
809
+ remap.set(oldPt, candidate);
810
+ usedPts.add(candidate);
811
+ candidate++;
812
+ }
813
+ return remap;
814
+ }
815
+ function rewriteRtpSavpfMPayloads(mLine, mapPt) {
816
+ if (!/\bRTP\/SAVPF\b/.test(mLine)) {
817
+ return mLine;
818
+ }
819
+ const tokens = mLine.split(/\s+/);
820
+ if (tokens.length < 4) {
821
+ return mLine;
822
+ }
823
+ const head = tokens.slice(0, 3).join(" ");
824
+ const tail = tokens.slice(3).map((t) => /^\d+$/.test(t) ? String(mapPt(Number(t))) : t);
825
+ return `${head} ${tail.join(" ")}`;
826
+ }
827
+ function payloadTypesFromSavpfMLine(mLine) {
828
+ const m = /\bRTP\/SAVPF\s+(.+)$/i.exec(mLine);
829
+ return m ? parsePayloads(m[1].trim()) : [];
830
+ }
831
+ function payloadTypeFromPtBoundAttributeLine(line) {
832
+ if (line.startsWith("a=rtpmap:")) {
833
+ const x = /^a=rtpmap:(\d+)/i.exec(line);
834
+ return x ? Number(x[1]) : null;
835
+ }
836
+ if (line.startsWith("a=fmtp:")) {
837
+ const x = /^a=fmtp:(\d+)/i.exec(line);
838
+ return x ? Number(x[1]) : null;
839
+ }
840
+ if (line.startsWith("a=rtcp-fb:")) {
841
+ const x = /^a=rtcp-fb:(\*|(\d+))/i.exec(line);
842
+ if (!x || x[1] === "*") return null;
843
+ return Number(x[2]);
844
+ }
845
+ if (line.startsWith("a=rtcp-fb-trr-int:")) {
846
+ const x = /^a=rtcp-fb-trr-int:(\*|(\d+))/i.exec(line);
847
+ if (!x || x[1] === "*") return null;
848
+ return Number(x[2]);
849
+ }
850
+ if (line.startsWith("a=imageattrs:")) {
851
+ const x = /^a=imageattrs:(\*|(\d+))/i.exec(line);
852
+ if (!x || x[1] === "*") return null;
853
+ return Number(x[2]);
854
+ }
855
+ return null;
856
+ }
857
+ function isPtBoundCodecAttributeLine(line) {
858
+ return payloadTypeFromPtBoundAttributeLine(line) !== null;
859
+ }
860
+ function reorderSingleRtpSavpfSection(sec) {
861
+ const mLine = sec[0];
862
+ if (!/\bRTP\/SAVPF\b/.test(mLine)) {
863
+ return sec;
864
+ }
865
+ const body = sec.slice(1);
866
+ let first = -1;
867
+ let last = -1;
868
+ for (let j = 0; j < body.length; j++) {
869
+ if (isPtBoundCodecAttributeLine(body[j])) {
870
+ if (first === -1) first = j;
871
+ last = j;
872
+ }
873
+ }
874
+ if (first === -1) {
875
+ return sec;
876
+ }
877
+ const prefix = body.slice(0, first);
878
+ const codecLines = body.slice(first, last + 1);
879
+ const suffix = body.slice(last + 1);
880
+ const mPts = payloadTypesFromSavpfMLine(mLine);
881
+ const buckets = /* @__PURE__ */ new Map();
882
+ for (const line of codecLines) {
883
+ const pt = payloadTypeFromPtBoundAttributeLine(line);
884
+ if (pt === null) continue;
885
+ const arr = buckets.get(pt);
886
+ if (arr) arr.push(line);
887
+ else buckets.set(pt, [line]);
888
+ }
889
+ const seenOrder = [];
890
+ for (const line of codecLines) {
891
+ const pt = payloadTypeFromPtBoundAttributeLine(line);
892
+ if (pt !== null && !seenOrder.includes(pt)) seenOrder.push(pt);
893
+ }
894
+ const outCodec = [];
895
+ for (const pt of mPts) {
896
+ const arr = buckets.get(pt);
897
+ if (!arr) continue;
898
+ outCodec.push(...arr);
899
+ buckets.delete(pt);
900
+ }
901
+ for (const pt of seenOrder) {
902
+ const arr = buckets.get(pt);
903
+ if (!arr) continue;
904
+ outCodec.push(...arr);
905
+ buckets.delete(pt);
906
+ }
907
+ for (const arr of buckets.values()) {
908
+ outCodec.push(...arr);
909
+ }
910
+ return [mLine, ...prefix, ...outCodec, ...suffix];
911
+ }
912
+ function reorderCodecAttributes(sdp) {
913
+ const sep = sdpLineSeparator(sdp);
914
+ const lines = splitSdpLines(sdp);
915
+ const out = [];
916
+ let i = 0;
917
+ while (i < lines.length) {
918
+ const line = lines[i];
919
+ if (!line.startsWith("m=")) {
920
+ out.push(line);
921
+ i++;
922
+ continue;
923
+ }
924
+ const mLine = line;
925
+ i++;
926
+ const rest = [];
927
+ while (i < lines.length && !lines[i].startsWith("m=")) {
928
+ rest.push(lines[i]);
929
+ i++;
930
+ }
931
+ out.push(...reorderSingleRtpSavpfSection([mLine, ...rest]));
932
+ }
933
+ return joinSdpLines(out, sep);
934
+ }
935
+ function applyRemapToMediaAttributeLine(line, remap) {
936
+ var _a, _b, _c, _d, _e, _f, _g, _h;
937
+ if (!line.startsWith("a=")) {
938
+ return line;
939
+ }
940
+ if (line.startsWith("a=rtpmap:")) {
941
+ const m = /^a=rtpmap:(\d+)/.exec(line);
942
+ if (!m) return line;
943
+ const pt = Number(m[1]);
944
+ const np = (_a = remap.get(pt)) != null ? _a : pt;
945
+ return np === pt ? line : line.replace(/^a=rtpmap:\d+/, `a=rtpmap:${np}`);
946
+ }
947
+ if (line.startsWith("a=fmtp:")) {
948
+ const m = /^a=fmtp:(\d+)\s(.*)$/.exec(line);
949
+ if (!m) return line;
950
+ const pt = Number(m[1]);
951
+ const np = (_b = remap.get(pt)) != null ? _b : pt;
952
+ const cfg = remapFmtpConfigForPayloadMap(m[2], remap);
953
+ return `a=fmtp:${np} ${cfg}`;
954
+ }
955
+ if (line.startsWith("a=rtcp-fb:")) {
956
+ const m = /^a=rtcp-fb:(\*|\d+)(\s.*)?$/.exec(line);
957
+ if (!m || m[1] === "*") return line;
958
+ const pt = Number(m[1]);
959
+ const np = (_c = remap.get(pt)) != null ? _c : pt;
960
+ return np === pt ? line : `a=rtcp-fb:${np}${(_d = m[2]) != null ? _d : ""}`;
961
+ }
962
+ if (line.startsWith("a=rtcp-fb-trr-int:")) {
963
+ const m = /^a=rtcp-fb-trr-int:(\*|\d+)(\s.*)?$/.exec(line);
964
+ if (!m || m[1] === "*") return line;
965
+ const pt = Number(m[1]);
966
+ const np = (_e = remap.get(pt)) != null ? _e : pt;
967
+ return np === pt ? line : `a=rtcp-fb-trr-int:${np}${(_f = m[2]) != null ? _f : ""}`;
968
+ }
969
+ if (line.startsWith("a=imageattrs:")) {
970
+ const m = /^a=imageattrs:(\*|\d+)(\s.*)?$/.exec(line);
971
+ if (!m || m[1] === "*") return line;
972
+ const pt = Number(m[1]);
973
+ const np = (_g = remap.get(pt)) != null ? _g : pt;
974
+ return np === pt ? line : `a=imageattrs:${np}${(_h = m[2]) != null ? _h : ""}`;
975
+ }
976
+ return line;
977
+ }
978
+ function stripTelephoneEventsPreserveOrder(sdp) {
979
+ const session = parse(sdp);
980
+ const telPerSection = session.media.map((media) => {
981
+ var _a;
982
+ const tel = /* @__PURE__ */ new Set();
983
+ for (const r of (_a = media.rtp) != null ? _a : []) {
984
+ if (/^telephone-event$/i.test(String(r.codec))) {
985
+ tel.add(Number(r.payload));
986
+ }
987
+ }
988
+ return tel;
989
+ });
990
+ if (!telPerSection.some((s) => s.size > 0)) {
991
+ return sdp;
992
+ }
993
+ const sep = sdpLineSeparator(sdp);
994
+ const lines = splitSdpLines(sdp);
995
+ let secIdx = -1;
996
+ const out = [];
997
+ for (const line of lines) {
998
+ if (line.startsWith("m=")) {
999
+ secIdx++;
1000
+ const drop = telPerSection[secIdx];
1001
+ if (!drop || drop.size === 0 || !/\bRTP\/SAVPF\b/.test(line)) {
1002
+ out.push(line);
1003
+ continue;
1004
+ }
1005
+ const tokens = line.split(/\s+/);
1006
+ const head = tokens.slice(0, 3).join(" ");
1007
+ const nums = tokens.slice(3).filter((t) => /^\d+$/.test(t)).map(Number).filter((p) => !drop.has(p));
1008
+ out.push(`${head} ${nums.join(" ")}`);
1009
+ continue;
1010
+ }
1011
+ if (secIdx >= 0) {
1012
+ const drop = telPerSection[secIdx];
1013
+ if (drop && drop.size > 0) {
1014
+ const rtp = /^a=rtpmap:(\d+)\s/i.exec(line);
1015
+ if (rtp && drop.has(Number(rtp[1]))) continue;
1016
+ const fmtp = /^a=fmtp:(\d+)\s/i.exec(line);
1017
+ if (fmtp && drop.has(Number(fmtp[1]))) continue;
1018
+ const rfb = /^a=rtcp-fb:(\d+)\s/i.exec(line);
1019
+ if (rfb && drop.has(Number(rfb[1]))) continue;
1020
+ const trr = /^a=rtcp-fb-trr-int:(\d+)\s/i.exec(line);
1021
+ if (trr && drop.has(Number(trr[1]))) continue;
1022
+ }
1023
+ }
1024
+ out.push(line);
1025
+ }
1026
+ return joinSdpLines(out, sep);
1027
+ }
1028
+ function transformOfferSdpCodecDynamicPts(sdp) {
1029
+ var _a;
1030
+ const session = parse(sdp);
1031
+ if (!session.media.some(mediaSectionNeedsSanitizedPtRelocate)) {
1032
+ return sdp;
1033
+ }
1034
+ const remaps = [];
1035
+ const forbidden = /* @__PURE__ */ new Set();
1036
+ for (const media of session.media) {
1037
+ const R = computeCodecRemapForMedia(media, forbidden);
1038
+ remaps.push(R);
1039
+ for (const p of mediaMLinePayloadTypes(media)) {
1040
+ forbidden.add((_a = R.get(p)) != null ? _a : p);
1041
+ }
1042
+ }
1043
+ const sep = sdpLineSeparator(sdp);
1044
+ const lines = splitSdpLines(sdp);
1045
+ let secIdx = -1;
1046
+ const out = [];
1047
+ for (let line of lines) {
1048
+ if (line.startsWith("m=")) {
1049
+ secIdx++;
1050
+ const R2 = remaps[secIdx];
1051
+ if (R2.size > 0 && /\bRTP\/SAVPF\b/.test(line)) {
1052
+ line = rewriteRtpSavpfMPayloads(line, (p) => {
1053
+ var _a2;
1054
+ return (_a2 = R2.get(p)) != null ? _a2 : p;
1055
+ });
1056
+ }
1057
+ out.push(line);
1058
+ continue;
1059
+ }
1060
+ const R = secIdx >= 0 ? remaps[secIdx] : null;
1061
+ if (!R || R.size === 0) {
1062
+ out.push(line);
1063
+ continue;
1064
+ }
1065
+ out.push(applyRemapToMediaAttributeLine(line, R));
1066
+ }
1067
+ return joinSdpLines(out, sep);
1068
+ }
1069
+ function sanitize(sdp) {
1070
+ const stripped = stripTelephoneEventsPreserveOrder(sdp);
1071
+ const remapped = transformOfferSdpCodecDynamicPts(stripped);
1072
+ return reorderCodecAttributes(remapped);
1073
+ }
1074
+
694
1075
  // src/utils/webrtc.ts
695
1076
  var DEFAULT_DATA_CHANNEL_LABEL = "data";
696
1077
  var FORCE_RELAY_MODE = false;
@@ -706,8 +1087,12 @@ function createDataChannel(pc, label) {
706
1087
  }
707
1088
  function createOffer(pc) {
708
1089
  return __async(this, null, function* () {
709
- const offer = yield pc.createOffer();
710
- yield pc.setLocalDescription(offer);
1090
+ var _a;
1091
+ const initial = yield pc.createOffer();
1092
+ const sdp = sanitize((_a = initial.sdp) != null ? _a : "");
1093
+ yield pc.setLocalDescription(
1094
+ new RTCSessionDescription({ type: initial.type, sdp })
1095
+ );
711
1096
  yield waitForIceGathering(pc);
712
1097
  const localDescription = pc.localDescription;
713
1098
  if (!localDescription) {
@@ -791,50 +1176,78 @@ function parseMessage(data) {
791
1176
  function closePeerConnection(pc) {
792
1177
  pc.close();
793
1178
  }
794
- function extractConnectionStats(report) {
795
- let rtt;
796
- let availableOutgoingBitrate;
797
- let localCandidateId;
798
- let framesPerSecond;
799
- let jitter;
800
- let packetLossRatio;
801
- report.forEach((stat) => {
802
- if (stat.type === "candidate-pair" && stat.state === "succeeded") {
803
- if (stat.currentRoundTripTime !== void 0) {
804
- rtt = stat.currentRoundTripTime * 1e3;
805
- }
806
- if (stat.availableOutgoingBitrate !== void 0) {
807
- availableOutgoingBitrate = stat.availableOutgoingBitrate;
808
- }
809
- localCandidateId = stat.localCandidateId;
810
- }
811
- if (stat.type === "inbound-rtp" && stat.kind === "video") {
812
- if (stat.framesPerSecond !== void 0) {
813
- framesPerSecond = stat.framesPerSecond;
814
- }
815
- if (stat.jitter !== void 0) {
816
- jitter = stat.jitter;
1179
+ function createRTCStatsExtractor() {
1180
+ let lastBytesReceived;
1181
+ let lastBytesSent;
1182
+ let lastCandPairTimestamp;
1183
+ return (report) => {
1184
+ let candPairId;
1185
+ let rtt;
1186
+ let availableOutgoingBitrate;
1187
+ let availableIncomingBitrate;
1188
+ let incomingBitrate;
1189
+ let outgoingBitrate;
1190
+ let videoInboundRtpId;
1191
+ let framesPerSecond;
1192
+ let jitter;
1193
+ let packetLossRatio;
1194
+ let candidateType;
1195
+ report.forEach((stat) => {
1196
+ if (candPairId === void 0 && stat.type === "candidate-pair" && stat.state === "succeeded" && stat.nominated) {
1197
+ candPairId = stat.id;
1198
+ if (stat.currentRoundTripTime !== void 0) {
1199
+ rtt = stat.currentRoundTripTime * 1e3;
1200
+ }
1201
+ if (stat.availableOutgoingBitrate !== void 0) {
1202
+ availableOutgoingBitrate = stat.availableOutgoingBitrate;
1203
+ }
1204
+ if (stat.availableIncomingBitrate != void 0) {
1205
+ availableIncomingBitrate = stat.availableIncomingBitrate;
1206
+ }
1207
+ const localCandidate = report.get(stat.localCandidateId);
1208
+ if (localCandidate == null ? void 0 : localCandidate.candidateType) {
1209
+ candidateType = localCandidate.candidateType;
1210
+ }
1211
+ const timeDiff = lastCandPairTimestamp !== void 0 ? stat.timestamp - lastCandPairTimestamp : 0;
1212
+ if (stat.bytesReceived !== void 0) {
1213
+ if (lastBytesReceived !== void 0 && timeDiff > 0) {
1214
+ incomingBitrate = (stat.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
1215
+ }
1216
+ lastBytesReceived = stat.bytesReceived;
1217
+ }
1218
+ if (stat.bytesSent !== void 0) {
1219
+ if (lastBytesSent !== void 0 && timeDiff > 0) {
1220
+ outgoingBitrate = (stat.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
1221
+ }
1222
+ lastBytesSent = stat.bytesSent;
1223
+ }
1224
+ lastCandPairTimestamp = stat.timestamp;
817
1225
  }
818
- if (stat.packetsReceived !== void 0 && stat.packetsLost !== void 0 && stat.packetsReceived + stat.packetsLost > 0) {
819
- packetLossRatio = stat.packetsLost / (stat.packetsReceived + stat.packetsLost);
1226
+ if (videoInboundRtpId === void 0 && stat.type === "inbound-rtp" && stat.kind === "video") {
1227
+ videoInboundRtpId = stat.id;
1228
+ if (stat.framesPerSecond !== void 0) {
1229
+ framesPerSecond = stat.framesPerSecond;
1230
+ }
1231
+ if (stat.jitter !== void 0) {
1232
+ jitter = stat.jitter;
1233
+ }
1234
+ if (stat.packetsReceived !== void 0 && stat.packetsLost !== void 0 && stat.packetsReceived + stat.packetsLost > 0) {
1235
+ packetLossRatio = stat.packetsLost / (stat.packetsReceived + stat.packetsLost);
1236
+ }
820
1237
  }
821
- }
822
- });
823
- let candidateType;
824
- if (localCandidateId) {
825
- const localCandidate = report.get(localCandidateId);
826
- if (localCandidate == null ? void 0 : localCandidate.candidateType) {
827
- candidateType = localCandidate.candidateType;
828
- }
829
- }
830
- return {
831
- rtt,
832
- candidateType,
833
- availableOutgoingBitrate,
834
- framesPerSecond,
835
- packetLossRatio,
836
- jitter,
837
- timestamp: Date.now()
1238
+ });
1239
+ return {
1240
+ rtt,
1241
+ candidateType,
1242
+ availableIncomingBitrate,
1243
+ availableOutgoingBitrate,
1244
+ incomingBitrate,
1245
+ outgoingBitrate,
1246
+ framesPerSecond,
1247
+ packetLossRatio,
1248
+ jitter,
1249
+ timestamp: Date.now()
1250
+ };
838
1251
  };
839
1252
  }
840
1253
 
@@ -1265,11 +1678,12 @@ var WebRTCTransportClient = class {
1265
1678
  }
1266
1679
  startStatsPolling() {
1267
1680
  this.stopStatsPolling();
1681
+ const statsExtractor = createRTCStatsExtractor();
1268
1682
  this.statsInterval = setInterval(() => __async(this, null, function* () {
1269
1683
  if (!this.peerConnection) return;
1270
1684
  try {
1271
1685
  const report = yield this.peerConnection.getStats();
1272
- this.stats = extractConnectionStats(report);
1686
+ this.stats = statsExtractor(report);
1273
1687
  this.emit("statsUpdate", this.stats);
1274
1688
  } catch (e) {
1275
1689
  }
@@ -1419,19 +1833,542 @@ var WebRTCTransportClient = class {
1419
1833
  };
1420
1834
 
1421
1835
  // src/core/Reactor.ts
1836
+ import { z as z3 } from "zod";
1837
+
1838
+ // src/utils/recording.ts
1422
1839
  import { z as z2 } from "zod";
1840
+ var RuntimeRecordingMessageType = {
1841
+ REQUEST_CLIP: "requestClip",
1842
+ REQUEST_RECORDING: "requestRecording",
1843
+ CLIP_READY: "clipReady",
1844
+ CLIP_FAILED: "clipFailed"
1845
+ };
1846
+ var RecordingError = class extends Error {
1847
+ constructor(code, reason) {
1848
+ super(`${code}: ${reason}`);
1849
+ this.code = code;
1850
+ this.reason = reason;
1851
+ this.name = "RecordingError";
1852
+ }
1853
+ };
1854
+ var ClipReadyPayloadSchema = z2.object({
1855
+ session_id: z2.string(),
1856
+ kind: z2.enum(["snap", "recording"]),
1857
+ start_marker: z2.number(),
1858
+ end_marker: z2.number(),
1859
+ now_marker: z2.number(),
1860
+ predicted_ready_at_ms: z2.number(),
1861
+ playlist_url: z2.string()
1862
+ }).passthrough();
1863
+ var ClipFailedPayloadSchema = z2.object({
1864
+ reason: z2.string().default("unknown")
1865
+ }).passthrough();
1866
+ function clipFromPayload(payload, options = {}) {
1867
+ const playlistUrl = options.coordinatorBaseUrl ? rewriteUrlHost(payload.playlist_url, options.coordinatorBaseUrl) : payload.playlist_url;
1868
+ return {
1869
+ sessionId: payload.session_id,
1870
+ kind: payload.kind,
1871
+ startMarker: payload.start_marker,
1872
+ endMarker: payload.end_marker,
1873
+ nowMarker: payload.now_marker,
1874
+ predictedReadyAtMs: payload.predicted_ready_at_ms,
1875
+ playlistUrl
1876
+ };
1877
+ }
1878
+ function rewriteUrlHost(target, base) {
1879
+ try {
1880
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(target)) {
1881
+ return new URL(target, base).toString();
1882
+ }
1883
+ const baseUrl = new URL(base);
1884
+ const parsed = new URL(target);
1885
+ parsed.protocol = baseUrl.protocol;
1886
+ parsed.hostname = baseUrl.hostname;
1887
+ parsed.port = baseUrl.port;
1888
+ return parsed.toString();
1889
+ } catch (e) {
1890
+ return target;
1891
+ }
1892
+ }
1893
+ var DEFAULT_PLAYLIST_POLL_SLACK_MS = 15e3;
1894
+ function fetchPlaylist(_0) {
1895
+ return __async(this, arguments, function* (playlistUrl, options = {}) {
1896
+ var _a, _b, _c, _d;
1897
+ const slackMs = (_a = options.slackMs) != null ? _a : DEFAULT_PLAYLIST_POLL_SLACK_MS;
1898
+ const minDelay = Math.max(0, (_b = options.minRetryDelayMs) != null ? _b : 200);
1899
+ const maxDelay = Math.max(minDelay, (_c = options.maxRetryDelayMs) != null ? _c : 2e3);
1900
+ const fallbackMaxRetries = (_d = options.maxRetries) != null ? _d : 5;
1901
+ const hasDeadline = typeof options.predictedReadyAtMs === "number";
1902
+ const startedPollingAt = Date.now();
1903
+ const deadlineMs = hasDeadline ? Math.max(options.predictedReadyAtMs, startedPollingAt) + slackMs : void 0;
1904
+ const headers = options.jwt ? { Authorization: `Bearer ${options.jwt}` } : void 0;
1905
+ let attempt = 0;
1906
+ let lastStatus = 0;
1907
+ while (true) {
1908
+ let response;
1909
+ try {
1910
+ response = yield fetch(playlistUrl, {
1911
+ signal: options.signal,
1912
+ headers
1913
+ });
1914
+ } catch (error) {
1915
+ throw new RecordingError(
1916
+ "PLAYLIST_FETCH_FAILED",
1917
+ `Network error fetching playlist: ${error.message}`
1918
+ );
1919
+ }
1920
+ lastStatus = response.status;
1921
+ if (response.status === 202) {
1922
+ if (hasDeadline) {
1923
+ if (Date.now() >= deadlineMs) {
1924
+ throw new RecordingError(
1925
+ "CLIP_NOT_READY",
1926
+ `Boundary chunk still pending after ${slackMs}ms grace (predicted ready ${new Date(
1927
+ options.predictedReadyAtMs
1928
+ ).toISOString()}). Runtime may have crashed mid-clip.`
1929
+ );
1930
+ }
1931
+ } else if (attempt >= fallbackMaxRetries) {
1932
+ throw new RecordingError(
1933
+ "CLIP_NOT_READY",
1934
+ `Manifest still pending after ${attempt + 1} attempts (last status ${lastStatus})`
1935
+ );
1936
+ }
1937
+ const headerDelay = parseRetryAfter(
1938
+ response.headers.get("Retry-After"),
1939
+ minDelay
1940
+ );
1941
+ const delay = Math.min(maxDelay, Math.max(minDelay, headerDelay));
1942
+ const clampedDelay = hasDeadline ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;
1943
+ yield sleep(clampedDelay, options.signal);
1944
+ attempt++;
1945
+ continue;
1946
+ }
1947
+ if (response.status === 200) {
1948
+ return yield response.text();
1949
+ }
1950
+ if (response.status === 410) {
1951
+ throw new RecordingError(
1952
+ "CLIP_GONE",
1953
+ "Clip is no longer available (chunks aged out or session unknown)"
1954
+ );
1955
+ }
1956
+ if (response.status === 404) {
1957
+ throw new RecordingError(
1958
+ "CLIP_GONE",
1959
+ "Session not found for clip playlist"
1960
+ );
1961
+ }
1962
+ throw new RecordingError(
1963
+ "PLAYLIST_FETCH_FAILED",
1964
+ `Manifest endpoint returned HTTP ${response.status}`
1965
+ );
1966
+ }
1967
+ });
1968
+ }
1969
+ function parsePlaylist(manifestBody, playlistUrl) {
1970
+ let initUrl;
1971
+ const segments = [];
1972
+ const lines = manifestBody.split(/\r?\n/);
1973
+ for (const line of lines) {
1974
+ const trimmed = line.trim();
1975
+ if (!trimmed) continue;
1976
+ if (trimmed.startsWith("#EXT-X-MAP")) {
1977
+ const match = trimmed.match(/URI="([^"]+)"/);
1978
+ if (match) {
1979
+ initUrl = resolveAgainst(match[1], playlistUrl);
1980
+ }
1981
+ continue;
1982
+ }
1983
+ if (trimmed.startsWith("#")) {
1984
+ continue;
1985
+ }
1986
+ segments.push(resolveAgainst(trimmed, playlistUrl));
1987
+ }
1988
+ if (!initUrl) {
1989
+ throw new RecordingError(
1990
+ "INVALID_PLAYLIST",
1991
+ "Playlist is missing an #EXT-X-MAP init segment URI"
1992
+ );
1993
+ }
1994
+ if (segments.length === 0) {
1995
+ throw new RecordingError(
1996
+ "INVALID_PLAYLIST",
1997
+ "Playlist contains no media segments"
1998
+ );
1999
+ }
2000
+ return { initUrl, segmentUrls: segments };
2001
+ }
2002
+ function createPlayableManifestUrl(manifestBody, playlistUrl) {
2003
+ if (typeof Blob === "undefined" || typeof URL === "undefined" || typeof URL.createObjectURL !== "function") {
2004
+ throw new RecordingError(
2005
+ "INVALID_PLAYLIST",
2006
+ "createPlayableManifestUrl requires a browser environment with URL.createObjectURL"
2007
+ );
2008
+ }
2009
+ const rewritten = absolutizeManifestUrls(manifestBody, playlistUrl);
2010
+ const blob = new Blob([rewritten], {
2011
+ type: "application/vnd.apple.mpegurl"
2012
+ });
2013
+ return URL.createObjectURL(blob);
2014
+ }
2015
+ function absolutizeManifestUrls(manifestBody, playlistUrl) {
2016
+ const eol = manifestBody.includes("\r\n") ? "\r\n" : "\n";
2017
+ const lines = manifestBody.split(/\r?\n/);
2018
+ const out = [];
2019
+ for (const line of lines) {
2020
+ if (line.startsWith("#EXT-X-MAP")) {
2021
+ out.push(
2022
+ line.replace(
2023
+ /URI="([^"]+)"/,
2024
+ (_, uri) => `URI="${resolveAgainst(uri, playlistUrl)}"`
2025
+ )
2026
+ );
2027
+ continue;
2028
+ }
2029
+ const trimmed = line.trim();
2030
+ if (!trimmed || trimmed.startsWith("#")) {
2031
+ out.push(line);
2032
+ continue;
2033
+ }
2034
+ out.push(resolveAgainst(trimmed, playlistUrl));
2035
+ }
2036
+ return out.join(eol);
2037
+ }
2038
+ function downloadClipAsFile(_0) {
2039
+ return __async(this, arguments, function* (clip, filename = "reactor-clip.mp4", options = {}) {
2040
+ var _a;
2041
+ const manifestBody = yield fetchPlaylist(clip.playlistUrl, {
2042
+ predictedReadyAtMs: clip.predictedReadyAtMs,
2043
+ signal: options.signal,
2044
+ jwt: options.jwt
2045
+ });
2046
+ const { initUrl, segmentUrls } = parsePlaylist(
2047
+ manifestBody,
2048
+ clip.playlistUrl
2049
+ );
2050
+ const orderedUrls = [initUrl, ...segmentUrls];
2051
+ const parts = [];
2052
+ let bytes = 0;
2053
+ for (let i = 0; i < orderedUrls.length; i++) {
2054
+ const url = orderedUrls[i];
2055
+ let response;
2056
+ try {
2057
+ response = yield fetch(url, { signal: options.signal });
2058
+ } catch (error) {
2059
+ throw new RecordingError(
2060
+ "CHUNK_FETCH_FAILED",
2061
+ `Network error fetching chunk ${i}: ${error.message}`
2062
+ );
2063
+ }
2064
+ if (!response.ok) {
2065
+ throw new RecordingError(
2066
+ "CHUNK_FETCH_FAILED",
2067
+ `Chunk ${i} returned HTTP ${response.status}`
2068
+ );
2069
+ }
2070
+ const data = yield response.arrayBuffer();
2071
+ parts.push(data);
2072
+ bytes += data.byteLength;
2073
+ (_a = options.onProgress) == null ? void 0 : _a.call(options, {
2074
+ fetched: i + 1,
2075
+ total: orderedUrls.length,
2076
+ bytes
2077
+ });
2078
+ }
2079
+ const blob = new Blob(parts, { type: "video/mp4" });
2080
+ if (filename === null) {
2081
+ return blob;
2082
+ }
2083
+ if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") {
2084
+ throw new RecordingError(
2085
+ "DOWNLOAD_UNSUPPORTED",
2086
+ "downloadClipAsFile requires a DOM environment; pass filename=null to skip the download trigger"
2087
+ );
2088
+ }
2089
+ triggerBrowserDownload(blob, filename);
2090
+ return blob;
2091
+ });
2092
+ }
2093
+ function resolveAgainst(target, base) {
2094
+ try {
2095
+ return new URL(target, base).toString();
2096
+ } catch (e) {
2097
+ return target;
2098
+ }
2099
+ }
2100
+ function parseRetryAfter(header, fallbackMs) {
2101
+ if (!header) return fallbackMs;
2102
+ const seconds = Number(header);
2103
+ if (Number.isFinite(seconds) && seconds >= 0) {
2104
+ return seconds * 1e3;
2105
+ }
2106
+ const dateMs = Date.parse(header);
2107
+ if (!Number.isNaN(dateMs)) {
2108
+ return Math.max(0, dateMs - Date.now());
2109
+ }
2110
+ return fallbackMs;
2111
+ }
2112
+ function sleep(ms, signal) {
2113
+ return new Promise((resolve, reject) => {
2114
+ if (signal == null ? void 0 : signal.aborted) {
2115
+ reject(new DOMException("Aborted", "AbortError"));
2116
+ return;
2117
+ }
2118
+ const timer = setTimeout(() => {
2119
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
2120
+ resolve();
2121
+ }, ms);
2122
+ const onAbort = () => {
2123
+ clearTimeout(timer);
2124
+ reject(new DOMException("Aborted", "AbortError"));
2125
+ };
2126
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
2127
+ });
2128
+ }
2129
+ function triggerBrowserDownload(blob, filename) {
2130
+ const objectUrl = URL.createObjectURL(blob);
2131
+ try {
2132
+ const a = document.createElement("a");
2133
+ a.href = objectUrl;
2134
+ a.download = filename;
2135
+ a.style.display = "none";
2136
+ document.body.appendChild(a);
2137
+ a.click();
2138
+ a.remove();
2139
+ } finally {
2140
+ URL.revokeObjectURL(objectUrl);
2141
+ }
2142
+ }
2143
+
2144
+ // src/core/RecordingClient.ts
2145
+ var DEFAULT_CLIP_REQUEST_TIMEOUT_MS = 1e4;
2146
+ var RecordingClient = class {
2147
+ constructor(host, options = {}) {
2148
+ this.host = host;
2149
+ // FIFO queue: the runtime processes requests in receipt order and
2150
+ // `clipFailed` carries no discriminator, so FIFO matching is the
2151
+ // simplest correct correlator.
2152
+ this.pendingClipRequests = [];
2153
+ /** Cleanup handles for the host event subscriptions. */
2154
+ this.unsubscribers = [];
2155
+ var _a;
2156
+ this.requestTimeoutMs = (_a = options.requestTimeoutMs) != null ? _a : DEFAULT_CLIP_REQUEST_TIMEOUT_MS;
2157
+ this.unsubscribers.push(
2158
+ this.host.onRuntimeMessage((message) => this.onRuntimeMessage(message))
2159
+ );
2160
+ this.unsubscribers.push(
2161
+ this.host.onStatusChanged((status) => this.onStatusChanged(status))
2162
+ );
2163
+ }
2164
+ /**
2165
+ * Request a clip covering the last `durationSeconds` of the live
2166
+ * session. See {@link Reactor.requestClip}.
2167
+ */
2168
+ requestClip(durationSeconds) {
2169
+ return __async(this, null, function* () {
2170
+ if (typeof durationSeconds !== "number" || !Number.isFinite(durationSeconds) || durationSeconds <= 0) {
2171
+ throw new RecordingError(
2172
+ "INVALID_DURATION",
2173
+ "durationSeconds must be a positive finite number"
2174
+ );
2175
+ }
2176
+ const status = this.host.getStatus();
2177
+ if (status !== "ready") {
2178
+ throw new RecordingError(
2179
+ "DISCONNECTED",
2180
+ `Cannot request clip while status is "${status}"`
2181
+ );
2182
+ }
2183
+ return this.dispatchClipRequest(RuntimeRecordingMessageType.REQUEST_CLIP, {
2184
+ duration_seconds: durationSeconds
2185
+ });
2186
+ });
2187
+ }
2188
+ /**
2189
+ * Request a clip covering the entire session up to "now". See
2190
+ * {@link Reactor.requestRecording}.
2191
+ */
2192
+ requestRecording() {
2193
+ return __async(this, null, function* () {
2194
+ const status = this.host.getStatus();
2195
+ if (status !== "ready") {
2196
+ throw new RecordingError(
2197
+ "DISCONNECTED",
2198
+ `Cannot request recording while status is "${status}"`
2199
+ );
2200
+ }
2201
+ return this.dispatchClipRequest(
2202
+ RuntimeRecordingMessageType.REQUEST_RECORDING,
2203
+ {}
2204
+ );
2205
+ });
2206
+ }
2207
+ /**
2208
+ * Poll `/clips` and return the raw manifest body. Same polling
2209
+ * semantics as the bare {@link fetchPlaylist} helper; the caller is
2210
+ * responsible for supplying the Coordinator JWT via `options.jwt`
2211
+ * (origin-scoped to `clip.playlistUrl`). In local mode against the
2212
+ * HttpRuntime, `options.jwt` should be omitted.
2213
+ */
2214
+ fetchPlaylist(_0) {
2215
+ return __async(this, arguments, function* (clip, options = {}) {
2216
+ return fetchPlaylist(clip.playlistUrl, __spreadValues({
2217
+ predictedReadyAtMs: clip.predictedReadyAtMs
2218
+ }, options));
2219
+ });
2220
+ }
2221
+ /**
2222
+ * Fetch the manifest and return a `blob:` URL suitable for
2223
+ * `<video src>` / `hls.js`. The player reads the manifest from
2224
+ * browser memory; chunk URLs inside are presigned S3 GETs.
2225
+ *
2226
+ * Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
2227
+ * when playback tears down. Pass `options.jwt` for production
2228
+ * `/clips` (the Coordinator hop) — see {@link FetchPlaylistOptions}.
2229
+ */
2230
+ getPlayableManifestUrl(_0) {
2231
+ return __async(this, arguments, function* (clip, options = {}) {
2232
+ const body = yield this.fetchPlaylist(clip, options);
2233
+ return createPlayableManifestUrl(body, clip.playlistUrl);
2234
+ });
2235
+ }
2236
+ /**
2237
+ * Thin delegation to {@link downloadClipAsFile}. Caller must pass
2238
+ * `options.jwt` in production — see {@link DownloadClipOptions}.
2239
+ */
2240
+ downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
2241
+ return __async(this, null, function* () {
2242
+ return downloadClipAsFile(clip, filename, options);
2243
+ });
2244
+ }
2245
+ /**
2246
+ * Drop every pending request and unsubscribe from host events.
2247
+ * Safe to call multiple times; further `requestClip` /
2248
+ * `requestRecording` calls after `destroy()` will hang waiting for
2249
+ * a response that will never arrive — host should not call into
2250
+ * the client after destroy.
2251
+ */
2252
+ destroy() {
2253
+ this.rejectPending("RecordingClient destroyed");
2254
+ while (this.unsubscribers.length > 0) {
2255
+ const off = this.unsubscribers.pop();
2256
+ try {
2257
+ off == null ? void 0 : off();
2258
+ } catch (e) {
2259
+ }
2260
+ }
2261
+ }
2262
+ /**
2263
+ * Register a pending FIFO entry, send the runtime message via
2264
+ * the host, and resolve when the next `clipReady` / `clipFailed`
2265
+ * arrives.
2266
+ */
2267
+ dispatchClipRequest(messageType, payload) {
2268
+ return new Promise((resolve, reject) => {
2269
+ const pending = { resolve, reject };
2270
+ pending.timeoutHandle = setTimeout(() => {
2271
+ const idx = this.pendingClipRequests.indexOf(pending);
2272
+ if (idx === -1) return;
2273
+ this.pendingClipRequests.splice(idx, 1);
2274
+ reject(
2275
+ new RecordingError(
2276
+ "REQUEST_TIMEOUT",
2277
+ `No clipReady/clipFailed within ${this.requestTimeoutMs}ms`
2278
+ )
2279
+ );
2280
+ }, this.requestTimeoutMs);
2281
+ this.pendingClipRequests.push(pending);
2282
+ try {
2283
+ void this.host.sendRuntimeCommand(messageType, payload);
2284
+ } catch (error) {
2285
+ const idx = this.pendingClipRequests.indexOf(pending);
2286
+ if (idx !== -1) this.pendingClipRequests.splice(idx, 1);
2287
+ if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
2288
+ reject(
2289
+ new RecordingError(
2290
+ "INTERNAL_ERROR",
2291
+ `Failed to send ${messageType}: ${error.message}`
2292
+ )
2293
+ );
2294
+ }
2295
+ });
2296
+ }
2297
+ /**
2298
+ * Match inbound `clipReady` / `clipFailed` to the next pending
2299
+ * request FIFO; ignore every other runtime message type.
2300
+ */
2301
+ onRuntimeMessage(message) {
2302
+ var _a;
2303
+ if (!message || typeof message !== "object") return;
2304
+ const msg = message;
2305
+ const type = msg.type;
2306
+ if (type !== RuntimeRecordingMessageType.CLIP_READY && type !== RuntimeRecordingMessageType.CLIP_FAILED) {
2307
+ return;
2308
+ }
2309
+ const pending = this.pendingClipRequests.shift();
2310
+ if (!pending) {
2311
+ console.warn("[Reactor] Received", type, "with no pending request");
2312
+ return;
2313
+ }
2314
+ if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
2315
+ if (type === RuntimeRecordingMessageType.CLIP_READY) {
2316
+ const parsed = ClipReadyPayloadSchema.safeParse(msg.data);
2317
+ if (!parsed.success) {
2318
+ pending.reject(
2319
+ new RecordingError(
2320
+ "INTERNAL_ERROR",
2321
+ `Malformed clipReady payload: ${parsed.error.message}`
2322
+ )
2323
+ );
2324
+ return;
2325
+ }
2326
+ pending.resolve(
2327
+ clipFromPayload(parsed.data, {
2328
+ coordinatorBaseUrl: this.host.getCoordinatorBaseUrl()
2329
+ })
2330
+ );
2331
+ return;
2332
+ }
2333
+ const parsedFail = ClipFailedPayloadSchema.safeParse((_a = msg.data) != null ? _a : {});
2334
+ const reason = parsedFail.success ? parsedFail.data.reason : "unknown";
2335
+ pending.reject(
2336
+ new RecordingError(
2337
+ reason === "recorder disabled" || reason === "recorder disabled or encoder crashed" ? "RECORDER_DISABLED" : "INTERNAL_ERROR",
2338
+ reason
2339
+ )
2340
+ );
2341
+ }
2342
+ onStatusChanged(status) {
2343
+ if (status === "disconnected") {
2344
+ this.rejectPending("Reactor disconnected");
2345
+ }
2346
+ }
2347
+ /** Reject every in-flight request with a typed disconnect error. */
2348
+ rejectPending(reason) {
2349
+ if (this.pendingClipRequests.length === 0) return;
2350
+ const pending = this.pendingClipRequests;
2351
+ this.pendingClipRequests = [];
2352
+ for (const entry of pending) {
2353
+ if (entry.timeoutHandle) clearTimeout(entry.timeoutHandle);
2354
+ entry.reject(new RecordingError("DISCONNECTED", reason));
2355
+ }
2356
+ }
2357
+ };
2358
+
2359
+ // src/core/Reactor.ts
1423
2360
  var LOCAL_COORDINATOR_URL = "http://localhost:8080";
1424
2361
  var DEFAULT_BASE_URL = "https://api.reactor.inc";
1425
- var TrackHintSchema = z2.object({
1426
- name: z2.string(),
1427
- kind: z2.enum(["video", "audio"]),
1428
- direction: z2.enum(["recvonly", "sendonly"])
2362
+ var TrackHintSchema = z3.object({
2363
+ name: z3.string(),
2364
+ kind: z3.enum(["video", "audio"]),
2365
+ direction: z3.enum(["recvonly", "sendonly"])
1429
2366
  });
1430
- var OptionsSchema = z2.object({
1431
- apiUrl: z2.string().default(DEFAULT_BASE_URL),
1432
- modelName: z2.string(),
1433
- local: z2.boolean().default(false),
1434
- modelTracks: z2.array(TrackHintSchema).optional()
2367
+ var OptionsSchema = z3.object({
2368
+ apiUrl: z3.string().default(DEFAULT_BASE_URL),
2369
+ modelName: z3.string(),
2370
+ local: z3.boolean().default(false),
2371
+ modelTracks: z3.array(TrackHintSchema).optional()
1435
2372
  });
1436
2373
  var Reactor = class {
1437
2374
  constructor(options) {
@@ -1448,6 +2385,19 @@ var Reactor = class {
1448
2385
  if (validatedOptions.modelTracks) {
1449
2386
  this.presetTracks = validatedOptions.modelTracks;
1450
2387
  }
2388
+ this.recording = new RecordingClient({
2389
+ onRuntimeMessage: (handler) => {
2390
+ this.on("runtimeMessage", handler);
2391
+ return () => this.off("runtimeMessage", handler);
2392
+ },
2393
+ onStatusChanged: (handler) => {
2394
+ this.on("statusChanged", handler);
2395
+ return () => this.off("statusChanged", handler);
2396
+ },
2397
+ sendRuntimeCommand: (command, data) => this.sendCommand(command, data, "runtime"),
2398
+ getStatus: () => this.status,
2399
+ getCoordinatorBaseUrl: () => this.coordinatorUrl
2400
+ });
1451
2401
  }
1452
2402
  on(event, handler) {
1453
2403
  if (!this.eventListeners.has(event)) {
@@ -1588,6 +2538,41 @@ var Reactor = class {
1588
2538
  return new FileRef(slot.presigned_id, name, mimeType, size);
1589
2539
  });
1590
2540
  }
2541
+ /**
2542
+ * Request a clip covering the last `durationSeconds` of the live
2543
+ * session. Capped server-side at `recording.clip_max_seconds`
2544
+ * (default 5 minutes). Resolves with a {@link Clip} whose
2545
+ * `playlistUrl` can be handed to any HLS-capable player.
2546
+ *
2547
+ * @throws {RecordingError} on invalid input, transport failure,
2548
+ * timeout, runtime-side `clipFailed`, or disconnect mid-request.
2549
+ */
2550
+ requestClip(durationSeconds) {
2551
+ return __async(this, null, function* () {
2552
+ return this.recording.requestClip(durationSeconds);
2553
+ });
2554
+ }
2555
+ /**
2556
+ * Request a clip covering the entire session up to "now". Same
2557
+ * mechanics as {@link requestClip} with `start = 0`; only the
2558
+ * resolved {@link Clip.kind} discriminator differs.
2559
+ */
2560
+ requestRecording() {
2561
+ return __async(this, null, function* () {
2562
+ return this.recording.requestRecording();
2563
+ });
2564
+ }
2565
+ /**
2566
+ * Stream the chunks referenced by `clip.playlistUrl` and trigger a
2567
+ * native browser download of the assembled fragmented-MP4 Blob.
2568
+ * Pass `filename: null` to skip the download trigger and receive
2569
+ * the Blob (useful for non-DOM consumers and tests).
2570
+ */
2571
+ downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
2572
+ return __async(this, null, function* () {
2573
+ return this.recording.downloadClipAsFile(clip, filename, options);
2574
+ });
2575
+ }
1591
2576
  /**
1592
2577
  * Publishes a MediaStreamTrack to a named sendonly track.
1593
2578
  * The transceiver is already set up from capabilities — this just
@@ -3141,17 +4126,311 @@ function WebcamStream({
3141
4126
  }
3142
4127
  );
3143
4128
  }
4129
+
4130
+ // src/react/ClipPlayer.tsx
4131
+ import { useEffect as useEffect5, useRef as useRef6, useState as useState5 } from "react";
4132
+ import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
4133
+ function ClipPlayer({
4134
+ clip,
4135
+ getJwt,
4136
+ slackMs,
4137
+ autoPlay = true,
4138
+ muted = true,
4139
+ className,
4140
+ style
4141
+ }) {
4142
+ const videoRef = useRef6(null);
4143
+ const [phase, setPhase] = useState5({ kind: "waiting" });
4144
+ const getJwtRef = useRef6(getJwt);
4145
+ const autoPlayRef = useRef6(autoPlay);
4146
+ const slackMsRef = useRef6(slackMs);
4147
+ useEffect5(() => {
4148
+ getJwtRef.current = getJwt;
4149
+ autoPlayRef.current = autoPlay;
4150
+ slackMsRef.current = slackMs;
4151
+ });
4152
+ useEffect5(() => {
4153
+ const video = videoRef.current;
4154
+ if (!video) return;
4155
+ const abort = new AbortController();
4156
+ let cancelled = false;
4157
+ let hlsInstance = null;
4158
+ let manifestBlobUrl = null;
4159
+ const fail = (message) => {
4160
+ if (cancelled) return;
4161
+ setPhase({ kind: "error", message });
4162
+ };
4163
+ const attachPlayer = (manifestUrl) => __async(null, null, function* () {
4164
+ const canPlayNative = video.canPlayType("application/vnd.apple.mpegurl") !== "";
4165
+ if (canPlayNative) {
4166
+ video.src = manifestUrl;
4167
+ if (autoPlayRef.current) {
4168
+ video.play().catch(() => {
4169
+ });
4170
+ }
4171
+ if (!cancelled) setPhase({ kind: "ready" });
4172
+ return;
4173
+ }
4174
+ let HlsCtor;
4175
+ try {
4176
+ const mod = yield import("hls.js");
4177
+ HlsCtor = mod.default;
4178
+ } catch (e) {
4179
+ fail(
4180
+ "HLS playback unavailable in this browser. Install `hls.js` as a peer dependency, or use Download."
4181
+ );
4182
+ return;
4183
+ }
4184
+ if (cancelled) return;
4185
+ if (!HlsCtor.isSupported()) {
4186
+ fail("This browser cannot play HLS clips. Use Download instead.");
4187
+ return;
4188
+ }
4189
+ const hls = new HlsCtor();
4190
+ hls.loadSource(manifestUrl);
4191
+ hls.attachMedia(video);
4192
+ hls.on(HlsCtor.Events.MANIFEST_PARSED, () => {
4193
+ if (cancelled) return;
4194
+ setPhase({ kind: "ready" });
4195
+ if (autoPlayRef.current) {
4196
+ video.play().catch(() => {
4197
+ });
4198
+ }
4199
+ });
4200
+ hls.on(HlsCtor.Events.ERROR, (_evt, data) => {
4201
+ var _a;
4202
+ if (cancelled) return;
4203
+ if (data.fatal) {
4204
+ fail(`Playback error: ${(_a = data.details) != null ? _a : "unknown"}`);
4205
+ return;
4206
+ }
4207
+ console.warn("[Reactor.ClipPlayer] hls.js non-fatal error", data);
4208
+ });
4209
+ hlsInstance = hls;
4210
+ });
4211
+ const setup = () => __async(null, null, function* () {
4212
+ try {
4213
+ setPhase({ kind: "waiting" });
4214
+ const jwt = getJwtRef.current ? yield getJwtRef.current() : void 0;
4215
+ if (cancelled) return;
4216
+ const body = yield fetchPlaylist(clip.playlistUrl, {
4217
+ predictedReadyAtMs: clip.predictedReadyAtMs,
4218
+ slackMs: slackMsRef.current,
4219
+ jwt,
4220
+ signal: abort.signal
4221
+ });
4222
+ if (cancelled) return;
4223
+ setPhase({ kind: "loading" });
4224
+ manifestBlobUrl = createPlayableManifestUrl(body, clip.playlistUrl);
4225
+ yield attachPlayer(manifestBlobUrl);
4226
+ } catch (err) {
4227
+ if (cancelled) return;
4228
+ if (err instanceof DOMException && err.name === "AbortError") {
4229
+ return;
4230
+ }
4231
+ const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4232
+ fail(message);
4233
+ }
4234
+ });
4235
+ setup();
4236
+ return () => {
4237
+ cancelled = true;
4238
+ abort.abort();
4239
+ hlsInstance == null ? void 0 : hlsInstance.destroy();
4240
+ video.pause();
4241
+ video.removeAttribute("src");
4242
+ video.load();
4243
+ if (manifestBlobUrl) URL.revokeObjectURL(manifestBlobUrl);
4244
+ };
4245
+ }, [clip]);
4246
+ const overlayText = phase.kind === "waiting" ? "Waiting for clip\u2026" : phase.kind === "loading" ? "Loading player\u2026" : null;
4247
+ return /* @__PURE__ */ jsxs3(
4248
+ "div",
4249
+ {
4250
+ className,
4251
+ style: __spreadValues({
4252
+ position: "relative",
4253
+ background: "#000",
4254
+ width: "100%",
4255
+ display: "flex",
4256
+ alignItems: "center",
4257
+ justifyContent: "center"
4258
+ }, style),
4259
+ children: [
4260
+ /* @__PURE__ */ jsx5(
4261
+ "video",
4262
+ {
4263
+ ref: videoRef,
4264
+ controls: true,
4265
+ playsInline: true,
4266
+ muted,
4267
+ style: {
4268
+ display: "block",
4269
+ width: "100%",
4270
+ height: "auto",
4271
+ maxHeight: "100%"
4272
+ }
4273
+ }
4274
+ ),
4275
+ overlayText && /* @__PURE__ */ jsx5(
4276
+ "div",
4277
+ {
4278
+ style: {
4279
+ position: "absolute",
4280
+ inset: 0,
4281
+ display: "flex",
4282
+ alignItems: "center",
4283
+ justifyContent: "center",
4284
+ color: "rgba(255,255,255,0.6)",
4285
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4286
+ letterSpacing: "0.1em",
4287
+ textTransform: "uppercase",
4288
+ pointerEvents: "none"
4289
+ },
4290
+ children: overlayText
4291
+ }
4292
+ ),
4293
+ phase.kind === "error" && /* @__PURE__ */ jsx5(
4294
+ "div",
4295
+ {
4296
+ style: {
4297
+ position: "absolute",
4298
+ inset: 0,
4299
+ display: "flex",
4300
+ alignItems: "center",
4301
+ justifyContent: "center",
4302
+ padding: 24,
4303
+ background: "rgba(0,0,0,0.8)",
4304
+ color: "#ef4444",
4305
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4306
+ textAlign: "center"
4307
+ },
4308
+ children: phase.message
4309
+ }
4310
+ )
4311
+ ]
4312
+ }
4313
+ );
4314
+ }
4315
+
4316
+ // src/react/useClipDownload.ts
4317
+ import { useCallback as useCallback2, useEffect as useEffect6, useRef as useRef7, useState as useState6 } from "react";
4318
+ function useClipDownload(clip, options = {}) {
4319
+ var _a;
4320
+ const [state, setState] = useState6({ kind: "idle" });
4321
+ const clipRef = useRef7(clip);
4322
+ const filenameRef = useRef7(
4323
+ (_a = options.filename) != null ? _a : "reactor-clip.mp4"
4324
+ );
4325
+ const getJwtRef = useRef7(options.getJwt);
4326
+ useEffect6(() => {
4327
+ clipRef.current = clip;
4328
+ filenameRef.current = options.filename === void 0 ? "reactor-clip.mp4" : options.filename;
4329
+ getJwtRef.current = options.getJwt;
4330
+ });
4331
+ const inFlightRef = useRef7(false);
4332
+ const download = useCallback2(() => __async(null, null, function* () {
4333
+ if (inFlightRef.current) return void 0;
4334
+ inFlightRef.current = true;
4335
+ setState({ kind: "downloading", fetched: 0, total: 0 });
4336
+ try {
4337
+ const jwt = getJwtRef.current ? yield getJwtRef.current() : void 0;
4338
+ const blob = yield downloadClipAsFile(
4339
+ clipRef.current,
4340
+ filenameRef.current,
4341
+ {
4342
+ jwt,
4343
+ onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
4344
+ }
4345
+ );
4346
+ setState({ kind: "idle" });
4347
+ return blob;
4348
+ } catch (err) {
4349
+ const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4350
+ setState({ kind: "error", message });
4351
+ return void 0;
4352
+ } finally {
4353
+ inFlightRef.current = false;
4354
+ }
4355
+ }), []);
4356
+ const reset = useCallback2(() => setState({ kind: "idle" }), []);
4357
+ return { state, download, reset };
4358
+ }
4359
+
4360
+ // src/react/ClipDownloadButton.tsx
4361
+ import { jsx as jsx6 } from "react/jsx-runtime";
4362
+ function ClipDownloadButton({
4363
+ clip,
4364
+ getJwt,
4365
+ filename = "reactor-clip.mp4",
4366
+ children,
4367
+ className,
4368
+ style,
4369
+ disabled
4370
+ }) {
4371
+ const { state, download } = useClipDownload(clip, { filename, getJwt });
4372
+ const downloading = state.kind === "downloading";
4373
+ const isDisabled = downloading || !!disabled;
4374
+ const content = typeof children === "function" ? children(state) : children !== void 0 ? children : defaultLabel(state);
4375
+ return /* @__PURE__ */ jsx6(
4376
+ "button",
4377
+ {
4378
+ type: "button",
4379
+ onClick: () => {
4380
+ void download();
4381
+ },
4382
+ disabled: isDisabled,
4383
+ title: state.kind === "error" ? state.message : void 0,
4384
+ className,
4385
+ style: __spreadValues({
4386
+ padding: "5px 12px",
4387
+ borderRadius: 4,
4388
+ border: "1px solid rgba(255,255,255,0.15)",
4389
+ background: "rgba(255,255,255,0.05)",
4390
+ color: "#fff",
4391
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4392
+ cursor: isDisabled ? "default" : "pointer",
4393
+ opacity: isDisabled ? 0.6 : 1,
4394
+ transition: "background-color 120ms ease"
4395
+ }, style),
4396
+ children: content
4397
+ }
4398
+ );
4399
+ }
4400
+ function defaultLabel(state) {
4401
+ if (state.kind === "downloading") {
4402
+ if (state.total > 0) {
4403
+ return `Downloading ${state.fetched}/${state.total}\u2026`;
4404
+ }
4405
+ return "Downloading\u2026";
4406
+ }
4407
+ return "Download";
4408
+ }
3144
4409
  export {
3145
4410
  AbortError,
4411
+ ClipDownloadButton,
4412
+ ClipPlayer,
3146
4413
  ConflictError,
3147
4414
  DEFAULT_BASE_URL,
4415
+ DEFAULT_CLIP_REQUEST_TIMEOUT_MS,
4416
+ DEFAULT_PLAYLIST_POLL_SLACK_MS,
3148
4417
  FileRef,
3149
4418
  Reactor,
3150
4419
  ReactorController,
3151
4420
  ReactorProvider,
3152
4421
  ReactorView,
4422
+ RecordingClient,
4423
+ RecordingError,
4424
+ RuntimeRecordingMessageType,
3153
4425
  WebcamStream,
4426
+ clipFromPayload,
4427
+ createPlayableManifestUrl,
4428
+ downloadClipAsFile,
4429
+ fetchPlaylist,
3154
4430
  isAbortError,
4431
+ parsePlaylist,
4432
+ rewriteUrlHost,
4433
+ useClipDownload,
3155
4434
  useReactor,
3156
4435
  useReactorInternalMessage,
3157
4436
  useReactorMessage,