@rebasepro/client 0.10.1-canary.31c773c → 0.10.1-canary.6f89f77

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.es.js CHANGED
@@ -170,6 +170,9 @@ function createTransport(config) {
170
170
  get apiPath() {
171
171
  return apiPath;
172
172
  },
173
+ get storageUrlOrigin() {
174
+ return config.storageUrlOrigin?.replace(/\/$/, "") || void 0;
175
+ },
173
176
  get fetchFn() {
174
177
  return fetchFn;
175
178
  },
@@ -295,19 +298,39 @@ function createAuth(transport, options) {
295
298
  */
296
299
  function isFatalRefreshError(err) {
297
300
  if (!(err instanceof RebaseApiError)) return false;
301
+ if (err.code === "TOKEN_ALREADY_USED") return false;
298
302
  if (err.code === "INVALID_TOKEN" || err.code === "TOKEN_EXPIRED") return true;
299
303
  return err.status === 401 || err.status === 403;
300
304
  }
305
+ /**
306
+ * Drop this client's session without telling the server.
307
+ *
308
+ * `signOut()` is a user action: it POSTs /logout, which revokes the whole
309
+ * sign-in. That is the wrong hammer for a refresh that failed. Our token
310
+ * may be stale precisely because a sibling tab holds a live one, and
311
+ * logging out on its behalf would turn one tab's bad luck into everybody
312
+ * being signed out — the exact failure this work exists to remove.
313
+ */
314
+ function abandonSessionLocally() {
315
+ currentSession = null;
316
+ clearStoredSession();
317
+ if (refreshTimeout) {
318
+ clearTimeout(refreshTimeout);
319
+ refreshTimeout = null;
320
+ }
321
+ transport.setToken(null);
322
+ emit("SIGNED_OUT", null);
323
+ }
301
324
  async function attemptScheduledRefresh(attempt) {
302
325
  try {
303
326
  await refreshSession();
304
327
  } catch (err) {
305
328
  if (isFatalRefreshError(err)) {
306
- signOut();
329
+ abandonSessionLocally();
307
330
  return;
308
331
  }
309
332
  if (attempt >= MAX_REFRESH_RETRIES) {
310
- signOut();
333
+ abandonSessionLocally();
311
334
  return;
312
335
  }
313
336
  const backoff = Math.min(REFRESH_RETRY_BASE_MS * 2 ** attempt, REFRESH_RETRY_MAX_MS);
@@ -528,9 +551,42 @@ function createAuth(transport, options) {
528
551
  transport.setToken(null);
529
552
  emit("SIGNED_OUT", null);
530
553
  }
554
+ /**
555
+ * Serialise refreshes across TABS, not just within one.
556
+ *
557
+ * The in-flight promise below covers callers inside a single JavaScript
558
+ * context. It does nothing about the far more common case: two tabs of the
559
+ * same app booting together, each firing its own /refresh with the same
560
+ * cookie. The server tolerates that now (superseded tokens stay usable for
561
+ * a grace window), but tolerating a stampede is not the same as avoiding
562
+ * one, and every extra rotation is another chance to end up holding a
563
+ * token whose response never arrived.
564
+ *
565
+ * Web Locks are best-effort on purpose. supabase-js shipped this and then
566
+ * spent a year fielding deadlock reports — a lock held by a crashed or
567
+ * frozen tab must never be able to wedge sign-in — so a lock we cannot
568
+ * take within the timeout is simply not taken, and the refresh proceeds
569
+ * unserialised, exactly as it did before.
570
+ */
571
+ const REFRESH_LOCK_NAME = "rebase-auth-refresh";
572
+ const REFRESH_LOCK_TIMEOUT_MS = 5e3;
573
+ async function withRefreshLock(fn) {
574
+ const locks = globalThis.navigator?.locks;
575
+ if (!locks?.request) return fn();
576
+ const controller = new AbortController();
577
+ const giveUp = setTimeout(() => controller.abort(), REFRESH_LOCK_TIMEOUT_MS);
578
+ try {
579
+ return await locks.request(REFRESH_LOCK_NAME, { signal: controller.signal }, async () => fn());
580
+ } catch (e) {
581
+ if (e?.name !== "AbortError") throw e;
582
+ return fn();
583
+ } finally {
584
+ clearTimeout(giveUp);
585
+ }
586
+ }
531
587
  function refreshSession() {
532
588
  if (inFlightRefresh) return inFlightRefresh;
533
- inFlightRefresh = doRefreshSession().finally(() => {
589
+ inFlightRefresh = withRefreshLock(() => doRefreshSession()).finally(() => {
534
590
  inFlightRefresh = null;
535
591
  });
536
592
  return inFlightRefresh;
@@ -1307,6 +1363,12 @@ function createFunctionsClient(transport) {
1307
1363
  */
1308
1364
  function createStorage(transport, storageId) {
1309
1365
  const urlsCache = /* @__PURE__ */ new Map();
1366
+ /**
1367
+ * Base for URLs the *browser* will fetch on its own (file downloads,
1368
+ * previews). API requests keep going to `baseUrl`; see
1369
+ * {@link RebaseClientConfig.storageUrlOrigin} for why these can differ.
1370
+ */
1371
+ const fileUrlBase = () => `${transport.storageUrlOrigin ?? transport.baseUrl}${transport.apiPath}`;
1310
1372
  /** Append ?storageId=... to a path when multi-backend routing is active. */
1311
1373
  const withStorageId = (path) => {
1312
1374
  if (!storageId) return path;
@@ -1344,7 +1406,7 @@ function createStorage(transport, storageId) {
1344
1406
  fileNotFound: true
1345
1407
  };
1346
1408
  if (isPublicStoragePath(filePath)) {
1347
- const publicConfig = { url: withStorageId(`${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}`) };
1409
+ const publicConfig = { url: withStorageId(`${fileUrlBase()}/storage/file/${filePath}`) };
1348
1410
  urlsCache.set(cacheKey, { config: publicConfig });
1349
1411
  return publicConfig;
1350
1412
  }
@@ -1352,7 +1414,7 @@ function createStorage(transport, storageId) {
1352
1414
  const result = await transport.request(withStorageId(`/storage/metadata/${filePath}`));
1353
1415
  if (result.data.public) {
1354
1416
  const publicConfig = {
1355
- url: withStorageId(`${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}`),
1417
+ url: withStorageId(`${fileUrlBase()}/storage/file/${filePath}`),
1356
1418
  metadata: result.data
1357
1419
  };
1358
1420
  urlsCache.set(cacheKey, { config: publicConfig });
@@ -1361,7 +1423,7 @@ function createStorage(transport, storageId) {
1361
1423
  const scopedToken = result.data.token;
1362
1424
  const tokenQuery = scopedToken ? `?token=${scopedToken}` : "";
1363
1425
  const downloadConfig = {
1364
- url: withStorageId(`${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}${tokenQuery}`),
1426
+ url: withStorageId(`${fileUrlBase()}/storage/file/${filePath}${tokenQuery}`),
1365
1427
  metadata: result.data
1366
1428
  };
1367
1429
  const expiresAt = result.data.tokenExpiresIn ? Date.now() + (result.data.tokenExpiresIn - 10) * 1e3 : void 0;
@@ -3829,6 +3891,8 @@ var OfflineManager = class {
3829
3891
  for (const slug of slugs) this.collections.set(slug, {
3830
3892
  rows: /* @__PURE__ */ new Map(),
3831
3893
  snapshots: /* @__PURE__ */ new Map(),
3894
+ fresh: /* @__PURE__ */ new Set(),
3895
+ freshRows: /* @__PURE__ */ new Set(),
3832
3896
  absent: /* @__PURE__ */ new Set(),
3833
3897
  ready: true
3834
3898
  });
@@ -3874,6 +3938,7 @@ var OfflineManager = class {
3874
3938
  this.connectivity.markFailure();
3875
3939
  }
3876
3940
  const answer = this.localFind(slug, params);
3941
+ this.notifyCollection(slug, false);
3877
3942
  return {
3878
3943
  data: answer.data,
3879
3944
  meta: answer.meta
@@ -4065,7 +4130,7 @@ var OfflineManager = class {
4065
4130
  emit: () => {
4066
4131
  if (closed || !this.collections.get(slug)?.ready) return;
4067
4132
  const result = this.answer(slug, params, this.snapshotFor(slug, params));
4068
- const signature = this.signature(slug, result.data, result.meta.total);
4133
+ const signature = `${result.fromCache ? "c" : "s"}${result.hasPendingWrites ? "p" : "-"}` + this.signature(slug, result.data, result.meta.total);
4069
4134
  if (observer.settled && signature === observer.signature) return;
4070
4135
  observer.signature = signature;
4071
4136
  observer.settled = true;
@@ -4117,13 +4182,15 @@ var OfflineManager = class {
4117
4182
  if (closed || !this.collections.get(slug)?.ready) return;
4118
4183
  const row = this.localRow(slug, id);
4119
4184
  const entry = this.collections.get(slug)?.rows.get(String(id));
4120
- const signature = row === void 0 ? MISSING : `${String(id)}:${entry?.rev ?? 0}`;
4185
+ const fromCache = !this.collections.get(slug)?.freshRows.has(String(id));
4186
+ const hasPendingWrites = this.hasPending(slug, id);
4187
+ const signature = `${fromCache ? "c" : "s"}${hasPendingWrites ? "p" : "-"}|` + (row === void 0 ? MISSING : `${String(id)}:${entry?.rev ?? 0}`);
4121
4188
  if (observer.settled && signature === observer.signature) return;
4122
4189
  observer.signature = signature;
4123
4190
  observer.settled = true;
4124
4191
  onResult(row, {
4125
- fromCache: true,
4126
- hasPendingWrites: this.hasPending(slug, id)
4192
+ fromCache,
4193
+ hasPendingWrites
4127
4194
  });
4128
4195
  }
4129
4196
  };
@@ -4194,6 +4261,8 @@ var OfflineManager = class {
4194
4261
  state = {
4195
4262
  rows: /* @__PURE__ */ new Map(),
4196
4263
  snapshots: /* @__PURE__ */ new Map(),
4264
+ fresh: /* @__PURE__ */ new Set(),
4265
+ freshRows: /* @__PURE__ */ new Set(),
4197
4266
  absent: /* @__PURE__ */ new Set(),
4198
4267
  ready: false
4199
4268
  };
@@ -4253,6 +4322,7 @@ var OfflineManager = class {
4253
4322
  answer(slug, params, snapshot) {
4254
4323
  const state = this.collections.get(slug);
4255
4324
  const exact = isExactlyEvaluable(params);
4325
+ const fromCache = !state?.fresh.has(buildQueryString(params));
4256
4326
  if (!state) return {
4257
4327
  data: [],
4258
4328
  meta: {
@@ -4269,7 +4339,7 @@ var OfflineManager = class {
4269
4339
  const local = runLocalQuery([...state.rows.values()].map((e) => e.row), params);
4270
4340
  return {
4271
4341
  ...local,
4272
- fromCache: true,
4342
+ fromCache,
4273
4343
  hasPendingWrites: local.data.some((row) => this.hasPending(slug, row.id)),
4274
4344
  partial: true
4275
4345
  };
@@ -4312,7 +4382,7 @@ var OfflineManager = class {
4312
4382
  offset,
4313
4383
  hasMore: snapshot.hasMore
4314
4384
  },
4315
- fromCache: true,
4385
+ fromCache,
4316
4386
  hasPendingWrites: rows.some((row) => this.hasPending(slug, row.id)),
4317
4387
  partial: !exact
4318
4388
  };
@@ -4320,6 +4390,7 @@ var OfflineManager = class {
4320
4390
  localFind(slug, params) {
4321
4391
  const state = this.collections.get(slug);
4322
4392
  const snapshot = this.snapshotFor(slug, params);
4393
+ state?.fresh.delete(buildQueryString(params));
4323
4394
  if (!snapshot && (!state || state.rows.size === 0)) throw offlineError(`Offline: no cached data for "${slug}".`);
4324
4395
  const answer = this.answer(slug, params, snapshot);
4325
4396
  return snapshot ? answer : {
@@ -4343,6 +4414,7 @@ var OfflineManager = class {
4343
4414
  cachedAt,
4344
4415
  rev: ++this.revCounter
4345
4416
  });
4417
+ state.freshRows.delete(key);
4346
4418
  this.forgetTombstone(slug, key);
4347
4419
  this.writeCache(this.rowKey(slug, key), dehydrateRow(row), cachedAt);
4348
4420
  this.evictRows(slug);
@@ -4359,8 +4431,9 @@ var OfflineManager = class {
4359
4431
  const existed = state.rows.delete(key);
4360
4432
  if (known) {
4361
4433
  state.absent.add(key);
4434
+ state.freshRows.add(key);
4362
4435
  this.writeCache(this.absentKey(slug, key), true);
4363
- }
4436
+ } else state.freshRows.delete(key);
4364
4437
  if (existed) this.deleteCache([this.rowKey(slug, key)]);
4365
4438
  }
4366
4439
  forgetTombstone(slug, key) {
@@ -4392,6 +4465,7 @@ var OfflineManager = class {
4392
4465
  continue;
4393
4466
  }
4394
4467
  this.forgetTombstone(slug, key);
4468
+ state.freshRows.add(key);
4395
4469
  const existing = state.rows.get(key);
4396
4470
  if (existing && JSON.stringify(existing.row) === JSON.stringify(merged)) {
4397
4471
  existing.cachedAt = cachedAt;
@@ -4462,6 +4536,7 @@ var OfflineManager = class {
4462
4536
  const state = this.collectionState(slug);
4463
4537
  const key = buildQueryString(params);
4464
4538
  state.snapshots.set(key, snapshot);
4539
+ state.fresh.add(key);
4465
4540
  this.writeCache(`${this.scope}|q|${slug}|${key}`, snapshot);
4466
4541
  this.evictSnapshots(slug);
4467
4542
  return snapshot;
@@ -4725,6 +4800,7 @@ var OfflineManager = class {
4725
4800
  cachedAt,
4726
4801
  rev: ++this.revCounter
4727
4802
  });
4803
+ if (this.applyPendingToRow(slug, key, void 0, op.mutationId) === void 0) state.freshRows.add(key);
4728
4804
  this.writeCache(this.rowKey(slug, key), dehydrateRow(merged), cachedAt);
4729
4805
  }
4730
4806
  /**