@reactor-team/js-sdk 2.9.3 → 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.js CHANGED
@@ -80,15 +80,29 @@ var __async = (__this, __arguments, generator) => {
80
80
  var index_exports = {};
81
81
  __export(index_exports, {
82
82
  AbortError: () => AbortError,
83
+ ClipDownloadButton: () => ClipDownloadButton,
84
+ ClipPlayer: () => ClipPlayer,
83
85
  ConflictError: () => ConflictError,
84
86
  DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
87
+ DEFAULT_CLIP_REQUEST_TIMEOUT_MS: () => DEFAULT_CLIP_REQUEST_TIMEOUT_MS,
88
+ DEFAULT_PLAYLIST_POLL_SLACK_MS: () => DEFAULT_PLAYLIST_POLL_SLACK_MS,
85
89
  FileRef: () => FileRef,
86
90
  Reactor: () => Reactor,
87
91
  ReactorController: () => ReactorController,
88
92
  ReactorProvider: () => ReactorProvider,
89
93
  ReactorView: () => ReactorView,
94
+ RecordingClient: () => RecordingClient,
95
+ RecordingError: () => RecordingError,
96
+ RuntimeRecordingMessageType: () => RuntimeRecordingMessageType,
90
97
  WebcamStream: () => WebcamStream,
98
+ clipFromPayload: () => clipFromPayload,
99
+ createPlayableManifestUrl: () => createPlayableManifestUrl,
100
+ downloadClipAsFile: () => downloadClipAsFile,
101
+ fetchPlaylist: () => fetchPlaylist,
91
102
  isAbortError: () => isAbortError,
103
+ parsePlaylist: () => parsePlaylist,
104
+ rewriteUrlHost: () => rewriteUrlHost,
105
+ useClipDownload: () => useClipDownload,
92
106
  useReactor: () => useReactor,
93
107
  useReactorInternalMessage: () => useReactorInternalMessage,
94
108
  useReactorMessage: () => useReactorMessage,
@@ -130,8 +144,24 @@ var import_zod = require("zod");
130
144
  // package.json
131
145
  var package_default = {
132
146
  name: "@reactor-team/js-sdk",
133
- version: "2.9.3",
134
- description: "Reactor JavaScript frontend SDK",
147
+ version: "2.10.0",
148
+ description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
149
+ license: "MIT",
150
+ repository: {
151
+ type: "git",
152
+ url: "https://github.com/reactor-team/js-sdk.git"
153
+ },
154
+ keywords: [
155
+ "reactor",
156
+ "sdk",
157
+ "frontend",
158
+ "react",
159
+ "webrtc",
160
+ "real-time",
161
+ "video",
162
+ "ai"
163
+ ],
164
+ author: "Reactor Technologies, Inc.",
135
165
  main: "dist/index.js",
136
166
  module: "dist/index.mjs",
137
167
  types: "dist/index.d.ts",
@@ -142,6 +172,10 @@ var package_default = {
142
172
  require: "./dist/index.js"
143
173
  }
144
174
  },
175
+ sideEffects: false,
176
+ engines: {
177
+ node: ">=18"
178
+ },
145
179
  files: [
146
180
  "dist",
147
181
  "README.md"
@@ -156,46 +190,34 @@ var package_default = {
156
190
  format: "prettier --write .",
157
191
  "format:check": "prettier --check ."
158
192
  },
159
- keywords: [
160
- "reactor",
161
- "frontend",
162
- "sdk"
163
- ],
164
- author: "Reactor Technologies, Inc.",
165
193
  reactor: {
166
194
  apiVersion: 1,
167
195
  webrtcVersion: "1.0"
168
196
  },
169
- license: "MIT",
170
- repository: {
171
- type: "git",
172
- url: "https://github.com/reactor-team/js-sdk.git"
173
- },
174
197
  packageManager: "pnpm@10.12.1",
198
+ dependencies: {
199
+ "sdp-transform": "^3.0.0",
200
+ zod: "^4.0.5"
201
+ },
202
+ peerDependencies: {
203
+ "hls.js": "^1.6.0",
204
+ react: "^17.0.0 || ^18.0.0 || ^19.0.0",
205
+ zustand: "^5.0.6"
206
+ },
207
+ peerDependenciesMeta: {
208
+ "hls.js": {
209
+ optional: true
210
+ }
211
+ },
175
212
  devDependencies: {
176
213
  "@roamhq/wrtc": "^0.8.0",
177
- "@types/inquirer": "^9.0.9",
178
214
  "@types/node": "^20",
179
215
  "@types/react": "^18.2.8",
180
- "@types/sdp-transform": "^2.15.0",
181
- "@types/ws": "^8.18.1",
216
+ "hls.js": "^1.6.0",
182
217
  prettier: "^3.6.2",
183
218
  tsup: "^8.5.0",
184
219
  typescript: "^5.8.3",
185
220
  vitest: "^3.0.0"
186
- },
187
- dependencies: {
188
- "@bufbuild/protobuf": "^2.0.0",
189
- chalk: "^5.3.0",
190
- inquirer: "^9.3.0",
191
- "sdp-transform": "^3.0.0",
192
- "simple-git": "^3.24.0",
193
- ws: "^8.18.3",
194
- zod: "^4.0.5"
195
- },
196
- peerDependencies: {
197
- react: "^17.0.0 || ^18.0.0 || ^19.0.0",
198
- zustand: "^5.0.6"
199
221
  }
200
222
  };
201
223
 
@@ -1872,19 +1894,542 @@ var WebRTCTransportClient = class {
1872
1894
  };
1873
1895
 
1874
1896
  // src/core/Reactor.ts
1897
+ var import_zod3 = require("zod");
1898
+
1899
+ // src/utils/recording.ts
1875
1900
  var import_zod2 = require("zod");
1901
+ var RuntimeRecordingMessageType = {
1902
+ REQUEST_CLIP: "requestClip",
1903
+ REQUEST_RECORDING: "requestRecording",
1904
+ CLIP_READY: "clipReady",
1905
+ CLIP_FAILED: "clipFailed"
1906
+ };
1907
+ var RecordingError = class extends Error {
1908
+ constructor(code, reason) {
1909
+ super(`${code}: ${reason}`);
1910
+ this.code = code;
1911
+ this.reason = reason;
1912
+ this.name = "RecordingError";
1913
+ }
1914
+ };
1915
+ var ClipReadyPayloadSchema = import_zod2.z.object({
1916
+ session_id: import_zod2.z.string(),
1917
+ kind: import_zod2.z.enum(["snap", "recording"]),
1918
+ start_marker: import_zod2.z.number(),
1919
+ end_marker: import_zod2.z.number(),
1920
+ now_marker: import_zod2.z.number(),
1921
+ predicted_ready_at_ms: import_zod2.z.number(),
1922
+ playlist_url: import_zod2.z.string()
1923
+ }).passthrough();
1924
+ var ClipFailedPayloadSchema = import_zod2.z.object({
1925
+ reason: import_zod2.z.string().default("unknown")
1926
+ }).passthrough();
1927
+ function clipFromPayload(payload, options = {}) {
1928
+ const playlistUrl = options.coordinatorBaseUrl ? rewriteUrlHost(payload.playlist_url, options.coordinatorBaseUrl) : payload.playlist_url;
1929
+ return {
1930
+ sessionId: payload.session_id,
1931
+ kind: payload.kind,
1932
+ startMarker: payload.start_marker,
1933
+ endMarker: payload.end_marker,
1934
+ nowMarker: payload.now_marker,
1935
+ predictedReadyAtMs: payload.predicted_ready_at_ms,
1936
+ playlistUrl
1937
+ };
1938
+ }
1939
+ function rewriteUrlHost(target, base) {
1940
+ try {
1941
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(target)) {
1942
+ return new URL(target, base).toString();
1943
+ }
1944
+ const baseUrl = new URL(base);
1945
+ const parsed = new URL(target);
1946
+ parsed.protocol = baseUrl.protocol;
1947
+ parsed.hostname = baseUrl.hostname;
1948
+ parsed.port = baseUrl.port;
1949
+ return parsed.toString();
1950
+ } catch (e) {
1951
+ return target;
1952
+ }
1953
+ }
1954
+ var DEFAULT_PLAYLIST_POLL_SLACK_MS = 15e3;
1955
+ function fetchPlaylist(_0) {
1956
+ return __async(this, arguments, function* (playlistUrl, options = {}) {
1957
+ var _a, _b, _c, _d;
1958
+ const slackMs = (_a = options.slackMs) != null ? _a : DEFAULT_PLAYLIST_POLL_SLACK_MS;
1959
+ const minDelay = Math.max(0, (_b = options.minRetryDelayMs) != null ? _b : 200);
1960
+ const maxDelay = Math.max(minDelay, (_c = options.maxRetryDelayMs) != null ? _c : 2e3);
1961
+ const fallbackMaxRetries = (_d = options.maxRetries) != null ? _d : 5;
1962
+ const hasDeadline = typeof options.predictedReadyAtMs === "number";
1963
+ const startedPollingAt = Date.now();
1964
+ const deadlineMs = hasDeadline ? Math.max(options.predictedReadyAtMs, startedPollingAt) + slackMs : void 0;
1965
+ const headers = options.jwt ? { Authorization: `Bearer ${options.jwt}` } : void 0;
1966
+ let attempt = 0;
1967
+ let lastStatus = 0;
1968
+ while (true) {
1969
+ let response;
1970
+ try {
1971
+ response = yield fetch(playlistUrl, {
1972
+ signal: options.signal,
1973
+ headers
1974
+ });
1975
+ } catch (error) {
1976
+ throw new RecordingError(
1977
+ "PLAYLIST_FETCH_FAILED",
1978
+ `Network error fetching playlist: ${error.message}`
1979
+ );
1980
+ }
1981
+ lastStatus = response.status;
1982
+ if (response.status === 202) {
1983
+ if (hasDeadline) {
1984
+ if (Date.now() >= deadlineMs) {
1985
+ throw new RecordingError(
1986
+ "CLIP_NOT_READY",
1987
+ `Boundary chunk still pending after ${slackMs}ms grace (predicted ready ${new Date(
1988
+ options.predictedReadyAtMs
1989
+ ).toISOString()}). Runtime may have crashed mid-clip.`
1990
+ );
1991
+ }
1992
+ } else if (attempt >= fallbackMaxRetries) {
1993
+ throw new RecordingError(
1994
+ "CLIP_NOT_READY",
1995
+ `Manifest still pending after ${attempt + 1} attempts (last status ${lastStatus})`
1996
+ );
1997
+ }
1998
+ const headerDelay = parseRetryAfter(
1999
+ response.headers.get("Retry-After"),
2000
+ minDelay
2001
+ );
2002
+ const delay = Math.min(maxDelay, Math.max(minDelay, headerDelay));
2003
+ const clampedDelay = hasDeadline ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;
2004
+ yield sleep(clampedDelay, options.signal);
2005
+ attempt++;
2006
+ continue;
2007
+ }
2008
+ if (response.status === 200) {
2009
+ return yield response.text();
2010
+ }
2011
+ if (response.status === 410) {
2012
+ throw new RecordingError(
2013
+ "CLIP_GONE",
2014
+ "Clip is no longer available (chunks aged out or session unknown)"
2015
+ );
2016
+ }
2017
+ if (response.status === 404) {
2018
+ throw new RecordingError(
2019
+ "CLIP_GONE",
2020
+ "Session not found for clip playlist"
2021
+ );
2022
+ }
2023
+ throw new RecordingError(
2024
+ "PLAYLIST_FETCH_FAILED",
2025
+ `Manifest endpoint returned HTTP ${response.status}`
2026
+ );
2027
+ }
2028
+ });
2029
+ }
2030
+ function parsePlaylist(manifestBody, playlistUrl) {
2031
+ let initUrl;
2032
+ const segments = [];
2033
+ const lines = manifestBody.split(/\r?\n/);
2034
+ for (const line of lines) {
2035
+ const trimmed = line.trim();
2036
+ if (!trimmed) continue;
2037
+ if (trimmed.startsWith("#EXT-X-MAP")) {
2038
+ const match = trimmed.match(/URI="([^"]+)"/);
2039
+ if (match) {
2040
+ initUrl = resolveAgainst(match[1], playlistUrl);
2041
+ }
2042
+ continue;
2043
+ }
2044
+ if (trimmed.startsWith("#")) {
2045
+ continue;
2046
+ }
2047
+ segments.push(resolveAgainst(trimmed, playlistUrl));
2048
+ }
2049
+ if (!initUrl) {
2050
+ throw new RecordingError(
2051
+ "INVALID_PLAYLIST",
2052
+ "Playlist is missing an #EXT-X-MAP init segment URI"
2053
+ );
2054
+ }
2055
+ if (segments.length === 0) {
2056
+ throw new RecordingError(
2057
+ "INVALID_PLAYLIST",
2058
+ "Playlist contains no media segments"
2059
+ );
2060
+ }
2061
+ return { initUrl, segmentUrls: segments };
2062
+ }
2063
+ function createPlayableManifestUrl(manifestBody, playlistUrl) {
2064
+ if (typeof Blob === "undefined" || typeof URL === "undefined" || typeof URL.createObjectURL !== "function") {
2065
+ throw new RecordingError(
2066
+ "INVALID_PLAYLIST",
2067
+ "createPlayableManifestUrl requires a browser environment with URL.createObjectURL"
2068
+ );
2069
+ }
2070
+ const rewritten = absolutizeManifestUrls(manifestBody, playlistUrl);
2071
+ const blob = new Blob([rewritten], {
2072
+ type: "application/vnd.apple.mpegurl"
2073
+ });
2074
+ return URL.createObjectURL(blob);
2075
+ }
2076
+ function absolutizeManifestUrls(manifestBody, playlistUrl) {
2077
+ const eol = manifestBody.includes("\r\n") ? "\r\n" : "\n";
2078
+ const lines = manifestBody.split(/\r?\n/);
2079
+ const out = [];
2080
+ for (const line of lines) {
2081
+ if (line.startsWith("#EXT-X-MAP")) {
2082
+ out.push(
2083
+ line.replace(
2084
+ /URI="([^"]+)"/,
2085
+ (_, uri) => `URI="${resolveAgainst(uri, playlistUrl)}"`
2086
+ )
2087
+ );
2088
+ continue;
2089
+ }
2090
+ const trimmed = line.trim();
2091
+ if (!trimmed || trimmed.startsWith("#")) {
2092
+ out.push(line);
2093
+ continue;
2094
+ }
2095
+ out.push(resolveAgainst(trimmed, playlistUrl));
2096
+ }
2097
+ return out.join(eol);
2098
+ }
2099
+ function downloadClipAsFile(_0) {
2100
+ return __async(this, arguments, function* (clip, filename = "reactor-clip.mp4", options = {}) {
2101
+ var _a;
2102
+ const manifestBody = yield fetchPlaylist(clip.playlistUrl, {
2103
+ predictedReadyAtMs: clip.predictedReadyAtMs,
2104
+ signal: options.signal,
2105
+ jwt: options.jwt
2106
+ });
2107
+ const { initUrl, segmentUrls } = parsePlaylist(
2108
+ manifestBody,
2109
+ clip.playlistUrl
2110
+ );
2111
+ const orderedUrls = [initUrl, ...segmentUrls];
2112
+ const parts = [];
2113
+ let bytes = 0;
2114
+ for (let i = 0; i < orderedUrls.length; i++) {
2115
+ const url = orderedUrls[i];
2116
+ let response;
2117
+ try {
2118
+ response = yield fetch(url, { signal: options.signal });
2119
+ } catch (error) {
2120
+ throw new RecordingError(
2121
+ "CHUNK_FETCH_FAILED",
2122
+ `Network error fetching chunk ${i}: ${error.message}`
2123
+ );
2124
+ }
2125
+ if (!response.ok) {
2126
+ throw new RecordingError(
2127
+ "CHUNK_FETCH_FAILED",
2128
+ `Chunk ${i} returned HTTP ${response.status}`
2129
+ );
2130
+ }
2131
+ const data = yield response.arrayBuffer();
2132
+ parts.push(data);
2133
+ bytes += data.byteLength;
2134
+ (_a = options.onProgress) == null ? void 0 : _a.call(options, {
2135
+ fetched: i + 1,
2136
+ total: orderedUrls.length,
2137
+ bytes
2138
+ });
2139
+ }
2140
+ const blob = new Blob(parts, { type: "video/mp4" });
2141
+ if (filename === null) {
2142
+ return blob;
2143
+ }
2144
+ if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") {
2145
+ throw new RecordingError(
2146
+ "DOWNLOAD_UNSUPPORTED",
2147
+ "downloadClipAsFile requires a DOM environment; pass filename=null to skip the download trigger"
2148
+ );
2149
+ }
2150
+ triggerBrowserDownload(blob, filename);
2151
+ return blob;
2152
+ });
2153
+ }
2154
+ function resolveAgainst(target, base) {
2155
+ try {
2156
+ return new URL(target, base).toString();
2157
+ } catch (e) {
2158
+ return target;
2159
+ }
2160
+ }
2161
+ function parseRetryAfter(header, fallbackMs) {
2162
+ if (!header) return fallbackMs;
2163
+ const seconds = Number(header);
2164
+ if (Number.isFinite(seconds) && seconds >= 0) {
2165
+ return seconds * 1e3;
2166
+ }
2167
+ const dateMs = Date.parse(header);
2168
+ if (!Number.isNaN(dateMs)) {
2169
+ return Math.max(0, dateMs - Date.now());
2170
+ }
2171
+ return fallbackMs;
2172
+ }
2173
+ function sleep(ms, signal) {
2174
+ return new Promise((resolve, reject) => {
2175
+ if (signal == null ? void 0 : signal.aborted) {
2176
+ reject(new DOMException("Aborted", "AbortError"));
2177
+ return;
2178
+ }
2179
+ const timer = setTimeout(() => {
2180
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
2181
+ resolve();
2182
+ }, ms);
2183
+ const onAbort = () => {
2184
+ clearTimeout(timer);
2185
+ reject(new DOMException("Aborted", "AbortError"));
2186
+ };
2187
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
2188
+ });
2189
+ }
2190
+ function triggerBrowserDownload(blob, filename) {
2191
+ const objectUrl = URL.createObjectURL(blob);
2192
+ try {
2193
+ const a = document.createElement("a");
2194
+ a.href = objectUrl;
2195
+ a.download = filename;
2196
+ a.style.display = "none";
2197
+ document.body.appendChild(a);
2198
+ a.click();
2199
+ a.remove();
2200
+ } finally {
2201
+ URL.revokeObjectURL(objectUrl);
2202
+ }
2203
+ }
2204
+
2205
+ // src/core/RecordingClient.ts
2206
+ var DEFAULT_CLIP_REQUEST_TIMEOUT_MS = 1e4;
2207
+ var RecordingClient = class {
2208
+ constructor(host, options = {}) {
2209
+ this.host = host;
2210
+ // FIFO queue: the runtime processes requests in receipt order and
2211
+ // `clipFailed` carries no discriminator, so FIFO matching is the
2212
+ // simplest correct correlator.
2213
+ this.pendingClipRequests = [];
2214
+ /** Cleanup handles for the host event subscriptions. */
2215
+ this.unsubscribers = [];
2216
+ var _a;
2217
+ this.requestTimeoutMs = (_a = options.requestTimeoutMs) != null ? _a : DEFAULT_CLIP_REQUEST_TIMEOUT_MS;
2218
+ this.unsubscribers.push(
2219
+ this.host.onRuntimeMessage((message) => this.onRuntimeMessage(message))
2220
+ );
2221
+ this.unsubscribers.push(
2222
+ this.host.onStatusChanged((status) => this.onStatusChanged(status))
2223
+ );
2224
+ }
2225
+ /**
2226
+ * Request a clip covering the last `durationSeconds` of the live
2227
+ * session. See {@link Reactor.requestClip}.
2228
+ */
2229
+ requestClip(durationSeconds) {
2230
+ return __async(this, null, function* () {
2231
+ if (typeof durationSeconds !== "number" || !Number.isFinite(durationSeconds) || durationSeconds <= 0) {
2232
+ throw new RecordingError(
2233
+ "INVALID_DURATION",
2234
+ "durationSeconds must be a positive finite number"
2235
+ );
2236
+ }
2237
+ const status = this.host.getStatus();
2238
+ if (status !== "ready") {
2239
+ throw new RecordingError(
2240
+ "DISCONNECTED",
2241
+ `Cannot request clip while status is "${status}"`
2242
+ );
2243
+ }
2244
+ return this.dispatchClipRequest(RuntimeRecordingMessageType.REQUEST_CLIP, {
2245
+ duration_seconds: durationSeconds
2246
+ });
2247
+ });
2248
+ }
2249
+ /**
2250
+ * Request a clip covering the entire session up to "now". See
2251
+ * {@link Reactor.requestRecording}.
2252
+ */
2253
+ requestRecording() {
2254
+ return __async(this, null, function* () {
2255
+ const status = this.host.getStatus();
2256
+ if (status !== "ready") {
2257
+ throw new RecordingError(
2258
+ "DISCONNECTED",
2259
+ `Cannot request recording while status is "${status}"`
2260
+ );
2261
+ }
2262
+ return this.dispatchClipRequest(
2263
+ RuntimeRecordingMessageType.REQUEST_RECORDING,
2264
+ {}
2265
+ );
2266
+ });
2267
+ }
2268
+ /**
2269
+ * Poll `/clips` and return the raw manifest body. Same polling
2270
+ * semantics as the bare {@link fetchPlaylist} helper; the caller is
2271
+ * responsible for supplying the Coordinator JWT via `options.jwt`
2272
+ * (origin-scoped to `clip.playlistUrl`). In local mode against the
2273
+ * HttpRuntime, `options.jwt` should be omitted.
2274
+ */
2275
+ fetchPlaylist(_0) {
2276
+ return __async(this, arguments, function* (clip, options = {}) {
2277
+ return fetchPlaylist(clip.playlistUrl, __spreadValues({
2278
+ predictedReadyAtMs: clip.predictedReadyAtMs
2279
+ }, options));
2280
+ });
2281
+ }
2282
+ /**
2283
+ * Fetch the manifest and return a `blob:` URL suitable for
2284
+ * `<video src>` / `hls.js`. The player reads the manifest from
2285
+ * browser memory; chunk URLs inside are presigned S3 GETs.
2286
+ *
2287
+ * Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
2288
+ * when playback tears down. Pass `options.jwt` for production
2289
+ * `/clips` (the Coordinator hop) — see {@link FetchPlaylistOptions}.
2290
+ */
2291
+ getPlayableManifestUrl(_0) {
2292
+ return __async(this, arguments, function* (clip, options = {}) {
2293
+ const body = yield this.fetchPlaylist(clip, options);
2294
+ return createPlayableManifestUrl(body, clip.playlistUrl);
2295
+ });
2296
+ }
2297
+ /**
2298
+ * Thin delegation to {@link downloadClipAsFile}. Caller must pass
2299
+ * `options.jwt` in production — see {@link DownloadClipOptions}.
2300
+ */
2301
+ downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
2302
+ return __async(this, null, function* () {
2303
+ return downloadClipAsFile(clip, filename, options);
2304
+ });
2305
+ }
2306
+ /**
2307
+ * Drop every pending request and unsubscribe from host events.
2308
+ * Safe to call multiple times; further `requestClip` /
2309
+ * `requestRecording` calls after `destroy()` will hang waiting for
2310
+ * a response that will never arrive — host should not call into
2311
+ * the client after destroy.
2312
+ */
2313
+ destroy() {
2314
+ this.rejectPending("RecordingClient destroyed");
2315
+ while (this.unsubscribers.length > 0) {
2316
+ const off = this.unsubscribers.pop();
2317
+ try {
2318
+ off == null ? void 0 : off();
2319
+ } catch (e) {
2320
+ }
2321
+ }
2322
+ }
2323
+ /**
2324
+ * Register a pending FIFO entry, send the runtime message via
2325
+ * the host, and resolve when the next `clipReady` / `clipFailed`
2326
+ * arrives.
2327
+ */
2328
+ dispatchClipRequest(messageType, payload) {
2329
+ return new Promise((resolve, reject) => {
2330
+ const pending = { resolve, reject };
2331
+ pending.timeoutHandle = setTimeout(() => {
2332
+ const idx = this.pendingClipRequests.indexOf(pending);
2333
+ if (idx === -1) return;
2334
+ this.pendingClipRequests.splice(idx, 1);
2335
+ reject(
2336
+ new RecordingError(
2337
+ "REQUEST_TIMEOUT",
2338
+ `No clipReady/clipFailed within ${this.requestTimeoutMs}ms`
2339
+ )
2340
+ );
2341
+ }, this.requestTimeoutMs);
2342
+ this.pendingClipRequests.push(pending);
2343
+ try {
2344
+ void this.host.sendRuntimeCommand(messageType, payload);
2345
+ } catch (error) {
2346
+ const idx = this.pendingClipRequests.indexOf(pending);
2347
+ if (idx !== -1) this.pendingClipRequests.splice(idx, 1);
2348
+ if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
2349
+ reject(
2350
+ new RecordingError(
2351
+ "INTERNAL_ERROR",
2352
+ `Failed to send ${messageType}: ${error.message}`
2353
+ )
2354
+ );
2355
+ }
2356
+ });
2357
+ }
2358
+ /**
2359
+ * Match inbound `clipReady` / `clipFailed` to the next pending
2360
+ * request FIFO; ignore every other runtime message type.
2361
+ */
2362
+ onRuntimeMessage(message) {
2363
+ var _a;
2364
+ if (!message || typeof message !== "object") return;
2365
+ const msg = message;
2366
+ const type = msg.type;
2367
+ if (type !== RuntimeRecordingMessageType.CLIP_READY && type !== RuntimeRecordingMessageType.CLIP_FAILED) {
2368
+ return;
2369
+ }
2370
+ const pending = this.pendingClipRequests.shift();
2371
+ if (!pending) {
2372
+ console.warn("[Reactor] Received", type, "with no pending request");
2373
+ return;
2374
+ }
2375
+ if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
2376
+ if (type === RuntimeRecordingMessageType.CLIP_READY) {
2377
+ const parsed = ClipReadyPayloadSchema.safeParse(msg.data);
2378
+ if (!parsed.success) {
2379
+ pending.reject(
2380
+ new RecordingError(
2381
+ "INTERNAL_ERROR",
2382
+ `Malformed clipReady payload: ${parsed.error.message}`
2383
+ )
2384
+ );
2385
+ return;
2386
+ }
2387
+ pending.resolve(
2388
+ clipFromPayload(parsed.data, {
2389
+ coordinatorBaseUrl: this.host.getCoordinatorBaseUrl()
2390
+ })
2391
+ );
2392
+ return;
2393
+ }
2394
+ const parsedFail = ClipFailedPayloadSchema.safeParse((_a = msg.data) != null ? _a : {});
2395
+ const reason = parsedFail.success ? parsedFail.data.reason : "unknown";
2396
+ pending.reject(
2397
+ new RecordingError(
2398
+ reason === "recorder disabled" || reason === "recorder disabled or encoder crashed" ? "RECORDER_DISABLED" : "INTERNAL_ERROR",
2399
+ reason
2400
+ )
2401
+ );
2402
+ }
2403
+ onStatusChanged(status) {
2404
+ if (status === "disconnected") {
2405
+ this.rejectPending("Reactor disconnected");
2406
+ }
2407
+ }
2408
+ /** Reject every in-flight request with a typed disconnect error. */
2409
+ rejectPending(reason) {
2410
+ if (this.pendingClipRequests.length === 0) return;
2411
+ const pending = this.pendingClipRequests;
2412
+ this.pendingClipRequests = [];
2413
+ for (const entry of pending) {
2414
+ if (entry.timeoutHandle) clearTimeout(entry.timeoutHandle);
2415
+ entry.reject(new RecordingError("DISCONNECTED", reason));
2416
+ }
2417
+ }
2418
+ };
2419
+
2420
+ // src/core/Reactor.ts
1876
2421
  var LOCAL_COORDINATOR_URL = "http://localhost:8080";
1877
2422
  var DEFAULT_BASE_URL = "https://api.reactor.inc";
1878
- var TrackHintSchema = import_zod2.z.object({
1879
- name: import_zod2.z.string(),
1880
- kind: import_zod2.z.enum(["video", "audio"]),
1881
- direction: import_zod2.z.enum(["recvonly", "sendonly"])
2423
+ var TrackHintSchema = import_zod3.z.object({
2424
+ name: import_zod3.z.string(),
2425
+ kind: import_zod3.z.enum(["video", "audio"]),
2426
+ direction: import_zod3.z.enum(["recvonly", "sendonly"])
1882
2427
  });
1883
- var OptionsSchema = import_zod2.z.object({
1884
- apiUrl: import_zod2.z.string().default(DEFAULT_BASE_URL),
1885
- modelName: import_zod2.z.string(),
1886
- local: import_zod2.z.boolean().default(false),
1887
- modelTracks: import_zod2.z.array(TrackHintSchema).optional()
2428
+ var OptionsSchema = import_zod3.z.object({
2429
+ apiUrl: import_zod3.z.string().default(DEFAULT_BASE_URL),
2430
+ modelName: import_zod3.z.string(),
2431
+ local: import_zod3.z.boolean().default(false),
2432
+ modelTracks: import_zod3.z.array(TrackHintSchema).optional()
1888
2433
  });
1889
2434
  var Reactor = class {
1890
2435
  constructor(options) {
@@ -1901,6 +2446,19 @@ var Reactor = class {
1901
2446
  if (validatedOptions.modelTracks) {
1902
2447
  this.presetTracks = validatedOptions.modelTracks;
1903
2448
  }
2449
+ this.recording = new RecordingClient({
2450
+ onRuntimeMessage: (handler) => {
2451
+ this.on("runtimeMessage", handler);
2452
+ return () => this.off("runtimeMessage", handler);
2453
+ },
2454
+ onStatusChanged: (handler) => {
2455
+ this.on("statusChanged", handler);
2456
+ return () => this.off("statusChanged", handler);
2457
+ },
2458
+ sendRuntimeCommand: (command, data) => this.sendCommand(command, data, "runtime"),
2459
+ getStatus: () => this.status,
2460
+ getCoordinatorBaseUrl: () => this.coordinatorUrl
2461
+ });
1904
2462
  }
1905
2463
  on(event, handler) {
1906
2464
  if (!this.eventListeners.has(event)) {
@@ -2041,6 +2599,41 @@ var Reactor = class {
2041
2599
  return new FileRef(slot.presigned_id, name, mimeType, size);
2042
2600
  });
2043
2601
  }
2602
+ /**
2603
+ * Request a clip covering the last `durationSeconds` of the live
2604
+ * session. Capped server-side at `recording.clip_max_seconds`
2605
+ * (default 5 minutes). Resolves with a {@link Clip} whose
2606
+ * `playlistUrl` can be handed to any HLS-capable player.
2607
+ *
2608
+ * @throws {RecordingError} on invalid input, transport failure,
2609
+ * timeout, runtime-side `clipFailed`, or disconnect mid-request.
2610
+ */
2611
+ requestClip(durationSeconds) {
2612
+ return __async(this, null, function* () {
2613
+ return this.recording.requestClip(durationSeconds);
2614
+ });
2615
+ }
2616
+ /**
2617
+ * Request a clip covering the entire session up to "now". Same
2618
+ * mechanics as {@link requestClip} with `start = 0`; only the
2619
+ * resolved {@link Clip.kind} discriminator differs.
2620
+ */
2621
+ requestRecording() {
2622
+ return __async(this, null, function* () {
2623
+ return this.recording.requestRecording();
2624
+ });
2625
+ }
2626
+ /**
2627
+ * Stream the chunks referenced by `clip.playlistUrl` and trigger a
2628
+ * native browser download of the assembled fragmented-MP4 Blob.
2629
+ * Pass `filename: null` to skip the download trigger and receive
2630
+ * the Blob (useful for non-DOM consumers and tests).
2631
+ */
2632
+ downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
2633
+ return __async(this, null, function* () {
2634
+ return this.recording.downloadClipAsFile(clip, filename, options);
2635
+ });
2636
+ }
2044
2637
  /**
2045
2638
  * Publishes a MediaStreamTrack to a named sendonly track.
2046
2639
  * The transceiver is already set up from capabilities — this just
@@ -3594,18 +4187,312 @@ function WebcamStream({
3594
4187
  }
3595
4188
  );
3596
4189
  }
4190
+
4191
+ // src/react/ClipPlayer.tsx
4192
+ var import_react8 = require("react");
4193
+ var import_jsx_runtime5 = require("react/jsx-runtime");
4194
+ function ClipPlayer({
4195
+ clip,
4196
+ getJwt,
4197
+ slackMs,
4198
+ autoPlay = true,
4199
+ muted = true,
4200
+ className,
4201
+ style
4202
+ }) {
4203
+ const videoRef = (0, import_react8.useRef)(null);
4204
+ const [phase, setPhase] = (0, import_react8.useState)({ kind: "waiting" });
4205
+ const getJwtRef = (0, import_react8.useRef)(getJwt);
4206
+ const autoPlayRef = (0, import_react8.useRef)(autoPlay);
4207
+ const slackMsRef = (0, import_react8.useRef)(slackMs);
4208
+ (0, import_react8.useEffect)(() => {
4209
+ getJwtRef.current = getJwt;
4210
+ autoPlayRef.current = autoPlay;
4211
+ slackMsRef.current = slackMs;
4212
+ });
4213
+ (0, import_react8.useEffect)(() => {
4214
+ const video = videoRef.current;
4215
+ if (!video) return;
4216
+ const abort = new AbortController();
4217
+ let cancelled = false;
4218
+ let hlsInstance = null;
4219
+ let manifestBlobUrl = null;
4220
+ const fail = (message) => {
4221
+ if (cancelled) return;
4222
+ setPhase({ kind: "error", message });
4223
+ };
4224
+ const attachPlayer = (manifestUrl) => __async(null, null, function* () {
4225
+ const canPlayNative = video.canPlayType("application/vnd.apple.mpegurl") !== "";
4226
+ if (canPlayNative) {
4227
+ video.src = manifestUrl;
4228
+ if (autoPlayRef.current) {
4229
+ video.play().catch(() => {
4230
+ });
4231
+ }
4232
+ if (!cancelled) setPhase({ kind: "ready" });
4233
+ return;
4234
+ }
4235
+ let HlsCtor;
4236
+ try {
4237
+ const mod = yield import("hls.js");
4238
+ HlsCtor = mod.default;
4239
+ } catch (e) {
4240
+ fail(
4241
+ "HLS playback unavailable in this browser. Install `hls.js` as a peer dependency, or use Download."
4242
+ );
4243
+ return;
4244
+ }
4245
+ if (cancelled) return;
4246
+ if (!HlsCtor.isSupported()) {
4247
+ fail("This browser cannot play HLS clips. Use Download instead.");
4248
+ return;
4249
+ }
4250
+ const hls = new HlsCtor();
4251
+ hls.loadSource(manifestUrl);
4252
+ hls.attachMedia(video);
4253
+ hls.on(HlsCtor.Events.MANIFEST_PARSED, () => {
4254
+ if (cancelled) return;
4255
+ setPhase({ kind: "ready" });
4256
+ if (autoPlayRef.current) {
4257
+ video.play().catch(() => {
4258
+ });
4259
+ }
4260
+ });
4261
+ hls.on(HlsCtor.Events.ERROR, (_evt, data) => {
4262
+ var _a;
4263
+ if (cancelled) return;
4264
+ if (data.fatal) {
4265
+ fail(`Playback error: ${(_a = data.details) != null ? _a : "unknown"}`);
4266
+ return;
4267
+ }
4268
+ console.warn("[Reactor.ClipPlayer] hls.js non-fatal error", data);
4269
+ });
4270
+ hlsInstance = hls;
4271
+ });
4272
+ const setup = () => __async(null, null, function* () {
4273
+ try {
4274
+ setPhase({ kind: "waiting" });
4275
+ const jwt = getJwtRef.current ? yield getJwtRef.current() : void 0;
4276
+ if (cancelled) return;
4277
+ const body = yield fetchPlaylist(clip.playlistUrl, {
4278
+ predictedReadyAtMs: clip.predictedReadyAtMs,
4279
+ slackMs: slackMsRef.current,
4280
+ jwt,
4281
+ signal: abort.signal
4282
+ });
4283
+ if (cancelled) return;
4284
+ setPhase({ kind: "loading" });
4285
+ manifestBlobUrl = createPlayableManifestUrl(body, clip.playlistUrl);
4286
+ yield attachPlayer(manifestBlobUrl);
4287
+ } catch (err) {
4288
+ if (cancelled) return;
4289
+ if (err instanceof DOMException && err.name === "AbortError") {
4290
+ return;
4291
+ }
4292
+ const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4293
+ fail(message);
4294
+ }
4295
+ });
4296
+ setup();
4297
+ return () => {
4298
+ cancelled = true;
4299
+ abort.abort();
4300
+ hlsInstance == null ? void 0 : hlsInstance.destroy();
4301
+ video.pause();
4302
+ video.removeAttribute("src");
4303
+ video.load();
4304
+ if (manifestBlobUrl) URL.revokeObjectURL(manifestBlobUrl);
4305
+ };
4306
+ }, [clip]);
4307
+ const overlayText = phase.kind === "waiting" ? "Waiting for clip\u2026" : phase.kind === "loading" ? "Loading player\u2026" : null;
4308
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
4309
+ "div",
4310
+ {
4311
+ className,
4312
+ style: __spreadValues({
4313
+ position: "relative",
4314
+ background: "#000",
4315
+ width: "100%",
4316
+ display: "flex",
4317
+ alignItems: "center",
4318
+ justifyContent: "center"
4319
+ }, style),
4320
+ children: [
4321
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4322
+ "video",
4323
+ {
4324
+ ref: videoRef,
4325
+ controls: true,
4326
+ playsInline: true,
4327
+ muted,
4328
+ style: {
4329
+ display: "block",
4330
+ width: "100%",
4331
+ height: "auto",
4332
+ maxHeight: "100%"
4333
+ }
4334
+ }
4335
+ ),
4336
+ overlayText && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4337
+ "div",
4338
+ {
4339
+ style: {
4340
+ position: "absolute",
4341
+ inset: 0,
4342
+ display: "flex",
4343
+ alignItems: "center",
4344
+ justifyContent: "center",
4345
+ color: "rgba(255,255,255,0.6)",
4346
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4347
+ letterSpacing: "0.1em",
4348
+ textTransform: "uppercase",
4349
+ pointerEvents: "none"
4350
+ },
4351
+ children: overlayText
4352
+ }
4353
+ ),
4354
+ phase.kind === "error" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4355
+ "div",
4356
+ {
4357
+ style: {
4358
+ position: "absolute",
4359
+ inset: 0,
4360
+ display: "flex",
4361
+ alignItems: "center",
4362
+ justifyContent: "center",
4363
+ padding: 24,
4364
+ background: "rgba(0,0,0,0.8)",
4365
+ color: "#ef4444",
4366
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4367
+ textAlign: "center"
4368
+ },
4369
+ children: phase.message
4370
+ }
4371
+ )
4372
+ ]
4373
+ }
4374
+ );
4375
+ }
4376
+
4377
+ // src/react/useClipDownload.ts
4378
+ var import_react9 = require("react");
4379
+ function useClipDownload(clip, options = {}) {
4380
+ var _a;
4381
+ const [state, setState] = (0, import_react9.useState)({ kind: "idle" });
4382
+ const clipRef = (0, import_react9.useRef)(clip);
4383
+ const filenameRef = (0, import_react9.useRef)(
4384
+ (_a = options.filename) != null ? _a : "reactor-clip.mp4"
4385
+ );
4386
+ const getJwtRef = (0, import_react9.useRef)(options.getJwt);
4387
+ (0, import_react9.useEffect)(() => {
4388
+ clipRef.current = clip;
4389
+ filenameRef.current = options.filename === void 0 ? "reactor-clip.mp4" : options.filename;
4390
+ getJwtRef.current = options.getJwt;
4391
+ });
4392
+ const inFlightRef = (0, import_react9.useRef)(false);
4393
+ const download = (0, import_react9.useCallback)(() => __async(null, null, function* () {
4394
+ if (inFlightRef.current) return void 0;
4395
+ inFlightRef.current = true;
4396
+ setState({ kind: "downloading", fetched: 0, total: 0 });
4397
+ try {
4398
+ const jwt = getJwtRef.current ? yield getJwtRef.current() : void 0;
4399
+ const blob = yield downloadClipAsFile(
4400
+ clipRef.current,
4401
+ filenameRef.current,
4402
+ {
4403
+ jwt,
4404
+ onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
4405
+ }
4406
+ );
4407
+ setState({ kind: "idle" });
4408
+ return blob;
4409
+ } catch (err) {
4410
+ const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4411
+ setState({ kind: "error", message });
4412
+ return void 0;
4413
+ } finally {
4414
+ inFlightRef.current = false;
4415
+ }
4416
+ }), []);
4417
+ const reset = (0, import_react9.useCallback)(() => setState({ kind: "idle" }), []);
4418
+ return { state, download, reset };
4419
+ }
4420
+
4421
+ // src/react/ClipDownloadButton.tsx
4422
+ var import_jsx_runtime6 = require("react/jsx-runtime");
4423
+ function ClipDownloadButton({
4424
+ clip,
4425
+ getJwt,
4426
+ filename = "reactor-clip.mp4",
4427
+ children,
4428
+ className,
4429
+ style,
4430
+ disabled
4431
+ }) {
4432
+ const { state, download } = useClipDownload(clip, { filename, getJwt });
4433
+ const downloading = state.kind === "downloading";
4434
+ const isDisabled = downloading || !!disabled;
4435
+ const content = typeof children === "function" ? children(state) : children !== void 0 ? children : defaultLabel(state);
4436
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
4437
+ "button",
4438
+ {
4439
+ type: "button",
4440
+ onClick: () => {
4441
+ void download();
4442
+ },
4443
+ disabled: isDisabled,
4444
+ title: state.kind === "error" ? state.message : void 0,
4445
+ className,
4446
+ style: __spreadValues({
4447
+ padding: "5px 12px",
4448
+ borderRadius: 4,
4449
+ border: "1px solid rgba(255,255,255,0.15)",
4450
+ background: "rgba(255,255,255,0.05)",
4451
+ color: "#fff",
4452
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4453
+ cursor: isDisabled ? "default" : "pointer",
4454
+ opacity: isDisabled ? 0.6 : 1,
4455
+ transition: "background-color 120ms ease"
4456
+ }, style),
4457
+ children: content
4458
+ }
4459
+ );
4460
+ }
4461
+ function defaultLabel(state) {
4462
+ if (state.kind === "downloading") {
4463
+ if (state.total > 0) {
4464
+ return `Downloading ${state.fetched}/${state.total}\u2026`;
4465
+ }
4466
+ return "Downloading\u2026";
4467
+ }
4468
+ return "Download";
4469
+ }
3597
4470
  // Annotate the CommonJS export names for ESM import in node:
3598
4471
  0 && (module.exports = {
3599
4472
  AbortError,
4473
+ ClipDownloadButton,
4474
+ ClipPlayer,
3600
4475
  ConflictError,
3601
4476
  DEFAULT_BASE_URL,
4477
+ DEFAULT_CLIP_REQUEST_TIMEOUT_MS,
4478
+ DEFAULT_PLAYLIST_POLL_SLACK_MS,
3602
4479
  FileRef,
3603
4480
  Reactor,
3604
4481
  ReactorController,
3605
4482
  ReactorProvider,
3606
4483
  ReactorView,
4484
+ RecordingClient,
4485
+ RecordingError,
4486
+ RuntimeRecordingMessageType,
3607
4487
  WebcamStream,
4488
+ clipFromPayload,
4489
+ createPlayableManifestUrl,
4490
+ downloadClipAsFile,
4491
+ fetchPlaylist,
3608
4492
  isAbortError,
4493
+ parsePlaylist,
4494
+ rewriteUrlHost,
4495
+ useClipDownload,
3609
4496
  useReactor,
3610
4497
  useReactorInternalMessage,
3611
4498
  useReactorMessage,