@spacelr/sdk 0.11.0 → 0.12.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.mjs CHANGED
@@ -1007,7 +1007,8 @@ var RealtimeClient = class {
1007
1007
  // gateways that haven't been updated yet are treated as pubsub-mode
1008
1008
  // so the SDK helper's fail-fast still fires correctly.
1009
1009
  realtimeMode: ack.realtimeMode ?? "pubsub",
1010
- latestStreamId: ack.latestStreamId ?? null
1010
+ latestStreamId: ack.latestStreamId ?? null,
1011
+ resumeCursor: ack.resumeCursor ?? null
1011
1012
  };
1012
1013
  }
1013
1014
  /**
@@ -1041,7 +1042,23 @@ var RealtimeClient = class {
1041
1042
  }
1042
1043
  await this.ensureConnected();
1043
1044
  const streamKey = `stream:${options.projectId}:${options.collectionName}`;
1044
- const subscriptionKey = this.streamSubscriptionKey(streamKey, options.where);
1045
+ const subscriptionKey = this.streamSubscriptionKey(
1046
+ streamKey,
1047
+ options.where,
1048
+ options.consumerId
1049
+ );
1050
+ if (options.consumerId) {
1051
+ const base = this.streamSubscriptionKey(streamKey, options.where);
1052
+ const mine = `${base}#${options.consumerId}`;
1053
+ for (const key of this.streamSubscriptions.keys()) {
1054
+ if (key.startsWith(`${base}#`) && key !== mine) {
1055
+ throw new SpacelrError(
1056
+ `A durable subscription for ${base} already exists on this client under a different consumerId. Use one consumerId per (collection, filter) per client.`,
1057
+ "DURABLE_CONSUMER_CONFLICT"
1058
+ );
1059
+ }
1060
+ }
1061
+ }
1045
1062
  const state = {
1046
1063
  options,
1047
1064
  lastDeliveredId: options.sinceId ?? null,
@@ -1074,6 +1091,7 @@ var RealtimeClient = class {
1074
1091
  options.onError?.(err);
1075
1092
  throw err;
1076
1093
  }
1094
+ this.captureDurableHandshake(state, ack);
1077
1095
  return {
1078
1096
  unsubscribe: () => this.unsubscribeStream(state),
1079
1097
  ack
@@ -1147,10 +1165,14 @@ var RealtimeClient = class {
1147
1165
  * encoding as `buildRoomKey` / the gateway's `streamSubscriptionKey`; it is a
1148
1166
  * client-local Map key only (never sent — the gateway derives its own).
1149
1167
  */
1150
- streamSubscriptionKey(streamKey, where) {
1151
- if (!where || Object.keys(where).length === 0) return streamKey;
1152
- const filterStr = Object.keys(where).sort().map((k) => `${k}=${JSON.stringify(where[k])}`).join("&");
1153
- return `${streamKey}?${filterStr}`;
1168
+ streamSubscriptionKey(streamKey, where, consumerId) {
1169
+ let key = streamKey;
1170
+ if (where && Object.keys(where).length > 0) {
1171
+ const filterStr = Object.keys(where).sort().map((k) => `${k}=${JSON.stringify(where[k])}`).join("&");
1172
+ key = `${streamKey}?${filterStr}`;
1173
+ }
1174
+ if (consumerId) key = `${key}#${consumerId}`;
1175
+ return key;
1154
1176
  }
1155
1177
  /**
1156
1178
  * All per-filter subscription sets registered for one collection's stream
@@ -1160,9 +1182,12 @@ var RealtimeClient = class {
1160
1182
  */
1161
1183
  streamSetsForStreamKey(streamKey) {
1162
1184
  const sets = [];
1163
- const prefix = `${streamKey}?`;
1185
+ const wherePrefix = `${streamKey}?`;
1186
+ const consumerPrefix = `${streamKey}#`;
1164
1187
  for (const [key, set] of this.streamSubscriptions) {
1165
- if (key === streamKey || key.startsWith(prefix)) sets.push(set);
1188
+ if (key === streamKey || key.startsWith(wherePrefix) || key.startsWith(consumerPrefix)) {
1189
+ sets.push(set);
1190
+ }
1166
1191
  }
1167
1192
  return sets;
1168
1193
  }
@@ -1330,6 +1355,21 @@ var RealtimeClient = class {
1330
1355
  }
1331
1356
  }
1332
1357
  });
1358
+ this.socket.on("subscription-reset", (info) => {
1359
+ if (!info || typeof info.projectId !== "string") return;
1360
+ for (const set of this.streamSubscriptions.values()) {
1361
+ for (const state of set) {
1362
+ if (state.options.consumerId && state.options.projectId === info.projectId) {
1363
+ state.options.onGap?.({
1364
+ projectId: info.projectId,
1365
+ collectionName: state.options.collectionName,
1366
+ retentionWindow: "unknown",
1367
+ reason: "evicted"
1368
+ });
1369
+ }
1370
+ }
1371
+ }
1372
+ });
1333
1373
  this.socket.on("disconnect", () => {
1334
1374
  if (this.disposed) return;
1335
1375
  if (initialConnect) return;
@@ -1525,9 +1565,66 @@ var RealtimeClient = class {
1525
1565
  );
1526
1566
  });
1527
1567
  }
1568
+ /** #768 — capture the durable fencing tokens from a successful handshake so
1569
+ * `ack-events` echoes the (generation, session) the server expects. */
1570
+ captureDurableHandshake(state, ack) {
1571
+ if (ack.generation !== void 0) state.generation = ack.generation;
1572
+ if (ack.session !== void 0) state.session = ack.session;
1573
+ }
1574
+ /**
1575
+ * #768 — schedule a coalesced durable ack. Only durable subscriptions (a
1576
+ * consumerId with a captured generation+session) ack. At most one ack per
1577
+ * microtask drain, carrying the highest delivered seq — cumulative on the
1578
+ * server, so a burst of N events costs one ack, not N.
1579
+ */
1580
+ scheduleDurableAck(state) {
1581
+ if (!state.options.consumerId || state.generation === void 0 || state.session === void 0 || state.ackFlushScheduled) {
1582
+ return;
1583
+ }
1584
+ state.ackFlushScheduled = true;
1585
+ queueMicrotask(() => {
1586
+ state.ackFlushScheduled = false;
1587
+ const seq = state.lastDeliveredId;
1588
+ if (seq) this.emitDurableAck(state, seq);
1589
+ });
1590
+ }
1591
+ /** #768 — emit `ack-events` for `seq`; a fenced/evicted response routes into
1592
+ * the gap-recovery path so the caller re-snapshots (§12.5/§12.1). */
1593
+ emitDurableAck(state, seq) {
1594
+ const socket = this.socket;
1595
+ if (!socket) return;
1596
+ const { projectId, collectionName, where, consumerId } = state.options;
1597
+ if (consumerId === void 0 || state.generation === void 0 || state.session === void 0) {
1598
+ return;
1599
+ }
1600
+ const payload = {
1601
+ projectId,
1602
+ collectionName,
1603
+ consumerId,
1604
+ generation: state.generation,
1605
+ session: state.session,
1606
+ seq
1607
+ };
1608
+ if (where && Object.keys(where).length > 0) payload["where"] = where;
1609
+ socket.emit(
1610
+ "ack-events",
1611
+ payload,
1612
+ (res) => {
1613
+ if (!res?.gap) return;
1614
+ if (!this.streamSubscriptions.get(state.subscriptionKey)?.has(state)) return;
1615
+ state.options.onGap?.({
1616
+ projectId,
1617
+ collectionName,
1618
+ retentionWindow: "unknown",
1619
+ reason: res.gap
1620
+ });
1621
+ }
1622
+ );
1623
+ }
1528
1624
  buildStreamPayload(state) {
1529
1625
  const { projectId, collectionName, where } = state.options;
1530
1626
  const payload = { projectId, collectionName };
1627
+ if (state.options.consumerId) payload["consumerId"] = state.options.consumerId;
1531
1628
  if (state.lastDeliveredId) {
1532
1629
  payload["sinceId"] = state.lastDeliveredId;
1533
1630
  } else if (state.options.fromStart) {
@@ -1568,6 +1665,7 @@ var RealtimeClient = class {
1568
1665
  try {
1569
1666
  await state.options.onEvent({ eventId: entryId, event: payload });
1570
1667
  state.lastDeliveredId = entryId;
1668
+ this.scheduleDurableAck(state);
1571
1669
  } catch (err) {
1572
1670
  const error = err instanceof Error ? err : new Error(String(err));
1573
1671
  try {
@@ -1606,6 +1704,11 @@ var RealtimeClient = class {
1606
1704
  }
1607
1705
  return;
1608
1706
  }
1707
+ for (const s of set) {
1708
+ s.generation = void 0;
1709
+ s.session = void 0;
1710
+ }
1711
+ this.captureDurableHandshake(primary, ack);
1609
1712
  if (!this.streamSubscriptions.has(primary.subscriptionKey)) {
1610
1713
  const payload = {
1611
1714
  projectId: primary.options.projectId,
@@ -1699,6 +1802,23 @@ function localStorageCursorStorage(prefix = "spacelr:cursor:") {
1699
1802
  };
1700
1803
  }
1701
1804
 
1805
+ // libs/sdk/src/core/consumer-id.ts
1806
+ var CONSUMER_ID_STORAGE_KEY = "spacelr:consumer-id";
1807
+ function generateConsumerId() {
1808
+ const c = globalThis.crypto;
1809
+ if (c?.randomUUID) return c.randomUUID();
1810
+ return (Math.random().toString(36).slice(2) + "-" + Date.now().toString(36)).slice(0, 128);
1811
+ }
1812
+ async function resolveConsumerId(explicit, storage, key = CONSUMER_ID_STORAGE_KEY) {
1813
+ if (explicit) return explicit;
1814
+ if (!storage) return generateConsumerId();
1815
+ const existing = await Promise.resolve(storage.load(key));
1816
+ if (existing) return existing;
1817
+ const generated = generateConsumerId();
1818
+ await Promise.resolve(storage.save(key, generated));
1819
+ return generated;
1820
+ }
1821
+
1702
1822
  // libs/sdk/src/modules/auth.module.ts
1703
1823
  function mapProfile(u) {
1704
1824
  const name = u.name ?? ([u.firstName, u.lastName].filter(Boolean).join(" ") || void 0) ?? u.displayName;
@@ -2717,6 +2837,13 @@ function compileMatcher(where, plan) {
2717
2837
  }
2718
2838
 
2719
2839
  // libs/sdk/src/modules/database.module.ts
2840
+ var RESNAPSHOT_GAP_REASONS = /* @__PURE__ */ new Set([
2841
+ "outside-retention-window",
2842
+ "replay-truncated",
2843
+ "evicted",
2844
+ "log-reset",
2845
+ "auth-unavailable"
2846
+ ]);
2720
2847
  var DEFAULT_CATCHUP_MAX_PAGES = 1e3;
2721
2848
  var DEFAULT_CATCHUP_MAX_DOCS = 5e4;
2722
2849
  var DEFAULT_CATCHUP_PAGE_SIZE = 100;
@@ -3110,6 +3237,7 @@ var CollectionRef = class {
3110
3237
  projectId: this.projectId,
3111
3238
  collectionName: this.collectionName,
3112
3239
  sinceId,
3240
+ consumerId: handlers.consumerId,
3113
3241
  // #685 — only meaningful on a fresh subscription (no sinceId/cursor);
3114
3242
  // buildStreamPayload ignores it once a cursor exists.
3115
3243
  fromStart: handlers.fromStart,
@@ -3226,6 +3354,11 @@ var CollectionRef = class {
3226
3354
  if (!this.realtime) {
3227
3355
  throw new Error("Realtime not available: no RealtimeClient configured");
3228
3356
  }
3357
+ if (opts.consumerId !== void 0 && !/^[A-Za-z0-9._-]{1,128}$/.test(opts.consumerId)) {
3358
+ throw new Error(
3359
+ `Invalid consumerId ${JSON.stringify(opts.consumerId)}: must match [A-Za-z0-9._-]{1,128}. Use resolveConsumerId() to generate one, or omit it for a stateless subscription.`
3360
+ );
3361
+ }
3229
3362
  let isActive = true;
3230
3363
  let currentUnsubscribe = null;
3231
3364
  let snapshotAbort = new AbortController();
@@ -3290,6 +3423,7 @@ var CollectionRef = class {
3290
3423
  projectId: this.projectId,
3291
3424
  collectionName: this.collectionName,
3292
3425
  sinceId: void 0,
3426
+ consumerId: opts.consumerId,
3293
3427
  where: streamWhere,
3294
3428
  onEvent: async ({ event }) => {
3295
3429
  if (!isActive) return;
@@ -3420,8 +3554,7 @@ var CollectionRef = class {
3420
3554
  };
3421
3555
  const handleGap = (info) => {
3422
3556
  if (!isActive) return;
3423
- if (info.reason !== "outside-retention-window" && info.reason !== "replay-truncated")
3424
- return;
3557
+ if (!RESNAPSHOT_GAP_REASONS.has(info.reason)) return;
3425
3558
  dispatchRecovery();
3426
3559
  };
3427
3560
  let subscribeAckResolved = false;
@@ -3434,6 +3567,7 @@ var CollectionRef = class {
3434
3567
  projectId: this.projectId,
3435
3568
  collectionName: this.collectionName,
3436
3569
  sinceId: void 0,
3570
+ consumerId: opts.consumerId,
3437
3571
  where: streamWhere,
3438
3572
  onEvent: async ({ event }) => {
3439
3573
  if (!isActive) return;
@@ -3482,11 +3616,10 @@ var CollectionRef = class {
3482
3616
  );
3483
3617
  }
3484
3618
  currentUnsubscribe = initial.unsubscribe;
3485
- let snapshotDocs;
3486
- try {
3487
- const snapshotResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
3488
- snapshotDocs = snapshotResult.documents;
3489
- recomputeTypedMatcherPlan(snapshotResult.coercionPlan);
3619
+ const isDurableResume = initial.resumeCursor !== null;
3620
+ let snapshotDocs = [];
3621
+ if (isDurableResume) {
3622
+ recomputeTypedMatcherPlan(void 0);
3490
3623
  initialPlanReady = true;
3491
3624
  for (let i = pendingInitialEvents.length - 1; i >= 0; i--) {
3492
3625
  if (!passesLiveGate(pendingInitialEvents[i])) {
@@ -3494,29 +3627,44 @@ var CollectionRef = class {
3494
3627
  }
3495
3628
  }
3496
3629
  warnIfNoGateAvailable();
3497
- } catch (err) {
3498
- currentUnsubscribe?.();
3499
- isActive = false;
3500
- const isAbort = err instanceof DOMException && err.name === "AbortError";
3501
- if (isAbort) throw err;
3502
- const error = err instanceof Error ? err : new Error(String(err));
3503
- if (opts.onSnapshotError) opts.onSnapshotError(error);
3504
- else opts.onError?.(error);
3505
- throw error;
3630
+ } else {
3631
+ try {
3632
+ const snapshotResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
3633
+ snapshotDocs = snapshotResult.documents;
3634
+ recomputeTypedMatcherPlan(snapshotResult.coercionPlan);
3635
+ initialPlanReady = true;
3636
+ for (let i = pendingInitialEvents.length - 1; i >= 0; i--) {
3637
+ if (!passesLiveGate(pendingInitialEvents[i])) {
3638
+ pendingInitialEvents.splice(i, 1);
3639
+ }
3640
+ }
3641
+ warnIfNoGateAvailable();
3642
+ } catch (err) {
3643
+ currentUnsubscribe?.();
3644
+ isActive = false;
3645
+ const isAbort = err instanceof DOMException && err.name === "AbortError";
3646
+ if (isAbort) throw err;
3647
+ const error = err instanceof Error ? err : new Error(String(err));
3648
+ if (opts.onSnapshotError) opts.onSnapshotError(error);
3649
+ else opts.onError?.(error);
3650
+ throw error;
3651
+ }
3506
3652
  }
3507
3653
  if (!isActive) {
3508
3654
  currentUnsubscribe?.();
3509
3655
  return () => void 0;
3510
3656
  }
3511
- try {
3512
- await opts.onSnapshot(snapshotDocs, initial.latestStreamId);
3513
- } catch (err) {
3514
- currentUnsubscribe?.();
3515
- currentUnsubscribe = null;
3516
- isActive = false;
3517
- const error = err instanceof Error ? err : new Error(String(err));
3518
- opts.onError?.(error);
3519
- throw error;
3657
+ if (!isDurableResume) {
3658
+ try {
3659
+ await opts.onSnapshot(snapshotDocs, initial.latestStreamId);
3660
+ } catch (err) {
3661
+ currentUnsubscribe?.();
3662
+ currentUnsubscribe = null;
3663
+ isActive = false;
3664
+ const error = err instanceof Error ? err : new Error(String(err));
3665
+ opts.onError?.(error);
3666
+ throw error;
3667
+ }
3520
3668
  }
3521
3669
  while (true) {
3522
3670
  if (!isActive) return () => void 0;
@@ -3903,6 +4051,7 @@ function createClient(config) {
3903
4051
  }
3904
4052
  export {
3905
4053
  BrowserTokenStorage,
4054
+ CONSUMER_ID_STORAGE_KEY,
3906
4055
  CodeChallengeMethod,
3907
4056
  CursorInvalidError,
3908
4057
  FileVisibility,
@@ -3927,6 +4076,7 @@ export {
3927
4076
  createClient,
3928
4077
  generatePKCEChallenge,
3929
4078
  localStorageCursorStorage,
3930
- memoryCursorStorage
4079
+ memoryCursorStorage,
4080
+ resolveConsumerId
3931
4081
  };
3932
4082
  //# sourceMappingURL=index.mjs.map