@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.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.3",
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,46 +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/sdp-transform": "^2.15.0",
134
- "@types/ws": "^8.18.1",
155
+ "hls.js": "^1.6.0",
135
156
  prettier: "^3.6.2",
136
157
  tsup: "^8.5.0",
137
158
  typescript: "^5.8.3",
138
159
  vitest: "^3.0.0"
139
- },
140
- dependencies: {
141
- "@bufbuild/protobuf": "^2.0.0",
142
- chalk: "^5.3.0",
143
- inquirer: "^9.3.0",
144
- "sdp-transform": "^3.0.0",
145
- "simple-git": "^3.24.0",
146
- ws: "^8.18.3",
147
- zod: "^4.0.5"
148
- },
149
- peerDependencies: {
150
- react: "^17.0.0 || ^18.0.0 || ^19.0.0",
151
- zustand: "^5.0.6"
152
160
  }
153
161
  };
154
162
 
@@ -1825,19 +1833,542 @@ var WebRTCTransportClient = class {
1825
1833
  };
1826
1834
 
1827
1835
  // src/core/Reactor.ts
1836
+ import { z as z3 } from "zod";
1837
+
1838
+ // src/utils/recording.ts
1828
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
1829
2360
  var LOCAL_COORDINATOR_URL = "http://localhost:8080";
1830
2361
  var DEFAULT_BASE_URL = "https://api.reactor.inc";
1831
- var TrackHintSchema = z2.object({
1832
- name: z2.string(),
1833
- kind: z2.enum(["video", "audio"]),
1834
- 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"])
1835
2366
  });
1836
- var OptionsSchema = z2.object({
1837
- apiUrl: z2.string().default(DEFAULT_BASE_URL),
1838
- modelName: z2.string(),
1839
- local: z2.boolean().default(false),
1840
- 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()
1841
2372
  });
1842
2373
  var Reactor = class {
1843
2374
  constructor(options) {
@@ -1854,6 +2385,19 @@ var Reactor = class {
1854
2385
  if (validatedOptions.modelTracks) {
1855
2386
  this.presetTracks = validatedOptions.modelTracks;
1856
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
+ });
1857
2401
  }
1858
2402
  on(event, handler) {
1859
2403
  if (!this.eventListeners.has(event)) {
@@ -1994,6 +2538,41 @@ var Reactor = class {
1994
2538
  return new FileRef(slot.presigned_id, name, mimeType, size);
1995
2539
  });
1996
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
+ }
1997
2576
  /**
1998
2577
  * Publishes a MediaStreamTrack to a named sendonly track.
1999
2578
  * The transceiver is already set up from capabilities — this just
@@ -3547,17 +4126,311 @@ function WebcamStream({
3547
4126
  }
3548
4127
  );
3549
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
+ }
3550
4409
  export {
3551
4410
  AbortError,
4411
+ ClipDownloadButton,
4412
+ ClipPlayer,
3552
4413
  ConflictError,
3553
4414
  DEFAULT_BASE_URL,
4415
+ DEFAULT_CLIP_REQUEST_TIMEOUT_MS,
4416
+ DEFAULT_PLAYLIST_POLL_SLACK_MS,
3554
4417
  FileRef,
3555
4418
  Reactor,
3556
4419
  ReactorController,
3557
4420
  ReactorProvider,
3558
4421
  ReactorView,
4422
+ RecordingClient,
4423
+ RecordingError,
4424
+ RuntimeRecordingMessageType,
3559
4425
  WebcamStream,
4426
+ clipFromPayload,
4427
+ createPlayableManifestUrl,
4428
+ downloadClipAsFile,
4429
+ fetchPlaylist,
3560
4430
  isAbortError,
4431
+ parsePlaylist,
4432
+ rewriteUrlHost,
4433
+ useClipDownload,
3561
4434
  useReactor,
3562
4435
  useReactorInternalMessage,
3563
4436
  useReactorMessage,