@reactor-team/js-sdk 2.12.1 → 2.12.3

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/README.md CHANGED
@@ -17,7 +17,7 @@ pnpm create reactor-app my-app
17
17
  cd my-app && pnpm install && pnpm dev
18
18
  ```
19
19
 
20
- Or wire it up by hand. Exchange your API key for a short-lived JWT on the server, then mount `<ReactorProvider>` in the client:
20
+ Or wire it up by hand. Exchange your API key on the server for a short-lived JWT **scoped to your model**, then mount `<ReactorProvider>` in the client. The `authorization_details` block is what downscopes the token: it can create a bounded number of sessions for that one model and act only on the sessions it created — a leaked token exposes nothing else on the account:
21
21
 
22
22
  ```ts
23
23
  // app/api/token/route.ts
@@ -26,7 +26,19 @@ import { NextResponse } from "next/server";
26
26
  export async function POST() {
27
27
  const r = await fetch("https://api.reactor.inc/tokens", {
28
28
  method: "POST",
29
- headers: { "Reactor-API-Key": process.env.REACTOR_API_KEY! },
29
+ headers: {
30
+ "Reactor-API-Key": process.env.REACTOR_API_KEY!,
31
+ "Content-Type": "application/json",
32
+ },
33
+ body: JSON.stringify({
34
+ authorization_details: [
35
+ {
36
+ type: "session",
37
+ resources: { models: { match: ["your-org/your-model-name"] } },
38
+ constraints: { max_sessions: 10 },
39
+ },
40
+ ],
41
+ }),
30
42
  });
31
43
  const { jwt } = await r.json();
32
44
  return NextResponse.json({ jwt });
package/dist/index.d.mts CHANGED
@@ -172,6 +172,10 @@ declare class AbortError extends Error {
172
172
  }
173
173
  /** Matches both our custom AbortError and the native DOMException thrown by fetch(). */
174
174
  declare function isAbortError(error: unknown): boolean;
175
+ declare class SessionLostError extends Error {
176
+ constructor(message: string);
177
+ }
178
+ declare function isSessionLostError(error: unknown): boolean;
175
179
  interface ReactorState$1 {
176
180
  status: ReactorStatus;
177
181
  lastError?: ReactorError;
@@ -190,6 +194,9 @@ interface ConnectOptions {
190
194
  * to keep recvonly tracks paused on connect and resume them individually via
191
195
  * `resumeTrack()` (e.g. multi-connection apps that only subscribe to a
192
196
  * subset of peers).
197
+ *
198
+ * A track that arrives after that is resumed on its own, so one track
199
+ * appearing never disturbs another the caller has paused.
193
200
  */
194
201
  autoResumeTracks?: boolean;
195
202
  /**
@@ -362,9 +369,10 @@ type ClipKind = "snap" | "recording";
362
369
  * - `predictedReadyAtMs` is a **Unix epoch in milliseconds** — the
363
370
  * runtime's estimate of when the boundary chunk will be servable
364
371
  * by `/clips`. Compare against `Date.now()` to drive a "ready in
365
- * Ns" indicator. The SDK uses this as the polling deadline: past
366
- * `predictedReadyAtMs + slackMs` and still 202, the SDK fails with
367
- * `CLIP_NOT_READY` on the assumption the runtime crashed.
372
+ * Ns" indicator. It is only an estimate: the SDK polls `/clips`
373
+ * until the manifest is actually ready and does not give up when
374
+ * this epoch passes (see {@link fetchPlaylist} for the polling and
375
+ * cancellation model).
368
376
  * - `playlistUrl` is short-lived in production (the embedded chunk
369
377
  * URLs are presigned for a few minutes). Re-issuing the request
370
378
  * produces a fresh URL with fresh presigning.
@@ -453,21 +461,29 @@ interface ParsedPlaylist {
453
461
  segmentUrls: string[];
454
462
  }
455
463
  /**
456
- * Default grace period after `predictedReadyAtMs` before
457
- * {@link fetchPlaylist} gives up. Applied from
458
- * `max(predictedReadyAtMs, pollStart)` so late clicks still get the
459
- * full window.
464
+ * Suggested grace period for callers that opt into a *bounded* wait by
465
+ * passing it as {@link FetchPlaylistOptions.slackMs}. It is **not** a
466
+ * default: {@link fetchPlaylist} polls indefinitely unless a bound is
467
+ * supplied. Provided so callers who do want the old ~15 s ceiling can
468
+ * ask for it by name rather than hard-coding a magic number.
460
469
  */
461
470
  declare const DEFAULT_PLAYLIST_POLL_SLACK_MS = 15000;
462
471
  interface FetchPlaylistOptions {
463
472
  /**
464
473
  * Unix epoch (ms) when the runtime predicts the boundary chunk will
465
- * be servable. Pass `clip.predictedReadyAtMs` here. When set, polling
466
- * continues until `predictedReadyAtMs + slackMs`; once past, a
467
- * stuck `202` produces `CLIP_NOT_READY` (assume runtime crashed).
474
+ * be servable. Pass `clip.predictedReadyAtMs` here. On its own it
475
+ * does *not* stop polling — it only anchors the optional `slackMs`
476
+ * deadline. Use it to drive a "ready in Ns" indicator.
468
477
  */
469
478
  predictedReadyAtMs?: number;
470
- /** Grace period after `predictedReadyAtMs`. Default {@link DEFAULT_PLAYLIST_POLL_SLACK_MS}. */
479
+ /**
480
+ * Opt-in grace period that turns polling into a *bounded* wait. When
481
+ * set to a finite value, a stuck `202` produces `CLIP_NOT_READY` once
482
+ * `max(predictedReadyAtMs, pollStart) + slackMs` passes. Omit (the
483
+ * default) to poll indefinitely until the manifest is ready or the
484
+ * caller aborts via `signal`. See {@link DEFAULT_PLAYLIST_POLL_SLACK_MS}
485
+ * for a sensible value if you want the old ~15 s ceiling.
486
+ */
471
487
  slackMs?: number;
472
488
  /**
473
489
  * Hard cap on the per-poll wait. The server's `Retry-After` header is
@@ -477,12 +493,18 @@ interface FetchPlaylistOptions {
477
493
  /** Floor on the per-poll wait so we don't hot-loop on cheap networks. Default 200 ms. */
478
494
  minRetryDelayMs?: number;
479
495
  /**
480
- * Fallback retry count used when `predictedReadyAtMs` is omitted
481
- * (e.g. someone calls `fetchPlaylist` directly with a saved URL,
482
- * outside of a fresh `Clip`). Default 5.
496
+ * Opt-in cap on the number of `202` responses tolerated before
497
+ * `CLIP_NOT_READY`. Omit (the default) to poll indefinitely; set it
498
+ * for a simple attempt-count ceiling when you don't have a
499
+ * `predictedReadyAtMs` to anchor a `slackMs` deadline.
483
500
  */
484
501
  maxRetries?: number;
485
- /** Aborts in-flight fetches and the inter-poll sleep. */
502
+ /**
503
+ * Aborts in-flight fetches and the inter-poll sleep. Because polling
504
+ * is unbounded by default, this is the primary way a caller ends a
505
+ * wait that is taking too long (a timeout, a user "cancel", a React
506
+ * unmount).
507
+ */
486
508
  signal?: AbortSignal;
487
509
  /**
488
510
  * Coordinator JWT. When set, attached as `Authorization: Bearer
@@ -495,14 +517,19 @@ interface FetchPlaylistOptions {
495
517
  * Fetch the playlist URL, polling on `202 Accepted` (which the manifest
496
518
  * endpoint returns while the boundary chunk is still uploading).
497
519
  *
498
- * Polling deadline is driven by `predictedReadyAtMs + slackMs` when a
499
- * `Clip` was just minted by the runtime; without that field the
500
- * function falls back to `maxRetries` attempts. Either way:
520
+ * Polling is **unbounded by default** — it keeps retrying on `202`
521
+ * until the manifest is ready or the caller aborts via `signal`. This
522
+ * matches the reality that a clip's boundary chunk can take arbitrarily
523
+ * long to land (a paused model closes no chunks; a long recording's
524
+ * final chunk is large). Callers own the give-up policy: pass `signal`
525
+ * to cancel, or opt into a ceiling with `slackMs` / `maxRetries`.
526
+ *
501
527
  * - `200` → returns the manifest body.
502
528
  * - `410` / `404` → throws `CLIP_GONE`.
503
529
  * - `5xx`/other → throws `PLAYLIST_FETCH_FAILED` (no retry).
504
- * - Past the deadline / retries with stuck `202` → throws
505
- * `CLIP_NOT_READY` (the runtime probably crashed mid-chunk).
530
+ * - `202` past an opt-in `slackMs` deadline or `maxRetries` cap →
531
+ * throws `CLIP_NOT_READY`.
532
+ * - aborted `signal` → rejects with the fetch/`sleep` `AbortError`.
506
533
  */
507
534
  declare function fetchPlaylist(playlistUrl: string, options?: FetchPlaylistOptions): Promise<string>;
508
535
  /**
@@ -718,6 +745,7 @@ declare class Reactor {
718
745
  * down its own transport but leaves the session alive.
719
746
  */
720
747
  private createdSession;
748
+ private retryingSessionLoss;
721
749
  private connectStartTime?;
722
750
  private connectionTimings?;
723
751
  private schema?;
@@ -797,6 +825,8 @@ declare class Reactor {
797
825
  unpublishTrack(name: string): Promise<void>;
798
826
  pauseTrack(name: string): void;
799
827
  resumeTrack(name: string): void;
828
+ /** Whether `name` is a track this client receives rather than sends. */
829
+ private isRecvonly;
800
830
  /**
801
831
  * Reconnects to an existing session with a fresh transport.
802
832
  */
@@ -1094,16 +1124,15 @@ interface ClipPlayerProps {
1094
1124
  */
1095
1125
  getJwt?: () => string | Promise<string>;
1096
1126
  /**
1097
- * Override the grace period beyond ``clip.predictedReadyAtMs``
1098
- * before the SDK gives up polling the ``/clips`` manifest endpoint
1099
- * with ``CLIP_NOT_READY``. Defaults to
1100
- * {@link DEFAULT_PLAYLIST_POLL_SLACK_MS} (15 s) — enough for snap
1101
- * clips, but long-running session recordings may legitimately need
1102
- * a minute or more for the final boundary chunk to finish encoding
1103
- * + uploading, in which case pass a larger value (e.g. ``120_000``
1104
- * for two-minute grace). Forwarded directly to
1105
- * {@link fetchPlaylist}'s ``slackMs`` option — see that helper for
1106
- * the polling semantics.
1127
+ * Opt into a *bounded* wait: give up polling the ``/clips`` manifest
1128
+ * endpoint with ``CLIP_NOT_READY`` once
1129
+ * ``max(clip.predictedReadyAtMs, pollStart) + slackMs`` passes. By
1130
+ * default this is **unset** — the player polls indefinitely until the
1131
+ * clip is ready, and stops only when it unmounts or ``clip`` changes
1132
+ * (both abort the in-flight poll). Set a value when you want a hard
1133
+ * ceiling (e.g. ``120_000`` for a two-minute cap). Forwarded
1134
+ * directly to {@link fetchPlaylist}'s ``slackMs`` option — see that
1135
+ * helper for the polling semantics.
1107
1136
  */
1108
1137
  slackMs?: number;
1109
1138
  /** Play automatically once the manifest is attached. Default ``true``. */
@@ -1326,4 +1355,4 @@ declare function useReactorInternalMessage(handler: (message: any) => void): voi
1326
1355
  */
1327
1356
  declare function useStats(): ConnectionStats | undefined;
1328
1357
 
1329
- 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 ModelSchema, type ModelSchemaOperation, type ModelSchemaPathItem, type ModerationAction, type ModerationEvent, type Options, type ParseClipOptions, Reactor, type ReactorConnectOptions, 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 };
1358
+ 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 ModelSchema, type ModelSchemaOperation, type ModelSchemaPathItem, type ModerationAction, type ModerationEvent, type Options, type ParseClipOptions, Reactor, type ReactorConnectOptions, type ReactorError, type ReactorEvent, ReactorProvider, type ReactorState$1 as ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecordingClient, type RecordingClientHost, RecordingError, RuntimeRecordingMessageType, SessionLostError, type SessionResponse, type TrackCapability, type UseClipDownloadOptions, type UseClipDownloadResult, WebcamStream, type WebcamStreamProps, clipFromPayload, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isAbortError, isSessionLostError, normalizeJwtSource, parsePlaylist, rewriteUrlHost, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useReactorStore, useStats };
package/dist/index.d.ts CHANGED
@@ -172,6 +172,10 @@ declare class AbortError extends Error {
172
172
  }
173
173
  /** Matches both our custom AbortError and the native DOMException thrown by fetch(). */
174
174
  declare function isAbortError(error: unknown): boolean;
175
+ declare class SessionLostError extends Error {
176
+ constructor(message: string);
177
+ }
178
+ declare function isSessionLostError(error: unknown): boolean;
175
179
  interface ReactorState$1 {
176
180
  status: ReactorStatus;
177
181
  lastError?: ReactorError;
@@ -190,6 +194,9 @@ interface ConnectOptions {
190
194
  * to keep recvonly tracks paused on connect and resume them individually via
191
195
  * `resumeTrack()` (e.g. multi-connection apps that only subscribe to a
192
196
  * subset of peers).
197
+ *
198
+ * A track that arrives after that is resumed on its own, so one track
199
+ * appearing never disturbs another the caller has paused.
193
200
  */
194
201
  autoResumeTracks?: boolean;
195
202
  /**
@@ -362,9 +369,10 @@ type ClipKind = "snap" | "recording";
362
369
  * - `predictedReadyAtMs` is a **Unix epoch in milliseconds** — the
363
370
  * runtime's estimate of when the boundary chunk will be servable
364
371
  * by `/clips`. Compare against `Date.now()` to drive a "ready in
365
- * Ns" indicator. The SDK uses this as the polling deadline: past
366
- * `predictedReadyAtMs + slackMs` and still 202, the SDK fails with
367
- * `CLIP_NOT_READY` on the assumption the runtime crashed.
372
+ * Ns" indicator. It is only an estimate: the SDK polls `/clips`
373
+ * until the manifest is actually ready and does not give up when
374
+ * this epoch passes (see {@link fetchPlaylist} for the polling and
375
+ * cancellation model).
368
376
  * - `playlistUrl` is short-lived in production (the embedded chunk
369
377
  * URLs are presigned for a few minutes). Re-issuing the request
370
378
  * produces a fresh URL with fresh presigning.
@@ -453,21 +461,29 @@ interface ParsedPlaylist {
453
461
  segmentUrls: string[];
454
462
  }
455
463
  /**
456
- * Default grace period after `predictedReadyAtMs` before
457
- * {@link fetchPlaylist} gives up. Applied from
458
- * `max(predictedReadyAtMs, pollStart)` so late clicks still get the
459
- * full window.
464
+ * Suggested grace period for callers that opt into a *bounded* wait by
465
+ * passing it as {@link FetchPlaylistOptions.slackMs}. It is **not** a
466
+ * default: {@link fetchPlaylist} polls indefinitely unless a bound is
467
+ * supplied. Provided so callers who do want the old ~15 s ceiling can
468
+ * ask for it by name rather than hard-coding a magic number.
460
469
  */
461
470
  declare const DEFAULT_PLAYLIST_POLL_SLACK_MS = 15000;
462
471
  interface FetchPlaylistOptions {
463
472
  /**
464
473
  * Unix epoch (ms) when the runtime predicts the boundary chunk will
465
- * be servable. Pass `clip.predictedReadyAtMs` here. When set, polling
466
- * continues until `predictedReadyAtMs + slackMs`; once past, a
467
- * stuck `202` produces `CLIP_NOT_READY` (assume runtime crashed).
474
+ * be servable. Pass `clip.predictedReadyAtMs` here. On its own it
475
+ * does *not* stop polling — it only anchors the optional `slackMs`
476
+ * deadline. Use it to drive a "ready in Ns" indicator.
468
477
  */
469
478
  predictedReadyAtMs?: number;
470
- /** Grace period after `predictedReadyAtMs`. Default {@link DEFAULT_PLAYLIST_POLL_SLACK_MS}. */
479
+ /**
480
+ * Opt-in grace period that turns polling into a *bounded* wait. When
481
+ * set to a finite value, a stuck `202` produces `CLIP_NOT_READY` once
482
+ * `max(predictedReadyAtMs, pollStart) + slackMs` passes. Omit (the
483
+ * default) to poll indefinitely until the manifest is ready or the
484
+ * caller aborts via `signal`. See {@link DEFAULT_PLAYLIST_POLL_SLACK_MS}
485
+ * for a sensible value if you want the old ~15 s ceiling.
486
+ */
471
487
  slackMs?: number;
472
488
  /**
473
489
  * Hard cap on the per-poll wait. The server's `Retry-After` header is
@@ -477,12 +493,18 @@ interface FetchPlaylistOptions {
477
493
  /** Floor on the per-poll wait so we don't hot-loop on cheap networks. Default 200 ms. */
478
494
  minRetryDelayMs?: number;
479
495
  /**
480
- * Fallback retry count used when `predictedReadyAtMs` is omitted
481
- * (e.g. someone calls `fetchPlaylist` directly with a saved URL,
482
- * outside of a fresh `Clip`). Default 5.
496
+ * Opt-in cap on the number of `202` responses tolerated before
497
+ * `CLIP_NOT_READY`. Omit (the default) to poll indefinitely; set it
498
+ * for a simple attempt-count ceiling when you don't have a
499
+ * `predictedReadyAtMs` to anchor a `slackMs` deadline.
483
500
  */
484
501
  maxRetries?: number;
485
- /** Aborts in-flight fetches and the inter-poll sleep. */
502
+ /**
503
+ * Aborts in-flight fetches and the inter-poll sleep. Because polling
504
+ * is unbounded by default, this is the primary way a caller ends a
505
+ * wait that is taking too long (a timeout, a user "cancel", a React
506
+ * unmount).
507
+ */
486
508
  signal?: AbortSignal;
487
509
  /**
488
510
  * Coordinator JWT. When set, attached as `Authorization: Bearer
@@ -495,14 +517,19 @@ interface FetchPlaylistOptions {
495
517
  * Fetch the playlist URL, polling on `202 Accepted` (which the manifest
496
518
  * endpoint returns while the boundary chunk is still uploading).
497
519
  *
498
- * Polling deadline is driven by `predictedReadyAtMs + slackMs` when a
499
- * `Clip` was just minted by the runtime; without that field the
500
- * function falls back to `maxRetries` attempts. Either way:
520
+ * Polling is **unbounded by default** — it keeps retrying on `202`
521
+ * until the manifest is ready or the caller aborts via `signal`. This
522
+ * matches the reality that a clip's boundary chunk can take arbitrarily
523
+ * long to land (a paused model closes no chunks; a long recording's
524
+ * final chunk is large). Callers own the give-up policy: pass `signal`
525
+ * to cancel, or opt into a ceiling with `slackMs` / `maxRetries`.
526
+ *
501
527
  * - `200` → returns the manifest body.
502
528
  * - `410` / `404` → throws `CLIP_GONE`.
503
529
  * - `5xx`/other → throws `PLAYLIST_FETCH_FAILED` (no retry).
504
- * - Past the deadline / retries with stuck `202` → throws
505
- * `CLIP_NOT_READY` (the runtime probably crashed mid-chunk).
530
+ * - `202` past an opt-in `slackMs` deadline or `maxRetries` cap →
531
+ * throws `CLIP_NOT_READY`.
532
+ * - aborted `signal` → rejects with the fetch/`sleep` `AbortError`.
506
533
  */
507
534
  declare function fetchPlaylist(playlistUrl: string, options?: FetchPlaylistOptions): Promise<string>;
508
535
  /**
@@ -718,6 +745,7 @@ declare class Reactor {
718
745
  * down its own transport but leaves the session alive.
719
746
  */
720
747
  private createdSession;
748
+ private retryingSessionLoss;
721
749
  private connectStartTime?;
722
750
  private connectionTimings?;
723
751
  private schema?;
@@ -797,6 +825,8 @@ declare class Reactor {
797
825
  unpublishTrack(name: string): Promise<void>;
798
826
  pauseTrack(name: string): void;
799
827
  resumeTrack(name: string): void;
828
+ /** Whether `name` is a track this client receives rather than sends. */
829
+ private isRecvonly;
800
830
  /**
801
831
  * Reconnects to an existing session with a fresh transport.
802
832
  */
@@ -1094,16 +1124,15 @@ interface ClipPlayerProps {
1094
1124
  */
1095
1125
  getJwt?: () => string | Promise<string>;
1096
1126
  /**
1097
- * Override the grace period beyond ``clip.predictedReadyAtMs``
1098
- * before the SDK gives up polling the ``/clips`` manifest endpoint
1099
- * with ``CLIP_NOT_READY``. Defaults to
1100
- * {@link DEFAULT_PLAYLIST_POLL_SLACK_MS} (15 s) — enough for snap
1101
- * clips, but long-running session recordings may legitimately need
1102
- * a minute or more for the final boundary chunk to finish encoding
1103
- * + uploading, in which case pass a larger value (e.g. ``120_000``
1104
- * for two-minute grace). Forwarded directly to
1105
- * {@link fetchPlaylist}'s ``slackMs`` option — see that helper for
1106
- * the polling semantics.
1127
+ * Opt into a *bounded* wait: give up polling the ``/clips`` manifest
1128
+ * endpoint with ``CLIP_NOT_READY`` once
1129
+ * ``max(clip.predictedReadyAtMs, pollStart) + slackMs`` passes. By
1130
+ * default this is **unset** — the player polls indefinitely until the
1131
+ * clip is ready, and stops only when it unmounts or ``clip`` changes
1132
+ * (both abort the in-flight poll). Set a value when you want a hard
1133
+ * ceiling (e.g. ``120_000`` for a two-minute cap). Forwarded
1134
+ * directly to {@link fetchPlaylist}'s ``slackMs`` option — see that
1135
+ * helper for the polling semantics.
1107
1136
  */
1108
1137
  slackMs?: number;
1109
1138
  /** Play automatically once the manifest is attached. Default ``true``. */
@@ -1326,4 +1355,4 @@ declare function useReactorInternalMessage(handler: (message: any) => void): voi
1326
1355
  */
1327
1356
  declare function useStats(): ConnectionStats | undefined;
1328
1357
 
1329
- 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 ModelSchema, type ModelSchemaOperation, type ModelSchemaPathItem, type ModerationAction, type ModerationEvent, type Options, type ParseClipOptions, Reactor, type ReactorConnectOptions, 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 };
1358
+ 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 ModelSchema, type ModelSchemaOperation, type ModelSchemaPathItem, type ModerationAction, type ModerationEvent, type Options, type ParseClipOptions, Reactor, type ReactorConnectOptions, type ReactorError, type ReactorEvent, ReactorProvider, type ReactorState$1 as ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecordingClient, type RecordingClientHost, RecordingError, RuntimeRecordingMessageType, SessionLostError, type SessionResponse, type TrackCapability, type UseClipDownloadOptions, type UseClipDownloadResult, WebcamStream, type WebcamStreamProps, clipFromPayload, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isAbortError, isSessionLostError, normalizeJwtSource, parsePlaylist, rewriteUrlHost, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useReactorStore, useStats };
package/dist/index.js CHANGED
@@ -93,12 +93,14 @@ __export(index_exports, {
93
93
  RecordingClient: () => RecordingClient,
94
94
  RecordingError: () => RecordingError,
95
95
  RuntimeRecordingMessageType: () => RuntimeRecordingMessageType,
96
+ SessionLostError: () => SessionLostError,
96
97
  WebcamStream: () => WebcamStream,
97
98
  clipFromPayload: () => clipFromPayload,
98
99
  createPlayableManifestUrl: () => createPlayableManifestUrl,
99
100
  downloadClipAsFile: () => downloadClipAsFile,
100
101
  fetchPlaylist: () => fetchPlaylist,
101
102
  isAbortError: () => isAbortError,
103
+ isSessionLostError: () => isSessionLostError,
102
104
  normalizeJwtSource: () => normalizeJwtSource,
103
105
  parsePlaylist: () => parsePlaylist,
104
106
  rewriteUrlHost: () => rewriteUrlHost,
@@ -137,6 +139,14 @@ var AbortError = class extends Error {
137
139
  function isAbortError(error) {
138
140
  return error instanceof AbortError || error instanceof Error && error.name === "AbortError";
139
141
  }
142
+ var SessionLostError = class extends Error {
143
+ constructor(message) {
144
+ super(message);
145
+ }
146
+ };
147
+ function isSessionLostError(error) {
148
+ return error instanceof SessionLostError;
149
+ }
140
150
 
141
151
  // src/core/auth.ts
142
152
  function normalizeJwtSource(source) {
@@ -152,7 +162,7 @@ var import_zod = require("zod");
152
162
  // package.json
153
163
  var package_default = {
154
164
  name: "@reactor-team/js-sdk",
155
- version: "2.12.1",
165
+ version: "2.12.3",
156
166
  description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
157
167
  license: "Apache-2.0",
158
168
  repository: {
@@ -754,6 +764,11 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
754
764
  });
755
765
  if (!response.ok) {
756
766
  const errorText = yield response.text();
767
+ if (response.status === 400) {
768
+ throw new SessionLostError(
769
+ `Failed to start session: ${response.status} ${errorText}`
770
+ );
771
+ }
757
772
  throw new Error(
758
773
  `Failed to start session: ${response.status} ${errorText}`
759
774
  );
@@ -1538,6 +1553,11 @@ var WebRTCTransportClient = class {
1538
1553
  yield this.checkVersionMismatch(response);
1539
1554
  if (response.status !== 201) {
1540
1555
  const errorText = yield response.text();
1556
+ if (response.status === 400) {
1557
+ throw new SessionLostError(
1558
+ `Failed to register connection: ${response.status} ${errorText}`
1559
+ );
1560
+ }
1541
1561
  throw new Error(
1542
1562
  `Failed to register connection: ${response.status} ${errorText}`
1543
1563
  );
@@ -1584,7 +1604,7 @@ var WebRTCTransportClient = class {
1584
1604
  );
1585
1605
  }
1586
1606
  if (response.status === 400) {
1587
- throw new Error(
1607
+ throw new SessionLostError(
1588
1608
  `[WebRTCTransport] Connection ${connectionId} rejected (400): ${errorText}`
1589
1609
  );
1590
1610
  }
@@ -1598,7 +1618,7 @@ var WebRTCTransportClient = class {
1598
1618
  sendIceCandidates(candidates, is_final) {
1599
1619
  return __async(this, null, function* () {
1600
1620
  if (this.connectionId === void 0) {
1601
- console.debug(
1621
+ console.warn(
1602
1622
  "[WebRTCTransport] ICE candidates dropped: no active connection"
1603
1623
  );
1604
1624
  return;
@@ -1651,6 +1671,12 @@ var WebRTCTransportClient = class {
1651
1671
  clearTimeout(this.iceCandidateFlushTimer);
1652
1672
  this.iceCandidateFlushTimer = void 0;
1653
1673
  }
1674
+ if (this.connectionId === void 0) {
1675
+ console.debug(
1676
+ "[WebRTCTransportClient] skipping ICE candidate flush because the connection is not established yet"
1677
+ );
1678
+ return;
1679
+ }
1654
1680
  const batch = this.pendingIceCandidates;
1655
1681
  this.pendingIceCandidates = [];
1656
1682
  if (batch.length === 0 && !isFinal) {
@@ -1819,6 +1845,11 @@ var WebRTCTransportClient = class {
1819
1845
  trackMapping,
1820
1846
  reconnect
1821
1847
  );
1848
+ if (this.pendingIceCandidates.length > 0) {
1849
+ this.flushPendingIceCandidates(
1850
+ this.peerConnection !== void 0 && this.peerConnection.iceGatheringState === "complete"
1851
+ );
1852
+ }
1822
1853
  const answerResponse = yield this.pollSdpAnswer(this.connectionId);
1823
1854
  this.iceStartTime = performance.now();
1824
1855
  yield setRemoteDescription(
@@ -2389,13 +2420,15 @@ var DEFAULT_PLAYLIST_POLL_SLACK_MS = 15e3;
2389
2420
  function fetchPlaylist(_0) {
2390
2421
  return __async(this, arguments, function* (playlistUrl, options = {}) {
2391
2422
  var _a, _b, _c, _d;
2392
- const slackMs = (_a = options.slackMs) != null ? _a : DEFAULT_PLAYLIST_POLL_SLACK_MS;
2393
- const minDelay = Math.max(0, (_b = options.minRetryDelayMs) != null ? _b : 200);
2394
- const maxDelay = Math.max(minDelay, (_c = options.maxRetryDelayMs) != null ? _c : 2e3);
2395
- const fallbackMaxRetries = (_d = options.maxRetries) != null ? _d : 5;
2396
- const hasDeadline = typeof options.predictedReadyAtMs === "number";
2423
+ const minDelay = Math.max(0, (_a = options.minRetryDelayMs) != null ? _a : 200);
2424
+ const maxDelay = Math.max(minDelay, (_b = options.maxRetryDelayMs) != null ? _b : 2e3);
2425
+ const hasDeadline = typeof options.slackMs === "number" && Number.isFinite(options.slackMs);
2397
2426
  const startedPollingAt = Date.now();
2398
- const deadlineMs = hasDeadline ? Math.max(options.predictedReadyAtMs, startedPollingAt) + slackMs : void 0;
2427
+ const deadlineMs = hasDeadline ? Math.max(
2428
+ (_c = options.predictedReadyAtMs) != null ? _c : startedPollingAt,
2429
+ startedPollingAt
2430
+ ) + options.slackMs : void 0;
2431
+ const maxRetries = typeof options.maxRetries === "number" ? options.maxRetries : void 0;
2399
2432
  const headers = options.jwt ? { Authorization: `Bearer ${options.jwt}` } : void 0;
2400
2433
  let attempt = 0;
2401
2434
  let lastStatus = 0;
@@ -2414,16 +2447,15 @@ function fetchPlaylist(_0) {
2414
2447
  }
2415
2448
  lastStatus = response.status;
2416
2449
  if (response.status === 202) {
2417
- if (hasDeadline) {
2418
- if (Date.now() >= deadlineMs) {
2419
- throw new RecordingError(
2420
- "CLIP_NOT_READY",
2421
- `Boundary chunk still pending after ${slackMs}ms grace (predicted ready ${new Date(
2422
- options.predictedReadyAtMs
2423
- ).toISOString()}). Runtime may have crashed mid-clip.`
2424
- );
2425
- }
2426
- } else if (attempt >= fallbackMaxRetries) {
2450
+ if (deadlineMs !== void 0 && Date.now() >= deadlineMs) {
2451
+ throw new RecordingError(
2452
+ "CLIP_NOT_READY",
2453
+ `Boundary chunk still pending after ${options.slackMs}ms grace (predicted ready ${new Date(
2454
+ (_d = options.predictedReadyAtMs) != null ? _d : startedPollingAt
2455
+ ).toISOString()}). Runtime may have crashed mid-clip.`
2456
+ );
2457
+ }
2458
+ if (maxRetries !== void 0 && attempt >= maxRetries) {
2427
2459
  throw new RecordingError(
2428
2460
  "CLIP_NOT_READY",
2429
2461
  `Manifest still pending after ${attempt + 1} attempts (last status ${lastStatus})`
@@ -2434,7 +2466,7 @@ function fetchPlaylist(_0) {
2434
2466
  minDelay
2435
2467
  );
2436
2468
  const delay = Math.min(maxDelay, Math.max(minDelay, headerDelay));
2437
- const clampedDelay = hasDeadline ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;
2469
+ const clampedDelay = deadlineMs !== void 0 ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;
2438
2470
  yield sleep(clampedDelay, options.signal);
2439
2471
  attempt++;
2440
2472
  continue;
@@ -3017,6 +3049,7 @@ var Reactor = class {
3017
3049
  * down its own transport but leaves the session alive.
3018
3050
  */
3019
3051
  this.createdSession = false;
3052
+ this.retryingSessionLoss = false;
3020
3053
  this.tracks = [];
3021
3054
  this.autoResumeTracks = false;
3022
3055
  this.eventListeners = /* @__PURE__ */ new Map();
@@ -3283,6 +3316,12 @@ var Reactor = class {
3283
3316
  var _a;
3284
3317
  (_a = this.transportClient) == null ? void 0 : _a.resumeTrack(name);
3285
3318
  }
3319
+ /** Whether `name` is a track this client receives rather than sends. */
3320
+ isRecvonly(name) {
3321
+ return this.tracks.some(
3322
+ (track) => track.name === name && track.direction === "recvonly"
3323
+ );
3324
+ }
3286
3325
  /**
3287
3326
  * Reconnects to an existing session with a fresh transport.
3288
3327
  */
@@ -3341,7 +3380,7 @@ var Reactor = class {
3341
3380
  */
3342
3381
  connect(jwtToken, options) {
3343
3382
  return __async(this, null, function* () {
3344
- var _a;
3383
+ var _a, _b, _c, _d;
3345
3384
  console.debug("[Reactor] Connecting, status:", this.status);
3346
3385
  if (jwtToken == void 0 && !this.local) {
3347
3386
  throw new Error("No authentication provided and not in local mode");
@@ -3429,6 +3468,19 @@ var Reactor = class {
3429
3468
  };
3430
3469
  } catch (error) {
3431
3470
  if (isAbortError(error)) return;
3471
+ if (!(options == null ? void 0 : options.sessionId) && !this.retryingSessionLoss && isSessionLostError(error)) {
3472
+ this.retryingSessionLoss = true;
3473
+ (_b = this.coordinatorClient) == null ? void 0 : _b.abort();
3474
+ (_c = this.transportClient) == null ? void 0 : _c.abort();
3475
+ (_d = this.transportClient) == null ? void 0 : _d.disconnect();
3476
+ this.setStatus("disconnected");
3477
+ try {
3478
+ yield this.connect(jwtToken, options);
3479
+ return;
3480
+ } finally {
3481
+ this.retryingSessionLoss = false;
3482
+ }
3483
+ }
3432
3484
  console.error("[Reactor] Connection failed:", error);
3433
3485
  this.createError(
3434
3486
  "CONNECTION_FAILED",
@@ -3501,12 +3553,8 @@ var Reactor = class {
3501
3553
  (name, track, stream) => {
3502
3554
  if (this.transportClient !== client) return;
3503
3555
  this.emit("trackReceived", name, track, stream);
3504
- if (this.autoResumeTracks) {
3505
- for (const track2 of this.tracks) {
3506
- if (track2.direction === "recvonly") {
3507
- this.resumeTrack(track2.name);
3508
- }
3509
- }
3556
+ if (this.autoResumeTracks && this.isRecvonly(name)) {
3557
+ this.resumeTrack(name);
3510
3558
  }
3511
3559
  }
3512
3560
  );
@@ -4615,9 +4663,16 @@ function useClipDownload(clip, options = {}) {
4615
4663
  getJwtRef.current = options.getJwt;
4616
4664
  });
4617
4665
  const inFlightRef = (0, import_react8.useRef)(false);
4666
+ const abortRef = (0, import_react8.useRef)(null);
4667
+ (0, import_react8.useEffect)(() => () => {
4668
+ var _a2;
4669
+ return (_a2 = abortRef.current) == null ? void 0 : _a2.abort();
4670
+ }, []);
4618
4671
  const download = (0, import_react8.useCallback)(() => __async(null, null, function* () {
4619
4672
  if (inFlightRef.current) return void 0;
4620
4673
  inFlightRef.current = true;
4674
+ const abort = new AbortController();
4675
+ abortRef.current = abort;
4621
4676
  setState({ kind: "downloading", fetched: 0, total: 0 });
4622
4677
  try {
4623
4678
  const explicit = getJwtRef.current;
@@ -4629,12 +4684,16 @@ function useClipDownload(clip, options = {}) {
4629
4684
  filenameRef.current,
4630
4685
  {
4631
4686
  jwt,
4687
+ signal: abort.signal,
4632
4688
  onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
4633
4689
  }
4634
4690
  );
4635
4691
  setState({ kind: "idle" });
4636
4692
  return blob;
4637
4693
  } catch (err) {
4694
+ if (err instanceof DOMException && err.name === "AbortError") {
4695
+ return void 0;
4696
+ }
4638
4697
  const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4639
4698
  setState({ kind: "error", message });
4640
4699
  return void 0;
@@ -4728,12 +4787,14 @@ function defaultLabel(state) {
4728
4787
  RecordingClient,
4729
4788
  RecordingError,
4730
4789
  RuntimeRecordingMessageType,
4790
+ SessionLostError,
4731
4791
  WebcamStream,
4732
4792
  clipFromPayload,
4733
4793
  createPlayableManifestUrl,
4734
4794
  downloadClipAsFile,
4735
4795
  fetchPlaylist,
4736
4796
  isAbortError,
4797
+ isSessionLostError,
4737
4798
  normalizeJwtSource,
4738
4799
  parsePlaylist,
4739
4800
  rewriteUrlHost,