@reactor-team/js-sdk 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -29,6 +29,8 @@ interface ReactorErrorOptions {
29
29
  operation?: string | undefined;
30
30
  retry_after_ms?: number | undefined;
31
31
  timestamp_ms?: number | undefined;
32
+ /** The underlying error, kept as the standard `Error.cause`. */
33
+ cause?: unknown;
32
34
  }
33
35
  declare class ReactorError extends Error {
34
36
  /** The code this class stands for. `ReactorError` itself is the fallback,
@@ -223,9 +225,16 @@ interface ConnectOptions {
223
225
  autoResumeTracks?: boolean;
224
226
  maxAttempts?: number;
225
227
  }
226
- /** A token, or a resolver called before every authenticated request.
227
- * Returning "" sends no Authorization header. */
228
- type JwtSource = string | (() => string | Promise<string>);
228
+ /** What a token is being resolved for. `sessionId` is set for every request
229
+ * that targets an existing session and unset for session creation. A
230
+ * resolver that mints a replacement token must bind it to that session
231
+ * (`resources.sessions.bind`), or the token cannot reach the session. */
232
+ interface JwtRequestContext {
233
+ sessionId?: string;
234
+ }
235
+ /** A token, or a resolver called before every authenticated request with a
236
+ * `JwtRequestContext`. Returning "" sends no Authorization header. */
237
+ type JwtSource = string | ((context?: JwtRequestContext) => string | Promise<string>);
229
238
  interface TrackCapability {
230
239
  name: string;
231
240
  kind: TrackKind;
@@ -549,10 +558,14 @@ interface FetchPlaylistOptions {
549
558
  */
550
559
  signal?: AbortSignal;
551
560
  /**
552
- * Coordinator JWT, attached as `Authorization: Bearer <jwt>` on the
553
- * manifest GET. Omit in local mode (HttpRuntime).
561
+ * Coordinator JWT for the manifest GET: a string, or a resolver called
562
+ * before every poll with `{ sessionId }`, so a long 202 wait can cross a
563
+ * token refresh. Omit in local mode (HttpRuntime).
554
564
  */
555
- jwt?: string;
565
+ jwt?: JwtSource;
566
+ /** The clip's session, handed to a resolver `jwt`. `downloadClipAsFile()`
567
+ * fills it from `clip.sessionId`. */
568
+ sessionId?: string;
556
569
  }
557
570
  /**
558
571
  * Fetch `playlistUrl`, polling on `202 Accepted` — returned while the
@@ -584,9 +597,10 @@ declare function parsePlaylist(manifestBody: string, playlistUrl: string): Parse
584
597
  */
585
598
  declare function createPlayableManifestUrl(manifestBody: string, playlistUrl: string): string;
586
599
  interface DownloadClipOptions {
587
- /** Coordinator JWT for the manifest GET. The chunks it references are S3
588
- * presigned URLs, fetched unauthenticated. */
589
- jwt?: string;
600
+ /** Coordinator JWT for the manifest GET: a string, or a resolver called
601
+ * per poll with `{ sessionId: clip.sessionId }`. The chunks the manifest
602
+ * references are S3 presigned URLs, fetched unauthenticated. */
603
+ jwt?: JwtSource;
590
604
  /** Cancels both the playlist poll and any in-flight chunk fetches. */
591
605
  signal?: AbortSignal;
592
606
  /** Called after each chunk completes — useful for progress UI. */
@@ -982,8 +996,10 @@ declare class Reactor implements Disposable {
982
996
  }
983
997
 
984
998
  /** Lazy resolver for a Coordinator/runtime bearer token, called immediately
985
- * before each authenticated request — see `JwtSource`. */
986
- type JwtResolver = () => string | Promise<string>;
999
+ * before each authenticated request with the session that request is for —
1000
+ * see `JwtSource` and `JwtRequestContext`. A resolver that ignores the
1001
+ * context keeps working. */
1002
+ type JwtResolver = (context?: JwtRequestContext) => string | Promise<string>;
987
1003
  /**
988
1004
  * Wraps a `JwtSource` into a `JwtResolver`: a static string becomes a
989
1005
  * resolver that always returns it, a resolver passes through unchanged.
@@ -1184,13 +1200,14 @@ interface ClipPlayerProps {
1184
1200
  clip: Clip;
1185
1201
  /**
1186
1202
  * Lazy resolver for the Coordinator JWT used on the manifest GET, called
1187
- * at request time so token refreshes are picked up automatically.
1203
+ * before every poll with `{ sessionId: clip.sessionId }` so token refreshes
1204
+ * are picked up automatically.
1188
1205
  *
1189
1206
  * Required outside a `ReactorProvider` in production; optional inside one
1190
1207
  * (inherits the provider's resolver). Omit in local-dev mode (HttpRuntime)
1191
1208
  * — the manifest endpoint there is auth-free.
1192
1209
  */
1193
- getJwt?: () => string | Promise<string>;
1210
+ getJwt?: JwtResolver;
1194
1211
  /**
1195
1212
  * Opt into a bounded wait: give up polling the manifest with
1196
1213
  * `CLIP_NOT_READY` once `max(clip.predictedReadyAtMs, pollStart) + slackMs`
@@ -1243,13 +1260,14 @@ interface UseClipDownloadOptions {
1243
1260
  filename?: string | null;
1244
1261
  /**
1245
1262
  * Lazy resolver for the Coordinator JWT used on the manifest GET. Called
1246
- * on every {@link UseClipDownloadResult.download} invocation, so token
1247
- * refreshes are picked up automatically.
1263
+ * before every poll of a {@link UseClipDownloadResult.download} with
1264
+ * `{ sessionId: clip.sessionId }`, so token refreshes are picked up
1265
+ * automatically.
1248
1266
  *
1249
1267
  * Optional inside a `ReactorProvider` (inherits the provider's resolver)
1250
1268
  * and in local-dev mode.
1251
1269
  */
1252
- getJwt?: () => string | Promise<string>;
1270
+ getJwt?: JwtResolver;
1253
1271
  }
1254
1272
  interface UseClipDownloadResult {
1255
1273
  /** Current state of the most recent download attempt. */
@@ -1294,7 +1312,7 @@ interface ClipDownloadButtonProps {
1294
1312
  clip: Clip;
1295
1313
  /** Lazy JWT resolver. Optional inside a `ReactorProvider` (inherits the
1296
1314
  * provider's resolver) and in local-dev mode. See `ClipPlayerProps.getJwt`. */
1297
- getJwt?: () => string | Promise<string>;
1315
+ getJwt?: JwtResolver;
1298
1316
  /** Filename for the saved MP4. Default `"reactor-clip.mp4"`. */
1299
1317
  filename?: string;
1300
1318
  /**
@@ -1324,4 +1342,4 @@ interface ClipDownloadButtonProps {
1324
1342
  }
1325
1343
  declare function ClipDownloadButton({ clip, getJwt, filename, children, className, style, disabled, onSuccess, onError, }: ClipDownloadButtonProps): react.JSX.Element;
1326
1344
 
1327
- export { AbortedError, BadRequestError, type Capabilities, type Clip, ClipDownloadButton, type ClipDownloadButtonProps, type ClipDownloadState, type ClipKind, ClipPlayer, type ClipPlayerProps, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_PLAYLIST_POLL_SLACK_MS, DecodeError, DisconnectedError, type DownloadClipOptions, type FetchPlaylistOptions, FileRef, InvalidStateError, type JwtResolver, type JwtSource, type MessageScope, MessageTooLargeError, type ModelSchema, type ModelSchemaOperation, type ModelSchemaPathItem, type ModerationAction, type ModerationEvent, NetworkError, NotFoundError, RateLimitedError, Reactor, type ReactorActions, type ReactorConnectOptions, ReactorError, type ReactorEventMap, type ReactorEventName, type ReactorMessage, type ReactorOptions, ReactorProvider, type ReactorProviderProps, type ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecorderDisabledError, RecordingError, RequestTimeoutError, ServerError, type SessionResponse, SessionTerminalError, type TrackCapability, type TrackDirection, type TrackKind, type TrackMappingEntry, TransportError, UnauthorizedError, type UseClipDownloadOptions, type UseClipDownloadResult, VersionMismatchError, WebcamStream, type WebcamStreamProps, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isFileRef, normalizeJwtSource, parsePlaylist, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useStats };
1345
+ export { AbortedError, BadRequestError, type Capabilities, type Clip, ClipDownloadButton, type ClipDownloadButtonProps, type ClipDownloadState, type ClipKind, ClipPlayer, type ClipPlayerProps, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_PLAYLIST_POLL_SLACK_MS, DecodeError, DisconnectedError, type DownloadClipOptions, type FetchPlaylistOptions, FileRef, InvalidStateError, type JwtRequestContext, type JwtResolver, type JwtSource, type MessageScope, MessageTooLargeError, type ModelSchema, type ModelSchemaOperation, type ModelSchemaPathItem, type ModerationAction, type ModerationEvent, NetworkError, NotFoundError, RateLimitedError, Reactor, type ReactorActions, type ReactorConnectOptions, ReactorError, type ReactorEventMap, type ReactorEventName, type ReactorMessage, type ReactorOptions, ReactorProvider, type ReactorProviderProps, type ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecorderDisabledError, RecordingError, RequestTimeoutError, ServerError, type SessionResponse, SessionTerminalError, type TrackCapability, type TrackDirection, type TrackKind, type TrackMappingEntry, TransportError, UnauthorizedError, type UseClipDownloadOptions, type UseClipDownloadResult, VersionMismatchError, WebcamStream, type WebcamStreamProps, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isFileRef, normalizeJwtSource, parsePlaylist, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useStats };
package/dist/index.d.ts CHANGED
@@ -29,6 +29,8 @@ interface ReactorErrorOptions {
29
29
  operation?: string | undefined;
30
30
  retry_after_ms?: number | undefined;
31
31
  timestamp_ms?: number | undefined;
32
+ /** The underlying error, kept as the standard `Error.cause`. */
33
+ cause?: unknown;
32
34
  }
33
35
  declare class ReactorError extends Error {
34
36
  /** The code this class stands for. `ReactorError` itself is the fallback,
@@ -223,9 +225,16 @@ interface ConnectOptions {
223
225
  autoResumeTracks?: boolean;
224
226
  maxAttempts?: number;
225
227
  }
226
- /** A token, or a resolver called before every authenticated request.
227
- * Returning "" sends no Authorization header. */
228
- type JwtSource = string | (() => string | Promise<string>);
228
+ /** What a token is being resolved for. `sessionId` is set for every request
229
+ * that targets an existing session and unset for session creation. A
230
+ * resolver that mints a replacement token must bind it to that session
231
+ * (`resources.sessions.bind`), or the token cannot reach the session. */
232
+ interface JwtRequestContext {
233
+ sessionId?: string;
234
+ }
235
+ /** A token, or a resolver called before every authenticated request with a
236
+ * `JwtRequestContext`. Returning "" sends no Authorization header. */
237
+ type JwtSource = string | ((context?: JwtRequestContext) => string | Promise<string>);
229
238
  interface TrackCapability {
230
239
  name: string;
231
240
  kind: TrackKind;
@@ -549,10 +558,14 @@ interface FetchPlaylistOptions {
549
558
  */
550
559
  signal?: AbortSignal;
551
560
  /**
552
- * Coordinator JWT, attached as `Authorization: Bearer <jwt>` on the
553
- * manifest GET. Omit in local mode (HttpRuntime).
561
+ * Coordinator JWT for the manifest GET: a string, or a resolver called
562
+ * before every poll with `{ sessionId }`, so a long 202 wait can cross a
563
+ * token refresh. Omit in local mode (HttpRuntime).
554
564
  */
555
- jwt?: string;
565
+ jwt?: JwtSource;
566
+ /** The clip's session, handed to a resolver `jwt`. `downloadClipAsFile()`
567
+ * fills it from `clip.sessionId`. */
568
+ sessionId?: string;
556
569
  }
557
570
  /**
558
571
  * Fetch `playlistUrl`, polling on `202 Accepted` — returned while the
@@ -584,9 +597,10 @@ declare function parsePlaylist(manifestBody: string, playlistUrl: string): Parse
584
597
  */
585
598
  declare function createPlayableManifestUrl(manifestBody: string, playlistUrl: string): string;
586
599
  interface DownloadClipOptions {
587
- /** Coordinator JWT for the manifest GET. The chunks it references are S3
588
- * presigned URLs, fetched unauthenticated. */
589
- jwt?: string;
600
+ /** Coordinator JWT for the manifest GET: a string, or a resolver called
601
+ * per poll with `{ sessionId: clip.sessionId }`. The chunks the manifest
602
+ * references are S3 presigned URLs, fetched unauthenticated. */
603
+ jwt?: JwtSource;
590
604
  /** Cancels both the playlist poll and any in-flight chunk fetches. */
591
605
  signal?: AbortSignal;
592
606
  /** Called after each chunk completes — useful for progress UI. */
@@ -982,8 +996,10 @@ declare class Reactor implements Disposable {
982
996
  }
983
997
 
984
998
  /** Lazy resolver for a Coordinator/runtime bearer token, called immediately
985
- * before each authenticated request — see `JwtSource`. */
986
- type JwtResolver = () => string | Promise<string>;
999
+ * before each authenticated request with the session that request is for —
1000
+ * see `JwtSource` and `JwtRequestContext`. A resolver that ignores the
1001
+ * context keeps working. */
1002
+ type JwtResolver = (context?: JwtRequestContext) => string | Promise<string>;
987
1003
  /**
988
1004
  * Wraps a `JwtSource` into a `JwtResolver`: a static string becomes a
989
1005
  * resolver that always returns it, a resolver passes through unchanged.
@@ -1184,13 +1200,14 @@ interface ClipPlayerProps {
1184
1200
  clip: Clip;
1185
1201
  /**
1186
1202
  * Lazy resolver for the Coordinator JWT used on the manifest GET, called
1187
- * at request time so token refreshes are picked up automatically.
1203
+ * before every poll with `{ sessionId: clip.sessionId }` so token refreshes
1204
+ * are picked up automatically.
1188
1205
  *
1189
1206
  * Required outside a `ReactorProvider` in production; optional inside one
1190
1207
  * (inherits the provider's resolver). Omit in local-dev mode (HttpRuntime)
1191
1208
  * — the manifest endpoint there is auth-free.
1192
1209
  */
1193
- getJwt?: () => string | Promise<string>;
1210
+ getJwt?: JwtResolver;
1194
1211
  /**
1195
1212
  * Opt into a bounded wait: give up polling the manifest with
1196
1213
  * `CLIP_NOT_READY` once `max(clip.predictedReadyAtMs, pollStart) + slackMs`
@@ -1243,13 +1260,14 @@ interface UseClipDownloadOptions {
1243
1260
  filename?: string | null;
1244
1261
  /**
1245
1262
  * Lazy resolver for the Coordinator JWT used on the manifest GET. Called
1246
- * on every {@link UseClipDownloadResult.download} invocation, so token
1247
- * refreshes are picked up automatically.
1263
+ * before every poll of a {@link UseClipDownloadResult.download} with
1264
+ * `{ sessionId: clip.sessionId }`, so token refreshes are picked up
1265
+ * automatically.
1248
1266
  *
1249
1267
  * Optional inside a `ReactorProvider` (inherits the provider's resolver)
1250
1268
  * and in local-dev mode.
1251
1269
  */
1252
- getJwt?: () => string | Promise<string>;
1270
+ getJwt?: JwtResolver;
1253
1271
  }
1254
1272
  interface UseClipDownloadResult {
1255
1273
  /** Current state of the most recent download attempt. */
@@ -1294,7 +1312,7 @@ interface ClipDownloadButtonProps {
1294
1312
  clip: Clip;
1295
1313
  /** Lazy JWT resolver. Optional inside a `ReactorProvider` (inherits the
1296
1314
  * provider's resolver) and in local-dev mode. See `ClipPlayerProps.getJwt`. */
1297
- getJwt?: () => string | Promise<string>;
1315
+ getJwt?: JwtResolver;
1298
1316
  /** Filename for the saved MP4. Default `"reactor-clip.mp4"`. */
1299
1317
  filename?: string;
1300
1318
  /**
@@ -1324,4 +1342,4 @@ interface ClipDownloadButtonProps {
1324
1342
  }
1325
1343
  declare function ClipDownloadButton({ clip, getJwt, filename, children, className, style, disabled, onSuccess, onError, }: ClipDownloadButtonProps): react.JSX.Element;
1326
1344
 
1327
- export { AbortedError, BadRequestError, type Capabilities, type Clip, ClipDownloadButton, type ClipDownloadButtonProps, type ClipDownloadState, type ClipKind, ClipPlayer, type ClipPlayerProps, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_PLAYLIST_POLL_SLACK_MS, DecodeError, DisconnectedError, type DownloadClipOptions, type FetchPlaylistOptions, FileRef, InvalidStateError, type JwtResolver, type JwtSource, type MessageScope, MessageTooLargeError, type ModelSchema, type ModelSchemaOperation, type ModelSchemaPathItem, type ModerationAction, type ModerationEvent, NetworkError, NotFoundError, RateLimitedError, Reactor, type ReactorActions, type ReactorConnectOptions, ReactorError, type ReactorEventMap, type ReactorEventName, type ReactorMessage, type ReactorOptions, ReactorProvider, type ReactorProviderProps, type ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecorderDisabledError, RecordingError, RequestTimeoutError, ServerError, type SessionResponse, SessionTerminalError, type TrackCapability, type TrackDirection, type TrackKind, type TrackMappingEntry, TransportError, UnauthorizedError, type UseClipDownloadOptions, type UseClipDownloadResult, VersionMismatchError, WebcamStream, type WebcamStreamProps, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isFileRef, normalizeJwtSource, parsePlaylist, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useStats };
1345
+ export { AbortedError, BadRequestError, type Capabilities, type Clip, ClipDownloadButton, type ClipDownloadButtonProps, type ClipDownloadState, type ClipKind, ClipPlayer, type ClipPlayerProps, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_PLAYLIST_POLL_SLACK_MS, DecodeError, DisconnectedError, type DownloadClipOptions, type FetchPlaylistOptions, FileRef, InvalidStateError, type JwtRequestContext, type JwtResolver, type JwtSource, type MessageScope, MessageTooLargeError, type ModelSchema, type ModelSchemaOperation, type ModelSchemaPathItem, type ModerationAction, type ModerationEvent, NetworkError, NotFoundError, RateLimitedError, Reactor, type ReactorActions, type ReactorConnectOptions, ReactorError, type ReactorEventMap, type ReactorEventName, type ReactorMessage, type ReactorOptions, ReactorProvider, type ReactorProviderProps, type ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecorderDisabledError, RecordingError, RequestTimeoutError, ServerError, type SessionResponse, SessionTerminalError, type TrackCapability, type TrackDirection, type TrackKind, type TrackMappingEntry, TransportError, UnauthorizedError, type UseClipDownloadOptions, type UseClipDownloadResult, VersionMismatchError, WebcamStream, type WebcamStreamProps, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isFileRef, normalizeJwtSource, parsePlaylist, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useStats };
package/dist/index.js CHANGED
@@ -56,7 +56,7 @@ var ReactorError = class extends Error {
56
56
  * compatibility — prefer `timestamp_ms`. */
57
57
  timestamp;
58
58
  constructor(message, options = {}) {
59
- super(message);
59
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
60
60
  this.name = "ReactorError";
61
61
  this.code = options.code ?? new.target.code;
62
62
  this.recoverable = options.recoverable ?? false;
@@ -157,7 +157,10 @@ function toReactorError(cause) {
157
157
  status: payload.status,
158
158
  operation: payload.operation,
159
159
  retry_after_ms: payload.retry_after_ms,
160
- timestamp_ms: payload.timestamp_ms
160
+ timestamp_ms: payload.timestamp_ms,
161
+ // A thrown JS error (a failed wasm load, say) keeps its stack and its own
162
+ // `cause` reachable; reactor-core's plain payload objects have neither.
163
+ cause: cause instanceof Error ? cause : void 0
161
164
  });
162
165
  }
163
166
 
@@ -558,27 +561,27 @@ function loadReactorWasm() {
558
561
  if (!modulePromise) {
559
562
  modulePromise = importWasmModule().catch((cause) => {
560
563
  modulePromise = null;
561
- throw new Error(
562
- "reactor-wasm failed to load. Run `mise run build:wasm` (or, from a published install, reinstall the package) and try again.",
563
- { cause }
564
- );
564
+ throw new Error(`reactor-wasm failed to load: ${describeCause(cause)}`, { cause });
565
565
  });
566
566
  }
567
567
  return modulePromise;
568
568
  }
569
569
  async function importWasmModule() {
570
- const module = await import(
571
- /* @vite-ignore */
572
- "./wasm/reactor_wasm.js"
573
- );
570
+ const module = await import("./wasm/reactor_wasm.js");
574
571
  await module.default();
575
572
  return module;
576
573
  }
574
+ function describeCause(cause) {
575
+ if (cause instanceof Error) {
576
+ return cause.message ? `${cause.name}: ${cause.message}` : cause.name;
577
+ }
578
+ return String(cause);
579
+ }
577
580
 
578
581
  // package.json
579
582
  var package_default = {
580
583
  name: "@reactor-team/js-sdk",
581
- version: "3.1.0",
584
+ version: "3.2.0",
582
585
  description: "Connect your JavaScript/TypeScript app to a live Reactor model in the browser.",
583
586
  license: "Apache-2.0",
584
587
  repository: {
@@ -638,6 +641,11 @@ var package_default = {
638
641
  }
639
642
  };
640
643
 
644
+ // src/internal/jwt-resolver.ts
645
+ async function resolveJwtSource(source, context) {
646
+ return typeof source === "function" ? source(context) : source;
647
+ }
648
+
641
649
  // src/recording.ts
642
650
  var RecordingError = class extends Error {
643
651
  constructor(code, reason) {
@@ -657,15 +665,16 @@ async function fetchPlaylist(playlistUrl, options = {}) {
657
665
  const startedPollingAt = Date.now();
658
666
  const deadlineMs = hasDeadline ? Math.max(options.predictedReadyAtMs ?? startedPollingAt, startedPollingAt) + options.slackMs : void 0;
659
667
  const maxRetries = typeof options.maxRetries === "number" ? options.maxRetries : void 0;
660
- const init = {};
661
- if (options.signal) {
662
- init.signal = options.signal;
663
- }
664
- if (options.jwt) {
665
- init.headers = { Authorization: `Bearer ${options.jwt}` };
666
- }
667
668
  let attempt = 0;
668
669
  while (true) {
670
+ const init = {};
671
+ if (options.signal) {
672
+ init.signal = options.signal;
673
+ }
674
+ const jwt = await resolveManifestJwt(options);
675
+ if (jwt) {
676
+ init.headers = { Authorization: `Bearer ${jwt}` };
677
+ }
669
678
  let response;
670
679
  try {
671
680
  response = await fetch(playlistUrl, init);
@@ -768,7 +777,10 @@ function absolutizeManifestUrls(manifestBody, playlistUrl) {
768
777
  return out.join(eol);
769
778
  }
770
779
  async function downloadClipAsFile(clip, filename = "reactor-clip.mp4", options = {}) {
771
- const playlistOptions = { predictedReadyAtMs: clip.predictedReadyAtMs };
780
+ const playlistOptions = {
781
+ predictedReadyAtMs: clip.predictedReadyAtMs,
782
+ sessionId: clip.sessionId
783
+ };
772
784
  if (options.signal) {
773
785
  playlistOptions.signal = options.signal;
774
786
  }
@@ -1006,6 +1018,27 @@ function parseRetryAfter(header, fallbackMs) {
1006
1018
  }
1007
1019
  return fallbackMs;
1008
1020
  }
1021
+ async function resolveManifestJwt(options) {
1022
+ if (options.jwt === void 0) {
1023
+ return void 0;
1024
+ }
1025
+ const context = options.sessionId === void 0 ? {} : { sessionId: options.sessionId };
1026
+ return abortable(resolveJwtSource(options.jwt, context), options.signal);
1027
+ }
1028
+ function abortable(promise, signal) {
1029
+ if (!signal) {
1030
+ return promise;
1031
+ }
1032
+ return new Promise((resolve, reject) => {
1033
+ const onAbort = () => reject(new DOMException("Aborted", "AbortError"));
1034
+ if (signal.aborted) {
1035
+ onAbort();
1036
+ } else {
1037
+ signal.addEventListener("abort", onAbort, { once: true });
1038
+ }
1039
+ void promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
1040
+ });
1041
+ }
1009
1042
  function sleep(ms, signal) {
1010
1043
  return new Promise((resolve, reject) => {
1011
1044
  if (signal?.aborted) {
@@ -2470,11 +2503,6 @@ function describeMediaError(error) {
2470
2503
  return error?.message ? `${message} (${error.message})` : message;
2471
2504
  }
2472
2505
 
2473
- // src/internal/jwt-resolver.ts
2474
- async function resolveJwtSource(source) {
2475
- return typeof source === "function" ? source() : source;
2476
- }
2477
-
2478
2506
  // src/react/ClipPlayer.tsx
2479
2507
  import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
2480
2508
  function ClipPlayer({
@@ -2524,21 +2552,17 @@ function ClipPlayer({
2524
2552
  const setup = async () => {
2525
2553
  try {
2526
2554
  setPhase({ kind: "waiting" });
2527
- const explicit = getJwtRef.current;
2528
- const fallback = storeRef.current?.getState().internal.reactor.getJwtResolver();
2529
- const jwt = explicit ? await explicit() : fallback !== void 0 ? await resolveJwtSource(fallback) : void 0;
2530
- if (cancelled) {
2531
- return;
2532
- }
2555
+ const source = () => getJwtRef.current ?? storeRef.current?.getState().internal.reactor.getJwtResolver();
2533
2556
  const playlistOptions = {
2534
2557
  predictedReadyAtMs: clip.predictedReadyAtMs,
2558
+ sessionId: clip.sessionId,
2535
2559
  signal: abort.signal
2536
2560
  };
2537
2561
  if (slackMsRef.current !== void 0) {
2538
2562
  playlistOptions.slackMs = slackMsRef.current;
2539
2563
  }
2540
- if (jwt !== void 0) {
2541
- playlistOptions.jwt = jwt;
2564
+ if (source() !== void 0) {
2565
+ playlistOptions.jwt = (context) => resolveJwtSource(source() ?? "", context);
2542
2566
  }
2543
2567
  const body = await fetchPlaylist(clip.playlistUrl, playlistOptions);
2544
2568
  if (cancelled) {
@@ -2684,15 +2708,13 @@ function useClipDownload(clip, options = {}) {
2684
2708
  abortRef.current = abort;
2685
2709
  setState({ kind: "downloading", fetched: 0, total: 0 });
2686
2710
  try {
2687
- const explicit = getJwtRef.current;
2688
- const fallback = storeRef.current?.getState().internal.reactor.getJwtResolver();
2689
- const jwt = explicit ? await explicit() : fallback !== void 0 ? await resolveJwtSource(fallback) : void 0;
2711
+ const source = () => getJwtRef.current ?? storeRef.current?.getState().internal.reactor.getJwtResolver();
2690
2712
  const downloadOptions = {
2691
2713
  signal: abort.signal,
2692
2714
  onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
2693
2715
  };
2694
- if (jwt !== void 0) {
2695
- downloadOptions.jwt = jwt;
2716
+ if (source() !== void 0) {
2717
+ downloadOptions.jwt = (context) => resolveJwtSource(source() ?? "", context);
2696
2718
  }
2697
2719
  const blob = await downloadClipAsFile(clipRef.current, filenameRef.current, downloadOptions);
2698
2720
  setState({ kind: "idle" });