@reactor-team/js-sdk 2.11.0 → 2.11.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/dist/index.mjs CHANGED
@@ -91,7 +91,7 @@ import { z } from "zod";
91
91
  // package.json
92
92
  var package_default = {
93
93
  name: "@reactor-team/js-sdk",
94
- version: "2.11.0",
94
+ version: "2.11.2",
95
95
  description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
96
96
  license: "Apache-2.0",
97
97
  repository: {
@@ -403,6 +403,18 @@ var CoordinatorClient = class {
403
403
  return parsed;
404
404
  });
405
405
  }
406
+ /**
407
+ * Attaches to a session created elsewhere (e.g. by a backend) instead of
408
+ * creating one via {@link createSession}. After this, {@link pollSessionReady}
409
+ * and {@link getSession} operate on the adopted id. The session must be owned
410
+ * by the account behind this client's JWT.
411
+ */
412
+ adoptSession(sessionId) {
413
+ return __async(this, null, function* () {
414
+ this.currentSessionId = sessionId;
415
+ console.debug("[CoordinatorClient] Adopted existing session:", sessionId);
416
+ });
417
+ }
406
418
  /**
407
419
  * Polls GET /sessions/{id} until the Runtime has accepted the session
408
420
  * and populated capabilities and selected_transport.
@@ -694,6 +706,48 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
694
706
  return CreateSessionResponseSchema.parse(data);
695
707
  });
696
708
  }
709
+ /**
710
+ * Adopts the local session for `connect({ sessionId })`: records the id and
711
+ * reads the session descriptor, caching it so {@link pollSessionReady}
712
+ * returns immediately. No `start_session` is issued.
713
+ *
714
+ * The local runtime hosts a single session (always id `"local"`), so the
715
+ * lookup ignores the specific id. This is a pure read of session info — it
716
+ * does not start or otherwise advance the session.
717
+ */
718
+ adoptSession(sessionId) {
719
+ return __async(this, null, function* () {
720
+ this.currentSessionId = sessionId;
721
+ this.cachedSessionResponse = yield this.getSession();
722
+ console.debug(
723
+ "[LocalCoordinatorClient] Adopted existing session:",
724
+ sessionId
725
+ );
726
+ });
727
+ }
728
+ /**
729
+ * Reads the local session descriptor (model, capabilities, transport,
730
+ * state) via the runtime's read-only `GET /session`.
731
+ *
732
+ * The local runtime exposes a single session, so — unlike the Coordinator's
733
+ * id-addressed `GET /sessions/{id}` — there is no id in the path. Read-only:
734
+ * it does not start or advance the session.
735
+ */
736
+ getSession() {
737
+ return __async(this, null, function* () {
738
+ const response = yield fetch(`${this.baseUrl}/session`, {
739
+ method: "GET",
740
+ headers: yield this.getHeaders(),
741
+ signal: this.signal
742
+ });
743
+ if (!response.ok) {
744
+ const errorText = yield response.text();
745
+ throw new Error(`Failed to get session: ${response.status} ${errorText}`);
746
+ }
747
+ const data = yield response.json();
748
+ return SessionResponseSchema.parse(data);
749
+ });
750
+ }
697
751
  /**
698
752
  * Returns the cached full session response immediately.
699
753
  * The local runtime already provided everything in start_session.
@@ -2673,9 +2727,13 @@ var Reactor = class {
2673
2727
  sendCommand(command, data, scope = "application") {
2674
2728
  return __async(this, null, function* () {
2675
2729
  var _a;
2676
- if (process.env.NODE_ENV !== "development" && this.status !== "ready") {
2677
- const errorMessage = `Cannot send message, status is ${this.status}`;
2678
- console.warn("[Reactor]", errorMessage);
2730
+ if (this.status !== "ready") {
2731
+ this.createError(
2732
+ "NOT_READY",
2733
+ `Cannot send command "${command}" while status is "${this.status}". Must be "ready".`,
2734
+ "api",
2735
+ true
2736
+ );
2679
2737
  return;
2680
2738
  }
2681
2739
  try {
@@ -2915,6 +2973,12 @@ var Reactor = class {
2915
2973
  * be a static string or a {@link JwtSource} resolver; pass a
2916
2974
  * resolver when the token is short-lived so each Coordinator HTTP
2917
2975
  * hop sees a fresh value.
2976
+ *
2977
+ * Pass `options.sessionId` to attach to a session that already exists
2978
+ * (e.g. one created by a backend) instead of creating a new one — session
2979
+ * creation is skipped and the transport is brought up against that id. The
2980
+ * `jwtToken` must be valid for the account that owns the session. Works in
2981
+ * local mode too (it looks the session up by id rather than starting one).
2918
2982
  */
2919
2983
  connect(jwtToken, options) {
2920
2984
  return __async(this, null, function* () {
@@ -2936,20 +3000,29 @@ var Reactor = class {
2936
3000
  jwtToken,
2937
3001
  model: this.model
2938
3002
  });
2939
- const tSession = performance.now();
2940
- const initialResponse = yield this.coordinatorClient.createSession();
2941
- const sessionCreationMs = performance.now() - tSession;
2942
- this.setSessionId(initialResponse.session_id);
2943
- console.debug(
2944
- "[Reactor] Session created:",
2945
- initialResponse.session_id,
2946
- "state:",
2947
- initialResponse.state
2948
- );
3003
+ let sessionCreationMs = 0;
3004
+ let sessionId;
3005
+ if (options == null ? void 0 : options.sessionId) {
3006
+ yield this.coordinatorClient.adoptSession(options.sessionId);
3007
+ sessionId = options.sessionId;
3008
+ console.debug("[Reactor] Attaching to existing session:", sessionId);
3009
+ } else {
3010
+ const tSession = performance.now();
3011
+ const initialResponse = yield this.coordinatorClient.createSession();
3012
+ sessionCreationMs = performance.now() - tSession;
3013
+ sessionId = initialResponse.session_id;
3014
+ console.debug(
3015
+ "[Reactor] Session created:",
3016
+ sessionId,
3017
+ "state:",
3018
+ initialResponse.state
3019
+ );
3020
+ }
3021
+ this.setSessionId(sessionId);
2949
3022
  this.setStatus("waiting");
2950
3023
  this.transportClient = new WebRTCTransportClient({
2951
3024
  baseUrl: this.coordinatorUrl,
2952
- sessionId: initialResponse.session_id,
3025
+ sessionId,
2953
3026
  jwtToken: this.local ? "local" : jwtToken,
2954
3027
  webrtcVersion: REACTOR_WEBRTC_VERSION,
2955
3028
  maxPollAttempts: options == null ? void 0 : options.maxAttempts
@@ -3368,7 +3441,10 @@ var createReactorStore = (initProps, publicState = defaultInitState) => {
3368
3441
  console.error("[ReactorStore] Failed to upload file:", error);
3369
3442
  throw error;
3370
3443
  }
3371
- })
3444
+ }),
3445
+ requestClip: (durationSeconds) => get().internal.reactor.requestClip(durationSeconds),
3446
+ requestRecording: () => get().internal.reactor.requestRecording(),
3447
+ downloadClipAsFile: (clip, filename, options) => get().internal.reactor.downloadClipAsFile(clip, filename, options)
3372
3448
  });
3373
3449
  });
3374
3450
  };
@@ -3496,7 +3572,7 @@ function ReactorProvider(_a) {
3496
3572
  console.error("[ReactorProvider] Failed to disconnect:", error);
3497
3573
  });
3498
3574
  };
3499
- }, [apiUrl, modelName, autoConnect, local, jwtSource, maxAttempts]);
3575
+ }, [apiUrl, modelName, local, jwtSource]);
3500
3576
  return /* @__PURE__ */ jsx(ReactorContext.Provider, { value: storeRef.current, children });
3501
3577
  }
3502
3578
  function useReactorStore(selector) {
@@ -3572,7 +3648,7 @@ function ReactorView({
3572
3648
  className,
3573
3649
  style,
3574
3650
  videoObjectFit = "contain",
3575
- muted = true
3651
+ muted = audioTrack === void 0
3576
3652
  }) {
3577
3653
  const { videoMediaTrack, audioMediaTrack } = useReactor((state) => {
3578
3654
  var _a, _b;
@@ -4215,6 +4291,8 @@ import { useEffect as useEffect4, useRef as useRef5, useState as useState4 } fro
4215
4291
  import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
4216
4292
  function WebcamStream({
4217
4293
  track,
4294
+ audio = false,
4295
+ audioTrack,
4218
4296
  className,
4219
4297
  style,
4220
4298
  videoConstraints = {
@@ -4222,7 +4300,10 @@ function WebcamStream({
4222
4300
  height: { ideal: 720 }
4223
4301
  },
4224
4302
  showWebcam = true,
4225
- videoObjectFit = "contain"
4303
+ videoObjectFit = "contain",
4304
+ onPermissionDenied,
4305
+ onPublished,
4306
+ onError
4226
4307
  }) {
4227
4308
  const [stream, setStream] = useState4(null);
4228
4309
  const [isPublishing, setIsPublishing] = useState4(false);
@@ -4234,12 +4315,28 @@ function WebcamStream({
4234
4315
  reactor: state.internal.reactor
4235
4316
  }));
4236
4317
  const videoRef = useRef5(null);
4318
+ const onPermissionDeniedRef = useRef5(onPermissionDenied);
4319
+ const onPublishedRef = useRef5(onPublished);
4320
+ const onErrorRef = useRef5(onError);
4321
+ useEffect4(() => {
4322
+ onPermissionDeniedRef.current = onPermissionDenied;
4323
+ onPublishedRef.current = onPublished;
4324
+ onErrorRef.current = onError;
4325
+ });
4326
+ const audioRequested = audio !== false && audio !== void 0;
4327
+ const audioEnabled = audioRequested && !!audioTrack;
4328
+ if (audioRequested && !audioTrack) {
4329
+ console.warn(
4330
+ "[WebcamStream] `audio` was set but `audioTrack` is missing; capturing video-only."
4331
+ );
4332
+ }
4237
4333
  const startWebcam = () => __async(null, null, function* () {
4334
+ var _a, _b;
4238
4335
  console.debug("[WebcamPublisher] Starting webcam");
4239
4336
  try {
4240
4337
  const mediaStream = yield navigator.mediaDevices.getUserMedia({
4241
4338
  video: videoConstraints,
4242
- audio: false
4339
+ audio: audioEnabled ? audio === true ? true : audio : false
4243
4340
  });
4244
4341
  console.debug("[WebcamPublisher] Webcam started successfully");
4245
4342
  setStream(mediaStream);
@@ -4249,16 +4346,34 @@ function WebcamStream({
4249
4346
  if (err instanceof DOMException && (err.name === "NotAllowedError" || err.name === "PermissionDeniedError")) {
4250
4347
  console.debug("[WebcamPublisher] Camera permission denied");
4251
4348
  setPermissionDenied(true);
4349
+ (_a = onPermissionDeniedRef.current) == null ? void 0 : _a.call(onPermissionDeniedRef);
4350
+ } else {
4351
+ (_b = onErrorRef.current) == null ? void 0 : _b.call(
4352
+ onErrorRef,
4353
+ err instanceof Error ? err : new Error(String(err))
4354
+ );
4252
4355
  }
4253
4356
  }
4254
4357
  });
4255
4358
  const stopWebcam = () => __async(null, null, function* () {
4359
+ var _a;
4256
4360
  console.debug("[WebcamPublisher] Stopping webcam");
4257
- try {
4258
- yield unpublish(track);
4259
- console.debug("[WebcamPublisher] Unpublished before stopping");
4260
- } catch (err) {
4261
- console.error("[WebcamPublisher] Error unpublishing before stop:", err);
4361
+ const unpublishTasks = [unpublish(track)];
4362
+ if (audioEnabled && audioTrack) {
4363
+ unpublishTasks.push(unpublish(audioTrack));
4364
+ }
4365
+ const results = yield Promise.allSettled(unpublishTasks);
4366
+ for (const r of results) {
4367
+ if (r.status === "rejected") {
4368
+ console.error(
4369
+ "[WebcamPublisher] Error unpublishing before stop:",
4370
+ r.reason
4371
+ );
4372
+ (_a = onErrorRef.current) == null ? void 0 : _a.call(
4373
+ onErrorRef,
4374
+ r.reason instanceof Error ? r.reason : new Error(String(r.reason))
4375
+ );
4376
+ }
4262
4377
  }
4263
4378
  setIsPublishing(false);
4264
4379
  stream == null ? void 0 : stream.getTracks().forEach((t) => {
@@ -4293,25 +4408,54 @@ function WebcamStream({
4293
4408
  console.debug(
4294
4409
  "[WebcamPublisher] Reactor ready, auto-publishing webcam stream"
4295
4410
  );
4296
- const videoTrack = stream.getVideoTracks()[0];
4297
- if (videoTrack) {
4298
- publish(track, videoTrack).then(() => {
4299
- console.debug("[WebcamPublisher] Auto-publish successful");
4300
- setIsPublishing(true);
4301
- }).catch((err) => {
4302
- console.error("[WebcamPublisher] Auto-publish failed:", err);
4303
- });
4304
- }
4411
+ const videoMediaTrack = stream.getVideoTracks()[0];
4412
+ const audioMediaTrack = audioEnabled && audioTrack ? stream.getAudioTracks()[0] : null;
4413
+ const tasks = [];
4414
+ if (videoMediaTrack) tasks.push(publish(track, videoMediaTrack));
4415
+ if (audioMediaTrack && audioTrack)
4416
+ tasks.push(publish(audioTrack, audioMediaTrack));
4417
+ if (tasks.length === 0) return;
4418
+ Promise.all(tasks).then(() => {
4419
+ var _a;
4420
+ console.debug("[WebcamPublisher] Auto-publish successful");
4421
+ setIsPublishing(true);
4422
+ (_a = onPublishedRef.current) == null ? void 0 : _a.call(onPublishedRef);
4423
+ }).catch((err) => {
4424
+ var _a;
4425
+ console.error("[WebcamPublisher] Auto-publish failed:", err);
4426
+ (_a = onErrorRef.current) == null ? void 0 : _a.call(
4427
+ onErrorRef,
4428
+ err instanceof Error ? err : new Error(String(err))
4429
+ );
4430
+ });
4305
4431
  } else if (status !== "ready" && isPublishing) {
4306
4432
  console.debug("[WebcamPublisher] Reactor not ready, auto-unpublishing");
4307
- unpublish(track).then(() => {
4308
- console.debug("[WebcamPublisher] Auto-unpublish successful");
4433
+ const tasks = [unpublish(track)];
4434
+ if (audioEnabled && audioTrack) tasks.push(unpublish(audioTrack));
4435
+ Promise.allSettled(tasks).then((results) => {
4436
+ var _a;
4437
+ for (const r of results) {
4438
+ if (r.status === "rejected") {
4439
+ console.error("[WebcamPublisher] Auto-unpublish failed:", r.reason);
4440
+ (_a = onErrorRef.current) == null ? void 0 : _a.call(
4441
+ onErrorRef,
4442
+ r.reason instanceof Error ? r.reason : new Error(String(r.reason))
4443
+ );
4444
+ }
4445
+ }
4309
4446
  setIsPublishing(false);
4310
- }).catch((err) => {
4311
- console.error("[WebcamPublisher] Auto-unpublish failed:", err);
4312
4447
  });
4313
4448
  }
4314
- }, [status, stream, isPublishing, publish, unpublish, track]);
4449
+ }, [
4450
+ status,
4451
+ stream,
4452
+ isPublishing,
4453
+ publish,
4454
+ unpublish,
4455
+ track,
4456
+ audioEnabled,
4457
+ audioTrack
4458
+ ]);
4315
4459
  useEffect4(() => {
4316
4460
  const handleError = (error) => {
4317
4461
  console.debug("[WebcamPublisher] Received error event:", error);
@@ -4414,7 +4558,8 @@ function ClipPlayer({
4414
4558
  autoPlay = true,
4415
4559
  muted = true,
4416
4560
  className,
4417
- style
4561
+ style,
4562
+ onError
4418
4563
  }) {
4419
4564
  const videoRef = useRef6(null);
4420
4565
  const [phase, setPhase] = useState5({ kind: "waiting" });
@@ -4422,13 +4567,21 @@ function ClipPlayer({
4422
4567
  const getJwtRef = useRef6(getJwt);
4423
4568
  const autoPlayRef = useRef6(autoPlay);
4424
4569
  const slackMsRef = useRef6(slackMs);
4570
+ const onErrorRef = useRef6(onError);
4425
4571
  const storeRef = useRef6(store);
4426
4572
  useEffect5(() => {
4427
4573
  getJwtRef.current = getJwt;
4428
4574
  autoPlayRef.current = autoPlay;
4429
4575
  slackMsRef.current = slackMs;
4576
+ onErrorRef.current = onError;
4430
4577
  storeRef.current = store;
4431
4578
  });
4579
+ useEffect5(() => {
4580
+ var _a;
4581
+ if (phase.kind === "error") {
4582
+ (_a = onErrorRef.current) == null ? void 0 : _a.call(onErrorRef, phase.error);
4583
+ }
4584
+ }, [phase]);
4432
4585
  useEffect5(() => {
4433
4586
  const video = videoRef.current;
4434
4587
  if (!video) return;
@@ -4436,9 +4589,10 @@ function ClipPlayer({
4436
4589
  let cancelled = false;
4437
4590
  let hlsInstance = null;
4438
4591
  let manifestBlobUrl = null;
4439
- const fail = (message) => {
4592
+ const fail = (error) => {
4440
4593
  if (cancelled) return;
4441
- setPhase({ kind: "error", message });
4594
+ const message = error instanceof RecordingError ? `${error.code}: ${error.reason}` : error.message;
4595
+ setPhase({ kind: "error", message, error });
4442
4596
  };
4443
4597
  const attachPlayer = (manifestUrl) => __async(null, null, function* () {
4444
4598
  const canPlayNative = video.canPlayType("application/vnd.apple.mpegurl") !== "";
@@ -4457,13 +4611,17 @@ function ClipPlayer({
4457
4611
  HlsCtor = mod.default;
4458
4612
  } catch (e) {
4459
4613
  fail(
4460
- "HLS playback unavailable in this browser. Install `hls.js` as a peer dependency, or use Download."
4614
+ new Error(
4615
+ "HLS playback unavailable in this browser. Install `hls.js` as a peer dependency, or use Download."
4616
+ )
4461
4617
  );
4462
4618
  return;
4463
4619
  }
4464
4620
  if (cancelled) return;
4465
4621
  if (!HlsCtor.isSupported()) {
4466
- fail("This browser cannot play HLS clips. Use Download instead.");
4622
+ fail(
4623
+ new Error("This browser cannot play HLS clips. Use Download instead.")
4624
+ );
4467
4625
  return;
4468
4626
  }
4469
4627
  const hls = new HlsCtor();
@@ -4481,7 +4639,7 @@ function ClipPlayer({
4481
4639
  var _a;
4482
4640
  if (cancelled) return;
4483
4641
  if (data.fatal) {
4484
- fail(`Playback error: ${(_a = data.details) != null ? _a : "unknown"}`);
4642
+ fail(new Error(`Playback error: ${(_a = data.details) != null ? _a : "unknown"}`));
4485
4643
  return;
4486
4644
  }
4487
4645
  console.warn("[Reactor.ClipPlayer] hls.js non-fatal error", data);
@@ -4512,8 +4670,7 @@ function ClipPlayer({
4512
4670
  if (err instanceof DOMException && err.name === "AbortError") {
4513
4671
  return;
4514
4672
  }
4515
- const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4516
- fail(message);
4673
+ fail(err instanceof Error ? err : new Error(String(err)));
4517
4674
  }
4518
4675
  });
4519
4676
  setup();
@@ -4597,6 +4754,9 @@ function ClipPlayer({
4597
4754
  );
4598
4755
  }
4599
4756
 
4757
+ // src/react/ClipDownloadButton.tsx
4758
+ import { useEffect as useEffect7, useRef as useRef8 } from "react";
4759
+
4600
4760
  // src/react/useClipDownload.ts
4601
4761
  import { useCallback as useCallback2, useContext as useContext3, useEffect as useEffect6, useRef as useRef7, useState as useState6 } from "react";
4602
4762
  function useClipDownload(clip, options = {}) {
@@ -4654,18 +4814,35 @@ function ClipDownloadButton({
4654
4814
  children,
4655
4815
  className,
4656
4816
  style,
4657
- disabled
4817
+ disabled,
4818
+ onSuccess,
4819
+ onError
4658
4820
  }) {
4659
4821
  const { state, download } = useClipDownload(clip, { filename, getJwt });
4660
4822
  const downloading = state.kind === "downloading";
4661
4823
  const isDisabled = downloading || !!disabled;
4824
+ const onSuccessRef = useRef8(onSuccess);
4825
+ const onErrorRef = useRef8(onError);
4826
+ useEffect7(() => {
4827
+ onSuccessRef.current = onSuccess;
4828
+ onErrorRef.current = onError;
4829
+ });
4830
+ useEffect7(() => {
4831
+ var _a;
4832
+ if (state.kind === "error") {
4833
+ (_a = onErrorRef.current) == null ? void 0 : _a.call(onErrorRef, new Error(state.message));
4834
+ }
4835
+ }, [state]);
4662
4836
  const content = typeof children === "function" ? children(state) : children !== void 0 ? children : defaultLabel(state);
4663
4837
  return /* @__PURE__ */ jsx6(
4664
4838
  "button",
4665
4839
  {
4666
4840
  type: "button",
4667
4841
  onClick: () => {
4668
- void download();
4842
+ void download().then((blob) => {
4843
+ var _a;
4844
+ if (blob) (_a = onSuccessRef.current) == null ? void 0 : _a.call(onSuccessRef, blob);
4845
+ });
4669
4846
  },
4670
4847
  disabled: isDisabled,
4671
4848
  title: state.kind === "error" ? state.message : void 0,