@reactor-team/js-sdk 2.9.3 → 2.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -178,6 +178,388 @@ interface ConnectionStats {
178
178
  }
179
179
  type ReactorEvent = "statusChanged" | "sessionIdChanged" | "message" | "runtimeMessage" | "trackReceived" | "error" | "sessionExpirationChanged" | "capabilitiesReceived" | "statsUpdate";
180
180
 
181
+ /**
182
+ * Lazy resolver for the Coordinator bearer token. The SDK calls this
183
+ * immediately before each authenticated HTTP request, so short-lived
184
+ * tokens (Clerk session JWTs, etc.) are refreshed transparently.
185
+ * Returning `""` suppresses the `Authorization` header entirely.
186
+ */
187
+ type JwtResolver = () => string | Promise<string>;
188
+ /** Static token, or a {@link JwtResolver} invoked per request. */
189
+ type JwtSource = string | JwtResolver;
190
+ /** Wrap a {@link JwtSource} into a {@link JwtResolver}. */
191
+ declare function normalizeJwtSource(source: JwtSource): JwtResolver;
192
+
193
+ /**
194
+ * Stateless primitives for the Reactor recording feature.
195
+ *
196
+ * This module owns:
197
+ * - Public-facing {@link Clip} type, {@link RecordingError} class, and
198
+ * the `RuntimeRecordingMessageType` enum.
199
+ * - Wire schemas (`ClipReadyPayloadSchema`, `ClipFailedPayloadSchema`)
200
+ * plus `clipFromPayload` to convert snake_case wire payloads into
201
+ * camelCase `Clip` objects.
202
+ * - HTTP helpers `fetchPlaylist` (deadline-driven polling) and
203
+ * `parsePlaylist` (HLS `.m3u8` parser).
204
+ * - The `downloadClipAsFile` helper that streams the referenced
205
+ * fMP4 chunks, remuxes them into a flat social-media-ready MP4
206
+ * via `mp4box` (PTS=0, faststart, `major_brand=isom`), and
207
+ * returns a Blob for browser download.
208
+ *
209
+ * Stateful pieces (FIFO promise correlator, in-flight request
210
+ * lifecycle, integration with Reactor's event bus) live in the
211
+ * `RecordingClient` class in `core/RecordingClient.ts`.
212
+ *
213
+ * Wire contract is documented end-to-end in the *Video Recording
214
+ * Feature* Notion page; the runtime side ships in
215
+ * `reactor_runtime/recording/`.
216
+ */
217
+
218
+ /**
219
+ * Names of the runtime-scoped messages used by the recording feature.
220
+ * Outbound names are sent via `Reactor.sendCommand(name, …, "runtime")`;
221
+ * inbound names appear as `message.type` on `runtimeMessage` events.
222
+ */
223
+ declare const RuntimeRecordingMessageType: {
224
+ readonly REQUEST_CLIP: "requestClip";
225
+ readonly REQUEST_RECORDING: "requestRecording";
226
+ readonly CLIP_READY: "clipReady";
227
+ readonly CLIP_FAILED: "clipFailed";
228
+ };
229
+ /** Discriminator on a {@link Clip}. `"snap"` from `requestClip`, `"recording"` from `requestRecording`. */
230
+ type ClipKind = "snap" | "recording";
231
+ /**
232
+ * Resolved outcome of a {@link Reactor.requestClip} / {@link Reactor.requestRecording} call.
233
+ *
234
+ * The runtime returns immediately on every request — it does *not*
235
+ * block until the in-progress chunk has been finalised. The response
236
+ * is a *promise*: `endMarker` reflects wall-clock at request time
237
+ * and may point inside a chunk ffmpeg is still writing. The
238
+ * `/clips` manifest endpoint returns `202 Retry-After` while that
239
+ * chunk is in flight; the SDK polls until `200`.
240
+ *
241
+ * - `startMarker` / `endMarker` / `nowMarker` are session-relative
242
+ * seconds since recorder start.
243
+ * - `predictedReadyAtMs` is a **Unix epoch in milliseconds** — the
244
+ * runtime's estimate of when the boundary chunk will be servable
245
+ * by `/clips`. Compare against `Date.now()` to drive a "ready in
246
+ * Ns" indicator. The SDK uses this as the polling deadline: past
247
+ * `predictedReadyAtMs + slackMs` and still 202, the SDK fails with
248
+ * `CLIP_NOT_READY` on the assumption the runtime crashed.
249
+ * - `playlistUrl` is short-lived in production (the embedded chunk
250
+ * URLs are presigned for a few minutes). Re-issuing the request
251
+ * produces a fresh URL with fresh presigning.
252
+ */
253
+ interface Clip {
254
+ sessionId: string;
255
+ kind: ClipKind;
256
+ startMarker: number;
257
+ endMarker: number;
258
+ nowMarker: number;
259
+ predictedReadyAtMs: number;
260
+ playlistUrl: string;
261
+ }
262
+ /**
263
+ * Error thrown when a recording request cannot be served.
264
+ *
265
+ * `code` is a stable, machine-readable identifier; `reason` is the
266
+ * raw string the runtime / manifest endpoint returned (passed through
267
+ * verbatim from `clipFailed.reason`, the `/clips` HTTP body, or the
268
+ * SDK's pre-flight check).
269
+ */
270
+ declare class RecordingError extends Error {
271
+ readonly code: "RECORDER_DISABLED" | "INVALID_DURATION" | "REQUEST_TIMEOUT" | "DISCONNECTED" | "CLIP_GONE" | "CLIP_NOT_READY" | "PLAYLIST_FETCH_FAILED" | "CHUNK_FETCH_FAILED" | "INVALID_PLAYLIST" | "DOWNLOAD_UNSUPPORTED" | "INTERNAL_ERROR";
272
+ readonly reason: string;
273
+ constructor(code: "RECORDER_DISABLED" | "INVALID_DURATION" | "REQUEST_TIMEOUT" | "DISCONNECTED" | "CLIP_GONE" | "CLIP_NOT_READY" | "PLAYLIST_FETCH_FAILED" | "CHUNK_FETCH_FAILED" | "INVALID_PLAYLIST" | "DOWNLOAD_UNSUPPORTED" | "INTERNAL_ERROR", reason: string);
274
+ }
275
+ /** `clipReady.data` payload as serialised by `ClipResult.to_dict()`. */
276
+ declare const ClipReadyPayloadSchema: z.ZodObject<{
277
+ session_id: z.ZodString;
278
+ kind: z.ZodEnum<{
279
+ snap: "snap";
280
+ recording: "recording";
281
+ }>;
282
+ start_marker: z.ZodNumber;
283
+ end_marker: z.ZodNumber;
284
+ now_marker: z.ZodNumber;
285
+ predicted_ready_at_ms: z.ZodNumber;
286
+ playlist_url: z.ZodString;
287
+ }, z.core.$loose>;
288
+ type ClipReadyPayload = z.infer<typeof ClipReadyPayloadSchema>;
289
+ /** `clipFailed.data` payload — short reason string from the runtime. */
290
+ declare const ClipFailedPayloadSchema: z.ZodObject<{
291
+ reason: z.ZodDefault<z.ZodString>;
292
+ }, z.core.$loose>;
293
+ type ClipFailedPayload = z.infer<typeof ClipFailedPayloadSchema>;
294
+ /** Options for {@link clipFromPayload}. */
295
+ interface ParseClipOptions {
296
+ /**
297
+ * Coordinator base URL. When set, resolves `payload.playlist_url`
298
+ * against this base — used to convert the runtime's path-only
299
+ * playlist URL (``/clips?session_id=…``) into an absolute URL the
300
+ * browser/SDK can fetch. Also handles the legacy case where an
301
+ * older runtime emits an absolute URL bound to its own
302
+ * ``0.0.0.0`` listener: the host/port are rewritten onto the
303
+ * coordinator.
304
+ */
305
+ coordinatorBaseUrl?: string;
306
+ }
307
+ /**
308
+ * Convert a validated {@link ClipReadyPayload} into the public {@link Clip}.
309
+ * Pure: no IO, no side effects.
310
+ */
311
+ declare function clipFromPayload(payload: ClipReadyPayload, options?: ParseClipOptions): Clip;
312
+ /**
313
+ * Resolve `target` against `base`, returning an absolute URL.
314
+ *
315
+ * Two cases:
316
+ *
317
+ * * **Path-only / relative target** (no scheme — e.g. the
318
+ * runtime's current ``/clips?session_id=…`` shape): joined
319
+ * against ``base`` via ``new URL(target, base)``, preserving
320
+ * path, query, and fragment.
321
+ * * **Absolute target** (``http://…`` / ``https://…``, e.g. a legacy
322
+ * runtime emitting a URL bound to its own ``0.0.0.0`` listener):
323
+ * scheme, hostname, and port are replaced with ``base``'s,
324
+ * preserving path, query, and fragment.
325
+ *
326
+ * Returns the original ``target`` on any parse failure rather than
327
+ * throwing — the SDK consumes the URL eagerly and shouldn't break
328
+ * a session over a malformed clip envelope.
329
+ */
330
+ declare function rewriteUrlHost(target: string, base: string): string;
331
+ /** Internal — segments referenced by an HLS manifest, in playback order. */
332
+ interface ParsedPlaylist {
333
+ initUrl: string;
334
+ segmentUrls: string[];
335
+ }
336
+ /**
337
+ * Default grace period after `predictedReadyAtMs` before
338
+ * {@link fetchPlaylist} gives up. Applied from
339
+ * `max(predictedReadyAtMs, pollStart)` so late clicks still get the
340
+ * full window.
341
+ */
342
+ declare const DEFAULT_PLAYLIST_POLL_SLACK_MS = 15000;
343
+ interface FetchPlaylistOptions {
344
+ /**
345
+ * Unix epoch (ms) when the runtime predicts the boundary chunk will
346
+ * be servable. Pass `clip.predictedReadyAtMs` here. When set, polling
347
+ * continues until `predictedReadyAtMs + slackMs`; once past, a
348
+ * stuck `202` produces `CLIP_NOT_READY` (assume runtime crashed).
349
+ */
350
+ predictedReadyAtMs?: number;
351
+ /** Grace period after `predictedReadyAtMs`. Default {@link DEFAULT_PLAYLIST_POLL_SLACK_MS}. */
352
+ slackMs?: number;
353
+ /**
354
+ * Hard cap on the per-poll wait. The server's `Retry-After` header is
355
+ * honored but clamped. Default 2000 ms keeps pending UI snappy.
356
+ */
357
+ maxRetryDelayMs?: number;
358
+ /** Floor on the per-poll wait so we don't hot-loop on cheap networks. Default 200 ms. */
359
+ minRetryDelayMs?: number;
360
+ /**
361
+ * Fallback retry count used when `predictedReadyAtMs` is omitted
362
+ * (e.g. someone calls `fetchPlaylist` directly with a saved URL,
363
+ * outside of a fresh `Clip`). Default 5.
364
+ */
365
+ maxRetries?: number;
366
+ /** Aborts in-flight fetches and the inter-poll sleep. */
367
+ signal?: AbortSignal;
368
+ /**
369
+ * Coordinator JWT. When set, attached as `Authorization: Bearer
370
+ * <jwt>` on the manifest GET — the Coordinator hop. In local mode
371
+ * (HttpRuntime), leave undefined.
372
+ */
373
+ jwt?: string;
374
+ }
375
+ /**
376
+ * Fetch the playlist URL, polling on `202 Accepted` (which the manifest
377
+ * endpoint returns while the boundary chunk is still uploading).
378
+ *
379
+ * Polling deadline is driven by `predictedReadyAtMs + slackMs` when a
380
+ * `Clip` was just minted by the runtime; without that field the
381
+ * function falls back to `maxRetries` attempts. Either way:
382
+ * - `200` → returns the manifest body.
383
+ * - `410` / `404` → throws `CLIP_GONE`.
384
+ * - `5xx`/other → throws `PLAYLIST_FETCH_FAILED` (no retry).
385
+ * - Past the deadline / retries with stuck `202` → throws
386
+ * `CLIP_NOT_READY` (the runtime probably crashed mid-chunk).
387
+ */
388
+ declare function fetchPlaylist(playlistUrl: string, options?: FetchPlaylistOptions): Promise<string>;
389
+ /**
390
+ * Parse an HLS `.m3u8` body into the init segment URL plus the ordered
391
+ * list of media segment URLs. Resolves relative URLs against the
392
+ * playlist URL itself.
393
+ */
394
+ declare function parsePlaylist(manifestBody: string, playlistUrl: string): ParsedPlaylist;
395
+ /**
396
+ * Wrap an HLS manifest body in a `blob:` URL suitable for `<video src>`
397
+ * or `hls.js`. Bypasses the "player can't set Authorization headers"
398
+ * problem: the manifest body is served from browser memory, and the
399
+ * chunk URLs inside are already-signed S3 GETs.
400
+ *
401
+ * Path-only / relative chunk URLs in the body are absolutized against
402
+ * ``playlistUrl`` first. Without this rewrite the browser would
403
+ * resolve them against the ``blob:`` URL's effective base — the page's
404
+ * origin — and a local-dev frontend on (e.g.) port 3000 would issue
405
+ * chunk fetches against its own dev server instead of the
406
+ * HttpRuntime's ``/clips/chunks/...`` endpoint on port 8080. In
407
+ * production / kind-cluster mode the manifest already carries absolute
408
+ * presigned S3 URLs and `resolveAgainst` is a no-op on them.
409
+ *
410
+ * Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
411
+ * when playback tears down. Browser-only; throws `INVALID_PLAYLIST`
412
+ * outside a DOM environment.
413
+ */
414
+ declare function createPlayableManifestUrl(manifestBody: string, playlistUrl: string): string;
415
+ interface DownloadClipOptions {
416
+ /**
417
+ * Coordinator JWT. Attached on the manifest GET only; the chunks
418
+ * referenced inside the manifest are S3 presigned URLs and are
419
+ * fetched unauthenticated.
420
+ */
421
+ jwt?: string;
422
+ /** Forwarded to every request. Cancels both the playlist poll and any in-flight chunk fetches. */
423
+ signal?: AbortSignal;
424
+ /** Called after each chunk completes — useful for progress UI. */
425
+ onProgress?: (info: {
426
+ fetched: number;
427
+ total: number;
428
+ bytes: number;
429
+ }) => void;
430
+ }
431
+ /**
432
+ * Stream the chunks referenced by `clip.playlistUrl`, remux the
433
+ * assembled bytes into a flat social-media-ready MP4, and (when
434
+ * `filename` is non-null) trigger a browser-native `<a download>`.
435
+ * Pass `filename: null` to skip the download trigger and just
436
+ * receive the Blob.
437
+ *
438
+ * The remux step rewrites the container only — H.264 NAL units and
439
+ * AAC packets pass through unchanged — so `start_time=0`,
440
+ * `+faststart`, and `major_brand=isom` come for free without any
441
+ * re-encode cost. See {@link maybeRemux} for the fallback
442
+ * semantics on the rare parse failure.
443
+ */
444
+ declare function downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
445
+
446
+ /**
447
+ * Per-Reactor recording client. Owns the FIFO promise correlator for
448
+ * inbound `clipReady` / `clipFailed` runtime messages and the
449
+ * lifecycle hooks (subscribe on construct, reject pending requests
450
+ * on disconnect). Reactor exposes thin delegations for the common
451
+ * case; this class is exported for advanced consumers and isolated
452
+ * testing.
453
+ */
454
+
455
+ /** Default per-request timeout for `clipReady` / `clipFailed`. */
456
+ declare const DEFAULT_CLIP_REQUEST_TIMEOUT_MS = 10000;
457
+ /** Slim adapter the {@link RecordingClient} requires from its host. */
458
+ interface RecordingClientHost {
459
+ /**
460
+ * Subscribe to runtime-scoped messages on the data channel.
461
+ * Returns an unsubscribe function. Mirrors the
462
+ * `reactor.on("runtimeMessage", …)` pattern.
463
+ */
464
+ onRuntimeMessage: (handler: (message: unknown) => void) => () => void;
465
+ /**
466
+ * Subscribe to status changes (so the client can reject pending
467
+ * requests on disconnect). Returns an unsubscribe function.
468
+ */
469
+ onStatusChanged: (handler: (status: ReactorStatus) => void) => () => void;
470
+ /**
471
+ * Send a runtime-scoped command on the data channel. The
472
+ * `RecordingClient` uses this to fire `requestClip` /
473
+ * `requestRecording`.
474
+ */
475
+ sendRuntimeCommand: (command: string, data: Record<string, unknown>) => Promise<void>;
476
+ /** Current connection status — guards `requestClip` before it goes on the wire. */
477
+ getStatus: () => ReactorStatus;
478
+ /**
479
+ * Coordinator base URL used to resolve `clip.playlistUrl` against.
480
+ *
481
+ * The runtime now emits a path-only ``playlist_url`` (e.g.
482
+ * ``/clips?session_id=…``) so the SDK is the absolute-origin owner
483
+ * for both local-dev (HttpRuntime on the SDK's ``apiUrl``) and
484
+ * production (Coordinator on the SDK's ``apiUrl``). We always
485
+ * resolve against the ``Reactor``'s coordinator URL — there is no
486
+ * remote-vs-local divergence on the read path.
487
+ *
488
+ * For backwards-compat with older runtimes that emitted absolute
489
+ * URLs (scheme + host bound to the runtime's own listener,
490
+ * e.g. ``http://0.0.0.0:8080/clips?…``), the same URL is also used
491
+ * to rewrite the host onto the coordinator — see
492
+ * ``rewriteUrlHost`` in ``utils/recording.ts``.
493
+ */
494
+ getCoordinatorBaseUrl: () => string | undefined;
495
+ }
496
+ declare class RecordingClient {
497
+ private readonly host;
498
+ private pendingClipRequests;
499
+ /** Timeout applied per request; configurable for tests. */
500
+ private readonly requestTimeoutMs;
501
+ /** Cleanup handles for the host event subscriptions. */
502
+ private readonly unsubscribers;
503
+ constructor(host: RecordingClientHost, options?: {
504
+ requestTimeoutMs?: number;
505
+ });
506
+ /**
507
+ * Request a clip covering the last `durationSeconds` of the live
508
+ * session. See {@link Reactor.requestClip}.
509
+ */
510
+ requestClip(durationSeconds: number): Promise<Clip>;
511
+ /**
512
+ * Request a clip covering the entire session up to "now". See
513
+ * {@link Reactor.requestRecording}.
514
+ */
515
+ requestRecording(): Promise<Clip>;
516
+ /**
517
+ * Poll `/clips` and return the raw manifest body. Same polling
518
+ * semantics as the bare {@link fetchPlaylist} helper; the caller is
519
+ * responsible for supplying the Coordinator JWT via `options.jwt`
520
+ * (origin-scoped to `clip.playlistUrl`). In local mode against the
521
+ * HttpRuntime, `options.jwt` should be omitted.
522
+ */
523
+ fetchPlaylist(clip: Clip, options?: FetchPlaylistOptions): Promise<string>;
524
+ /**
525
+ * Fetch the manifest and return a `blob:` URL suitable for
526
+ * `<video src>` / `hls.js`. The player reads the manifest from
527
+ * browser memory; chunk URLs inside are presigned S3 GETs.
528
+ *
529
+ * Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
530
+ * when playback tears down. Pass `options.jwt` for production
531
+ * `/clips` (the Coordinator hop) — see {@link FetchPlaylistOptions}.
532
+ */
533
+ getPlayableManifestUrl(clip: Clip, options?: FetchPlaylistOptions): Promise<string>;
534
+ /**
535
+ * Thin delegation to {@link downloadClipAsFile}. Caller must pass
536
+ * `options.jwt` in production — see {@link DownloadClipOptions}.
537
+ */
538
+ downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
539
+ /**
540
+ * Drop every pending request and unsubscribe from host events.
541
+ * Safe to call multiple times; further `requestClip` /
542
+ * `requestRecording` calls after `destroy()` will hang waiting for
543
+ * a response that will never arrive — host should not call into
544
+ * the client after destroy.
545
+ */
546
+ destroy(): void;
547
+ /**
548
+ * Register a pending FIFO entry, send the runtime message via
549
+ * the host, and resolve when the next `clipReady` / `clipFailed`
550
+ * arrives.
551
+ */
552
+ private dispatchClipRequest;
553
+ /**
554
+ * Match inbound `clipReady` / `clipFailed` to the next pending
555
+ * request FIFO; ignore every other runtime message type.
556
+ */
557
+ private onRuntimeMessage;
558
+ private onStatusChanged;
559
+ /** Reject every in-flight request with a typed disconnect error. */
560
+ private rejectPending;
561
+ }
562
+
181
563
  declare const DEFAULT_BASE_URL = "https://api.reactor.inc";
182
564
  declare const OptionsSchema: z.ZodObject<{
183
565
  apiUrl: z.ZodDefault<z.ZodString>;
@@ -214,8 +596,18 @@ declare class Reactor {
214
596
  private tracks;
215
597
  private presetTracks?;
216
598
  private sessionResponse?;
599
+ private jwtResolver?;
600
+ /** Per-Reactor recording client. See {@link RecordingClient}. */
601
+ readonly recording: RecordingClient;
217
602
  constructor(options: Options);
218
603
  private eventListeners;
604
+ /**
605
+ * Returns the JWT resolver supplied to the most recent
606
+ * {@link connect} call, or `undefined` if none was set (pre-connect
607
+ * or local mode). Used by clip surfaces as a fallback when their
608
+ * own `getJwt` prop is omitted.
609
+ */
610
+ getJwtResolver(): JwtResolver | undefined;
219
611
  on(event: ReactorEvent, handler: EventHandler): void;
220
612
  off(event: ReactorEvent, handler: EventHandler): void;
221
613
  emit(event: ReactorEvent, ...args: any[]): void;
@@ -244,6 +636,29 @@ declare class Reactor {
244
636
  uploadFile(file: File | Blob, options?: {
245
637
  name?: string;
246
638
  }): Promise<FileRef>;
639
+ /**
640
+ * Request a clip covering the last `durationSeconds` of the live
641
+ * session. Capped server-side at `recording.clip_max_seconds`
642
+ * (default 5 minutes). Resolves with a {@link Clip} whose
643
+ * `playlistUrl` can be handed to any HLS-capable player.
644
+ *
645
+ * @throws {RecordingError} on invalid input, transport failure,
646
+ * timeout, runtime-side `clipFailed`, or disconnect mid-request.
647
+ */
648
+ requestClip(durationSeconds: number): Promise<Clip>;
649
+ /**
650
+ * Request a clip covering the entire session up to "now". Same
651
+ * mechanics as {@link requestClip} with `start = 0`; only the
652
+ * resolved {@link Clip.kind} discriminator differs.
653
+ */
654
+ requestRecording(): Promise<Clip>;
655
+ /**
656
+ * Stream the chunks referenced by `clip.playlistUrl` and trigger a
657
+ * native browser download of the assembled fragmented-MP4 Blob.
658
+ * Pass `filename: null` to skip the download trigger and receive
659
+ * the Blob (useful for non-DOM consumers and tests).
660
+ */
661
+ downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
247
662
  /**
248
663
  * Publishes a MediaStreamTrack to a named sendonly track.
249
664
  * The transceiver is already set up from capabilities — this just
@@ -257,9 +672,12 @@ declare class Reactor {
257
672
  reconnect(options?: ConnectOptions): Promise<void>;
258
673
  /**
259
674
  * Connects to the coordinator, creates a session, then establishes
260
- * the transport using server-declared capabilities.
675
+ * the transport using server-declared capabilities. `jwtToken` may
676
+ * be a static string or a {@link JwtSource} resolver; pass a
677
+ * resolver when the token is short-lived so each Coordinator HTTP
678
+ * hop sees a fresh value.
261
679
  */
262
- connect(jwtToken?: string, options?: ConnectOptions): Promise<void>;
680
+ connect(jwtToken?: JwtSource, options?: ConnectOptions): Promise<void>;
263
681
  /**
264
682
  * Sets up event handlers for the transport client.
265
683
  * Each handler captures the client reference to ignore stale events.
@@ -296,11 +714,12 @@ interface ReactorState {
296
714
  lastError?: ReactorError;
297
715
  sessionId?: string;
298
716
  sessionExpiration?: number;
299
- jwtToken?: string;
717
+ /** Token source for Coordinator HTTP calls — see {@link JwtSource}. */
718
+ jwtToken?: JwtSource;
300
719
  }
301
720
  interface ReactorActions {
302
721
  sendCommand(command: string, data: any, scope?: MessageScope): Promise<void>;
303
- connect(jwtToken?: string, options?: ConnectOptions): Promise<void>;
722
+ connect(jwtToken?: JwtSource, options?: ConnectOptions): Promise<void>;
304
723
  disconnect(recoverable?: boolean): Promise<void>;
305
724
  publish(name: string, track: MediaStreamTrack): Promise<void>;
306
725
  unpublish(name: string): Promise<void>;
@@ -316,7 +735,8 @@ type ReactorStore = ReactorState & ReactorActions & {
316
735
  internal: ReactorInternalState;
317
736
  };
318
737
  interface ReactorInitializationProps extends Options {
319
- jwtToken?: string;
738
+ /** Token source for the underlying {@link Reactor} — see {@link JwtSource}. */
739
+ jwtToken?: JwtSource;
320
740
  }
321
741
 
322
742
  /**
@@ -327,12 +747,22 @@ interface ReactorConnectOptions extends ConnectOptions {
327
747
  /** Whether to automatically connect when the provider mounts. Default: false. */
328
748
  autoConnect?: boolean;
329
749
  }
330
- interface ReactorProviderProps extends ReactorInitializationProps {
750
+ interface ReactorProviderProps extends Omit<ReactorInitializationProps, "jwtToken"> {
331
751
  connectOptions?: ReactorConnectOptions;
752
+ /**
753
+ * Static JWT token. Use when you hold a long-lived SDK JWT (e.g.
754
+ * minted via `/tokens`). For short-lived tokens use {@link getJwt}.
755
+ */
332
756
  jwtToken?: string;
757
+ /**
758
+ * Lazy JWT resolver invoked immediately before each Coordinator
759
+ * HTTP request. Preferred for short-lived tokens. Wins over
760
+ * {@link jwtToken} when both are provided.
761
+ */
762
+ getJwt?: JwtResolver;
333
763
  children?: ReactNode;
334
764
  }
335
- declare function ReactorProvider({ children, connectOptions, jwtToken, ...props }: ReactorProviderProps): react_jsx_runtime.JSX.Element;
765
+ declare function ReactorProvider({ children, connectOptions, jwtToken, getJwt, ...props }: ReactorProviderProps): react_jsx_runtime.JSX.Element;
336
766
  declare function useReactorStore<T = ReactorStore>(selector: (state: ReactorStore) => T): T;
337
767
 
338
768
  interface ReactorViewProps {
@@ -380,6 +810,249 @@ interface WebcamStreamProps {
380
810
  }
381
811
  declare function WebcamStream({ track, className, style, videoConstraints, showWebcam, videoObjectFit, }: WebcamStreamProps): react_jsx_runtime.JSX.Element;
382
812
 
813
+ /**
814
+ * Video preview for a captured {@link Clip}.
815
+ *
816
+ * Renders an HLS manifest through the browser's native
817
+ * ``<video controls>`` element. On Safari / iOS the manifest is
818
+ * attached directly (native HLS support). On Chrome / Firefox / Edge
819
+ * ``hls.js`` is dynamically imported — declared as an **optional peer
820
+ * dependency** so consumers who don't use this component aren't billed
821
+ * the ~80 KB. If ``hls.js`` isn't installed and native HLS isn't
822
+ * available the player surfaces an inline error overlay; the
823
+ * underlying chunks remain downloadable via {@link useClipDownload} /
824
+ * {@link ClipDownloadButton} (which don't depend on hls.js at all).
825
+ *
826
+ * **Preview only.** This component intentionally does *not* render a
827
+ * download UI. Compose it with {@link ClipDownloadButton} or build
828
+ * your own download surface around {@link useClipDownload} — the
829
+ * separation keeps both pieces independently extendible and avoids
830
+ * baking layout decisions into the SDK.
831
+ *
832
+ * Unlike {@link ReactorView} / {@link WebcamStream} this component
833
+ * **does not require a ``ReactorProvider``** in the tree. It
834
+ * operates on the ``Clip`` value alone, so it stays usable after
835
+ * ``reactor.disconnect()`` and works with clips loaded from
836
+ * fixtures, server logs, or any other source. When a
837
+ * ``ReactorProvider`` is mounted above, an omitted ``getJwt``
838
+ * inherits the provider's resolver.
839
+ *
840
+ * @example Compose with the download button (explicit `getJwt`):
841
+ * ```tsx
842
+ * <div>
843
+ * <ClipPlayer clip={clip} getJwt={() => jwt} />
844
+ * <ClipDownloadButton clip={clip} getJwt={() => jwt} />
845
+ * </div>
846
+ * ```
847
+ *
848
+ * @example Local dev (HttpRuntime, no auth on /clips):
849
+ * ```tsx
850
+ * <ClipPlayer clip={clip} />
851
+ * ```
852
+ */
853
+ interface ClipPlayerProps {
854
+ /**
855
+ * The captured clip to play. When this prop changes by reference
856
+ * the player re-fetches the manifest and re-attaches the player.
857
+ */
858
+ clip: Clip;
859
+ /**
860
+ * Lazy resolver for the Coordinator JWT used on the ``/clips``
861
+ * manifest GET. Called at request time so token refreshes are
862
+ * picked up automatically.
863
+ *
864
+ * - **Production:** required outside a ``<ReactorProvider>``;
865
+ * optional inside one (inherits the provider's resolver).
866
+ * - **Local-dev (HttpRuntime):** omit — ``/clips`` is auth-free.
867
+ *
868
+ * Chunk URLs inside the manifest are presigned (prod) or
869
+ * unauthenticated (local) and are fetched without
870
+ * ``Authorization`` in either case.
871
+ */
872
+ getJwt?: () => string | Promise<string>;
873
+ /**
874
+ * Override the grace period beyond ``clip.predictedReadyAtMs``
875
+ * before the SDK gives up polling the ``/clips`` manifest endpoint
876
+ * with ``CLIP_NOT_READY``. Defaults to
877
+ * {@link DEFAULT_PLAYLIST_POLL_SLACK_MS} (15 s) — enough for snap
878
+ * clips, but long-running session recordings may legitimately need
879
+ * a minute or more for the final boundary chunk to finish encoding
880
+ * + uploading, in which case pass a larger value (e.g. ``120_000``
881
+ * for two-minute grace). Forwarded directly to
882
+ * {@link fetchPlaylist}'s ``slackMs`` option — see that helper for
883
+ * the polling semantics.
884
+ */
885
+ slackMs?: number;
886
+ /** Play automatically once the manifest is attached. Default ``true``. */
887
+ autoPlay?: boolean;
888
+ /**
889
+ * Start muted. Default ``true`` because browser autoplay policies
890
+ * block audio-bearing video from playing without a user gesture;
891
+ * the user can unmute via the native ``<video controls>``.
892
+ */
893
+ muted?: boolean;
894
+ className?: string;
895
+ style?: React.CSSProperties;
896
+ }
897
+ declare function ClipPlayer({ clip, getJwt, slackMs, autoPlay, muted, className, style, }: ClipPlayerProps): react_jsx_runtime.JSX.Element;
898
+
899
+ /**
900
+ * State machine for an in-progress clip download.
901
+ *
902
+ * - ``idle``: no download in flight (initial state, and what the hook
903
+ * returns to after a successful save).
904
+ * - ``downloading``: chunks are being fetched. ``fetched`` and
905
+ * ``total`` count the number of chunks (init segment + media
906
+ * segments) — useful for a progress bar. ``total`` is 0 until the
907
+ * manifest is parsed and the chunk count is known.
908
+ * - ``error``: most recent attempt failed; the ``message`` is suitable
909
+ * for surfacing inline. ``RecordingError`` instances are formatted
910
+ * as ``"<CODE>: <reason>"`` for grep-ability.
911
+ */
912
+ type ClipDownloadState = {
913
+ kind: "idle";
914
+ } | {
915
+ kind: "downloading";
916
+ fetched: number;
917
+ total: number;
918
+ } | {
919
+ kind: "error";
920
+ message: string;
921
+ };
922
+ interface UseClipDownloadOptions {
923
+ /**
924
+ * Filename used when the browser save dialog opens. Pass ``null``
925
+ * to skip the ``<a download>`` trigger entirely — the returned
926
+ * Blob is still resolved so the caller can ``URL.createObjectURL``
927
+ * it or re-upload it. Default ``"reactor-clip.mp4"``.
928
+ */
929
+ filename?: string | null;
930
+ /**
931
+ * Lazy resolver for the Coordinator JWT used on the ``/clips``
932
+ * manifest GET. Called on every {@link download} invocation, so
933
+ * token refreshes are picked up automatically.
934
+ *
935
+ * Optional inside a ``<ReactorProvider>`` (inherits the provider's
936
+ * resolver) and in local-dev mode. See
937
+ * {@link ClipPlayerProps.getJwt}.
938
+ */
939
+ getJwt?: () => string | Promise<string>;
940
+ }
941
+ interface UseClipDownloadResult {
942
+ /** Current state of the most recent download attempt. */
943
+ state: ClipDownloadState;
944
+ /**
945
+ * Trigger a download. Resolves with the assembled fragmented-MP4
946
+ * Blob, or ``undefined`` if a download was already in flight (the
947
+ * call is a no-op in that case — guarding against double-click is
948
+ * the hook's responsibility, not the caller's).
949
+ *
950
+ * Errors are caught and surfaced via {@link state} — the returned
951
+ * Promise still resolves to ``undefined`` rather than rejecting,
952
+ * because the typical caller is a click handler that doesn't await.
953
+ * Use ``state.kind === "error"`` to drive failure UI.
954
+ */
955
+ download: () => Promise<Blob | undefined>;
956
+ /** Reset to ``idle``. Does *not* cancel an in-flight download. */
957
+ reset: () => void;
958
+ }
959
+ /**
960
+ * Headless download primitive for a {@link Clip}.
961
+ *
962
+ * Wraps {@link downloadClipAsFile} in a React state machine so the
963
+ * consumer can render any button they want, anywhere they want, and
964
+ * still get progress + error feedback. Used internally by
965
+ * {@link ClipPlayer}'s built-in download button — when you need
966
+ * custom placement or styling, set ``showDownloadButton={false}`` on
967
+ * the player and call this hook directly.
968
+ *
969
+ * Stable callback identity: ``download`` and ``reset`` are the same
970
+ * function reference across renders, so they're safe to pass through
971
+ * memoized children without forcing re-renders.
972
+ *
973
+ * @example Render a download button anywhere in your tree:
974
+ * ```tsx
975
+ * function ClipCard({ clip }: { clip: Clip }) {
976
+ * const jwt = useReactor((s) => s.jwtToken);
977
+ * const { state, download } = useClipDownload(clip, {
978
+ * filename: `snap-${clip.sessionId}.mp4`,
979
+ * getJwt: jwt ? () => jwt : undefined,
980
+ * });
981
+ * return (
982
+ * <button onClick={download} disabled={state.kind === "downloading"}>
983
+ * {state.kind === "downloading"
984
+ * ? `${state.fetched}/${state.total}`
985
+ * : state.kind === "error"
986
+ * ? "Retry"
987
+ * : "Download"}
988
+ * </button>
989
+ * );
990
+ * }
991
+ * ```
992
+ */
993
+ declare function useClipDownload(clip: Clip, options?: UseClipDownloadOptions): UseClipDownloadResult;
994
+
995
+ /**
996
+ * Standalone download button for a captured {@link Clip}.
997
+ *
998
+ * Drops anywhere in your UI — modal headers, list rows, hover menus,
999
+ * floating action buttons — and is responsible for nothing more than
1000
+ * triggering a download and reflecting its state. Internally wraps
1001
+ * {@link useClipDownload}; for completely custom UIs (progress bars,
1002
+ * menu items, post-download blob handling) call that hook directly.
1003
+ *
1004
+ * Styling is intentionally minimal. Override via ``className``,
1005
+ * ``style``, or replace the inner content with the ``children``
1006
+ * render-prop. No CSS file is shipped — every default style is
1007
+ * inline so it loses to anything the consumer provides.
1008
+ *
1009
+ * @example Default label, state-aware:
1010
+ * ```tsx
1011
+ * <ClipDownloadButton clip={clip} getJwt={() => jwt} />
1012
+ * ```
1013
+ *
1014
+ * @example Custom label that follows the state:
1015
+ * ```tsx
1016
+ * <ClipDownloadButton clip={clip} getJwt={() => jwt}>
1017
+ * {(s) => (s.kind === "downloading" ? `${s.fetched}/${s.total}` : "Save MP4")}
1018
+ * </ClipDownloadButton>
1019
+ * ```
1020
+ *
1021
+ * @example Static label:
1022
+ * ```tsx
1023
+ * <ClipDownloadButton clip={clip} getJwt={() => jwt}>Save</ClipDownloadButton>
1024
+ * ```
1025
+ */
1026
+ interface ClipDownloadButtonProps {
1027
+ /** The clip to download. */
1028
+ clip: Clip;
1029
+ /**
1030
+ * Lazy JWT resolver. Optional inside a ``<ReactorProvider>``
1031
+ * (inherits the provider's resolver) and in local-dev mode. See
1032
+ * {@link ClipPlayerProps.getJwt}.
1033
+ */
1034
+ getJwt?: () => string | Promise<string>;
1035
+ /** Filename for the saved MP4. Default ``"reactor-clip.mp4"``. */
1036
+ filename?: string;
1037
+ /**
1038
+ * Inner content of the button. Three forms:
1039
+ *
1040
+ * - **Omitted** — renders a sensible default label that follows
1041
+ * the state (``"Download"`` / ``"Downloading 3/8…"`` / etc.).
1042
+ * - **`ReactNode`** — static label. No state-driven text.
1043
+ * - **`(state) => ReactNode`** — state-aware render function;
1044
+ * use for custom progress strings, spinners, etc.
1045
+ */
1046
+ children?: React.ReactNode | ((state: ClipDownloadState) => React.ReactNode);
1047
+ /** Forwarded to the underlying ``<button>``. */
1048
+ className?: string;
1049
+ /** Forwarded to the underlying ``<button>`` — merges *after* the defaults so each property overrides. */
1050
+ style?: React.CSSProperties;
1051
+ /** Forwarded to the underlying ``<button>``. ORed with the internal "downloading" state. */
1052
+ disabled?: boolean;
1053
+ }
1054
+ declare function ClipDownloadButton({ clip, getJwt, filename, children, className, style, disabled, }: ClipDownloadButtonProps): react_jsx_runtime.JSX.Element;
1055
+
383
1056
  /**
384
1057
  * Generic hook for accessing selected parts of the Reactor store.
385
1058
  *
@@ -413,4 +1086,4 @@ declare function useReactorInternalMessage(handler: (message: any) => void): voi
413
1086
  */
414
1087
  declare function useStats(): ConnectionStats | undefined;
415
1088
 
416
- export { AbortError, type Capabilities, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_BASE_URL, FileRef, type MessageScope, type Options, Reactor, type ReactorConnectOptions, ReactorController, type ReactorControllerProps, type ReactorError, type ReactorEvent, ReactorProvider, type ReactorState$1 as ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, type SessionResponse, type TrackCapability, WebcamStream, type WebcamStreamProps, isAbortError, useReactor, useReactorInternalMessage, useReactorMessage, useReactorStore, useStats };
1089
+ export { AbortError, type Capabilities, type Clip, ClipDownloadButton, type ClipDownloadButtonProps, type ClipDownloadState, type ClipFailedPayload, type ClipKind, ClipPlayer, type ClipPlayerProps, type ClipReadyPayload, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_BASE_URL, DEFAULT_CLIP_REQUEST_TIMEOUT_MS, DEFAULT_PLAYLIST_POLL_SLACK_MS, type DownloadClipOptions, type FetchPlaylistOptions, FileRef, type JwtResolver, type JwtSource, type MessageScope, type Options, type ParseClipOptions, Reactor, type ReactorConnectOptions, ReactorController, type ReactorControllerProps, type ReactorError, type ReactorEvent, ReactorProvider, type ReactorState$1 as ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecordingClient, type RecordingClientHost, RecordingError, RuntimeRecordingMessageType, type SessionResponse, type TrackCapability, type UseClipDownloadOptions, type UseClipDownloadResult, WebcamStream, type WebcamStreamProps, clipFromPayload, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isAbortError, normalizeJwtSource, parsePlaylist, rewriteUrlHost, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useReactorStore, useStats };