@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.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,18 +1802,36 @@ 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;
1705
1825
  return {
1706
1826
  id: u.id ?? u._id ?? u.userId ?? u.sub ?? "",
1707
- email: u.email ?? "",
1827
+ // Honest null for email-less (passkey-only) accounts (#780), not a '' coercion.
1828
+ email: u.email ?? null,
1708
1829
  username: u.username,
1709
1830
  name,
1710
1831
  roles: u.roles ?? []
1711
1832
  };
1712
1833
  }
1713
- var AuthModule = class {
1834
+ var AuthModule = class _AuthModule {
1714
1835
  constructor(http, tokenManager, config) {
1715
1836
  this.stateListeners = /* @__PURE__ */ new Set();
1716
1837
  this.lastEmittedState = null;
@@ -2026,6 +2147,82 @@ var AuthModule = class {
2026
2147
  await this.storeTokensFromLogin(result);
2027
2148
  return result;
2028
2149
  }
2150
+ /**
2151
+ * Fetch WebAuthn attestation options to begin an email-less passkey SIGNUP
2152
+ * (#780) — creating a brand-new account with no email and no password. The
2153
+ * project must have passkeys AND public registration enabled. No account is
2154
+ * created until {@link verifyPasskeySignup} succeeds.
2155
+ *
2156
+ * IMPORTANT (identity routing, B8): a signup ceremony always mints a NEW
2157
+ * account. Before offering signup, the app MUST first attempt a discoverable
2158
+ * passkey login ({@link beginPasskeyLogin} with no email); only offer signup
2159
+ * when the user has no existing passkey. Skipping this creates duplicate,
2160
+ * fragmented accounts. {@link createUserWithPasskey} bundles that fallback.
2161
+ */
2162
+ async beginPasskeySignup(displayName) {
2163
+ return this.http.request({
2164
+ method: "POST",
2165
+ path: "/auth/passkey/signup/options",
2166
+ body: displayName ? { displayName } : {}
2167
+ });
2168
+ }
2169
+ /**
2170
+ * Verify a WebAuthn attestation produced by `navigator.credentials.create()`
2171
+ * against the options from {@link beginPasskeySignup}, materializing the
2172
+ * email-less account and returning JWT tokens (the caller is now logged in).
2173
+ */
2174
+ async verifyPasskeySignup(response) {
2175
+ const result = await this.http.request({
2176
+ method: "POST",
2177
+ path: "/auth/passkey/signup/verify",
2178
+ body: { response }
2179
+ });
2180
+ await this.storeTokensFromLogin(result);
2181
+ return result;
2182
+ }
2183
+ /**
2184
+ * One-call email-less passkey signup with the B1 idempotency fallback baked
2185
+ * in. The browser WebAuthn functions are injected (the SDK stays transport-
2186
+ * only and does not depend on `@simplewebauthn/browser`):
2187
+ *
2188
+ * 1. `beginPasskeySignup` → `startRegistration` → `verifyPasskeySignup`.
2189
+ * 2. If verify fails with `challenge_expired`, a network/timeout error, or
2190
+ * `passkey_already_registered` (the account was in fact created but the
2191
+ * response was lost, or the passkey already exists), fall back to a fresh
2192
+ * discoverable LOGIN ceremony and return that session. That fallback IS the
2193
+ * idempotency mechanism — the server never mints a session from a bare
2194
+ * credential lookup.
2195
+ * 3. If the login fallback also fails (genuinely no credential), the original
2196
+ * error is surfaced so the app can restart signup.
2197
+ */
2198
+ async createUserWithPasskey(ceremony) {
2199
+ const options = await this.beginPasskeySignup(ceremony.displayName);
2200
+ const attestation = await ceremony.startRegistration(options);
2201
+ try {
2202
+ return await this.verifyPasskeySignup(attestation);
2203
+ } catch (error) {
2204
+ if (!_AuthModule.isSignupFallbackError(error)) {
2205
+ throw error;
2206
+ }
2207
+ try {
2208
+ const loginOptions = await this.beginPasskeyLogin();
2209
+ const assertion = await ceremony.startAuthentication(loginOptions);
2210
+ return await this.verifyPasskeyLogin(assertion);
2211
+ } catch {
2212
+ throw error;
2213
+ }
2214
+ }
2215
+ }
2216
+ static isSignupFallbackError(error) {
2217
+ if (error instanceof SpacelrNetworkError || error instanceof SpacelrTimeoutError) {
2218
+ return true;
2219
+ }
2220
+ if (error instanceof SpacelrError) {
2221
+ const message = (error.message || "").toLowerCase();
2222
+ return error.statusCode === 409 || message.includes("challenge_expired") || message.includes("already_registered");
2223
+ }
2224
+ return false;
2225
+ }
2029
2226
  /**
2030
2227
  * Fetch WebAuthn attestation options to register a new passkey for the
2031
2228
  * currently authenticated user.
@@ -2717,6 +2914,13 @@ function compileMatcher(where, plan) {
2717
2914
  }
2718
2915
 
2719
2916
  // libs/sdk/src/modules/database.module.ts
2917
+ var RESNAPSHOT_GAP_REASONS = /* @__PURE__ */ new Set([
2918
+ "outside-retention-window",
2919
+ "replay-truncated",
2920
+ "evicted",
2921
+ "log-reset",
2922
+ "auth-unavailable"
2923
+ ]);
2720
2924
  var DEFAULT_CATCHUP_MAX_PAGES = 1e3;
2721
2925
  var DEFAULT_CATCHUP_MAX_DOCS = 5e4;
2722
2926
  var DEFAULT_CATCHUP_PAGE_SIZE = 100;
@@ -3110,6 +3314,7 @@ var CollectionRef = class {
3110
3314
  projectId: this.projectId,
3111
3315
  collectionName: this.collectionName,
3112
3316
  sinceId,
3317
+ consumerId: handlers.consumerId,
3113
3318
  // #685 — only meaningful on a fresh subscription (no sinceId/cursor);
3114
3319
  // buildStreamPayload ignores it once a cursor exists.
3115
3320
  fromStart: handlers.fromStart,
@@ -3226,6 +3431,11 @@ var CollectionRef = class {
3226
3431
  if (!this.realtime) {
3227
3432
  throw new Error("Realtime not available: no RealtimeClient configured");
3228
3433
  }
3434
+ if (opts.consumerId !== void 0 && !/^[A-Za-z0-9._-]{1,128}$/.test(opts.consumerId)) {
3435
+ throw new Error(
3436
+ `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.`
3437
+ );
3438
+ }
3229
3439
  let isActive = true;
3230
3440
  let currentUnsubscribe = null;
3231
3441
  let snapshotAbort = new AbortController();
@@ -3290,6 +3500,7 @@ var CollectionRef = class {
3290
3500
  projectId: this.projectId,
3291
3501
  collectionName: this.collectionName,
3292
3502
  sinceId: void 0,
3503
+ consumerId: opts.consumerId,
3293
3504
  where: streamWhere,
3294
3505
  onEvent: async ({ event }) => {
3295
3506
  if (!isActive) return;
@@ -3420,8 +3631,7 @@ var CollectionRef = class {
3420
3631
  };
3421
3632
  const handleGap = (info) => {
3422
3633
  if (!isActive) return;
3423
- if (info.reason !== "outside-retention-window" && info.reason !== "replay-truncated")
3424
- return;
3634
+ if (!RESNAPSHOT_GAP_REASONS.has(info.reason)) return;
3425
3635
  dispatchRecovery();
3426
3636
  };
3427
3637
  let subscribeAckResolved = false;
@@ -3434,6 +3644,7 @@ var CollectionRef = class {
3434
3644
  projectId: this.projectId,
3435
3645
  collectionName: this.collectionName,
3436
3646
  sinceId: void 0,
3647
+ consumerId: opts.consumerId,
3437
3648
  where: streamWhere,
3438
3649
  onEvent: async ({ event }) => {
3439
3650
  if (!isActive) return;
@@ -3482,11 +3693,10 @@ var CollectionRef = class {
3482
3693
  );
3483
3694
  }
3484
3695
  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);
3696
+ const isDurableResume = initial.resumeCursor !== null;
3697
+ let snapshotDocs = [];
3698
+ if (isDurableResume) {
3699
+ recomputeTypedMatcherPlan(void 0);
3490
3700
  initialPlanReady = true;
3491
3701
  for (let i = pendingInitialEvents.length - 1; i >= 0; i--) {
3492
3702
  if (!passesLiveGate(pendingInitialEvents[i])) {
@@ -3494,29 +3704,44 @@ var CollectionRef = class {
3494
3704
  }
3495
3705
  }
3496
3706
  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;
3707
+ } else {
3708
+ try {
3709
+ const snapshotResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
3710
+ snapshotDocs = snapshotResult.documents;
3711
+ recomputeTypedMatcherPlan(snapshotResult.coercionPlan);
3712
+ initialPlanReady = true;
3713
+ for (let i = pendingInitialEvents.length - 1; i >= 0; i--) {
3714
+ if (!passesLiveGate(pendingInitialEvents[i])) {
3715
+ pendingInitialEvents.splice(i, 1);
3716
+ }
3717
+ }
3718
+ warnIfNoGateAvailable();
3719
+ } catch (err) {
3720
+ currentUnsubscribe?.();
3721
+ isActive = false;
3722
+ const isAbort = err instanceof DOMException && err.name === "AbortError";
3723
+ if (isAbort) throw err;
3724
+ const error = err instanceof Error ? err : new Error(String(err));
3725
+ if (opts.onSnapshotError) opts.onSnapshotError(error);
3726
+ else opts.onError?.(error);
3727
+ throw error;
3728
+ }
3506
3729
  }
3507
3730
  if (!isActive) {
3508
3731
  currentUnsubscribe?.();
3509
3732
  return () => void 0;
3510
3733
  }
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;
3734
+ if (!isDurableResume) {
3735
+ try {
3736
+ await opts.onSnapshot(snapshotDocs, initial.latestStreamId);
3737
+ } catch (err) {
3738
+ currentUnsubscribe?.();
3739
+ currentUnsubscribe = null;
3740
+ isActive = false;
3741
+ const error = err instanceof Error ? err : new Error(String(err));
3742
+ opts.onError?.(error);
3743
+ throw error;
3744
+ }
3520
3745
  }
3521
3746
  while (true) {
3522
3747
  if (!isActive) return () => void 0;
@@ -3903,6 +4128,7 @@ function createClient(config) {
3903
4128
  }
3904
4129
  export {
3905
4130
  BrowserTokenStorage,
4131
+ CONSUMER_ID_STORAGE_KEY,
3906
4132
  CodeChallengeMethod,
3907
4133
  CursorInvalidError,
3908
4134
  FileVisibility,
@@ -3927,6 +4153,7 @@ export {
3927
4153
  createClient,
3928
4154
  generatePKCEChallenge,
3929
4155
  localStorageCursorStorage,
3930
- memoryCursorStorage
4156
+ memoryCursorStorage,
4157
+ resolveConsumerId
3931
4158
  };
3932
4159
  //# sourceMappingURL=index.mjs.map