@reactor-team/js-sdk 2.12.1 → 2.12.2

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;
@@ -362,9 +366,10 @@ type ClipKind = "snap" | "recording";
362
366
  * - `predictedReadyAtMs` is a **Unix epoch in milliseconds** — the
363
367
  * runtime's estimate of when the boundary chunk will be servable
364
368
  * 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.
369
+ * Ns" indicator. It is only an estimate: the SDK polls `/clips`
370
+ * until the manifest is actually ready and does not give up when
371
+ * this epoch passes (see {@link fetchPlaylist} for the polling and
372
+ * cancellation model).
368
373
  * - `playlistUrl` is short-lived in production (the embedded chunk
369
374
  * URLs are presigned for a few minutes). Re-issuing the request
370
375
  * produces a fresh URL with fresh presigning.
@@ -453,21 +458,29 @@ interface ParsedPlaylist {
453
458
  segmentUrls: string[];
454
459
  }
455
460
  /**
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.
461
+ * Suggested grace period for callers that opt into a *bounded* wait by
462
+ * passing it as {@link FetchPlaylistOptions.slackMs}. It is **not** a
463
+ * default: {@link fetchPlaylist} polls indefinitely unless a bound is
464
+ * supplied. Provided so callers who do want the old ~15 s ceiling can
465
+ * ask for it by name rather than hard-coding a magic number.
460
466
  */
461
467
  declare const DEFAULT_PLAYLIST_POLL_SLACK_MS = 15000;
462
468
  interface FetchPlaylistOptions {
463
469
  /**
464
470
  * 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).
471
+ * be servable. Pass `clip.predictedReadyAtMs` here. On its own it
472
+ * does *not* stop polling — it only anchors the optional `slackMs`
473
+ * deadline. Use it to drive a "ready in Ns" indicator.
468
474
  */
469
475
  predictedReadyAtMs?: number;
470
- /** Grace period after `predictedReadyAtMs`. Default {@link DEFAULT_PLAYLIST_POLL_SLACK_MS}. */
476
+ /**
477
+ * Opt-in grace period that turns polling into a *bounded* wait. When
478
+ * set to a finite value, a stuck `202` produces `CLIP_NOT_READY` once
479
+ * `max(predictedReadyAtMs, pollStart) + slackMs` passes. Omit (the
480
+ * default) to poll indefinitely until the manifest is ready or the
481
+ * caller aborts via `signal`. See {@link DEFAULT_PLAYLIST_POLL_SLACK_MS}
482
+ * for a sensible value if you want the old ~15 s ceiling.
483
+ */
471
484
  slackMs?: number;
472
485
  /**
473
486
  * Hard cap on the per-poll wait. The server's `Retry-After` header is
@@ -477,12 +490,18 @@ interface FetchPlaylistOptions {
477
490
  /** Floor on the per-poll wait so we don't hot-loop on cheap networks. Default 200 ms. */
478
491
  minRetryDelayMs?: number;
479
492
  /**
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.
493
+ * Opt-in cap on the number of `202` responses tolerated before
494
+ * `CLIP_NOT_READY`. Omit (the default) to poll indefinitely; set it
495
+ * for a simple attempt-count ceiling when you don't have a
496
+ * `predictedReadyAtMs` to anchor a `slackMs` deadline.
483
497
  */
484
498
  maxRetries?: number;
485
- /** Aborts in-flight fetches and the inter-poll sleep. */
499
+ /**
500
+ * Aborts in-flight fetches and the inter-poll sleep. Because polling
501
+ * is unbounded by default, this is the primary way a caller ends a
502
+ * wait that is taking too long (a timeout, a user "cancel", a React
503
+ * unmount).
504
+ */
486
505
  signal?: AbortSignal;
487
506
  /**
488
507
  * Coordinator JWT. When set, attached as `Authorization: Bearer
@@ -495,14 +514,19 @@ interface FetchPlaylistOptions {
495
514
  * Fetch the playlist URL, polling on `202 Accepted` (which the manifest
496
515
  * endpoint returns while the boundary chunk is still uploading).
497
516
  *
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:
517
+ * Polling is **unbounded by default** — it keeps retrying on `202`
518
+ * until the manifest is ready or the caller aborts via `signal`. This
519
+ * matches the reality that a clip's boundary chunk can take arbitrarily
520
+ * long to land (a paused model closes no chunks; a long recording's
521
+ * final chunk is large). Callers own the give-up policy: pass `signal`
522
+ * to cancel, or opt into a ceiling with `slackMs` / `maxRetries`.
523
+ *
501
524
  * - `200` → returns the manifest body.
502
525
  * - `410` / `404` → throws `CLIP_GONE`.
503
526
  * - `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).
527
+ * - `202` past an opt-in `slackMs` deadline or `maxRetries` cap →
528
+ * throws `CLIP_NOT_READY`.
529
+ * - aborted `signal` → rejects with the fetch/`sleep` `AbortError`.
506
530
  */
507
531
  declare function fetchPlaylist(playlistUrl: string, options?: FetchPlaylistOptions): Promise<string>;
508
532
  /**
@@ -718,6 +742,7 @@ declare class Reactor {
718
742
  * down its own transport but leaves the session alive.
719
743
  */
720
744
  private createdSession;
745
+ private retryingSessionLoss;
721
746
  private connectStartTime?;
722
747
  private connectionTimings?;
723
748
  private schema?;
@@ -1094,16 +1119,15 @@ interface ClipPlayerProps {
1094
1119
  */
1095
1120
  getJwt?: () => string | Promise<string>;
1096
1121
  /**
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.
1122
+ * Opt into a *bounded* wait: give up polling the ``/clips`` manifest
1123
+ * endpoint with ``CLIP_NOT_READY`` once
1124
+ * ``max(clip.predictedReadyAtMs, pollStart) + slackMs`` passes. By
1125
+ * default this is **unset** — the player polls indefinitely until the
1126
+ * clip is ready, and stops only when it unmounts or ``clip`` changes
1127
+ * (both abort the in-flight poll). Set a value when you want a hard
1128
+ * ceiling (e.g. ``120_000`` for a two-minute cap). Forwarded
1129
+ * directly to {@link fetchPlaylist}'s ``slackMs`` option — see that
1130
+ * helper for the polling semantics.
1107
1131
  */
1108
1132
  slackMs?: number;
1109
1133
  /** Play automatically once the manifest is attached. Default ``true``. */
@@ -1326,4 +1350,4 @@ declare function useReactorInternalMessage(handler: (message: any) => void): voi
1326
1350
  */
1327
1351
  declare function useStats(): ConnectionStats | undefined;
1328
1352
 
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 };
1353
+ 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;
@@ -362,9 +366,10 @@ type ClipKind = "snap" | "recording";
362
366
  * - `predictedReadyAtMs` is a **Unix epoch in milliseconds** — the
363
367
  * runtime's estimate of when the boundary chunk will be servable
364
368
  * 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.
369
+ * Ns" indicator. It is only an estimate: the SDK polls `/clips`
370
+ * until the manifest is actually ready and does not give up when
371
+ * this epoch passes (see {@link fetchPlaylist} for the polling and
372
+ * cancellation model).
368
373
  * - `playlistUrl` is short-lived in production (the embedded chunk
369
374
  * URLs are presigned for a few minutes). Re-issuing the request
370
375
  * produces a fresh URL with fresh presigning.
@@ -453,21 +458,29 @@ interface ParsedPlaylist {
453
458
  segmentUrls: string[];
454
459
  }
455
460
  /**
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.
461
+ * Suggested grace period for callers that opt into a *bounded* wait by
462
+ * passing it as {@link FetchPlaylistOptions.slackMs}. It is **not** a
463
+ * default: {@link fetchPlaylist} polls indefinitely unless a bound is
464
+ * supplied. Provided so callers who do want the old ~15 s ceiling can
465
+ * ask for it by name rather than hard-coding a magic number.
460
466
  */
461
467
  declare const DEFAULT_PLAYLIST_POLL_SLACK_MS = 15000;
462
468
  interface FetchPlaylistOptions {
463
469
  /**
464
470
  * 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).
471
+ * be servable. Pass `clip.predictedReadyAtMs` here. On its own it
472
+ * does *not* stop polling — it only anchors the optional `slackMs`
473
+ * deadline. Use it to drive a "ready in Ns" indicator.
468
474
  */
469
475
  predictedReadyAtMs?: number;
470
- /** Grace period after `predictedReadyAtMs`. Default {@link DEFAULT_PLAYLIST_POLL_SLACK_MS}. */
476
+ /**
477
+ * Opt-in grace period that turns polling into a *bounded* wait. When
478
+ * set to a finite value, a stuck `202` produces `CLIP_NOT_READY` once
479
+ * `max(predictedReadyAtMs, pollStart) + slackMs` passes. Omit (the
480
+ * default) to poll indefinitely until the manifest is ready or the
481
+ * caller aborts via `signal`. See {@link DEFAULT_PLAYLIST_POLL_SLACK_MS}
482
+ * for a sensible value if you want the old ~15 s ceiling.
483
+ */
471
484
  slackMs?: number;
472
485
  /**
473
486
  * Hard cap on the per-poll wait. The server's `Retry-After` header is
@@ -477,12 +490,18 @@ interface FetchPlaylistOptions {
477
490
  /** Floor on the per-poll wait so we don't hot-loop on cheap networks. Default 200 ms. */
478
491
  minRetryDelayMs?: number;
479
492
  /**
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.
493
+ * Opt-in cap on the number of `202` responses tolerated before
494
+ * `CLIP_NOT_READY`. Omit (the default) to poll indefinitely; set it
495
+ * for a simple attempt-count ceiling when you don't have a
496
+ * `predictedReadyAtMs` to anchor a `slackMs` deadline.
483
497
  */
484
498
  maxRetries?: number;
485
- /** Aborts in-flight fetches and the inter-poll sleep. */
499
+ /**
500
+ * Aborts in-flight fetches and the inter-poll sleep. Because polling
501
+ * is unbounded by default, this is the primary way a caller ends a
502
+ * wait that is taking too long (a timeout, a user "cancel", a React
503
+ * unmount).
504
+ */
486
505
  signal?: AbortSignal;
487
506
  /**
488
507
  * Coordinator JWT. When set, attached as `Authorization: Bearer
@@ -495,14 +514,19 @@ interface FetchPlaylistOptions {
495
514
  * Fetch the playlist URL, polling on `202 Accepted` (which the manifest
496
515
  * endpoint returns while the boundary chunk is still uploading).
497
516
  *
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:
517
+ * Polling is **unbounded by default** — it keeps retrying on `202`
518
+ * until the manifest is ready or the caller aborts via `signal`. This
519
+ * matches the reality that a clip's boundary chunk can take arbitrarily
520
+ * long to land (a paused model closes no chunks; a long recording's
521
+ * final chunk is large). Callers own the give-up policy: pass `signal`
522
+ * to cancel, or opt into a ceiling with `slackMs` / `maxRetries`.
523
+ *
501
524
  * - `200` → returns the manifest body.
502
525
  * - `410` / `404` → throws `CLIP_GONE`.
503
526
  * - `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).
527
+ * - `202` past an opt-in `slackMs` deadline or `maxRetries` cap →
528
+ * throws `CLIP_NOT_READY`.
529
+ * - aborted `signal` → rejects with the fetch/`sleep` `AbortError`.
506
530
  */
507
531
  declare function fetchPlaylist(playlistUrl: string, options?: FetchPlaylistOptions): Promise<string>;
508
532
  /**
@@ -718,6 +742,7 @@ declare class Reactor {
718
742
  * down its own transport but leaves the session alive.
719
743
  */
720
744
  private createdSession;
745
+ private retryingSessionLoss;
721
746
  private connectStartTime?;
722
747
  private connectionTimings?;
723
748
  private schema?;
@@ -1094,16 +1119,15 @@ interface ClipPlayerProps {
1094
1119
  */
1095
1120
  getJwt?: () => string | Promise<string>;
1096
1121
  /**
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.
1122
+ * Opt into a *bounded* wait: give up polling the ``/clips`` manifest
1123
+ * endpoint with ``CLIP_NOT_READY`` once
1124
+ * ``max(clip.predictedReadyAtMs, pollStart) + slackMs`` passes. By
1125
+ * default this is **unset** — the player polls indefinitely until the
1126
+ * clip is ready, and stops only when it unmounts or ``clip`` changes
1127
+ * (both abort the in-flight poll). Set a value when you want a hard
1128
+ * ceiling (e.g. ``120_000`` for a two-minute cap). Forwarded
1129
+ * directly to {@link fetchPlaylist}'s ``slackMs`` option — see that
1130
+ * helper for the polling semantics.
1107
1131
  */
1108
1132
  slackMs?: number;
1109
1133
  /** Play automatically once the manifest is attached. Default ``true``. */
@@ -1326,4 +1350,4 @@ declare function useReactorInternalMessage(handler: (message: any) => void): voi
1326
1350
  */
1327
1351
  declare function useStats(): ConnectionStats | undefined;
1328
1352
 
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 };
1353
+ 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.2",
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();
@@ -3341,7 +3374,7 @@ var Reactor = class {
3341
3374
  */
3342
3375
  connect(jwtToken, options) {
3343
3376
  return __async(this, null, function* () {
3344
- var _a;
3377
+ var _a, _b, _c, _d;
3345
3378
  console.debug("[Reactor] Connecting, status:", this.status);
3346
3379
  if (jwtToken == void 0 && !this.local) {
3347
3380
  throw new Error("No authentication provided and not in local mode");
@@ -3429,6 +3462,19 @@ var Reactor = class {
3429
3462
  };
3430
3463
  } catch (error) {
3431
3464
  if (isAbortError(error)) return;
3465
+ if (!(options == null ? void 0 : options.sessionId) && !this.retryingSessionLoss && isSessionLostError(error)) {
3466
+ this.retryingSessionLoss = true;
3467
+ (_b = this.coordinatorClient) == null ? void 0 : _b.abort();
3468
+ (_c = this.transportClient) == null ? void 0 : _c.abort();
3469
+ (_d = this.transportClient) == null ? void 0 : _d.disconnect();
3470
+ this.setStatus("disconnected");
3471
+ try {
3472
+ yield this.connect(jwtToken, options);
3473
+ return;
3474
+ } finally {
3475
+ this.retryingSessionLoss = false;
3476
+ }
3477
+ }
3432
3478
  console.error("[Reactor] Connection failed:", error);
3433
3479
  this.createError(
3434
3480
  "CONNECTION_FAILED",
@@ -4615,9 +4661,16 @@ function useClipDownload(clip, options = {}) {
4615
4661
  getJwtRef.current = options.getJwt;
4616
4662
  });
4617
4663
  const inFlightRef = (0, import_react8.useRef)(false);
4664
+ const abortRef = (0, import_react8.useRef)(null);
4665
+ (0, import_react8.useEffect)(() => () => {
4666
+ var _a2;
4667
+ return (_a2 = abortRef.current) == null ? void 0 : _a2.abort();
4668
+ }, []);
4618
4669
  const download = (0, import_react8.useCallback)(() => __async(null, null, function* () {
4619
4670
  if (inFlightRef.current) return void 0;
4620
4671
  inFlightRef.current = true;
4672
+ const abort = new AbortController();
4673
+ abortRef.current = abort;
4621
4674
  setState({ kind: "downloading", fetched: 0, total: 0 });
4622
4675
  try {
4623
4676
  const explicit = getJwtRef.current;
@@ -4629,12 +4682,16 @@ function useClipDownload(clip, options = {}) {
4629
4682
  filenameRef.current,
4630
4683
  {
4631
4684
  jwt,
4685
+ signal: abort.signal,
4632
4686
  onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
4633
4687
  }
4634
4688
  );
4635
4689
  setState({ kind: "idle" });
4636
4690
  return blob;
4637
4691
  } catch (err) {
4692
+ if (err instanceof DOMException && err.name === "AbortError") {
4693
+ return void 0;
4694
+ }
4638
4695
  const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4639
4696
  setState({ kind: "error", message });
4640
4697
  return void 0;
@@ -4728,12 +4785,14 @@ function defaultLabel(state) {
4728
4785
  RecordingClient,
4729
4786
  RecordingError,
4730
4787
  RuntimeRecordingMessageType,
4788
+ SessionLostError,
4731
4789
  WebcamStream,
4732
4790
  clipFromPayload,
4733
4791
  createPlayableManifestUrl,
4734
4792
  downloadClipAsFile,
4735
4793
  fetchPlaylist,
4736
4794
  isAbortError,
4795
+ isSessionLostError,
4737
4796
  normalizeJwtSource,
4738
4797
  parsePlaylist,
4739
4798
  rewriteUrlHost,