@spacelr/sdk 0.10.2 → 0.10.4

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.mts CHANGED
@@ -581,6 +581,18 @@ interface StreamSubscriptionOptions {
581
581
  projectId: string;
582
582
  collectionName: string;
583
583
  sinceId?: string;
584
+ /**
585
+ * #685 — "replay from earliest retained". When true, a brand-new subscription
586
+ * (no prior cursor) replays every retained stream entry from the earliest
587
+ * still-retained id before going live, each entry gated by the same
588
+ * per-event rule check as live delivery. Lets a first-time subscriber
589
+ * bootstrap history for a recipient-scoped collection. Ignored on reconnect
590
+ * (a stored cursor resumes from the last delivered event instead) and
591
+ * overrides `sinceId` on the first subscription. Coverage is bounded by the
592
+ * stream's retention window; a truncated replay still fires `onGap` with
593
+ * `replay-truncated`.
594
+ */
595
+ fromStart?: boolean;
584
596
  where?: WhereFilter;
585
597
  /**
586
598
  * Called for each delivered event. Awaited — the cursor does NOT advance
@@ -693,6 +705,32 @@ declare class RealtimeClient {
693
705
  onConnectionStateChanged(listener: (state: ConnectionState) => void): () => void;
694
706
  private setConnectionState;
695
707
  private buildRoomKey;
708
+ /**
709
+ * Stream subscription identity (#643): `streamKey` + canonical(`where`), so
710
+ * two `subscribeEvents` on the same collection with different filters get
711
+ * distinct handshakes/readers instead of one colliding on the bare streamKey.
712
+ * Empty/absent `where` keeps the bare streamKey. Same type-preserving sorted
713
+ * encoding as `buildRoomKey` / the gateway's `streamSubscriptionKey`; it is a
714
+ * client-local Map key only (never sent — the gateway derives its own).
715
+ */
716
+ private streamSubscriptionKey;
717
+ /**
718
+ * All per-filter subscription sets registered for one collection's stream
719
+ * (#643). The socket delivers events keyed only by `streamKey` (no `where`),
720
+ * so a dispatch / gap for `streamKey` must reach every filter variant:
721
+ * the bare `streamKey` entry plus any `${streamKey}?…` filtered entries.
722
+ */
723
+ private streamSetsForStreamKey;
724
+ /**
725
+ * Whether a stream event should reach a subscriber with this `where`. The
726
+ * server already filters doc-bearing events per per-filter reader, but events
727
+ * arrive on one socket without a `where`, so we re-filter to route each to the
728
+ * right subscriber (and as defense against desync/over-delivery). An event
729
+ * with no document (tombstone delete) can't be filtered — it is delivered to
730
+ * every subscriber on the collection, as the server forwards it to every
731
+ * reader. Empty `where` matches everything.
732
+ */
733
+ private eventMatchesStreamWhere;
696
734
  private ensureConnected;
697
735
  private connect;
698
736
  private eventMatchesRoom;
@@ -1220,6 +1258,18 @@ interface SubscribeWithSnapshotOptions<T> {
1220
1258
  interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1221
1259
  /** Cursor to resume from. Undefined = fresh subscription, deliver only new events. */
1222
1260
  sinceId?: string;
1261
+ /**
1262
+ * #685 — "replay from earliest retained". When true, a fresh subscription
1263
+ * (no `sinceId` and no stored cursor) first replays every retained stream
1264
+ * entry from the earliest still-retained id, each gated by the same rule
1265
+ * check as live delivery, before going live. Lets a first-time subscriber
1266
+ * bootstrap history for a recipient-scoped collection (e.g. a chat invite /
1267
+ * MLS Welcome written before they subscribed). Ignored once a cursor exists
1268
+ * (reconnect resumes from the last delivered event). Coverage is bounded by
1269
+ * the stream's retention window; a truncated replay fires `onGap` with
1270
+ * `replay-truncated`.
1271
+ */
1272
+ fromStart?: boolean;
1223
1273
  where?: WhereFilter;
1224
1274
  /**
1225
1275
  * Optional resume-cursor store. When set, the SDK loads the previous cursor
package/dist/index.d.ts CHANGED
@@ -581,6 +581,18 @@ interface StreamSubscriptionOptions {
581
581
  projectId: string;
582
582
  collectionName: string;
583
583
  sinceId?: string;
584
+ /**
585
+ * #685 — "replay from earliest retained". When true, a brand-new subscription
586
+ * (no prior cursor) replays every retained stream entry from the earliest
587
+ * still-retained id before going live, each entry gated by the same
588
+ * per-event rule check as live delivery. Lets a first-time subscriber
589
+ * bootstrap history for a recipient-scoped collection. Ignored on reconnect
590
+ * (a stored cursor resumes from the last delivered event instead) and
591
+ * overrides `sinceId` on the first subscription. Coverage is bounded by the
592
+ * stream's retention window; a truncated replay still fires `onGap` with
593
+ * `replay-truncated`.
594
+ */
595
+ fromStart?: boolean;
584
596
  where?: WhereFilter;
585
597
  /**
586
598
  * Called for each delivered event. Awaited — the cursor does NOT advance
@@ -693,6 +705,32 @@ declare class RealtimeClient {
693
705
  onConnectionStateChanged(listener: (state: ConnectionState) => void): () => void;
694
706
  private setConnectionState;
695
707
  private buildRoomKey;
708
+ /**
709
+ * Stream subscription identity (#643): `streamKey` + canonical(`where`), so
710
+ * two `subscribeEvents` on the same collection with different filters get
711
+ * distinct handshakes/readers instead of one colliding on the bare streamKey.
712
+ * Empty/absent `where` keeps the bare streamKey. Same type-preserving sorted
713
+ * encoding as `buildRoomKey` / the gateway's `streamSubscriptionKey`; it is a
714
+ * client-local Map key only (never sent — the gateway derives its own).
715
+ */
716
+ private streamSubscriptionKey;
717
+ /**
718
+ * All per-filter subscription sets registered for one collection's stream
719
+ * (#643). The socket delivers events keyed only by `streamKey` (no `where`),
720
+ * so a dispatch / gap for `streamKey` must reach every filter variant:
721
+ * the bare `streamKey` entry plus any `${streamKey}?…` filtered entries.
722
+ */
723
+ private streamSetsForStreamKey;
724
+ /**
725
+ * Whether a stream event should reach a subscriber with this `where`. The
726
+ * server already filters doc-bearing events per per-filter reader, but events
727
+ * arrive on one socket without a `where`, so we re-filter to route each to the
728
+ * right subscriber (and as defense against desync/over-delivery). An event
729
+ * with no document (tombstone delete) can't be filtered — it is delivered to
730
+ * every subscriber on the collection, as the server forwards it to every
731
+ * reader. Empty `where` matches everything.
732
+ */
733
+ private eventMatchesStreamWhere;
696
734
  private ensureConnected;
697
735
  private connect;
698
736
  private eventMatchesRoom;
@@ -1220,6 +1258,18 @@ interface SubscribeWithSnapshotOptions<T> {
1220
1258
  interface SubscribeEventsHandlers<T = Record<string, unknown>> {
1221
1259
  /** Cursor to resume from. Undefined = fresh subscription, deliver only new events. */
1222
1260
  sinceId?: string;
1261
+ /**
1262
+ * #685 — "replay from earliest retained". When true, a fresh subscription
1263
+ * (no `sinceId` and no stored cursor) first replays every retained stream
1264
+ * entry from the earliest still-retained id, each gated by the same rule
1265
+ * check as live delivery, before going live. Lets a first-time subscriber
1266
+ * bootstrap history for a recipient-scoped collection (e.g. a chat invite /
1267
+ * MLS Welcome written before they subscribed). Ignored once a cursor exists
1268
+ * (reconnect resumes from the last delivered event). Coverage is bounded by
1269
+ * the stream's retention window; a truncated replay fires `onGap` with
1270
+ * `replay-truncated`.
1271
+ */
1272
+ fromStart?: boolean;
1223
1273
  where?: WhereFilter;
1224
1274
  /**
1225
1275
  * Optional resume-cursor store. When set, the SDK loads the previous cursor
package/dist/index.js CHANGED
@@ -883,13 +883,15 @@ var RealtimeClient = class {
883
883
  }
884
884
  await this.ensureConnected();
885
885
  const streamKey = `stream:${options.projectId}:${options.collectionName}`;
886
+ const subscriptionKey = this.streamSubscriptionKey(streamKey, options.where);
886
887
  const state = {
887
888
  options,
888
889
  lastDeliveredId: options.sinceId ?? null,
889
890
  streamKey,
891
+ subscriptionKey,
890
892
  dispatchQueue: Promise.resolve()
891
893
  };
892
- const existing = this.streamSubscriptions.get(streamKey);
894
+ const existing = this.streamSubscriptions.get(subscriptionKey);
893
895
  if (existing && existing.size > 0) {
894
896
  existing.add(state);
895
897
  const syntheticAck = {
@@ -904,13 +906,13 @@ var RealtimeClient = class {
904
906
  }
905
907
  const set = /* @__PURE__ */ new Set();
906
908
  set.add(state);
907
- this.streamSubscriptions.set(streamKey, set);
909
+ this.streamSubscriptions.set(subscriptionKey, set);
908
910
  try {
909
911
  const ack = await this.emitSubscribeEvents(state);
910
912
  if (ack.error) {
911
913
  const message = ack.message ?? ack.error;
912
914
  const err = new SpacelrError(message, ack.error);
913
- this.evictStreamKey(streamKey, err, state);
915
+ this.evictStreamKey(subscriptionKey, err, state);
914
916
  options.onError?.(err);
915
917
  throw err;
916
918
  }
@@ -920,7 +922,7 @@ var RealtimeClient = class {
920
922
  };
921
923
  } catch (err) {
922
924
  const error = err instanceof Error ? err : new Error(String(err));
923
- this.evictStreamKey(streamKey, error, state);
925
+ this.evictStreamKey(subscriptionKey, error, state);
924
926
  throw error;
925
927
  }
926
928
  }
@@ -979,6 +981,52 @@ var RealtimeClient = class {
979
981
  const filterStr = Object.keys(where).sort().map((k) => `${k}=${JSON.stringify(where[k])}`).join("&");
980
982
  return `${base}?${filterStr}`;
981
983
  }
984
+ /**
985
+ * Stream subscription identity (#643): `streamKey` + canonical(`where`), so
986
+ * two `subscribeEvents` on the same collection with different filters get
987
+ * distinct handshakes/readers instead of one colliding on the bare streamKey.
988
+ * Empty/absent `where` keeps the bare streamKey. Same type-preserving sorted
989
+ * encoding as `buildRoomKey` / the gateway's `streamSubscriptionKey`; it is a
990
+ * client-local Map key only (never sent — the gateway derives its own).
991
+ */
992
+ streamSubscriptionKey(streamKey, where) {
993
+ if (!where || Object.keys(where).length === 0) return streamKey;
994
+ const filterStr = Object.keys(where).sort().map((k) => `${k}=${JSON.stringify(where[k])}`).join("&");
995
+ return `${streamKey}?${filterStr}`;
996
+ }
997
+ /**
998
+ * All per-filter subscription sets registered for one collection's stream
999
+ * (#643). The socket delivers events keyed only by `streamKey` (no `where`),
1000
+ * so a dispatch / gap for `streamKey` must reach every filter variant:
1001
+ * the bare `streamKey` entry plus any `${streamKey}?…` filtered entries.
1002
+ */
1003
+ streamSetsForStreamKey(streamKey) {
1004
+ const sets = [];
1005
+ const prefix = `${streamKey}?`;
1006
+ for (const [key, set] of this.streamSubscriptions) {
1007
+ if (key === streamKey || key.startsWith(prefix)) sets.push(set);
1008
+ }
1009
+ return sets;
1010
+ }
1011
+ /**
1012
+ * Whether a stream event should reach a subscriber with this `where`. The
1013
+ * server already filters doc-bearing events per per-filter reader, but events
1014
+ * arrive on one socket without a `where`, so we re-filter to route each to the
1015
+ * right subscriber (and as defense against desync/over-delivery). An event
1016
+ * with no document (tombstone delete) can't be filtered — it is delivered to
1017
+ * every subscriber on the collection, as the server forwards it to every
1018
+ * reader. Empty `where` matches everything.
1019
+ */
1020
+ eventMatchesStreamWhere(event, where) {
1021
+ if (!where || Object.keys(where).length === 0) return true;
1022
+ if (!event.document) return true;
1023
+ for (const [key, value] of Object.entries(where)) {
1024
+ if (!whereValueMatches(resolveWherePath(event.document, key), value)) {
1025
+ return false;
1026
+ }
1027
+ }
1028
+ return true;
1029
+ }
982
1030
  async ensureConnected() {
983
1031
  if (this.socket?.connected) return;
984
1032
  if (this.connecting) {
@@ -1117,10 +1165,10 @@ var RealtimeClient = class {
1117
1165
  });
1118
1166
  this.socket.on("event-gap", (info) => {
1119
1167
  const streamKey = `stream:${info.projectId}:${info.collectionName}`;
1120
- const set = this.streamSubscriptions.get(streamKey);
1121
- if (!set) return;
1122
- for (const state of set) {
1123
- state.options.onGap?.(info);
1168
+ for (const set of this.streamSetsForStreamKey(streamKey)) {
1169
+ for (const state of set) {
1170
+ state.options.onGap?.(info);
1171
+ }
1124
1172
  }
1125
1173
  });
1126
1174
  this.socket.on("disconnect", () => {
@@ -1320,43 +1368,55 @@ var RealtimeClient = class {
1320
1368
  buildStreamPayload(state) {
1321
1369
  const { projectId, collectionName, where } = state.options;
1322
1370
  const payload = { projectId, collectionName };
1323
- if (state.lastDeliveredId) payload["sinceId"] = state.lastDeliveredId;
1371
+ if (state.lastDeliveredId) {
1372
+ payload["sinceId"] = state.lastDeliveredId;
1373
+ } else if (state.options.fromStart) {
1374
+ payload["fromStart"] = true;
1375
+ }
1324
1376
  if (where && Object.keys(where).length > 0) payload["where"] = where;
1325
1377
  return payload;
1326
1378
  }
1327
1379
  unsubscribeStream(state) {
1328
- const set = this.streamSubscriptions.get(state.streamKey);
1380
+ const set = this.streamSubscriptions.get(state.subscriptionKey);
1329
1381
  if (!set) return;
1330
1382
  set.delete(state);
1331
1383
  if (set.size === 0) {
1332
- this.streamSubscriptions.delete(state.streamKey);
1333
- this.socket?.emit("unsubscribe-events", {
1384
+ this.streamSubscriptions.delete(state.subscriptionKey);
1385
+ const payload = {
1334
1386
  projectId: state.options.projectId,
1335
1387
  collectionName: state.options.collectionName
1336
- });
1388
+ };
1389
+ if (state.options.where && Object.keys(state.options.where).length > 0) {
1390
+ payload["where"] = state.options.where;
1391
+ }
1392
+ this.socket?.emit("unsubscribe-events", payload);
1337
1393
  }
1338
1394
  }
1339
1395
  dispatchStreamEvent(payload) {
1340
1396
  if (!payload.eventId) return Promise.resolve();
1341
1397
  const streamKey = `stream:${payload.projectId}:${payload.collectionName}`;
1342
- const set = this.streamSubscriptions.get(streamKey);
1343
- if (!set) return Promise.resolve();
1398
+ const sets = this.streamSetsForStreamKey(streamKey);
1399
+ if (sets.length === 0) return Promise.resolve();
1344
1400
  const entryId = payload.eventId;
1345
- for (const state of set) {
1346
- state.dispatchQueue = state.dispatchQueue.then(async () => {
1347
- const liveSet = this.streamSubscriptions.get(state.streamKey);
1348
- if (!liveSet?.has(state)) return;
1349
- try {
1350
- await state.options.onEvent({ eventId: entryId, event: payload });
1351
- state.lastDeliveredId = entryId;
1352
- } catch (err) {
1353
- const error = err instanceof Error ? err : new Error(String(err));
1401
+ for (const set of sets) {
1402
+ for (const state of set) {
1403
+ if (!this.eventMatchesStreamWhere(payload, state.options.where)) continue;
1404
+ state.dispatchQueue = state.dispatchQueue.then(async () => {
1405
+ const liveSet = this.streamSubscriptions.get(state.subscriptionKey);
1406
+ if (!liveSet?.has(state)) return;
1407
+ if (state.lastDeliveredId === entryId) return;
1354
1408
  try {
1355
- state.options.onError?.(error);
1356
- } catch {
1409
+ await state.options.onEvent({ eventId: entryId, event: payload });
1410
+ state.lastDeliveredId = entryId;
1411
+ } catch (err) {
1412
+ const error = err instanceof Error ? err : new Error(String(err));
1413
+ try {
1414
+ state.options.onError?.(error);
1415
+ } catch {
1416
+ }
1357
1417
  }
1358
- }
1359
- });
1418
+ });
1419
+ }
1360
1420
  }
1361
1421
  return Promise.resolve();
1362
1422
  }
@@ -1382,15 +1442,19 @@ var RealtimeClient = class {
1382
1442
  state.options.onError?.(err);
1383
1443
  }
1384
1444
  if (PERMANENT_STREAM_ACK_ERRORS.has(ack.error)) {
1385
- this.streamSubscriptions.delete(primary.streamKey);
1445
+ this.streamSubscriptions.delete(primary.subscriptionKey);
1386
1446
  }
1387
1447
  return;
1388
1448
  }
1389
- if (!this.streamSubscriptions.has(primary.streamKey)) {
1390
- this.socket?.emit("unsubscribe-events", {
1449
+ if (!this.streamSubscriptions.has(primary.subscriptionKey)) {
1450
+ const payload = {
1391
1451
  projectId: primary.options.projectId,
1392
1452
  collectionName: primary.options.collectionName
1393
- });
1453
+ };
1454
+ if (primary.options.where && Object.keys(primary.options.where).length > 0) {
1455
+ payload["where"] = primary.options.where;
1456
+ }
1457
+ this.socket?.emit("unsubscribe-events", payload);
1394
1458
  }
1395
1459
  } catch (err) {
1396
1460
  const error = err instanceof Error ? err : new Error(String(err));
@@ -1422,8 +1486,8 @@ var RealtimeClient = class {
1422
1486
  * streamKey via the dedup path. Fires `onError` on all siblings, then
1423
1487
  * removes the entire streamKey entry from `streamSubscriptions`.
1424
1488
  */
1425
- evictStreamKey(streamKey, err, primary) {
1426
- const set = this.streamSubscriptions.get(streamKey);
1489
+ evictStreamKey(subscriptionKey, err, primary) {
1490
+ const set = this.streamSubscriptions.get(subscriptionKey);
1427
1491
  if (!set) return;
1428
1492
  for (const sibling of [...set]) {
1429
1493
  if (sibling !== primary) {
@@ -1431,7 +1495,7 @@ var RealtimeClient = class {
1431
1495
  }
1432
1496
  set.delete(sibling);
1433
1497
  }
1434
- this.streamSubscriptions.delete(streamKey);
1498
+ this.streamSubscriptions.delete(subscriptionKey);
1435
1499
  }
1436
1500
  };
1437
1501
 
@@ -2622,6 +2686,9 @@ var CollectionRef = class {
2622
2686
  projectId: this.projectId,
2623
2687
  collectionName: this.collectionName,
2624
2688
  sinceId,
2689
+ // #685 — only meaningful on a fresh subscription (no sinceId/cursor);
2690
+ // buildStreamPayload ignores it once a cursor exists.
2691
+ fromStart: handlers.fromStart,
2625
2692
  where: handlers.where,
2626
2693
  onEvent,
2627
2694
  onGap: handlers.onGap,