@cf-sync/client 0.4.0 → 0.4.1

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
@@ -220,7 +220,7 @@ function withToken(url, token) {
220
220
  * instance is always safe — it just forfeits reload continuity.
221
221
  */
222
222
  function defaultClientId(workspaceId) {
223
- const key = `cf-sync:client-id:${encodeURIComponent(workspaceId)}`;
223
+ const key = clientIdKey(workspaceId);
224
224
  try {
225
225
  const stored = sessionStorage.getItem(key);
226
226
  if (stored) return stored;
@@ -231,6 +231,59 @@ function defaultClientId(workspaceId) {
231
231
  return crypto.randomUUID();
232
232
  }
233
233
  }
234
+ function clientIdKey(workspaceId) {
235
+ return `cf-sync:client-id:${encodeURIComponent(workspaceId)}`;
236
+ }
237
+ /**
238
+ * Claims made in this document, keyed by the id each started from (fresh ids
239
+ * included). A later or replacement client in the same tab joins the same
240
+ * claim, even one still waiting on its lock, instead of finding its own
241
+ * document's lock taken.
242
+ */
243
+ const claims = /* @__PURE__ */ new Map();
244
+ function holdClientId(locks, clientId) {
245
+ return new Promise((resolve) => {
246
+ locks.request(`cf-sync:client:${clientId}`, { ifAvailable: true }, (lock) => {
247
+ if (!lock) {
248
+ resolve("taken");
249
+ return;
250
+ }
251
+ resolve("held");
252
+ return new Promise(() => {});
253
+ }).catch(() => resolve("unavailable"));
254
+ });
255
+ }
256
+ async function claimOrMint(locks, workspaceId, clientId) {
257
+ if (await holdClientId(locks, clientId) !== "taken") return clientId;
258
+ const fresh = crypto.randomUUID();
259
+ claims.set(fresh, Promise.resolve(fresh));
260
+ try {
261
+ sessionStorage.setItem(clientIdKey(workspaceId), fresh);
262
+ } catch {}
263
+ await holdClientId(locks, fresh);
264
+ return fresh;
265
+ }
266
+ /**
267
+ * Confirms the managed clientId belongs to this tab alone. Duplicating a tab
268
+ * clones its sessionStorage, so the copy would present the original's id: the
269
+ * server would supersede the original's socket, and both tabs would share one
270
+ * mutation sequence and outbox partition. A Web Lock held per id for the
271
+ * document's lifetime tells a duplicate (another live tab holds the lock) from
272
+ * a reload or a crash-restored tab (the lock died with the old document), so
273
+ * only the duplicate mints a fresh id and reloads keep replaying their outbox.
274
+ * Without Web Locks (outside a browser document, sandboxed frames) the id is
275
+ * kept as before.
276
+ */
277
+ function claimClientId(workspaceId, clientId) {
278
+ const locks = typeof document !== "undefined" && typeof navigator !== "undefined" ? navigator.locks : void 0;
279
+ if (!locks) return Promise.resolve(clientId);
280
+ let claim = claims.get(clientId);
281
+ if (!claim) {
282
+ claim = claimOrMint(locks, workspaceId, clientId);
283
+ claims.set(clientId, claim);
284
+ }
285
+ return claim;
286
+ }
234
287
  const FATAL_RELOAD_MIN_INTERVAL_MS = 6e4;
235
288
  /**
236
289
  * Default fatal handling: reload into the (presumably newer) bundle — the
@@ -620,6 +673,7 @@ var SyncClient = class {
620
673
  this.#clientId = opts.clientId ?? defaultClientId(opts.workspaceId);
621
674
  this.#url = buildSyncUrl(opts.url, opts.pathPrefix ?? "/sync", opts.workspaceId, this.#clientId);
622
675
  this.#store = opts.store ?? (opts.persist ? createDefaultStore(opts.workspaceId, this.#clientId, opts.logger ?? consoleLogger) : void 0);
676
+ this.#hydrating = this.#store !== void 0;
623
677
  this.mutate = buildMutate(Object.keys(opts.app.mutators), (name, args) => this.#guardMutation(name, args, this.#mutateByName(name, args)));
624
678
  const self = this;
625
679
  this.presence = {
@@ -822,6 +876,26 @@ var SyncClient = class {
822
876
  this.#clearStartNudge();
823
877
  this.#listenForWake(true);
824
878
  this.#setStatus("connecting");
879
+ if (this.#opts.clientId === void 0 && this.#opts.store === void 0 && typeof document !== "undefined") {
880
+ claimClientId(this.#opts.workspaceId, this.#clientId).then((clientId) => {
881
+ if (this.#stopped) return;
882
+ if (clientId !== this.#clientId) this.#adoptClientId(clientId);
883
+ this.#begin();
884
+ });
885
+ return;
886
+ }
887
+ this.#begin();
888
+ }
889
+ #adoptClientId(clientId) {
890
+ const opts = this.#opts;
891
+ this.#clientId = clientId;
892
+ this.#url = buildSyncUrl(opts.url, opts.pathPrefix ?? "/sync", opts.workspaceId, clientId);
893
+ if (opts.persist) {
894
+ this.#store?.close?.();
895
+ this.#store = createDefaultStore(opts.workspaceId, clientId, opts.logger ?? consoleLogger);
896
+ }
897
+ }
898
+ #begin() {
825
899
  const store = this.#store;
826
900
  if (store) {
827
901
  this.#hydrating = true;
@@ -1682,7 +1756,7 @@ var SyncClient = class {
1682
1756
  this.#persistScheduled = true;
1683
1757
  queueMicrotask(() => {
1684
1758
  this.#persistScheduled = false;
1685
- if (this.#stopped) return;
1759
+ if (this.#stopped || this.#hydrating || store !== this.#store) return;
1686
1760
  store.saveOutbox(this.#outboxSnapshot(), this.#confirmedLmid).catch((err) => this.#log("warn", "[cf-sync] failed to persist outbox", err));
1687
1761
  });
1688
1762
  }
@@ -52,7 +52,7 @@ Durable storage for synced rows, the cursor, and the outbox — pass your own [`
52
52
 
53
53
  `string` · default: managed by the library
54
54
 
55
- Identifies one contiguous mutation sequence — unique per SyncClient instance (per tab/session), never shared across concurrent tabs. The managed default is persisted per workspace in sessionStorage (reload continuity without cross-tab sharing), random where sessionStorage is unavailable. Pass explicitly to take over the lifecycle.
55
+ Identifies one contiguous mutation sequence — unique per SyncClient instance (per tab/session), never shared across concurrent tabs. The managed default is persisted per workspace in sessionStorage (reload continuity without cross-tab sharing), random where sessionStorage is unavailable. Duplicating a tab copies its sessionStorage, so in a browser the client holds a Web Lock on its id for the page's lifetime: a duplicate finds the lock taken and mints its own id before hydrating, while a reload or a crash-restored tab keeps its id and replays its queued mutations. This applies to the managed id with `persist` or no store, where Web Locks exist; with an explicit `clientId`, a custom `store`, or no Web Locks, the app must keep concurrent tabs from sharing an id. Pass explicitly to take over the lifecycle.
56
56
 
57
57
  ### authToken
58
58
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cf-sync/client",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Browser client for cf-sync: SyncClient (optimistic mutations, offline outbox, IndexedDB mirror, presence) and a TanStack DB collection adapter, with React hooks",
5
5
  "license": "MIT",
6
6
  "repository": {