@reactor-team/js-sdk 3.0.1 → 3.0.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.d.cts CHANGED
@@ -155,10 +155,11 @@ declare class RecorderDisabledError extends ReactorError {
155
155
  }
156
156
 
157
157
  /**
158
- * Reference to a file uploaded via `Reactor.uploadFile()`. Pass it back as a
159
- * top-level value in `sendCommand()`'s `data` and it's extracted and sent as
160
- * a separate upload reference rather than embedded in the JSON payload —
161
- * see `extractFileRefs()`.
158
+ * Reference to a file uploaded via `Reactor.uploadFile()`. Pass it back in
159
+ * `sendCommand()`'s `data` wherever the model's schema declares a file: as a
160
+ * top-level value it's extracted and sent as a separate upload reference,
161
+ * and inside an array or object it's serialized as one — see
162
+ * `extractFileRefs()`.
162
163
  */
163
164
  declare class FileRef {
164
165
  readonly uploadId: string;
@@ -639,6 +640,43 @@ declare class Reactor implements Disposable {
639
640
  * take ownership of Rust value while it was borrowed") or corrupt it
640
641
  * outright. */
641
642
  private readonly queue;
643
+ /** In-flight calls to `withReaderAccess()` — a "reply" `.catch(() => {})`
644
+ * copy of each, never the caller's own promise, so one rejecting can't
645
+ * make `Promise.all()` in `withWriterAccess()` reject and skip waiting
646
+ * for the rest. See `withReaderAccess()`/`withWriterAccess()`. */
647
+ private readonly activeReads;
648
+ /** True for the span of a `withWriterAccess()` call — after it has waited
649
+ * out every read active when it started, before it releases the ones
650
+ * that arrived while it ran. */
651
+ private writerActive;
652
+ /** Readers parked in `withReaderAccess()`'s wait loop, woken once
653
+ * `withWriterAccess()` finishes; each re-checks `writerActive` rather
654
+ * than assuming its turn, since another writer already queued behind the
655
+ * first one may have claimed it first. */
656
+ private writerIdleWaiters;
657
+ /**
658
+ * Runs a read — sendCommand()/requestSchema()/requestClip()/
659
+ * requestRecording() — excluded from a lifecycle op (`withWriterAccess()`)
660
+ * but not from other reads: unlike `queue`, concurrent reads run
661
+ * concurrently. Queuing them the same way `queue` serializes writes would
662
+ * head-of-line block an unrelated command, or even disconnect() itself,
663
+ * behind one slow reply (the binding correlates replies independently, so
664
+ * nothing requires this to be serial).
665
+ *
666
+ * Race-free the same way the wasm binding's own `readyState` check is: the
667
+ * `writerActive` check and this call's registration in `activeReads` both
668
+ * happen before the first `await` inside *fn*, so nothing can run between
669
+ * them on a single-threaded JS event loop.
670
+ */
671
+ private withReaderAccess;
672
+ /**
673
+ * Runs a lifecycle op's client-touching body exclusively: waits out every
674
+ * read already in flight, then blocks new ones (`writerActive`) until it
675
+ * finishes. Only ever called from inside a `queue`-serialized task, so at
676
+ * most one writer runs this at a time — it doesn't serialize against
677
+ * itself, only against `activeReads`.
678
+ */
679
+ private withWriterAccess;
642
680
  constructor(options: ReactorOptions);
643
681
  /**
644
682
  * `jwt`, when given, replaces whatever `new Reactor({ jwt })` was given —
@@ -680,9 +718,11 @@ declare class Reactor implements Disposable {
680
718
  * mode) actually hands back `null` — normalized here so callers can rely
681
719
  * on the documented type instead of the binding's serialization quirk.
682
720
  *
683
- * A `FileRef` (from `uploadFile`) may be passed as a top-level value in
684
- * `data` alongside regular parameters — it is extracted and sent as a
685
- * separate upload reference rather than embedded in the JSON payload.
721
+ * A `FileRef` (from `uploadFile`) may be passed in `data` wherever the
722
+ * model's schema declares a file. As a top-level value it is extracted and
723
+ * sent as a separate upload reference rather than embedded in the JSON
724
+ * payload; inside an array or object (a parameter that takes several files,
725
+ * say) it is serialized as an upload reference in place.
686
726
  *
687
727
  * Unlike every other method here, this never rejects — a failure (the
688
728
  * session isn't `"ready"`, the send itself fails, …) is reported through
@@ -806,8 +846,9 @@ declare class Reactor implements Disposable {
806
846
  downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
807
847
  /**
808
848
  * Uploads a file to the session's object store, resolving with a
809
- * `FileRef` to pass as a top-level value in a `sendCommand()`'s `data`
810
- * (see `extractFileRefs`). The binding itself takes `(file, name?)`
849
+ * `FileRef` to pass in a `sendCommand()`'s `data`, at the top level or
850
+ * inside an array or object (see `extractFileRefs`). The binding itself
851
+ * takes `(file, name?)`
811
852
  * positionally and already applies the right defaulting — a bare
812
853
  * `Blob`'s name falls back to `"upload"`, and an empty/missing mime type
813
854
  * to `"application/octet-stream"` — so there's nothing to wrap here.
package/dist/index.d.ts CHANGED
@@ -155,10 +155,11 @@ declare class RecorderDisabledError extends ReactorError {
155
155
  }
156
156
 
157
157
  /**
158
- * Reference to a file uploaded via `Reactor.uploadFile()`. Pass it back as a
159
- * top-level value in `sendCommand()`'s `data` and it's extracted and sent as
160
- * a separate upload reference rather than embedded in the JSON payload —
161
- * see `extractFileRefs()`.
158
+ * Reference to a file uploaded via `Reactor.uploadFile()`. Pass it back in
159
+ * `sendCommand()`'s `data` wherever the model's schema declares a file: as a
160
+ * top-level value it's extracted and sent as a separate upload reference,
161
+ * and inside an array or object it's serialized as one — see
162
+ * `extractFileRefs()`.
162
163
  */
163
164
  declare class FileRef {
164
165
  readonly uploadId: string;
@@ -639,6 +640,43 @@ declare class Reactor implements Disposable {
639
640
  * take ownership of Rust value while it was borrowed") or corrupt it
640
641
  * outright. */
641
642
  private readonly queue;
643
+ /** In-flight calls to `withReaderAccess()` — a "reply" `.catch(() => {})`
644
+ * copy of each, never the caller's own promise, so one rejecting can't
645
+ * make `Promise.all()` in `withWriterAccess()` reject and skip waiting
646
+ * for the rest. See `withReaderAccess()`/`withWriterAccess()`. */
647
+ private readonly activeReads;
648
+ /** True for the span of a `withWriterAccess()` call — after it has waited
649
+ * out every read active when it started, before it releases the ones
650
+ * that arrived while it ran. */
651
+ private writerActive;
652
+ /** Readers parked in `withReaderAccess()`'s wait loop, woken once
653
+ * `withWriterAccess()` finishes; each re-checks `writerActive` rather
654
+ * than assuming its turn, since another writer already queued behind the
655
+ * first one may have claimed it first. */
656
+ private writerIdleWaiters;
657
+ /**
658
+ * Runs a read — sendCommand()/requestSchema()/requestClip()/
659
+ * requestRecording() — excluded from a lifecycle op (`withWriterAccess()`)
660
+ * but not from other reads: unlike `queue`, concurrent reads run
661
+ * concurrently. Queuing them the same way `queue` serializes writes would
662
+ * head-of-line block an unrelated command, or even disconnect() itself,
663
+ * behind one slow reply (the binding correlates replies independently, so
664
+ * nothing requires this to be serial).
665
+ *
666
+ * Race-free the same way the wasm binding's own `readyState` check is: the
667
+ * `writerActive` check and this call's registration in `activeReads` both
668
+ * happen before the first `await` inside *fn*, so nothing can run between
669
+ * them on a single-threaded JS event loop.
670
+ */
671
+ private withReaderAccess;
672
+ /**
673
+ * Runs a lifecycle op's client-touching body exclusively: waits out every
674
+ * read already in flight, then blocks new ones (`writerActive`) until it
675
+ * finishes. Only ever called from inside a `queue`-serialized task, so at
676
+ * most one writer runs this at a time — it doesn't serialize against
677
+ * itself, only against `activeReads`.
678
+ */
679
+ private withWriterAccess;
642
680
  constructor(options: ReactorOptions);
643
681
  /**
644
682
  * `jwt`, when given, replaces whatever `new Reactor({ jwt })` was given —
@@ -680,9 +718,11 @@ declare class Reactor implements Disposable {
680
718
  * mode) actually hands back `null` — normalized here so callers can rely
681
719
  * on the documented type instead of the binding's serialization quirk.
682
720
  *
683
- * A `FileRef` (from `uploadFile`) may be passed as a top-level value in
684
- * `data` alongside regular parameters — it is extracted and sent as a
685
- * separate upload reference rather than embedded in the JSON payload.
721
+ * A `FileRef` (from `uploadFile`) may be passed in `data` wherever the
722
+ * model's schema declares a file. As a top-level value it is extracted and
723
+ * sent as a separate upload reference rather than embedded in the JSON
724
+ * payload; inside an array or object (a parameter that takes several files,
725
+ * say) it is serialized as an upload reference in place.
686
726
  *
687
727
  * Unlike every other method here, this never rejects — a failure (the
688
728
  * session isn't `"ready"`, the send itself fails, …) is reported through
@@ -806,8 +846,9 @@ declare class Reactor implements Disposable {
806
846
  downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
807
847
  /**
808
848
  * Uploads a file to the session's object store, resolving with a
809
- * `FileRef` to pass as a top-level value in a `sendCommand()`'s `data`
810
- * (see `extractFileRefs`). The binding itself takes `(file, name?)`
849
+ * `FileRef` to pass in a `sendCommand()`'s `data`, at the top level or
850
+ * inside an array or object (see `extractFileRefs`). The binding itself
851
+ * takes `(file, name?)`
811
852
  * positionally and already applies the right defaulting — a bare
812
853
  * `Blob`'s name falls back to `"upload"`, and an empty/missing mime type
813
854
  * to `"application/octet-stream"` — so there's nothing to wrap here.
package/dist/index.js CHANGED
@@ -244,16 +244,53 @@ function extractFileRefs(data) {
244
244
  let uploads;
245
245
  let scalars;
246
246
  for (const [key, value] of Object.entries(data)) {
247
- if (!isFileRef(value)) {
247
+ if (isFileRef(value)) {
248
+ uploads ??= {};
249
+ scalars ??= { ...data };
250
+ uploads[key] = toWireFileRef(value);
251
+ delete scalars[key];
248
252
  continue;
249
253
  }
250
- uploads ??= {};
251
- scalars ??= { ...data };
252
- uploads[key] = toWireFileRef(value);
253
- delete scalars[key];
254
+ const rewritten = rewriteNestedFileRefs(value);
255
+ if (rewritten !== value) {
256
+ scalars ??= { ...data };
257
+ scalars[key] = rewritten;
258
+ }
254
259
  }
255
260
  return { data: scalars ?? data, uploads };
256
261
  }
262
+ function rewriteNestedFileRefs(value) {
263
+ if (isFileRef(value)) {
264
+ return toWireFileRef(value);
265
+ }
266
+ if (Array.isArray(value)) {
267
+ const elements = value;
268
+ let copy;
269
+ elements.forEach((element, index) => {
270
+ const rewritten = rewriteNestedFileRefs(element);
271
+ if (rewritten !== element) {
272
+ copy ??= [...elements];
273
+ copy[index] = rewritten;
274
+ }
275
+ });
276
+ return copy ?? elements;
277
+ }
278
+ if (isSerializedAsObject(value)) {
279
+ let copy;
280
+ for (const [key, element] of Object.entries(value)) {
281
+ const rewritten = rewriteNestedFileRefs(element);
282
+ if (rewritten !== element) {
283
+ copy ??= { ...value };
284
+ copy[key] = rewritten;
285
+ }
286
+ }
287
+ return copy ?? value;
288
+ }
289
+ return value;
290
+ }
291
+ function isSerializedAsObject(value) {
292
+ return typeof value === "object" && value !== null && !ArrayBuffer.isView(value);
293
+ }
257
294
 
258
295
  // src/internal/recording.ts
259
296
  function toPublicClip(clip) {
@@ -375,7 +412,7 @@ async function importWasmModule() {
375
412
  // package.json
376
413
  var package_default = {
377
414
  name: "@reactor-team/js-sdk",
378
- version: "3.0.1",
415
+ version: "3.0.2",
379
416
  description: "Connect your JavaScript/TypeScript app to a live Reactor model in the browser.",
380
417
  license: "Apache-2.0",
381
418
  repository: {
@@ -868,6 +905,70 @@ var Reactor = class {
868
905
  * take ownership of Rust value while it was borrowed") or corrupt it
869
906
  * outright. */
870
907
  queue = new AwaitQueue();
908
+ /** In-flight calls to `withReaderAccess()` — a "reply" `.catch(() => {})`
909
+ * copy of each, never the caller's own promise, so one rejecting can't
910
+ * make `Promise.all()` in `withWriterAccess()` reject and skip waiting
911
+ * for the rest. See `withReaderAccess()`/`withWriterAccess()`. */
912
+ activeReads = /* @__PURE__ */ new Set();
913
+ /** True for the span of a `withWriterAccess()` call — after it has waited
914
+ * out every read active when it started, before it releases the ones
915
+ * that arrived while it ran. */
916
+ writerActive = false;
917
+ /** Readers parked in `withReaderAccess()`'s wait loop, woken once
918
+ * `withWriterAccess()` finishes; each re-checks `writerActive` rather
919
+ * than assuming its turn, since another writer already queued behind the
920
+ * first one may have claimed it first. */
921
+ writerIdleWaiters = [];
922
+ /**
923
+ * Runs a read — sendCommand()/requestSchema()/requestClip()/
924
+ * requestRecording() — excluded from a lifecycle op (`withWriterAccess()`)
925
+ * but not from other reads: unlike `queue`, concurrent reads run
926
+ * concurrently. Queuing them the same way `queue` serializes writes would
927
+ * head-of-line block an unrelated command, or even disconnect() itself,
928
+ * behind one slow reply (the binding correlates replies independently, so
929
+ * nothing requires this to be serial).
930
+ *
931
+ * Race-free the same way the wasm binding's own `readyState` check is: the
932
+ * `writerActive` check and this call's registration in `activeReads` both
933
+ * happen before the first `await` inside *fn*, so nothing can run between
934
+ * them on a single-threaded JS event loop.
935
+ */
936
+ async withReaderAccess(fn) {
937
+ while (this.writerActive) {
938
+ await new Promise((resolve) => this.writerIdleWaiters.push(resolve));
939
+ }
940
+ const result = fn();
941
+ const tracked = result.catch(() => void 0);
942
+ this.activeReads.add(tracked);
943
+ try {
944
+ return await result;
945
+ } finally {
946
+ this.activeReads.delete(tracked);
947
+ }
948
+ }
949
+ /**
950
+ * Runs a lifecycle op's client-touching body exclusively: waits out every
951
+ * read already in flight, then blocks new ones (`writerActive`) until it
952
+ * finishes. Only ever called from inside a `queue`-serialized task, so at
953
+ * most one writer runs this at a time — it doesn't serialize against
954
+ * itself, only against `activeReads`.
955
+ */
956
+ async withWriterAccess(fn) {
957
+ this.writerActive = true;
958
+ if (this.activeReads.size > 0) {
959
+ await Promise.all(this.activeReads);
960
+ }
961
+ try {
962
+ return await fn();
963
+ } finally {
964
+ this.writerActive = false;
965
+ const waiters = this.writerIdleWaiters;
966
+ this.writerIdleWaiters = [];
967
+ for (const wake of waiters) {
968
+ wake();
969
+ }
970
+ }
971
+ }
871
972
  constructor(options) {
872
973
  const { jwt, ...clientOptions } = options;
873
974
  this.clientOptions = { sdkVersion: package_default.version, ...clientOptions };
@@ -891,10 +992,13 @@ var Reactor = class {
891
992
  this.jwt = jwt;
892
993
  this.client?.setJwt(jwt);
893
994
  }
894
- await this.queue.push(async () => {
895
- const client = await this.getOrCreateClient();
896
- await client.connect(options);
897
- }, "connect");
995
+ await this.queue.push(
996
+ () => this.withWriterAccess(async () => {
997
+ const client = await this.getOrCreateClient();
998
+ await client.connect(options);
999
+ }),
1000
+ "connect"
1001
+ );
898
1002
  } catch (cause) {
899
1003
  throw this.captureError(cause);
900
1004
  }
@@ -917,15 +1021,18 @@ var Reactor = class {
917
1021
  async disconnect(recoverable = false) {
918
1022
  this.assertNotDisposed();
919
1023
  try {
920
- await this.queue.push(async () => {
921
- if (this.client) {
922
- await this.client.disconnect();
923
- }
924
- this.resetConnectionState();
925
- if (!recoverable) {
926
- this.freeClient();
927
- }
928
- }, "disconnect");
1024
+ await this.queue.push(
1025
+ () => this.withWriterAccess(async () => {
1026
+ if (this.client) {
1027
+ await this.client.disconnect();
1028
+ }
1029
+ this.resetConnectionState();
1030
+ if (!recoverable) {
1031
+ this.freeClient();
1032
+ }
1033
+ }),
1034
+ "disconnect"
1035
+ );
929
1036
  } catch (cause) {
930
1037
  throw this.captureError(cause);
931
1038
  }
@@ -939,10 +1046,13 @@ var Reactor = class {
939
1046
  async reconnect(options) {
940
1047
  this.assertNotDisposed();
941
1048
  try {
942
- await this.queue.push(async () => {
943
- const client = await this.getOrCreateClient();
944
- await client.reconnect(options);
945
- }, "reconnect");
1049
+ await this.queue.push(
1050
+ () => this.withWriterAccess(async () => {
1051
+ const client = await this.getOrCreateClient();
1052
+ await client.reconnect(options);
1053
+ }),
1054
+ "reconnect"
1055
+ );
946
1056
  } catch (cause) {
947
1057
  throw this.captureError(cause);
948
1058
  }
@@ -957,9 +1067,11 @@ var Reactor = class {
957
1067
  * mode) actually hands back `null` — normalized here so callers can rely
958
1068
  * on the documented type instead of the binding's serialization quirk.
959
1069
  *
960
- * A `FileRef` (from `uploadFile`) may be passed as a top-level value in
961
- * `data` alongside regular parameters — it is extracted and sent as a
962
- * separate upload reference rather than embedded in the JSON payload.
1070
+ * A `FileRef` (from `uploadFile`) may be passed in `data` wherever the
1071
+ * model's schema declares a file. As a top-level value it is extracted and
1072
+ * sent as a separate upload reference rather than embedded in the JSON
1073
+ * payload; inside an array or object (a parameter that takes several files,
1074
+ * say) it is serialized as an upload reference in place.
963
1075
  *
964
1076
  * Unlike every other method here, this never rejects — a failure (the
965
1077
  * session isn't `"ready"`, the send itself fails, …) is reported through
@@ -981,9 +1093,11 @@ var Reactor = class {
981
1093
  }
982
1094
  try {
983
1095
  this.assertNotDisposed();
984
- const client = await this.getOrCreateClient();
985
1096
  const extracted = extractFileRefs(data);
986
- const reply = await client.sendCommand(command, extracted.data, extracted.uploads);
1097
+ const reply = await this.withReaderAccess(async () => {
1098
+ const client = await this.getOrCreateClient();
1099
+ return client.sendCommand(command, extracted.data, extracted.uploads);
1100
+ });
987
1101
  return reply ?? void 0;
988
1102
  } catch (cause) {
989
1103
  this.emitError(cause);
@@ -1010,8 +1124,10 @@ var Reactor = class {
1010
1124
  switch (command) {
1011
1125
  case "requestSchema":
1012
1126
  try {
1013
- const client = await this.getOrCreateClient();
1014
- await this.refreshSchema(client);
1127
+ await this.withReaderAccess(async () => {
1128
+ const client = await this.getOrCreateClient();
1129
+ await this.refreshSchema(client);
1130
+ });
1015
1131
  } catch (cause) {
1016
1132
  this.emitError(cause);
1017
1133
  }
@@ -1033,8 +1149,10 @@ var Reactor = class {
1033
1149
  async requestSchema() {
1034
1150
  this.assertNotDisposed();
1035
1151
  try {
1036
- const client = await this.getOrCreateClient();
1037
- return this.normalizeSchema(await client.requestSchema());
1152
+ return await this.withReaderAccess(async () => {
1153
+ const client = await this.getOrCreateClient();
1154
+ return this.normalizeSchema(await client.requestSchema());
1155
+ });
1038
1156
  } catch (cause) {
1039
1157
  throw this.captureError(cause);
1040
1158
  }
@@ -1174,8 +1292,10 @@ var Reactor = class {
1174
1292
  async requestClip(durationSeconds) {
1175
1293
  this.assertNotDisposed();
1176
1294
  try {
1177
- const client = await this.getOrCreateClient();
1178
- return toPublicClip(await client.requestClip(durationSeconds));
1295
+ return await this.withReaderAccess(async () => {
1296
+ const client = await this.getOrCreateClient();
1297
+ return toPublicClip(await client.requestClip(durationSeconds));
1298
+ });
1179
1299
  } catch (cause) {
1180
1300
  throw this.captureError(cause);
1181
1301
  }
@@ -1184,8 +1304,10 @@ var Reactor = class {
1184
1304
  async requestRecording() {
1185
1305
  this.assertNotDisposed();
1186
1306
  try {
1187
- const client = await this.getOrCreateClient();
1188
- return toPublicClip(await client.requestRecording());
1307
+ return await this.withReaderAccess(async () => {
1308
+ const client = await this.getOrCreateClient();
1309
+ return toPublicClip(await client.requestRecording());
1310
+ });
1189
1311
  } catch (cause) {
1190
1312
  throw this.captureError(cause);
1191
1313
  }
@@ -1197,8 +1319,9 @@ var Reactor = class {
1197
1319
  // ── Uploads ─────────────────────────────────────────────────────────────
1198
1320
  /**
1199
1321
  * Uploads a file to the session's object store, resolving with a
1200
- * `FileRef` to pass as a top-level value in a `sendCommand()`'s `data`
1201
- * (see `extractFileRefs`). The binding itself takes `(file, name?)`
1322
+ * `FileRef` to pass in a `sendCommand()`'s `data`, at the top level or
1323
+ * inside an array or object (see `extractFileRefs`). The binding itself
1324
+ * takes `(file, name?)`
1202
1325
  * positionally and already applies the right defaulting — a bare
1203
1326
  * `Blob`'s name falls back to `"upload"`, and an empty/missing mime type
1204
1327
  * to `"application/octet-stream"` — so there's nothing to wrap here.
@@ -1272,7 +1395,7 @@ var Reactor = class {
1272
1395
  this.resetConnectionState();
1273
1396
  this.emitter.clear();
1274
1397
  if (client) {
1275
- void this.queue.push(() => client.free(), "dispose").catch(() => {
1398
+ void this.queue.push(() => this.withWriterAccess(() => Promise.resolve(client.free())), "dispose").catch(() => {
1276
1399
  });
1277
1400
  }
1278
1401
  }