@spacelr/sdk 0.11.0 → 0.13.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.js CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  BrowserTokenStorage: () => BrowserTokenStorage,
24
+ CONSUMER_ID_STORAGE_KEY: () => CONSUMER_ID_STORAGE_KEY,
24
25
  CodeChallengeMethod: () => CodeChallengeMethod,
25
26
  CursorInvalidError: () => CursorInvalidError,
26
27
  FileVisibility: () => FileVisibility,
@@ -45,7 +46,8 @@ __export(index_exports, {
45
46
  createClient: () => createClient,
46
47
  generatePKCEChallenge: () => generatePKCEChallenge,
47
48
  localStorageCursorStorage: () => localStorageCursorStorage,
48
- memoryCursorStorage: () => memoryCursorStorage
49
+ memoryCursorStorage: () => memoryCursorStorage,
50
+ resolveConsumerId: () => resolveConsumerId
49
51
  });
50
52
  module.exports = __toCommonJS(index_exports);
51
53
 
@@ -1051,7 +1053,8 @@ var RealtimeClient = class {
1051
1053
  // gateways that haven't been updated yet are treated as pubsub-mode
1052
1054
  // so the SDK helper's fail-fast still fires correctly.
1053
1055
  realtimeMode: ack.realtimeMode ?? "pubsub",
1054
- latestStreamId: ack.latestStreamId ?? null
1056
+ latestStreamId: ack.latestStreamId ?? null,
1057
+ resumeCursor: ack.resumeCursor ?? null
1055
1058
  };
1056
1059
  }
1057
1060
  /**
@@ -1085,7 +1088,23 @@ var RealtimeClient = class {
1085
1088
  }
1086
1089
  await this.ensureConnected();
1087
1090
  const streamKey = `stream:${options.projectId}:${options.collectionName}`;
1088
- const subscriptionKey = this.streamSubscriptionKey(streamKey, options.where);
1091
+ const subscriptionKey = this.streamSubscriptionKey(
1092
+ streamKey,
1093
+ options.where,
1094
+ options.consumerId
1095
+ );
1096
+ if (options.consumerId) {
1097
+ const base = this.streamSubscriptionKey(streamKey, options.where);
1098
+ const mine = `${base}#${options.consumerId}`;
1099
+ for (const key of this.streamSubscriptions.keys()) {
1100
+ if (key.startsWith(`${base}#`) && key !== mine) {
1101
+ throw new SpacelrError(
1102
+ `A durable subscription for ${base} already exists on this client under a different consumerId. Use one consumerId per (collection, filter) per client.`,
1103
+ "DURABLE_CONSUMER_CONFLICT"
1104
+ );
1105
+ }
1106
+ }
1107
+ }
1089
1108
  const state = {
1090
1109
  options,
1091
1110
  lastDeliveredId: options.sinceId ?? null,
@@ -1118,6 +1137,7 @@ var RealtimeClient = class {
1118
1137
  options.onError?.(err);
1119
1138
  throw err;
1120
1139
  }
1140
+ this.captureDurableHandshake(state, ack);
1121
1141
  return {
1122
1142
  unsubscribe: () => this.unsubscribeStream(state),
1123
1143
  ack
@@ -1191,10 +1211,14 @@ var RealtimeClient = class {
1191
1211
  * encoding as `buildRoomKey` / the gateway's `streamSubscriptionKey`; it is a
1192
1212
  * client-local Map key only (never sent — the gateway derives its own).
1193
1213
  */
1194
- streamSubscriptionKey(streamKey, where) {
1195
- if (!where || Object.keys(where).length === 0) return streamKey;
1196
- const filterStr = Object.keys(where).sort().map((k) => `${k}=${JSON.stringify(where[k])}`).join("&");
1197
- return `${streamKey}?${filterStr}`;
1214
+ streamSubscriptionKey(streamKey, where, consumerId) {
1215
+ let key = streamKey;
1216
+ if (where && Object.keys(where).length > 0) {
1217
+ const filterStr = Object.keys(where).sort().map((k) => `${k}=${JSON.stringify(where[k])}`).join("&");
1218
+ key = `${streamKey}?${filterStr}`;
1219
+ }
1220
+ if (consumerId) key = `${key}#${consumerId}`;
1221
+ return key;
1198
1222
  }
1199
1223
  /**
1200
1224
  * All per-filter subscription sets registered for one collection's stream
@@ -1204,9 +1228,12 @@ var RealtimeClient = class {
1204
1228
  */
1205
1229
  streamSetsForStreamKey(streamKey) {
1206
1230
  const sets = [];
1207
- const prefix = `${streamKey}?`;
1231
+ const wherePrefix = `${streamKey}?`;
1232
+ const consumerPrefix = `${streamKey}#`;
1208
1233
  for (const [key, set] of this.streamSubscriptions) {
1209
- if (key === streamKey || key.startsWith(prefix)) sets.push(set);
1234
+ if (key === streamKey || key.startsWith(wherePrefix) || key.startsWith(consumerPrefix)) {
1235
+ sets.push(set);
1236
+ }
1210
1237
  }
1211
1238
  return sets;
1212
1239
  }
@@ -1374,6 +1401,21 @@ var RealtimeClient = class {
1374
1401
  }
1375
1402
  }
1376
1403
  });
1404
+ this.socket.on("subscription-reset", (info) => {
1405
+ if (!info || typeof info.projectId !== "string") return;
1406
+ for (const set of this.streamSubscriptions.values()) {
1407
+ for (const state of set) {
1408
+ if (state.options.consumerId && state.options.projectId === info.projectId) {
1409
+ state.options.onGap?.({
1410
+ projectId: info.projectId,
1411
+ collectionName: state.options.collectionName,
1412
+ retentionWindow: "unknown",
1413
+ reason: "evicted"
1414
+ });
1415
+ }
1416
+ }
1417
+ }
1418
+ });
1377
1419
  this.socket.on("disconnect", () => {
1378
1420
  if (this.disposed) return;
1379
1421
  if (initialConnect) return;
@@ -1569,9 +1611,66 @@ var RealtimeClient = class {
1569
1611
  );
1570
1612
  });
1571
1613
  }
1614
+ /** #768 — capture the durable fencing tokens from a successful handshake so
1615
+ * `ack-events` echoes the (generation, session) the server expects. */
1616
+ captureDurableHandshake(state, ack) {
1617
+ if (ack.generation !== void 0) state.generation = ack.generation;
1618
+ if (ack.session !== void 0) state.session = ack.session;
1619
+ }
1620
+ /**
1621
+ * #768 — schedule a coalesced durable ack. Only durable subscriptions (a
1622
+ * consumerId with a captured generation+session) ack. At most one ack per
1623
+ * microtask drain, carrying the highest delivered seq — cumulative on the
1624
+ * server, so a burst of N events costs one ack, not N.
1625
+ */
1626
+ scheduleDurableAck(state) {
1627
+ if (!state.options.consumerId || state.generation === void 0 || state.session === void 0 || state.ackFlushScheduled) {
1628
+ return;
1629
+ }
1630
+ state.ackFlushScheduled = true;
1631
+ queueMicrotask(() => {
1632
+ state.ackFlushScheduled = false;
1633
+ const seq = state.lastDeliveredId;
1634
+ if (seq) this.emitDurableAck(state, seq);
1635
+ });
1636
+ }
1637
+ /** #768 — emit `ack-events` for `seq`; a fenced/evicted response routes into
1638
+ * the gap-recovery path so the caller re-snapshots (§12.5/§12.1). */
1639
+ emitDurableAck(state, seq) {
1640
+ const socket = this.socket;
1641
+ if (!socket) return;
1642
+ const { projectId, collectionName, where, consumerId } = state.options;
1643
+ if (consumerId === void 0 || state.generation === void 0 || state.session === void 0) {
1644
+ return;
1645
+ }
1646
+ const payload = {
1647
+ projectId,
1648
+ collectionName,
1649
+ consumerId,
1650
+ generation: state.generation,
1651
+ session: state.session,
1652
+ seq
1653
+ };
1654
+ if (where && Object.keys(where).length > 0) payload["where"] = where;
1655
+ socket.emit(
1656
+ "ack-events",
1657
+ payload,
1658
+ (res) => {
1659
+ if (!res?.gap) return;
1660
+ if (!this.streamSubscriptions.get(state.subscriptionKey)?.has(state)) return;
1661
+ state.options.onGap?.({
1662
+ projectId,
1663
+ collectionName,
1664
+ retentionWindow: "unknown",
1665
+ reason: res.gap
1666
+ });
1667
+ }
1668
+ );
1669
+ }
1572
1670
  buildStreamPayload(state) {
1573
1671
  const { projectId, collectionName, where } = state.options;
1574
1672
  const payload = { projectId, collectionName };
1673
+ if (state.options.consumerId) payload["consumerId"] = state.options.consumerId;
1575
1674
  if (state.lastDeliveredId) {
1576
1675
  payload["sinceId"] = state.lastDeliveredId;
1577
1676
  } else if (state.options.fromStart) {
@@ -1612,6 +1711,7 @@ var RealtimeClient = class {
1612
1711
  try {
1613
1712
  await state.options.onEvent({ eventId: entryId, event: payload });
1614
1713
  state.lastDeliveredId = entryId;
1714
+ this.scheduleDurableAck(state);
1615
1715
  } catch (err) {
1616
1716
  const error = err instanceof Error ? err : new Error(String(err));
1617
1717
  try {
@@ -1650,6 +1750,11 @@ var RealtimeClient = class {
1650
1750
  }
1651
1751
  return;
1652
1752
  }
1753
+ for (const s of set) {
1754
+ s.generation = void 0;
1755
+ s.session = void 0;
1756
+ }
1757
+ this.captureDurableHandshake(primary, ack);
1653
1758
  if (!this.streamSubscriptions.has(primary.subscriptionKey)) {
1654
1759
  const payload = {
1655
1760
  projectId: primary.options.projectId,
@@ -1743,18 +1848,36 @@ function localStorageCursorStorage(prefix = "spacelr:cursor:") {
1743
1848
  };
1744
1849
  }
1745
1850
 
1851
+ // libs/sdk/src/core/consumer-id.ts
1852
+ var CONSUMER_ID_STORAGE_KEY = "spacelr:consumer-id";
1853
+ function generateConsumerId() {
1854
+ const c = globalThis.crypto;
1855
+ if (c?.randomUUID) return c.randomUUID();
1856
+ return (Math.random().toString(36).slice(2) + "-" + Date.now().toString(36)).slice(0, 128);
1857
+ }
1858
+ async function resolveConsumerId(explicit, storage, key = CONSUMER_ID_STORAGE_KEY) {
1859
+ if (explicit) return explicit;
1860
+ if (!storage) return generateConsumerId();
1861
+ const existing = await Promise.resolve(storage.load(key));
1862
+ if (existing) return existing;
1863
+ const generated = generateConsumerId();
1864
+ await Promise.resolve(storage.save(key, generated));
1865
+ return generated;
1866
+ }
1867
+
1746
1868
  // libs/sdk/src/modules/auth.module.ts
1747
1869
  function mapProfile(u) {
1748
1870
  const name = u.name ?? ([u.firstName, u.lastName].filter(Boolean).join(" ") || void 0) ?? u.displayName;
1749
1871
  return {
1750
1872
  id: u.id ?? u._id ?? u.userId ?? u.sub ?? "",
1751
- email: u.email ?? "",
1873
+ // Honest null for email-less (passkey-only) accounts (#780), not a '' coercion.
1874
+ email: u.email ?? null,
1752
1875
  username: u.username,
1753
1876
  name,
1754
1877
  roles: u.roles ?? []
1755
1878
  };
1756
1879
  }
1757
- var AuthModule = class {
1880
+ var AuthModule = class _AuthModule {
1758
1881
  constructor(http, tokenManager, config) {
1759
1882
  this.stateListeners = /* @__PURE__ */ new Set();
1760
1883
  this.lastEmittedState = null;
@@ -2070,6 +2193,82 @@ var AuthModule = class {
2070
2193
  await this.storeTokensFromLogin(result);
2071
2194
  return result;
2072
2195
  }
2196
+ /**
2197
+ * Fetch WebAuthn attestation options to begin an email-less passkey SIGNUP
2198
+ * (#780) — creating a brand-new account with no email and no password. The
2199
+ * project must have passkeys AND public registration enabled. No account is
2200
+ * created until {@link verifyPasskeySignup} succeeds.
2201
+ *
2202
+ * IMPORTANT (identity routing, B8): a signup ceremony always mints a NEW
2203
+ * account. Before offering signup, the app MUST first attempt a discoverable
2204
+ * passkey login ({@link beginPasskeyLogin} with no email); only offer signup
2205
+ * when the user has no existing passkey. Skipping this creates duplicate,
2206
+ * fragmented accounts. {@link createUserWithPasskey} bundles that fallback.
2207
+ */
2208
+ async beginPasskeySignup(displayName) {
2209
+ return this.http.request({
2210
+ method: "POST",
2211
+ path: "/auth/passkey/signup/options",
2212
+ body: displayName ? { displayName } : {}
2213
+ });
2214
+ }
2215
+ /**
2216
+ * Verify a WebAuthn attestation produced by `navigator.credentials.create()`
2217
+ * against the options from {@link beginPasskeySignup}, materializing the
2218
+ * email-less account and returning JWT tokens (the caller is now logged in).
2219
+ */
2220
+ async verifyPasskeySignup(response) {
2221
+ const result = await this.http.request({
2222
+ method: "POST",
2223
+ path: "/auth/passkey/signup/verify",
2224
+ body: { response }
2225
+ });
2226
+ await this.storeTokensFromLogin(result);
2227
+ return result;
2228
+ }
2229
+ /**
2230
+ * One-call email-less passkey signup with the B1 idempotency fallback baked
2231
+ * in. The browser WebAuthn functions are injected (the SDK stays transport-
2232
+ * only and does not depend on `@simplewebauthn/browser`):
2233
+ *
2234
+ * 1. `beginPasskeySignup` → `startRegistration` → `verifyPasskeySignup`.
2235
+ * 2. If verify fails with `challenge_expired`, a network/timeout error, or
2236
+ * `passkey_already_registered` (the account was in fact created but the
2237
+ * response was lost, or the passkey already exists), fall back to a fresh
2238
+ * discoverable LOGIN ceremony and return that session. That fallback IS the
2239
+ * idempotency mechanism — the server never mints a session from a bare
2240
+ * credential lookup.
2241
+ * 3. If the login fallback also fails (genuinely no credential), the original
2242
+ * error is surfaced so the app can restart signup.
2243
+ */
2244
+ async createUserWithPasskey(ceremony) {
2245
+ const options = await this.beginPasskeySignup(ceremony.displayName);
2246
+ const attestation = await ceremony.startRegistration(options);
2247
+ try {
2248
+ return await this.verifyPasskeySignup(attestation);
2249
+ } catch (error) {
2250
+ if (!_AuthModule.isSignupFallbackError(error)) {
2251
+ throw error;
2252
+ }
2253
+ try {
2254
+ const loginOptions = await this.beginPasskeyLogin();
2255
+ const assertion = await ceremony.startAuthentication(loginOptions);
2256
+ return await this.verifyPasskeyLogin(assertion);
2257
+ } catch {
2258
+ throw error;
2259
+ }
2260
+ }
2261
+ }
2262
+ static isSignupFallbackError(error) {
2263
+ if (error instanceof SpacelrNetworkError || error instanceof SpacelrTimeoutError) {
2264
+ return true;
2265
+ }
2266
+ if (error instanceof SpacelrError) {
2267
+ const message = (error.message || "").toLowerCase();
2268
+ return error.statusCode === 409 || message.includes("challenge_expired") || message.includes("already_registered");
2269
+ }
2270
+ return false;
2271
+ }
2073
2272
  /**
2074
2273
  * Fetch WebAuthn attestation options to register a new passkey for the
2075
2274
  * currently authenticated user.
@@ -2761,6 +2960,13 @@ function compileMatcher(where, plan) {
2761
2960
  }
2762
2961
 
2763
2962
  // libs/sdk/src/modules/database.module.ts
2963
+ var RESNAPSHOT_GAP_REASONS = /* @__PURE__ */ new Set([
2964
+ "outside-retention-window",
2965
+ "replay-truncated",
2966
+ "evicted",
2967
+ "log-reset",
2968
+ "auth-unavailable"
2969
+ ]);
2764
2970
  var DEFAULT_CATCHUP_MAX_PAGES = 1e3;
2765
2971
  var DEFAULT_CATCHUP_MAX_DOCS = 5e4;
2766
2972
  var DEFAULT_CATCHUP_PAGE_SIZE = 100;
@@ -3154,6 +3360,7 @@ var CollectionRef = class {
3154
3360
  projectId: this.projectId,
3155
3361
  collectionName: this.collectionName,
3156
3362
  sinceId,
3363
+ consumerId: handlers.consumerId,
3157
3364
  // #685 — only meaningful on a fresh subscription (no sinceId/cursor);
3158
3365
  // buildStreamPayload ignores it once a cursor exists.
3159
3366
  fromStart: handlers.fromStart,
@@ -3270,6 +3477,11 @@ var CollectionRef = class {
3270
3477
  if (!this.realtime) {
3271
3478
  throw new Error("Realtime not available: no RealtimeClient configured");
3272
3479
  }
3480
+ if (opts.consumerId !== void 0 && !/^[A-Za-z0-9._-]{1,128}$/.test(opts.consumerId)) {
3481
+ throw new Error(
3482
+ `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.`
3483
+ );
3484
+ }
3273
3485
  let isActive = true;
3274
3486
  let currentUnsubscribe = null;
3275
3487
  let snapshotAbort = new AbortController();
@@ -3334,6 +3546,7 @@ var CollectionRef = class {
3334
3546
  projectId: this.projectId,
3335
3547
  collectionName: this.collectionName,
3336
3548
  sinceId: void 0,
3549
+ consumerId: opts.consumerId,
3337
3550
  where: streamWhere,
3338
3551
  onEvent: async ({ event }) => {
3339
3552
  if (!isActive) return;
@@ -3464,8 +3677,7 @@ var CollectionRef = class {
3464
3677
  };
3465
3678
  const handleGap = (info) => {
3466
3679
  if (!isActive) return;
3467
- if (info.reason !== "outside-retention-window" && info.reason !== "replay-truncated")
3468
- return;
3680
+ if (!RESNAPSHOT_GAP_REASONS.has(info.reason)) return;
3469
3681
  dispatchRecovery();
3470
3682
  };
3471
3683
  let subscribeAckResolved = false;
@@ -3478,6 +3690,7 @@ var CollectionRef = class {
3478
3690
  projectId: this.projectId,
3479
3691
  collectionName: this.collectionName,
3480
3692
  sinceId: void 0,
3693
+ consumerId: opts.consumerId,
3481
3694
  where: streamWhere,
3482
3695
  onEvent: async ({ event }) => {
3483
3696
  if (!isActive) return;
@@ -3526,11 +3739,10 @@ var CollectionRef = class {
3526
3739
  );
3527
3740
  }
3528
3741
  currentUnsubscribe = initial.unsubscribe;
3529
- let snapshotDocs;
3530
- try {
3531
- const snapshotResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
3532
- snapshotDocs = snapshotResult.documents;
3533
- recomputeTypedMatcherPlan(snapshotResult.coercionPlan);
3742
+ const isDurableResume = initial.resumeCursor !== null;
3743
+ let snapshotDocs = [];
3744
+ if (isDurableResume) {
3745
+ recomputeTypedMatcherPlan(void 0);
3534
3746
  initialPlanReady = true;
3535
3747
  for (let i = pendingInitialEvents.length - 1; i >= 0; i--) {
3536
3748
  if (!passesLiveGate(pendingInitialEvents[i])) {
@@ -3538,29 +3750,44 @@ var CollectionRef = class {
3538
3750
  }
3539
3751
  }
3540
3752
  warnIfNoGateAvailable();
3541
- } catch (err) {
3542
- currentUnsubscribe?.();
3543
- isActive = false;
3544
- const isAbort = err instanceof DOMException && err.name === "AbortError";
3545
- if (isAbort) throw err;
3546
- const error = err instanceof Error ? err : new Error(String(err));
3547
- if (opts.onSnapshotError) opts.onSnapshotError(error);
3548
- else opts.onError?.(error);
3549
- throw error;
3753
+ } else {
3754
+ try {
3755
+ const snapshotResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
3756
+ snapshotDocs = snapshotResult.documents;
3757
+ recomputeTypedMatcherPlan(snapshotResult.coercionPlan);
3758
+ initialPlanReady = true;
3759
+ for (let i = pendingInitialEvents.length - 1; i >= 0; i--) {
3760
+ if (!passesLiveGate(pendingInitialEvents[i])) {
3761
+ pendingInitialEvents.splice(i, 1);
3762
+ }
3763
+ }
3764
+ warnIfNoGateAvailable();
3765
+ } catch (err) {
3766
+ currentUnsubscribe?.();
3767
+ isActive = false;
3768
+ const isAbort = err instanceof DOMException && err.name === "AbortError";
3769
+ if (isAbort) throw err;
3770
+ const error = err instanceof Error ? err : new Error(String(err));
3771
+ if (opts.onSnapshotError) opts.onSnapshotError(error);
3772
+ else opts.onError?.(error);
3773
+ throw error;
3774
+ }
3550
3775
  }
3551
3776
  if (!isActive) {
3552
3777
  currentUnsubscribe?.();
3553
3778
  return () => void 0;
3554
3779
  }
3555
- try {
3556
- await opts.onSnapshot(snapshotDocs, initial.latestStreamId);
3557
- } catch (err) {
3558
- currentUnsubscribe?.();
3559
- currentUnsubscribe = null;
3560
- isActive = false;
3561
- const error = err instanceof Error ? err : new Error(String(err));
3562
- opts.onError?.(error);
3563
- throw error;
3780
+ if (!isDurableResume) {
3781
+ try {
3782
+ await opts.onSnapshot(snapshotDocs, initial.latestStreamId);
3783
+ } catch (err) {
3784
+ currentUnsubscribe?.();
3785
+ currentUnsubscribe = null;
3786
+ isActive = false;
3787
+ const error = err instanceof Error ? err : new Error(String(err));
3788
+ opts.onError?.(error);
3789
+ throw error;
3790
+ }
3564
3791
  }
3565
3792
  while (true) {
3566
3793
  if (!isActive) return () => void 0;
@@ -3948,6 +4175,7 @@ function createClient(config) {
3948
4175
  // Annotate the CommonJS export names for ESM import in node:
3949
4176
  0 && (module.exports = {
3950
4177
  BrowserTokenStorage,
4178
+ CONSUMER_ID_STORAGE_KEY,
3951
4179
  CodeChallengeMethod,
3952
4180
  CursorInvalidError,
3953
4181
  FileVisibility,
@@ -3972,6 +4200,7 @@ function createClient(config) {
3972
4200
  createClient,
3973
4201
  generatePKCEChallenge,
3974
4202
  localStorageCursorStorage,
3975
- memoryCursorStorage
4203
+ memoryCursorStorage,
4204
+ resolveConsumerId
3976
4205
  });
3977
4206
  //# sourceMappingURL=index.js.map