@rebasepro/client 0.10.0 → 0.10.1-canary.14e53ae

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
@@ -1,4 +1,4 @@
1
- import { DEFAULT_STORAGE_SOURCE_KEY, EntityReference, EntityRelation, GeoPoint, PUBLIC_STORAGE_PREFIX, RebaseApiError, RebaseApiError as RebaseApiError$1, RebaseClientError, Vector, isPublicStoragePath } from "@rebasepro/types";
1
+ import { DEFAULT_STORAGE_SOURCE_KEY, EntityReference, EntityRelation, GeoPoint, PUBLIC_STORAGE_PREFIX, RebaseApiError, RebaseApiError as RebaseApiError$1, RebaseClientError, Vector, isPublicStoragePath, toCanonicalOp } from "@rebasepro/types";
2
2
  import { COMPOSITE_ID_SEPARATOR, QueryBuilder, and, buildCompositeId, cond, or, serializeFilter, serializeLogicalCondition, serializeOrderBy } from "@rebasepro/common";
3
3
  import { toSnakeCase } from "@rebasepro/utils";
4
4
  //#region src/reviver.ts
@@ -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;
@@ -1145,6 +1201,44 @@ function createCollectionClient(transport, slug, ws) {
1145
1201
  });
1146
1202
  return (await transport.request(basePath + "/count" + qs, { method: "GET" })).count ?? 0;
1147
1203
  },
1204
+ observe(params, onResult, onError, options) {
1205
+ let closed = false;
1206
+ const emit = (result) => {
1207
+ if (closed) return;
1208
+ onResult({
1209
+ ...result,
1210
+ fromCache: false,
1211
+ hasPendingWrites: false,
1212
+ partial: false
1213
+ });
1214
+ };
1215
+ client.find(params).then(emit).catch((error) => {
1216
+ if (!closed) onError?.(error);
1217
+ });
1218
+ const live = options?.realtime !== false && client.listen ? client.listen(params, emit, onError) : void 0;
1219
+ return () => {
1220
+ closed = true;
1221
+ live?.();
1222
+ };
1223
+ },
1224
+ observeById(id, onResult, onError, options) {
1225
+ let closed = false;
1226
+ const emit = (row) => {
1227
+ if (closed) return;
1228
+ onResult(row, {
1229
+ fromCache: false,
1230
+ hasPendingWrites: false
1231
+ });
1232
+ };
1233
+ client.findById(id).then(emit).catch((error) => {
1234
+ if (!closed) onError?.(error);
1235
+ });
1236
+ const live = options?.realtime !== false && client.listenById ? client.listenById(id, emit, onError) : void 0;
1237
+ return () => {
1238
+ closed = true;
1239
+ live?.();
1240
+ };
1241
+ },
1148
1242
  where(columnOrCondition, operator, value) {
1149
1243
  const builder = new SDKQueryBuilder(client);
1150
1244
  if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
@@ -1269,6 +1363,12 @@ function createFunctionsClient(transport) {
1269
1363
  */
1270
1364
  function createStorage(transport, storageId) {
1271
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}`;
1272
1372
  /** Append ?storageId=... to a path when multi-backend routing is active. */
1273
1373
  const withStorageId = (path) => {
1274
1374
  if (!storageId) return path;
@@ -1306,7 +1406,7 @@ function createStorage(transport, storageId) {
1306
1406
  fileNotFound: true
1307
1407
  };
1308
1408
  if (isPublicStoragePath(filePath)) {
1309
- const publicConfig = { url: withStorageId(`${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}`) };
1409
+ const publicConfig = { url: withStorageId(`${fileUrlBase()}/storage/file/${filePath}`) };
1310
1410
  urlsCache.set(cacheKey, { config: publicConfig });
1311
1411
  return publicConfig;
1312
1412
  }
@@ -1314,7 +1414,7 @@ function createStorage(transport, storageId) {
1314
1414
  const result = await transport.request(withStorageId(`/storage/metadata/${filePath}`));
1315
1415
  if (result.data.public) {
1316
1416
  const publicConfig = {
1317
- url: withStorageId(`${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}`),
1417
+ url: withStorageId(`${fileUrlBase()}/storage/file/${filePath}`),
1318
1418
  metadata: result.data
1319
1419
  };
1320
1420
  urlsCache.set(cacheKey, { config: publicConfig });
@@ -1323,7 +1423,7 @@ function createStorage(transport, storageId) {
1323
1423
  const scopedToken = result.data.token;
1324
1424
  const tokenQuery = scopedToken ? `?token=${scopedToken}` : "";
1325
1425
  const downloadConfig = {
1326
- url: withStorageId(`${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}${tokenQuery}`),
1426
+ url: withStorageId(`${fileUrlBase()}/storage/file/${filePath}${tokenQuery}`),
1327
1427
  metadata: result.data
1328
1428
  };
1329
1429
  const expiresAt = result.data.tokenExpiresIn ? Date.now() + (result.data.tokenExpiresIn - 10) * 1e3 : void 0;
@@ -2955,6 +3055,1929 @@ var RebaseRealtimeChannel = class {
2955
3055
  }
2956
3056
  };
2957
3057
  //#endregion
3058
+ //#region src/offline-codec.ts
3059
+ /**
3060
+ * Lossless round-tripping of rows through the offline store.
3061
+ *
3062
+ * Both persistence backends move values by structured clone, which keeps
3063
+ * `Date` but flattens every class instance to a plain object. For
3064
+ * `EntityReference`/`EntityRelation` that is harmless — they carry their own
3065
+ * `__type` discriminator, so the JSON reviver can rebuild them — but
3066
+ * `GeoPoint` and `Vector` do not, and would come back out of the cache as
3067
+ * anonymous `{ latitude, longitude }` / `{ value }` bags. A row read from the
3068
+ * cache must be indistinguishable from the same row read from the network, so
3069
+ * those two are tagged on the way in and revived on the way out.
3070
+ *
3071
+ * Type tests here are structural rather than `instanceof`, because a structured
3072
+ * clone can arrive from another realm — an iframe, a worker, or the polyfill
3073
+ * the tests run against — where the constructor identity differs but the value
3074
+ * is the real thing. Only *plain* objects are walked; anything else is passed
3075
+ * through whole, so a class instance is never quietly reduced to `{}`.
3076
+ */
3077
+ function isDate(value) {
3078
+ return Object.prototype.toString.call(value) === "[object Date]";
3079
+ }
3080
+ /** An object literal — not a Date, RegExp, Map, or any class instance. */
3081
+ function isPlainObject(value) {
3082
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
3083
+ const proto = Object.getPrototypeOf(value);
3084
+ if (proto === null || proto === Object.prototype) return true;
3085
+ return proto.constructor?.name === "Object";
3086
+ }
3087
+ function dehydrateValue(value) {
3088
+ if (value === null || value === void 0) return value;
3089
+ if (value instanceof GeoPoint) return {
3090
+ __type: "GeoPoint",
3091
+ latitude: value.latitude,
3092
+ longitude: value.longitude
3093
+ };
3094
+ if (value instanceof Vector) return {
3095
+ __type: "Vector",
3096
+ value: [...value.value]
3097
+ };
3098
+ if (value instanceof EntityReference || value instanceof EntityRelation) return value;
3099
+ if (Array.isArray(value)) return value.map(dehydrateValue);
3100
+ if (isPlainObject(value)) {
3101
+ const out = {};
3102
+ for (const [key, inner] of Object.entries(value)) out[key] = dehydrateValue(inner);
3103
+ return out;
3104
+ }
3105
+ return value;
3106
+ }
3107
+ function hydrateValue(value) {
3108
+ if (value === null || value === void 0 || isDate(value)) return value;
3109
+ if (Array.isArray(value)) return value.map(hydrateValue);
3110
+ if (typeof value === "object") {
3111
+ const revived = rebaseReviver("", value);
3112
+ if (revived !== value) return revived;
3113
+ if (!isPlainObject(value)) return value;
3114
+ const out = {};
3115
+ for (const [key, inner] of Object.entries(value)) out[key] = hydrateValue(inner);
3116
+ return out;
3117
+ }
3118
+ return value;
3119
+ }
3120
+ /** Prepare a row for the store. */
3121
+ function dehydrateRow(row) {
3122
+ return dehydrateValue(row);
3123
+ }
3124
+ /** Restore a row read back from the store. */
3125
+ function hydrateRow(row) {
3126
+ return hydrateValue(row);
3127
+ }
3128
+ //#endregion
3129
+ //#region src/offline-connectivity.ts
3130
+ /**
3131
+ * Whether the network is worth trying, and when to try again after it wasn't.
3132
+ *
3133
+ * `navigator.onLine` is necessary but not sufficient: it reports the state of
3134
+ * the network interface, so it stays `true` behind a captive portal, on a
3135
+ * connection that resolves DNS but reaches nothing, and while the API itself
3136
+ * is down. This tracks what actually happened to requests as well, so the
3137
+ * first failure is the only one an app pays for — everything after it inside
3138
+ * the backoff window skips the doomed round trip and answers from the local
3139
+ * store immediately, which is the difference between an app that freezes when
3140
+ * the wifi drops and one that does not.
3141
+ */
3142
+ /** The request never reached the server, so nothing was decided by it. */
3143
+ function isNetworkError(error) {
3144
+ if (error instanceof RebaseApiError) return error.status === 0;
3145
+ if (error instanceof TypeError) return true;
3146
+ const name = error?.name;
3147
+ return name === "AbortError" || name === "TimeoutError" || name === "NetworkError";
3148
+ }
3149
+ /**
3150
+ * Statuses that mean "not now" rather than "not ever": a queued write that
3151
+ * gets one of these is worth replaying, while a 400 or a 403 never will be.
3152
+ * 500 is deliberately absent — an unhandled server error is far more often a
3153
+ * bug the same payload will hit again than a blip, and retrying it forever
3154
+ * jams every write behind it.
3155
+ */
3156
+ var RETRYABLE_STATUSES = new Set([
3157
+ 408,
3158
+ 425,
3159
+ 429,
3160
+ 502,
3161
+ 503,
3162
+ 504
3163
+ ]);
3164
+ /** Is this failure worth another attempt later? */
3165
+ function isRetryableError(error) {
3166
+ if (isNetworkError(error)) return true;
3167
+ if (error instanceof RebaseApiError) return error.status !== void 0 && RETRYABLE_STATUSES.has(error.status);
3168
+ return false;
3169
+ }
3170
+ var ConnectivityMonitor = class {
3171
+ state = "online";
3172
+ backoffMs;
3173
+ initialBackoffMs;
3174
+ maxBackoffMs;
3175
+ retryAt = 0;
3176
+ timer;
3177
+ listeners = /* @__PURE__ */ new Set();
3178
+ respectBackoff;
3179
+ now;
3180
+ setTimer;
3181
+ clearTimer;
3182
+ /** Called when the backoff window expires, to drive an automatic retry. */
3183
+ onRetryDue;
3184
+ handleOnline = () => {
3185
+ this.retryAt = 0;
3186
+ this.backoffMs = this.initialBackoffMs;
3187
+ this.clearPendingTimer();
3188
+ this.setState("online");
3189
+ this.onRetryDue?.();
3190
+ };
3191
+ handleOffline = () => {
3192
+ this.setState("offline");
3193
+ };
3194
+ constructor(options = {}) {
3195
+ this.initialBackoffMs = options.initialBackoffMs ?? 1e3;
3196
+ this.maxBackoffMs = Math.max(this.initialBackoffMs, options.maxBackoffMs ?? 6e4);
3197
+ this.backoffMs = this.initialBackoffMs;
3198
+ this.respectBackoff = options.respectBackoff ?? true;
3199
+ this.now = options.now ?? (() => Date.now());
3200
+ this.setTimer = options.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
3201
+ this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle));
3202
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
3203
+ window.addEventListener("online", this.handleOnline);
3204
+ window.addEventListener("offline", this.handleOffline);
3205
+ }
3206
+ if (typeof navigator !== "undefined" && navigator.onLine === false) this.state = "offline";
3207
+ }
3208
+ /** What the app should be told: are we connected? */
3209
+ isOnline() {
3210
+ if (typeof navigator !== "undefined" && navigator.onLine === false) return false;
3211
+ return this.state === "online";
3212
+ }
3213
+ /**
3214
+ * Should this request even be sent? False means "answer from the local
3215
+ * store instead" — the request would only burn a timeout to reach the same
3216
+ * conclusion the last one already did.
3217
+ */
3218
+ shouldAttempt() {
3219
+ if (typeof navigator !== "undefined" && navigator.onLine === false) return false;
3220
+ if (this.state === "online" || !this.respectBackoff) return true;
3221
+ return this.now() >= this.retryAt;
3222
+ }
3223
+ /** A request reached the server. */
3224
+ markSuccess() {
3225
+ this.backoffMs = this.initialBackoffMs;
3226
+ this.retryAt = 0;
3227
+ this.clearPendingTimer();
3228
+ this.setState("online");
3229
+ }
3230
+ /** A request did not reach the server: we are offline until proven otherwise. */
3231
+ markFailure() {
3232
+ this.deferRetry();
3233
+ this.setState("offline");
3234
+ }
3235
+ /**
3236
+ * Back off and try again later without claiming the connection is gone.
3237
+ * This is what a 429 or a 503 deserves — the server answered, so the app
3238
+ * is demonstrably online; it just should not hammer.
3239
+ */
3240
+ deferRetry() {
3241
+ const jitter = .8 + Math.random() * .4;
3242
+ this.retryAt = this.now() + this.backoffMs * jitter;
3243
+ const delay = Math.max(0, this.retryAt - this.now());
3244
+ this.backoffMs = Math.min(this.maxBackoffMs, this.backoffMs * 2);
3245
+ this.scheduleRetry(delay);
3246
+ }
3247
+ /** Milliseconds until the next attempt is allowed; 0 when one is allowed now. */
3248
+ msUntilRetry() {
3249
+ if (this.state === "online") return 0;
3250
+ return Math.max(0, this.retryAt - this.now());
3251
+ }
3252
+ onChange(listener) {
3253
+ this.listeners.add(listener);
3254
+ return () => this.listeners.delete(listener);
3255
+ }
3256
+ dispose() {
3257
+ if (typeof window !== "undefined" && typeof window.removeEventListener === "function") {
3258
+ window.removeEventListener("online", this.handleOnline);
3259
+ window.removeEventListener("offline", this.handleOffline);
3260
+ }
3261
+ this.clearPendingTimer();
3262
+ this.listeners.clear();
3263
+ this.onRetryDue = void 0;
3264
+ }
3265
+ scheduleRetry(delay) {
3266
+ this.clearPendingTimer();
3267
+ if (!this.onRetryDue) return;
3268
+ this.timer = this.setTimer(() => {
3269
+ this.timer = void 0;
3270
+ this.onRetryDue?.();
3271
+ }, delay);
3272
+ this.timer.unref?.();
3273
+ }
3274
+ clearPendingTimer() {
3275
+ if (this.timer !== void 0) {
3276
+ this.clearTimer(this.timer);
3277
+ this.timer = void 0;
3278
+ }
3279
+ }
3280
+ setState(next) {
3281
+ if (this.state === next) return;
3282
+ this.state = next;
3283
+ const online = this.isOnline();
3284
+ for (const listener of this.listeners) listener(online);
3285
+ }
3286
+ };
3287
+ //#endregion
3288
+ //#region src/offline-store.ts
3289
+ /**
3290
+ * Monotonic within a tab, unique across tabs, and sortable as a plain string:
3291
+ * `<ms base36, padded>-<counter>-<random>`. The padding is what keeps
3292
+ * lexicographic order equal to chronological order, and the random suffix is
3293
+ * what stops two tabs from writing the same queue key in the same millisecond
3294
+ * — which would silently drop one of the two writes.
3295
+ */
3296
+ var mutationCounter = 0;
3297
+ function createMutationId(now = Date.now()) {
3298
+ return `${now.toString(36).padStart(10, "0")}-${(mutationCounter = (mutationCounter + 1) % 1679616).toString(36).padStart(4, "0")}-${Math.random().toString(36).slice(2, 10).padStart(8, "0")}`;
3299
+ }
3300
+ /**
3301
+ * In-memory store: the default outside the browser and the workhorse of the
3302
+ * test suite. Values are deep-copied on the way in and out so a caller
3303
+ * mutating a returned row cannot silently edit the "persisted" copy — the
3304
+ * IndexedDB implementation gets the same guarantee for free from structured
3305
+ * cloning, and the two must not differ in aliasing behaviour.
3306
+ */
3307
+ var MemoryOfflineStore = class {
3308
+ cache = /* @__PURE__ */ new Map();
3309
+ queue = /* @__PURE__ */ new Map();
3310
+ async getCache(key) {
3311
+ const entry = this.cache.get(key);
3312
+ return entry ? structuredClone(entry) : void 0;
3313
+ }
3314
+ async setCache(key, entry) {
3315
+ this.cache.set(key, structuredClone(entry));
3316
+ }
3317
+ async setCacheMany(entries) {
3318
+ for (const { key, entry } of entries) this.cache.set(key, structuredClone(entry));
3319
+ }
3320
+ async deleteCache(keys) {
3321
+ for (const key of keys) this.cache.delete(key);
3322
+ }
3323
+ async listCache(prefix) {
3324
+ const out = [];
3325
+ for (const [key, entry] of this.cache) if (key.startsWith(prefix)) out.push({
3326
+ key,
3327
+ cachedAt: entry.cachedAt
3328
+ });
3329
+ return out;
3330
+ }
3331
+ async listCacheEntries(prefix) {
3332
+ const out = [];
3333
+ for (const [key, entry] of this.cache) if (key.startsWith(prefix)) out.push({
3334
+ key,
3335
+ ...structuredClone(entry)
3336
+ });
3337
+ out.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
3338
+ return out;
3339
+ }
3340
+ async enqueue(key, mutation) {
3341
+ this.queue.set(key, structuredClone(mutation));
3342
+ }
3343
+ async dequeue(key) {
3344
+ this.queue.delete(key);
3345
+ }
3346
+ async listQueue(prefix) {
3347
+ return [...this.queue.entries()].filter(([key]) => key.startsWith(prefix)).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, mutation]) => structuredClone(mutation));
3348
+ }
3349
+ async clear(prefix) {
3350
+ for (const key of [...this.cache.keys()]) if (key.startsWith(prefix)) this.cache.delete(key);
3351
+ for (const key of [...this.queue.keys()]) if (key.startsWith(prefix)) this.queue.delete(key);
3352
+ }
3353
+ };
3354
+ var IDB_NAME = "rebase-offline";
3355
+ /**
3356
+ * v2 introduced the normalized row cache and string mutation ids. A v1
3357
+ * database holds whole-response blobs under keys this version cannot read and
3358
+ * queue entries ordered by a numeric `seq` this version no longer writes, so
3359
+ * the upgrade drops both stores rather than trying to translate them. Offline
3360
+ * support had not shipped in a release when v2 landed, so nothing in the wild
3361
+ * loses a queued write to this.
3362
+ */
3363
+ var IDB_VERSION = 2;
3364
+ var CACHE_STORE = "cache";
3365
+ var QUEUE_STORE = "queue";
3366
+ /** The exclusive upper bound of an IDBKeyRange covering every key under `prefix`. */
3367
+ function prefixRange(prefix) {
3368
+ return IDBKeyRange.bound(prefix, prefix + "￿", false, false);
3369
+ }
3370
+ function requestToPromise(request) {
3371
+ return new Promise((resolve, reject) => {
3372
+ request.onsuccess = () => resolve(request.result);
3373
+ request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB request failed"));
3374
+ });
3375
+ }
3376
+ /** Resolve when the whole transaction commits, not just when the last request returns. */
3377
+ function transactionDone(tx) {
3378
+ return new Promise((resolve, reject) => {
3379
+ tx.oncomplete = () => resolve();
3380
+ tx.onabort = tx.onerror = () => reject(tx.error ?? /* @__PURE__ */ new Error("IndexedDB transaction failed"));
3381
+ });
3382
+ }
3383
+ /**
3384
+ * IndexedDB-backed store — the browser default, so cached rows and queued
3385
+ * writes survive a reload or a browser restart. Everything lives in one
3386
+ * database with two object stores; keys are the manager's full prefixed
3387
+ * strings, so multiple users (scopes) share the database without ever
3388
+ * sharing entries.
3389
+ */
3390
+ var IndexedDBOfflineStore = class {
3391
+ dbPromise;
3392
+ open() {
3393
+ if (!this.dbPromise) this.dbPromise = new Promise((resolve, reject) => {
3394
+ const request = indexedDB.open(IDB_NAME, IDB_VERSION);
3395
+ request.onupgradeneeded = (event) => {
3396
+ const db = request.result;
3397
+ if (event.oldVersion > 0 && event.oldVersion < 2) {
3398
+ if (db.objectStoreNames.contains(CACHE_STORE)) db.deleteObjectStore(CACHE_STORE);
3399
+ if (db.objectStoreNames.contains(QUEUE_STORE)) db.deleteObjectStore(QUEUE_STORE);
3400
+ }
3401
+ if (!db.objectStoreNames.contains(CACHE_STORE)) db.createObjectStore(CACHE_STORE);
3402
+ if (!db.objectStoreNames.contains(QUEUE_STORE)) db.createObjectStore(QUEUE_STORE);
3403
+ };
3404
+ request.onsuccess = () => {
3405
+ const db = request.result;
3406
+ db.onversionchange = () => {
3407
+ db.close();
3408
+ this.dbPromise = void 0;
3409
+ };
3410
+ resolve(db);
3411
+ };
3412
+ request.onerror = () => {
3413
+ this.dbPromise = void 0;
3414
+ reject(request.error ?? /* @__PURE__ */ new Error("Failed to open IndexedDB"));
3415
+ };
3416
+ request.onblocked = () => {
3417
+ this.dbPromise = void 0;
3418
+ reject(/* @__PURE__ */ new Error("IndexedDB upgrade blocked by another tab"));
3419
+ };
3420
+ });
3421
+ return this.dbPromise;
3422
+ }
3423
+ async store(name, mode) {
3424
+ return (await this.open()).transaction(name, mode).objectStore(name);
3425
+ }
3426
+ async getCache(key) {
3427
+ return await requestToPromise((await this.store(CACHE_STORE, "readonly")).get(key));
3428
+ }
3429
+ async setCache(key, entry) {
3430
+ await requestToPromise((await this.store(CACHE_STORE, "readwrite")).put(entry, key));
3431
+ }
3432
+ async setCacheMany(entries) {
3433
+ if (entries.length === 0) return;
3434
+ const store = await this.store(CACHE_STORE, "readwrite");
3435
+ for (const { key, entry } of entries) store.put(entry, key);
3436
+ await transactionDone(store.transaction);
3437
+ }
3438
+ async deleteCache(keys) {
3439
+ if (keys.length === 0) return;
3440
+ const store = await this.store(CACHE_STORE, "readwrite");
3441
+ for (const key of keys) store.delete(key);
3442
+ await transactionDone(store.transaction);
3443
+ }
3444
+ async listCache(prefix) {
3445
+ const store = await this.store(CACHE_STORE, "readonly");
3446
+ const [keys, entries] = await Promise.all([requestToPromise(store.getAllKeys(prefixRange(prefix))), requestToPromise(store.getAll(prefixRange(prefix)))]);
3447
+ return keys.map((key, i) => ({
3448
+ key: String(key),
3449
+ cachedAt: entries[i]?.cachedAt ?? 0
3450
+ }));
3451
+ }
3452
+ async listCacheEntries(prefix) {
3453
+ const store = await this.store(CACHE_STORE, "readonly");
3454
+ const [keys, entries] = await Promise.all([requestToPromise(store.getAllKeys(prefixRange(prefix))), requestToPromise(store.getAll(prefixRange(prefix)))]);
3455
+ return keys.map((key, i) => {
3456
+ const entry = entries[i];
3457
+ return {
3458
+ key: String(key),
3459
+ value: entry?.value,
3460
+ cachedAt: entry?.cachedAt ?? 0
3461
+ };
3462
+ });
3463
+ }
3464
+ async enqueue(key, mutation) {
3465
+ await requestToPromise((await this.store(QUEUE_STORE, "readwrite")).put(mutation, key));
3466
+ }
3467
+ async dequeue(key) {
3468
+ await requestToPromise((await this.store(QUEUE_STORE, "readwrite")).delete(key));
3469
+ }
3470
+ async listQueue(prefix) {
3471
+ return await requestToPromise((await this.store(QUEUE_STORE, "readonly")).getAll(prefixRange(prefix)));
3472
+ }
3473
+ async clear(prefix) {
3474
+ await requestToPromise((await this.store(CACHE_STORE, "readwrite")).delete(prefixRange(prefix)));
3475
+ await requestToPromise((await this.store(QUEUE_STORE, "readwrite")).delete(prefixRange(prefix)));
3476
+ }
3477
+ };
3478
+ //#endregion
3479
+ //#region src/offline-query.ts
3480
+ /**
3481
+ * A local evaluator for `FindParams`, so cached rows can answer a query the
3482
+ * client has never sent to the server — and so a row written offline shows up
3483
+ * in every filtered list it belongs to, not just in unfiltered ones.
3484
+ *
3485
+ * This mirrors the Postgres driver's semantics rather than JavaScript's:
3486
+ *
3487
+ * - Comparing against NULL is *unknown*, not false-or-true. `status != "done"`
3488
+ * excludes rows where `status` is null, exactly as SQL does — a JS `!==`
3489
+ * would have included them.
3490
+ * - `ORDER BY` puts nulls last ascending and first descending, which is the
3491
+ * Postgres default.
3492
+ * - The wire format carries no types, so values arriving as strings are
3493
+ * compared numerically against numeric columns and as instants against
3494
+ * date columns. `["==", "3"]` matches the number `3`, as it does server-side.
3495
+ *
3496
+ * Two things it deliberately approximates, both flagged by
3497
+ * {@link isExactlyEvaluable}: `searchString` becomes a case-insensitive
3498
+ * substring scan over the row's string fields (the server runs real full-text
3499
+ * search over the collection's configured columns), and `include` cannot be
3500
+ * evaluated at all, because the related rows live in collections this query
3501
+ * knows nothing about.
3502
+ */
3503
+ var collator = typeof Intl !== "undefined" && typeof Intl.Collator === "function" ? new Intl.Collator(void 0, {
3504
+ numeric: false,
3505
+ sensitivity: "variant"
3506
+ }) : void 0;
3507
+ function isNullish(value) {
3508
+ return value === null || value === void 0;
3509
+ }
3510
+ /**
3511
+ * Reduce a value to something comparable. Relations compare by the id they
3512
+ * point at — the column holds a foreign key, so that is what the server
3513
+ * compares too.
3514
+ */
3515
+ function toComparable(value) {
3516
+ if (value instanceof Date) return value.getTime();
3517
+ if (value instanceof EntityRelation) return value.id;
3518
+ if (value && typeof value === "object") {
3519
+ const record = value;
3520
+ if (typeof record.__type === "string" && "id" in record) return record.id;
3521
+ }
3522
+ return value;
3523
+ }
3524
+ /**
3525
+ * Three-way compare with SQL's type coercion but not its collation. Returns
3526
+ * `undefined` when the two values are not ordered relative to each other,
3527
+ * which is how NULL propagates through a comparison.
3528
+ */
3529
+ function compareValues(a, b) {
3530
+ const left = toComparable(a);
3531
+ const right = toComparable(b);
3532
+ if (isNullish(left) || isNullish(right)) return void 0;
3533
+ if (typeof left === "boolean" || typeof right === "boolean") return (left === true || left === "true" || left === 1 ? 1 : 0) - (right === true || right === "true" || right === 1 ? 1 : 0);
3534
+ const leftNum = typeof left === "number" ? left : numericOrNaN(left);
3535
+ const rightNum = typeof right === "number" ? right : numericOrNaN(right);
3536
+ if (!Number.isNaN(leftNum) && !Number.isNaN(rightNum)) return leftNum < rightNum ? -1 : leftNum > rightNum ? 1 : 0;
3537
+ if (typeof left === "number" || typeof right === "number") {
3538
+ const leftTime = toTime(left);
3539
+ const rightTime = toTime(right);
3540
+ if (leftTime !== void 0 && rightTime !== void 0) return leftTime < rightTime ? -1 : leftTime > rightTime ? 1 : 0;
3541
+ }
3542
+ const leftStr = String(left);
3543
+ const rightStr = String(right);
3544
+ if (collator) return collator.compare(leftStr, rightStr);
3545
+ return leftStr < rightStr ? -1 : leftStr > rightStr ? 1 : 0;
3546
+ }
3547
+ function numericOrNaN(value) {
3548
+ if (typeof value === "number") return value;
3549
+ if (typeof value === "string" && value.trim() !== "") {
3550
+ const n = Number(value);
3551
+ return Number.isNaN(n) ? NaN : n;
3552
+ }
3553
+ if (typeof value === "bigint") return Number(value);
3554
+ return NaN;
3555
+ }
3556
+ function toTime(value) {
3557
+ if (typeof value === "number") return value;
3558
+ if (typeof value === "string") {
3559
+ const t = Date.parse(value);
3560
+ return Number.isNaN(t) ? void 0 : t;
3561
+ }
3562
+ }
3563
+ /** Equality with the wire's type erasure allowed for, but never across NULL. */
3564
+ function looseEquals(a, b) {
3565
+ const left = toComparable(a);
3566
+ const right = toComparable(b);
3567
+ if (isNullish(left) || isNullish(right)) return isNullish(left) && isNullish(right);
3568
+ if (left === right) return true;
3569
+ return compareValues(left, right) === 0;
3570
+ }
3571
+ /**
3572
+ * Translate a SQL `LIKE` pattern to an anchored regular expression.
3573
+ * `%` matches any run of characters, `_` exactly one, and a backslash escapes
3574
+ * either of them.
3575
+ */
3576
+ function likeToRegExp(pattern, caseInsensitive) {
3577
+ let source = "^";
3578
+ for (let i = 0; i < pattern.length; i++) {
3579
+ const char = pattern[i];
3580
+ if (char === "\\" && i + 1 < pattern.length) {
3581
+ source += pattern[i + 1].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3582
+ i++;
3583
+ } else if (char === "%") source += "[\\s\\S]*";
3584
+ else if (char === "_") source += "[\\s\\S]";
3585
+ else source += char.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3586
+ }
3587
+ return new RegExp(source + "$", caseInsensitive ? "i" : "");
3588
+ }
3589
+ function asArray(value) {
3590
+ if (Array.isArray(value)) return value;
3591
+ if (value === void 0) return [];
3592
+ return [value];
3593
+ }
3594
+ /** Evaluate one canonical operator against one row value. */
3595
+ function matchesOperator(rowValue, op, filterValue) {
3596
+ switch (op) {
3597
+ case "is-null": return isNullish(rowValue);
3598
+ case "is-not-null": return !isNullish(rowValue);
3599
+ case "==": return looseEquals(rowValue, filterValue);
3600
+ case "!=":
3601
+ if (isNullish(rowValue)) return false;
3602
+ return !looseEquals(rowValue, filterValue);
3603
+ case "<":
3604
+ case "<=":
3605
+ case ">":
3606
+ case ">=": {
3607
+ const cmp = compareValues(rowValue, filterValue);
3608
+ if (cmp === void 0) return false;
3609
+ if (op === "<") return cmp < 0;
3610
+ if (op === "<=") return cmp <= 0;
3611
+ if (op === ">") return cmp > 0;
3612
+ return cmp >= 0;
3613
+ }
3614
+ case "in":
3615
+ if (isNullish(rowValue)) return false;
3616
+ return asArray(filterValue).some((v) => looseEquals(rowValue, v));
3617
+ case "not-in":
3618
+ if (isNullish(rowValue)) return false;
3619
+ return !asArray(filterValue).some((v) => looseEquals(rowValue, v));
3620
+ case "array-contains":
3621
+ if (!Array.isArray(rowValue)) return false;
3622
+ return rowValue.some((v) => looseEquals(v, filterValue));
3623
+ case "array-contains-any": {
3624
+ if (!Array.isArray(rowValue)) return false;
3625
+ const wanted = asArray(filterValue);
3626
+ return rowValue.some((v) => wanted.some((w) => looseEquals(v, w)));
3627
+ }
3628
+ case "like":
3629
+ case "not-like":
3630
+ case "ilike":
3631
+ case "not-ilike": {
3632
+ if (isNullish(rowValue)) return false;
3633
+ const insensitive = op === "ilike" || op === "not-ilike";
3634
+ const negated = op === "not-like" || op === "not-ilike";
3635
+ const matched = likeToRegExp(String(filterValue), insensitive).test(String(rowValue));
3636
+ return negated ? !matched : matched;
3637
+ }
3638
+ default: return true;
3639
+ }
3640
+ }
3641
+ function isTuple(value) {
3642
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && toCanonicalOp(value[0]) !== void 0;
3643
+ }
3644
+ /** Evaluate a `where` clause: every field, and every tuple on a field, AND-ed. */
3645
+ function matchesWhere(row, where) {
3646
+ if (!where) return true;
3647
+ for (const [field, condition] of Object.entries(where)) {
3648
+ if (condition === void 0) continue;
3649
+ const tuples = isTuple(condition) ? [condition] : Array.isArray(condition) ? condition.filter(isTuple) : [];
3650
+ for (const [rawOp, value] of tuples) {
3651
+ const op = toCanonicalOp(rawOp) ?? rawOp;
3652
+ if (!matchesOperator(row[field], op, value)) return false;
3653
+ }
3654
+ }
3655
+ return true;
3656
+ }
3657
+ /** Evaluate a nested and/or tree. */
3658
+ function matchesLogical(row, condition) {
3659
+ if (!condition) return true;
3660
+ if ("type" in condition) {
3661
+ const children = condition.conditions ?? [];
3662
+ if (children.length === 0) return true;
3663
+ return condition.type === "or" ? children.some((c) => matchesLogical(row, c)) : children.every((c) => matchesLogical(row, c));
3664
+ }
3665
+ const op = toCanonicalOp(condition.operator) ?? condition.operator;
3666
+ return matchesOperator(row[condition.column], op, condition.value);
3667
+ }
3668
+ /**
3669
+ * Approximate the server's full-text search with a case-insensitive substring
3670
+ * scan over the row's own string fields. Narrower than the real thing (no
3671
+ * stemming, no configured search columns), and it never matches a field the
3672
+ * cached row does not carry — a local list may therefore be missing rows the
3673
+ * server would have returned, which is why {@link isExactlyEvaluable} refuses
3674
+ * to call a search query exact.
3675
+ */
3676
+ function matchesSearch(row, searchString) {
3677
+ if (!searchString) return true;
3678
+ const needle = searchString.trim().toLowerCase();
3679
+ if (!needle) return true;
3680
+ for (const value of Object.values(row)) {
3681
+ if (typeof value === "string" && value.toLowerCase().includes(needle)) return true;
3682
+ if (typeof value === "number" && String(value).includes(needle)) return true;
3683
+ }
3684
+ return false;
3685
+ }
3686
+ /** Does this row belong in the result set for `params`, ignoring pagination? */
3687
+ function matchesParams(row, params) {
3688
+ if (!params) return true;
3689
+ return matchesWhere(row, params.where) && matchesLogical(row, params.logical) && matchesSearch(row, params.searchString);
3690
+ }
3691
+ /**
3692
+ * Sort in place, Postgres-style: nulls last ascending, first descending, with
3693
+ * the row id as a tiebreak so paging through an unsorted-but-equal run does
3694
+ * not shuffle rows between pages.
3695
+ */
3696
+ function sortRows(rows, orderBy) {
3697
+ if (!orderBy) return rows;
3698
+ const [field, direction = "asc"] = orderBy;
3699
+ const sign = direction === "desc" ? -1 : 1;
3700
+ return rows.sort((a, b) => {
3701
+ const av = a[field];
3702
+ const bv = b[field];
3703
+ const aNull = isNullish(toComparable(av));
3704
+ const bNull = isNullish(toComparable(bv));
3705
+ if (aNull || bNull) {
3706
+ if (aNull && bNull) return tiebreak(a, b);
3707
+ return (aNull ? 1 : -1) * (direction === "desc" ? -1 : 1);
3708
+ }
3709
+ const cmp = compareValues(av, bv);
3710
+ if (cmp === void 0 || cmp === 0) return tiebreak(a, b);
3711
+ return cmp * sign;
3712
+ });
3713
+ }
3714
+ function tiebreak(a, b) {
3715
+ return compareValues(a.id, b.id) ?? 0;
3716
+ }
3717
+ /** Resolve `page`/`offset`/`limit` the way the server does. */
3718
+ function resolvePagination(params) {
3719
+ const limit = params?.limit ?? 20;
3720
+ return {
3721
+ limit,
3722
+ offset: params?.page != null ? Math.max(0, (params.page - 1) * limit) : params?.offset ?? 0
3723
+ };
3724
+ }
3725
+ /**
3726
+ * Can a locally evaluated answer to `params` be trusted to match the server's,
3727
+ * assuming the cache holds every row of the collection?
3728
+ *
3729
+ * `include` pulls in rows from other collections that this evaluator never
3730
+ * sees, and `searchString` is only approximated — both make the local answer a
3731
+ * best effort rather than an equivalent one.
3732
+ */
3733
+ function isExactlyEvaluable(params) {
3734
+ if (!params) return true;
3735
+ if (params.include && params.include.length > 0) return false;
3736
+ if (params.searchString) return false;
3737
+ return true;
3738
+ }
3739
+ /** Run a full query — filter, sort, paginate — over a set of rows. */
3740
+ function runLocalQuery(rows, params) {
3741
+ const matched = rows.filter((row) => matchesParams(row, params));
3742
+ sortRows(matched, params?.orderBy);
3743
+ const { limit, offset } = resolvePagination(params);
3744
+ const page = matched.slice(offset, offset + limit);
3745
+ return {
3746
+ data: page,
3747
+ meta: {
3748
+ total: matched.length,
3749
+ limit,
3750
+ offset,
3751
+ hasMore: offset + page.length < matched.length
3752
+ }
3753
+ };
3754
+ }
3755
+ //#endregion
3756
+ //#region src/offline.ts
3757
+ /** True when a read failed because there was neither network nor local data. */
3758
+ function isOfflineError(error) {
3759
+ return error instanceof RebaseApiError && error.code === "offline";
3760
+ }
3761
+ function offlineError(message) {
3762
+ return new RebaseApiError(message, {
3763
+ status: 0,
3764
+ code: "offline"
3765
+ });
3766
+ }
3767
+ function generateOfflineId() {
3768
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
3769
+ return `off-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
3770
+ }
3771
+ var MISSING = "\0missing";
3772
+ var OfflineManager = class {
3773
+ store;
3774
+ maxCachedQueries;
3775
+ maxCachedRows;
3776
+ maxRetries;
3777
+ onSyncError;
3778
+ createInner;
3779
+ inners = /* @__PURE__ */ new Map();
3780
+ connectivity;
3781
+ scope = "anon";
3782
+ /** The local database: normalized rows and query snapshots per collection. */
3783
+ collections = /* @__PURE__ */ new Map();
3784
+ /** In-memory mirror of the current scope's queue, in replay order. */
3785
+ queue = [];
3786
+ queueLoad;
3787
+ /** Serializes enqueues so concurrent writes keep the order the app made them. */
3788
+ enqueueChain = Promise.resolve();
3789
+ flushPromise;
3790
+ queueListeners = /* @__PURE__ */ new Set();
3791
+ statusListeners = /* @__PURE__ */ new Set();
3792
+ observers = /* @__PURE__ */ new Map();
3793
+ refreshPending = /* @__PURE__ */ new Set();
3794
+ revCounter = 0;
3795
+ disposed = false;
3796
+ currentStatus = {
3797
+ online: true,
3798
+ syncing: false,
3799
+ pending: 0
3800
+ };
3801
+ channel;
3802
+ tabId = createMutationId();
3803
+ api;
3804
+ constructor(config, createInner) {
3805
+ this.store = config.store ?? (typeof indexedDB !== "undefined" ? new IndexedDBOfflineStore() : new MemoryOfflineStore());
3806
+ this.maxCachedQueries = config.maxCachedQueriesPerCollection ?? 50;
3807
+ this.maxCachedRows = config.maxCachedRowsPerCollection ?? 5e3;
3808
+ this.maxRetries = config.maxRetries ?? 5;
3809
+ this.onSyncError = config.onSyncError;
3810
+ this.createInner = createInner;
3811
+ const maxBackoffMs = config.syncIntervalMs ?? 6e4;
3812
+ this.connectivity = new ConnectivityMonitor({
3813
+ maxBackoffMs: Math.max(1e3, maxBackoffMs),
3814
+ respectBackoff: maxBackoffMs > 0
3815
+ });
3816
+ if (maxBackoffMs > 0) this.connectivity.onRetryDue = () => {
3817
+ this.sync().catch(() => void 0);
3818
+ };
3819
+ this.connectivity.onChange((online) => {
3820
+ this.patchStatus({ online });
3821
+ if (online) this.revalidateAll();
3822
+ });
3823
+ this.currentStatus.online = this.connectivity.isOnline();
3824
+ if ((config.crossTab ?? this.store instanceof IndexedDBOfflineStore) && typeof BroadcastChannel !== "undefined") try {
3825
+ this.channel = new BroadcastChannel("rebase-offline");
3826
+ this.channel.onmessage = (event) => this.onBroadcast(event.data);
3827
+ this.channel.unref?.();
3828
+ } catch {}
3829
+ this.api = {
3830
+ sync: () => this.sync(),
3831
+ pending: async () => {
3832
+ await this.ensureQueueLoaded();
3833
+ return this.queue.map((m) => structuredClone(m));
3834
+ },
3835
+ status: () => ({ ...this.currentStatus }),
3836
+ onStatusChange: (listener) => {
3837
+ this.statusListeners.add(listener);
3838
+ return () => this.statusListeners.delete(listener);
3839
+ },
3840
+ clear: async () => {
3841
+ await this.store.clear(`${this.scope}|`);
3842
+ this.queue = [];
3843
+ this.resetCollections();
3844
+ this.patchStatus({
3845
+ pending: 0,
3846
+ lastError: void 0
3847
+ });
3848
+ this.notifyQueue();
3849
+ for (const slug of this.observers.keys()) this.notifyCollection(slug, false);
3850
+ },
3851
+ onQueueChange: (listener) => {
3852
+ this.queueListeners.add(listener);
3853
+ return () => this.queueListeners.delete(listener);
3854
+ }
3855
+ };
3856
+ }
3857
+ /**
3858
+ * Cache and queue are partitioned per signed-in user: cached rows are
3859
+ * RLS-filtered for the user who fetched them, and queued writes must
3860
+ * replay under the credentials that made them — so neither may ever leak
3861
+ * across a sign-out/sign-in on a shared browser.
3862
+ */
3863
+ setScope(uid) {
3864
+ const next = uid || "anon";
3865
+ if (next === this.scope) return;
3866
+ this.scope = next;
3867
+ this.queueLoad = void 0;
3868
+ this.queue = [];
3869
+ this.resetCollections();
3870
+ this.patchStatus({
3871
+ pending: 0,
3872
+ lastError: void 0
3873
+ });
3874
+ this.notifyQueue();
3875
+ for (const slug of this.observers.keys()) this.notifyCollection(slug, false);
3876
+ this.revalidateAll();
3877
+ this.sync().catch(() => void 0);
3878
+ }
3879
+ /**
3880
+ * Throw away every local row, for a scope change or an explicit clear.
3881
+ *
3882
+ * The state objects are replaced rather than emptied, so a load still in
3883
+ * flight for the previous user fails its identity check and discards what
3884
+ * it read instead of grafting it onto the new one. The replacements are
3885
+ * marked ready: nothing needs loading until something asks, and observers
3886
+ * have to be told *now* that the rows they are showing are gone.
3887
+ */
3888
+ resetCollections() {
3889
+ const slugs = [...this.collections.keys()];
3890
+ this.collections = /* @__PURE__ */ new Map();
3891
+ for (const slug of slugs) this.collections.set(slug, {
3892
+ rows: /* @__PURE__ */ new Map(),
3893
+ snapshots: /* @__PURE__ */ new Map(),
3894
+ fresh: /* @__PURE__ */ new Set(),
3895
+ freshRows: /* @__PURE__ */ new Set(),
3896
+ absent: /* @__PURE__ */ new Set(),
3897
+ ready: true
3898
+ });
3899
+ }
3900
+ /** Release listeners, timers and the cross-tab channel (client.close()). */
3901
+ dispose() {
3902
+ this.disposed = true;
3903
+ this.connectivity.dispose();
3904
+ try {
3905
+ this.channel?.close();
3906
+ } catch {}
3907
+ this.observers.clear();
3908
+ this.queueListeners.clear();
3909
+ this.statusListeners.clear();
3910
+ }
3911
+ wrap(slug, inner) {
3912
+ this.inners.set(slug, inner);
3913
+ const wrapped = {
3914
+ find: async (params) => {
3915
+ const state = await this.ensureCollection(slug);
3916
+ if (this.connectivity.shouldAttempt()) try {
3917
+ const res = await inner.find(params);
3918
+ this.connectivity.markSuccess();
3919
+ await this.ingest(slug, res.data ?? []);
3920
+ const snapshot = this.recordSnapshot(slug, params, res);
3921
+ const answer = this.answer(slug, params, snapshot);
3922
+ this.notifyCollection(slug, false);
3923
+ return {
3924
+ data: answer.data,
3925
+ meta: answer.meta
3926
+ };
3927
+ } catch (error) {
3928
+ if (!isNetworkError(error)) {
3929
+ if (isRetryableError(error) && this.hasLocalAnswer(state, slug, params)) {
3930
+ const answer = this.answer(slug, params, this.snapshotFor(slug, params));
3931
+ return {
3932
+ data: answer.data,
3933
+ meta: answer.meta
3934
+ };
3935
+ }
3936
+ throw error;
3937
+ }
3938
+ this.connectivity.markFailure();
3939
+ }
3940
+ const answer = this.localFind(slug, params);
3941
+ this.notifyCollection(slug, false);
3942
+ return {
3943
+ data: answer.data,
3944
+ meta: answer.meta
3945
+ };
3946
+ },
3947
+ findById: async (id) => {
3948
+ await this.ensureCollection(slug);
3949
+ if (this.connectivity.shouldAttempt()) try {
3950
+ const row = await inner.findById(id);
3951
+ this.connectivity.markSuccess();
3952
+ if (row !== void 0) await this.ingest(slug, [row]);
3953
+ else if (!this.hasPending(slug, id)) this.removeLocalRow(slug, id, true);
3954
+ this.notifyCollection(slug, false);
3955
+ return this.localRow(slug, id);
3956
+ } catch (error) {
3957
+ if (!isNetworkError(error)) throw error;
3958
+ this.connectivity.markFailure();
3959
+ }
3960
+ const local = this.localRow(slug, id);
3961
+ if (local !== void 0 || this.hasPending(slug, id)) return local;
3962
+ if (this.collections.get(slug)?.absent.has(String(id))) return void 0;
3963
+ throw offlineError(`Offline: "${slug}" row ${String(id)} is not in the local database.`);
3964
+ },
3965
+ create: async (data, id) => {
3966
+ await this.ensureCollection(slug);
3967
+ if (this.connectivity.shouldAttempt()) try {
3968
+ const row = await inner.create(data, id);
3969
+ this.connectivity.markSuccess();
3970
+ await this.ingest(slug, [row]);
3971
+ this.notifyCollection(slug);
3972
+ this.scheduleRefresh(slug);
3973
+ return row;
3974
+ } catch (error) {
3975
+ if (!isNetworkError(error)) throw error;
3976
+ this.connectivity.markFailure();
3977
+ }
3978
+ const providedId = id ?? data.id;
3979
+ const rowId = providedId ?? generateOfflineId();
3980
+ const row = {
3981
+ ...data,
3982
+ id: rowId
3983
+ };
3984
+ await this.enqueue({
3985
+ collection: slug,
3986
+ type: "create",
3987
+ id: rowId,
3988
+ data: row,
3989
+ generatedId: providedId === void 0,
3990
+ rollback: { rows: { [String(rowId)]: this.rawLocalRow(slug, rowId) ?? null } }
3991
+ });
3992
+ this.setLocalRow(slug, rowId, row);
3993
+ this.notifyCollection(slug);
3994
+ return row;
3995
+ },
3996
+ createMany: async (data, options) => {
3997
+ await this.ensureCollection(slug);
3998
+ if (!Array.isArray(data)) throw new TypeError("createMany expects an array of records.");
3999
+ if (data.length === 0) return [];
4000
+ if (this.connectivity.shouldAttempt()) try {
4001
+ const rows = await inner.createMany(data, options);
4002
+ this.connectivity.markSuccess();
4003
+ await this.ingest(slug, rows);
4004
+ this.notifyCollection(slug);
4005
+ this.scheduleRefresh(slug);
4006
+ return rows;
4007
+ } catch (error) {
4008
+ if (!isNetworkError(error)) throw error;
4009
+ this.connectivity.markFailure();
4010
+ }
4011
+ const rows = data.map((r) => ({
4012
+ ...r,
4013
+ id: r.id ?? generateOfflineId()
4014
+ }));
4015
+ const rollback = {};
4016
+ for (const row of rows) {
4017
+ const key = String(row.id);
4018
+ rollback[key] = this.rawLocalRow(slug, row.id) ?? null;
4019
+ }
4020
+ await this.enqueue({
4021
+ collection: slug,
4022
+ type: "createMany",
4023
+ data: rows,
4024
+ upsert: options?.upsert,
4025
+ rollback: { rows: rollback }
4026
+ });
4027
+ for (const row of rows) this.setLocalRow(slug, row.id, row);
4028
+ this.notifyCollection(slug);
4029
+ return rows;
4030
+ },
4031
+ update: async (id, data) => {
4032
+ await this.ensureCollection(slug);
4033
+ if (this.connectivity.shouldAttempt()) try {
4034
+ const row = await inner.update(id, data);
4035
+ this.connectivity.markSuccess();
4036
+ await this.ingest(slug, [row]);
4037
+ this.notifyCollection(slug);
4038
+ return row;
4039
+ } catch (error) {
4040
+ if (!isNetworkError(error)) throw error;
4041
+ this.connectivity.markFailure();
4042
+ }
4043
+ const base = this.rawLocalRow(slug, id);
4044
+ await this.enqueue({
4045
+ collection: slug,
4046
+ type: "update",
4047
+ id,
4048
+ data,
4049
+ rollback: { rows: { [String(id)]: base ?? null } }
4050
+ });
4051
+ const optimistic = {
4052
+ ...base ?? {},
4053
+ ...data,
4054
+ id
4055
+ };
4056
+ this.setLocalRow(slug, id, optimistic);
4057
+ this.notifyCollection(slug);
4058
+ return optimistic;
4059
+ },
4060
+ delete: async (id) => {
4061
+ await this.ensureCollection(slug);
4062
+ if (this.connectivity.shouldAttempt()) try {
4063
+ await inner.delete(id);
4064
+ this.connectivity.markSuccess();
4065
+ this.removeLocalRow(slug, id, true);
4066
+ this.notifyCollection(slug);
4067
+ this.scheduleRefresh(slug);
4068
+ return;
4069
+ } catch (error) {
4070
+ if (!isNetworkError(error)) throw error;
4071
+ this.connectivity.markFailure();
4072
+ }
4073
+ await this.enqueue({
4074
+ collection: slug,
4075
+ type: "delete",
4076
+ id,
4077
+ rollback: { rows: { [String(id)]: this.rawLocalRow(slug, id) ?? null } }
4078
+ });
4079
+ this.removeLocalRow(slug, id);
4080
+ this.notifyCollection(slug);
4081
+ },
4082
+ count: async (params) => {
4083
+ await this.ensureCollection(slug);
4084
+ if (this.connectivity.shouldAttempt()) try {
4085
+ const n = await inner.count(params);
4086
+ this.connectivity.markSuccess();
4087
+ this.writeCache(this.countKey(slug, params), n);
4088
+ return Math.max(0, n + this.pendingDelta(slug, params));
4089
+ } catch (error) {
4090
+ if (!isNetworkError(error)) throw error;
4091
+ this.connectivity.markFailure();
4092
+ }
4093
+ const cached = await this.readCache(this.countKey(slug, params));
4094
+ if (cached !== void 0) return Math.max(0, cached + this.pendingDelta(slug, params));
4095
+ const state = this.collections.get(slug);
4096
+ if (state && state.rows.size > 0) return runLocalQuery([...state.rows.values()].map((e) => e.row), params).meta.total;
4097
+ throw offlineError(`Offline: no cached count for "${slug}".`);
4098
+ },
4099
+ observe: (params, onResult, onError, options) => this.observe(slug, wrapped, inner, params, onResult, onError, options),
4100
+ observeById: (id, onResult, onError, options) => this.observeById(slug, wrapped, inner, id, onResult, onError, options),
4101
+ where(columnOrCondition, operator, value) {
4102
+ const builder = new SDKQueryBuilder(wrapped);
4103
+ if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
4104
+ return builder.where(columnOrCondition, operator, value);
4105
+ },
4106
+ orderBy: (column, direction) => new SDKQueryBuilder(wrapped).orderBy(column, direction),
4107
+ limit: (count) => new SDKQueryBuilder(wrapped).limit(count),
4108
+ offset: (count) => new SDKQueryBuilder(wrapped).offset(count),
4109
+ search: (searchString) => new SDKQueryBuilder(wrapped).search(searchString),
4110
+ include: (...relations) => new SDKQueryBuilder(wrapped).include(...relations)
4111
+ };
4112
+ if (inner.listen) wrapped.listen = (params, onUpdate, onError) => inner.listen(params, (response) => {
4113
+ this.ingest(slug, response.data ?? []).then(() => this.notifyCollection(slug, false));
4114
+ onUpdate(response);
4115
+ }, onError);
4116
+ if (inner.listenById) wrapped.listenById = (id, onUpdate, onError) => inner.listenById(id, (row) => {
4117
+ if (row) this.ingest(slug, [row]).then(() => this.notifyCollection(slug, false));
4118
+ onUpdate(row);
4119
+ }, onError);
4120
+ return wrapped;
4121
+ }
4122
+ observe(slug, wrapped, inner, params, onResult, onError, options) {
4123
+ let closed = false;
4124
+ let unlisten;
4125
+ const observer = {
4126
+ slug,
4127
+ params,
4128
+ settled: false,
4129
+ refresh: () => wrapped.find(params).catch(() => void 0),
4130
+ emit: () => {
4131
+ if (closed || !this.collections.get(slug)?.ready) return;
4132
+ const result = this.answer(slug, params, this.snapshotFor(slug, params));
4133
+ const signature = `${result.fromCache ? "c" : "s"}${result.hasPendingWrites ? "p" : "-"}` + this.signature(slug, result.data, result.meta.total);
4134
+ if (observer.settled && signature === observer.signature) return;
4135
+ observer.signature = signature;
4136
+ observer.settled = true;
4137
+ onResult(observer.error ? {
4138
+ ...result,
4139
+ error: observer.error
4140
+ } : result);
4141
+ }
4142
+ };
4143
+ this.observersFor(slug).add(observer);
4144
+ (async () => {
4145
+ await this.ensureCollection(slug);
4146
+ if (closed) return;
4147
+ if (this.hasLocalAnswer(this.collections.get(slug), slug, params)) observer.emit();
4148
+ try {
4149
+ await wrapped.find(params);
4150
+ observer.error = void 0;
4151
+ } catch (error) {
4152
+ observer.error = error;
4153
+ if (closed) return;
4154
+ if (!observer.settled) {
4155
+ onError?.(error);
4156
+ return;
4157
+ }
4158
+ }
4159
+ if (!closed) observer.emit();
4160
+ })();
4161
+ if (options?.realtime !== false && inner.listen) unlisten = inner.listen(params, (response) => {
4162
+ this.ingest(slug, response.data ?? []).then(() => {
4163
+ this.recordSnapshot(slug, params, response);
4164
+ this.notifyCollection(slug, false);
4165
+ });
4166
+ }, onError);
4167
+ return () => {
4168
+ closed = true;
4169
+ this.observersFor(slug).delete(observer);
4170
+ unlisten?.();
4171
+ };
4172
+ }
4173
+ observeById(slug, wrapped, inner, id, onResult, onError, options) {
4174
+ let closed = false;
4175
+ let unlisten;
4176
+ const observer = {
4177
+ slug,
4178
+ id,
4179
+ settled: false,
4180
+ refresh: () => wrapped.findById(id).catch(() => void 0),
4181
+ emit: () => {
4182
+ if (closed || !this.collections.get(slug)?.ready) return;
4183
+ const row = this.localRow(slug, id);
4184
+ const entry = this.collections.get(slug)?.rows.get(String(id));
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}`);
4188
+ if (observer.settled && signature === observer.signature) return;
4189
+ observer.signature = signature;
4190
+ observer.settled = true;
4191
+ onResult(row, {
4192
+ fromCache,
4193
+ hasPendingWrites
4194
+ });
4195
+ }
4196
+ };
4197
+ this.observersFor(slug).add(observer);
4198
+ (async () => {
4199
+ await this.ensureCollection(slug);
4200
+ if (closed) return;
4201
+ if (this.localRow(slug, id) !== void 0) observer.emit();
4202
+ try {
4203
+ await wrapped.findById(id);
4204
+ } catch (error) {
4205
+ if (closed) return;
4206
+ if (!observer.settled) {
4207
+ onError?.(error);
4208
+ return;
4209
+ }
4210
+ }
4211
+ if (!closed) observer.emit();
4212
+ })();
4213
+ if (options?.realtime !== false && inner.listenById) unlisten = inner.listenById(id, (row) => {
4214
+ if (!row) {
4215
+ if (!this.hasPending(slug, id)) this.removeLocalRow(slug, id, true);
4216
+ this.notifyCollection(slug, false);
4217
+ return;
4218
+ }
4219
+ this.ingest(slug, [row]).then(() => this.notifyCollection(slug, false));
4220
+ }, onError);
4221
+ return () => {
4222
+ closed = true;
4223
+ this.observersFor(slug).delete(observer);
4224
+ unlisten?.();
4225
+ };
4226
+ }
4227
+ observersFor(slug) {
4228
+ let set = this.observers.get(slug);
4229
+ if (!set) {
4230
+ set = /* @__PURE__ */ new Set();
4231
+ this.observers.set(slug, set);
4232
+ }
4233
+ return set;
4234
+ }
4235
+ /** Cheap change detection: which rows, in what order, at which revision. */
4236
+ signature(slug, rows, total) {
4237
+ const state = this.collections.get(slug);
4238
+ return `${total}|${rows.map((row) => {
4239
+ const key = String(row.id);
4240
+ return `${key}:${state?.rows.get(key)?.rev ?? 0}`;
4241
+ }).join(",")}`;
4242
+ }
4243
+ notifyCollection(slug, broadcast = true) {
4244
+ const set = this.observers.get(slug);
4245
+ if (set) for (const observer of [...set]) observer.emit();
4246
+ if (broadcast) this.broadcast({
4247
+ type: "rows",
4248
+ slugs: [slug]
4249
+ });
4250
+ }
4251
+ /** Connectivity came back (or the user changed): re-read everything live. */
4252
+ revalidateAll() {
4253
+ for (const slug of this.observers.keys()) {
4254
+ this.notifyCollection(slug, false);
4255
+ this.scheduleRefresh(slug);
4256
+ }
4257
+ }
4258
+ collectionState(slug) {
4259
+ let state = this.collections.get(slug);
4260
+ if (!state) {
4261
+ state = {
4262
+ rows: /* @__PURE__ */ new Map(),
4263
+ snapshots: /* @__PURE__ */ new Map(),
4264
+ fresh: /* @__PURE__ */ new Set(),
4265
+ freshRows: /* @__PURE__ */ new Set(),
4266
+ absent: /* @__PURE__ */ new Set(),
4267
+ ready: false
4268
+ };
4269
+ this.collections.set(slug, state);
4270
+ }
4271
+ return state;
4272
+ }
4273
+ ensureCollection(slug) {
4274
+ const state = this.collectionState(slug);
4275
+ if (!state.loaded) {
4276
+ const scope = this.scope;
4277
+ state.loaded = (async () => {
4278
+ await this.ensureQueueLoaded();
4279
+ const [rows, snapshots, absent] = await Promise.all([
4280
+ this.store.listCacheEntries(`${scope}|row|${slug}|`).catch(() => []),
4281
+ this.store.listCacheEntries(`${scope}|q|${slug}|`).catch(() => []),
4282
+ this.store.listCache(`${scope}|abs|${slug}|`).catch(() => [])
4283
+ ]);
4284
+ if (this.scope !== scope || this.collections.get(slug) !== state) return;
4285
+ for (const entry of rows) {
4286
+ const row = entry.value;
4287
+ if (!row || row.id === void 0 || row.id === null) continue;
4288
+ state.rows.set(String(row.id), {
4289
+ row: hydrateRow(row),
4290
+ cachedAt: entry.cachedAt,
4291
+ rev: ++this.revCounter
4292
+ });
4293
+ }
4294
+ for (const entry of snapshots) {
4295
+ const key = entry.key.slice(`${scope}|q|${slug}|`.length);
4296
+ if (entry.value) state.snapshots.set(key, entry.value);
4297
+ }
4298
+ for (const entry of absent) state.absent.add(entry.key.slice(`${scope}|abs|${slug}|`.length));
4299
+ })().catch(() => void 0).finally(() => {
4300
+ state.ready = true;
4301
+ });
4302
+ }
4303
+ return state.loaded.then(() => state);
4304
+ }
4305
+ snapshotFor(slug, params) {
4306
+ return this.collections.get(slug)?.snapshots.get(buildQueryString(params));
4307
+ }
4308
+ hasLocalAnswer(state, slug, params) {
4309
+ if (!state) return false;
4310
+ return state.snapshots.has(buildQueryString(params)) || state.rows.size > 0;
4311
+ }
4312
+ /**
4313
+ * Answer a query from the local database.
4314
+ *
4315
+ * With a snapshot, the server's own page — its ids, order and total — is
4316
+ * the skeleton, and the local rows fill it in: rows deleted locally drop
4317
+ * out, rows edited locally show the edit, and rows *created* locally join
4318
+ * the first page if they match. Without one, the query is evaluated
4319
+ * outright over every cached row, which is the best that can be done for a
4320
+ * query the server has never answered here.
4321
+ */
4322
+ answer(slug, params, snapshot) {
4323
+ const state = this.collections.get(slug);
4324
+ const exact = isExactlyEvaluable(params);
4325
+ const fromCache = !state?.fresh.has(buildQueryString(params));
4326
+ if (!state) return {
4327
+ data: [],
4328
+ meta: {
4329
+ total: 0,
4330
+ limit: params?.limit ?? 20,
4331
+ offset: params?.offset ?? 0,
4332
+ hasMore: false
4333
+ },
4334
+ fromCache: true,
4335
+ hasPendingWrites: false,
4336
+ partial: true
4337
+ };
4338
+ if (!snapshot) {
4339
+ const local = runLocalQuery([...state.rows.values()].map((e) => e.row), params);
4340
+ return {
4341
+ ...local,
4342
+ fromCache,
4343
+ hasPendingWrites: local.data.some((row) => this.hasPending(slug, row.id)),
4344
+ partial: true
4345
+ };
4346
+ }
4347
+ const rows = [];
4348
+ const seen = /* @__PURE__ */ new Set();
4349
+ /** Rows the server counted that we know are no longer in the result. */
4350
+ let removed = 0;
4351
+ for (const id of snapshot.ids) {
4352
+ const key = String(id);
4353
+ const entry = state.rows.get(key);
4354
+ if (!entry) {
4355
+ if (state.absent.has(key) || this.hasPending(slug, key)) removed++;
4356
+ continue;
4357
+ }
4358
+ if (exact && this.hasPending(slug, key) && !matchesParams(entry.row, params)) {
4359
+ removed++;
4360
+ continue;
4361
+ }
4362
+ rows.push(entry.row);
4363
+ seen.add(key);
4364
+ }
4365
+ let added = 0;
4366
+ const offset = snapshot.offset ?? 0;
4367
+ if (exact && offset === 0) {
4368
+ for (const [key, entry] of state.rows) {
4369
+ if (seen.has(key) || !this.hasPending(slug, key)) continue;
4370
+ if (!this.isLocallyCreated(slug, key)) continue;
4371
+ if (!matchesParams(entry.row, params)) continue;
4372
+ rows.push(entry.row);
4373
+ added++;
4374
+ }
4375
+ if (added > 0 && params?.orderBy) sortRows(rows, params.orderBy);
4376
+ }
4377
+ return {
4378
+ data: rows,
4379
+ meta: {
4380
+ total: Math.max(rows.length, snapshot.total - removed + added),
4381
+ limit: snapshot.limit,
4382
+ offset,
4383
+ hasMore: snapshot.hasMore
4384
+ },
4385
+ fromCache,
4386
+ hasPendingWrites: rows.some((row) => this.hasPending(slug, row.id)),
4387
+ partial: !exact
4388
+ };
4389
+ }
4390
+ localFind(slug, params) {
4391
+ const state = this.collections.get(slug);
4392
+ const snapshot = this.snapshotFor(slug, params);
4393
+ state?.fresh.delete(buildQueryString(params));
4394
+ if (!snapshot && (!state || state.rows.size === 0)) throw offlineError(`Offline: no cached data for "${slug}".`);
4395
+ const answer = this.answer(slug, params, snapshot);
4396
+ return snapshot ? answer : {
4397
+ ...answer,
4398
+ partial: true
4399
+ };
4400
+ }
4401
+ rawLocalRow(slug, id) {
4402
+ const entry = this.collections.get(slug)?.rows.get(String(id));
4403
+ return entry ? { ...entry.row } : void 0;
4404
+ }
4405
+ localRow(slug, id) {
4406
+ return this.collections.get(slug)?.rows.get(String(id))?.row;
4407
+ }
4408
+ setLocalRow(slug, id, row) {
4409
+ const state = this.collectionState(slug);
4410
+ const key = String(id);
4411
+ const cachedAt = Date.now();
4412
+ state.rows.set(key, {
4413
+ row: { ...row },
4414
+ cachedAt,
4415
+ rev: ++this.revCounter
4416
+ });
4417
+ state.freshRows.delete(key);
4418
+ this.forgetTombstone(slug, key);
4419
+ this.writeCache(this.rowKey(slug, key), dehydrateRow(row), cachedAt);
4420
+ this.evictRows(slug);
4421
+ }
4422
+ /**
4423
+ * Drop a row and, when the server is the one saying it is gone, remember
4424
+ * that. "I looked it up and it does not exist" is real knowledge: without
4425
+ * it, opening a deleted row while offline would report a missing local
4426
+ * database instead of a missing row.
4427
+ */
4428
+ removeLocalRow(slug, id, known = false) {
4429
+ const state = this.collectionState(slug);
4430
+ const key = String(id);
4431
+ const existed = state.rows.delete(key);
4432
+ if (known) {
4433
+ state.absent.add(key);
4434
+ state.freshRows.add(key);
4435
+ this.writeCache(this.absentKey(slug, key), true);
4436
+ } else state.freshRows.delete(key);
4437
+ if (existed) this.deleteCache([this.rowKey(slug, key)]);
4438
+ }
4439
+ forgetTombstone(slug, key) {
4440
+ if (!this.collectionState(slug).absent.delete(key)) return;
4441
+ this.deleteCache([this.absentKey(slug, key)]);
4442
+ }
4443
+ /**
4444
+ * Merge server rows into the local database. A row with unsynced local
4445
+ * writes keeps them: the server's copy is the base the queued mutations
4446
+ * are re-applied to, not a replacement for what the user did.
4447
+ *
4448
+ * Rows that came back unchanged keep their identity and revision, so a
4449
+ * refetch that changed nothing does not re-render every live query that
4450
+ * touches them — or rewrite them all to disk.
4451
+ */
4452
+ async ingest(slug, rows) {
4453
+ if (rows.length === 0) return;
4454
+ const state = await this.ensureCollection(slug);
4455
+ const cachedAt = Date.now();
4456
+ const writes = [];
4457
+ const deletes = [];
4458
+ for (const raw of rows) {
4459
+ if (!raw || raw.id === void 0 || raw.id === null) continue;
4460
+ const key = String(raw.id);
4461
+ const merged = this.hasPending(slug, key) ? this.applyPendingToRow(slug, key, { ...raw }) : { ...raw };
4462
+ if (merged === void 0) {
4463
+ state.rows.delete(key);
4464
+ deletes.push(this.rowKey(slug, key));
4465
+ continue;
4466
+ }
4467
+ this.forgetTombstone(slug, key);
4468
+ state.freshRows.add(key);
4469
+ const existing = state.rows.get(key);
4470
+ if (existing && JSON.stringify(existing.row) === JSON.stringify(merged)) {
4471
+ existing.cachedAt = cachedAt;
4472
+ continue;
4473
+ }
4474
+ state.rows.set(key, {
4475
+ row: merged,
4476
+ cachedAt,
4477
+ rev: ++this.revCounter
4478
+ });
4479
+ writes.push({
4480
+ key: this.rowKey(slug, key),
4481
+ entry: {
4482
+ value: dehydrateRow(merged),
4483
+ cachedAt
4484
+ }
4485
+ });
4486
+ }
4487
+ if (writes.length > 0) this.store.setCacheMany(writes).catch(() => void 0);
4488
+ if (deletes.length > 0) this.deleteCache(deletes);
4489
+ this.evictRows(slug);
4490
+ }
4491
+ /**
4492
+ * Fold the queued mutations for one row over a base, newest last.
4493
+ * `afterMutationId` skips everything up to and including that mutation,
4494
+ * which is how a just-replayed write avoids being applied on top of the
4495
+ * server's response to it.
4496
+ */
4497
+ applyPendingToRow(slug, idKey, base, afterMutationId) {
4498
+ let row = base;
4499
+ let skipping = afterMutationId !== void 0;
4500
+ for (const op of this.queue) {
4501
+ if (skipping) {
4502
+ if (op.mutationId === afterMutationId) skipping = false;
4503
+ continue;
4504
+ }
4505
+ if (op.collection !== slug) continue;
4506
+ if (op.type === "createMany") {
4507
+ const match = op.data?.find((r) => String(r.id) === idKey);
4508
+ if (match) row = { ...match };
4509
+ continue;
4510
+ }
4511
+ if (op.id === void 0 || String(op.id) !== idKey) continue;
4512
+ if (op.type === "create") row = { ...op.data };
4513
+ else if (op.type === "update") row = {
4514
+ ...row ?? {},
4515
+ ...op.data,
4516
+ id: op.id
4517
+ };
4518
+ else if (op.type === "delete") row = void 0;
4519
+ }
4520
+ return row;
4521
+ }
4522
+ recordSnapshot(slug, params, result) {
4523
+ const meta = result.meta ?? {
4524
+ total: result.data?.length ?? 0,
4525
+ limit: 20,
4526
+ offset: 0,
4527
+ hasMore: false
4528
+ };
4529
+ const snapshot = {
4530
+ ids: (result.data ?? []).map((row) => row.id).filter((id) => id !== void 0),
4531
+ total: meta.total ?? result.data?.length ?? 0,
4532
+ limit: meta.limit ?? params?.limit ?? 20,
4533
+ offset: meta.offset ?? params?.offset ?? 0,
4534
+ hasMore: meta.hasMore ?? false
4535
+ };
4536
+ const state = this.collectionState(slug);
4537
+ const key = buildQueryString(params);
4538
+ state.snapshots.set(key, snapshot);
4539
+ state.fresh.add(key);
4540
+ this.writeCache(`${this.scope}|q|${slug}|${key}`, snapshot);
4541
+ this.evictSnapshots(slug);
4542
+ return snapshot;
4543
+ }
4544
+ /**
4545
+ * A write changed which rows belong in a list, and only the server can say
4546
+ * how — a row it generated is in no cached page, and the totals moved.
4547
+ * Re-run every live query on the collection; queries nobody is watching
4548
+ * are corrected by their next `find`.
4549
+ *
4550
+ * Coalesced per microtask so a burst of writes costs one round trip, and
4551
+ * skipped entirely while offline, where the local database is already the
4552
+ * best answer available.
4553
+ */
4554
+ scheduleRefresh(slug) {
4555
+ if (this.refreshPending.has(slug)) return;
4556
+ const observers = this.observers.get(slug);
4557
+ if (!observers || observers.size === 0) return;
4558
+ this.refreshPending.add(slug);
4559
+ Promise.resolve().then(() => {
4560
+ this.refreshPending.delete(slug);
4561
+ if (this.disposed || !this.connectivity.shouldAttempt()) return;
4562
+ for (const observer of [...this.observers.get(slug) ?? []]) observer.refresh();
4563
+ });
4564
+ }
4565
+ evictRows(slug) {
4566
+ const state = this.collections.get(slug);
4567
+ if (!state || state.rows.size <= this.maxCachedRows) return;
4568
+ const evictable = [...state.rows.entries()].filter(([key]) => !this.hasPending(slug, key)).sort((a, b) => a[1].cachedAt - b[1].cachedAt);
4569
+ const excess = state.rows.size - this.maxCachedRows;
4570
+ const doomed = evictable.slice(0, excess);
4571
+ for (const [key] of doomed) state.rows.delete(key);
4572
+ if (doomed.length > 0) this.deleteCache(doomed.map(([key]) => this.rowKey(slug, key)));
4573
+ if (state.absent.size > this.maxCachedRows) {
4574
+ const stale = [...state.absent].slice(0, state.absent.size - this.maxCachedRows);
4575
+ for (const key of stale) state.absent.delete(key);
4576
+ this.deleteCache(stale.map((key) => this.absentKey(slug, key)));
4577
+ }
4578
+ }
4579
+ evictSnapshots(slug) {
4580
+ const state = this.collections.get(slug);
4581
+ if (!state || state.snapshots.size <= this.maxCachedQueries) return;
4582
+ const excess = state.snapshots.size - this.maxCachedQueries;
4583
+ const doomed = [...state.snapshots.keys()].slice(0, excess);
4584
+ for (const key of doomed) state.snapshots.delete(key);
4585
+ this.deleteCache(doomed.map((key) => `${this.scope}|q|${slug}|${key}`));
4586
+ }
4587
+ ensureQueueLoaded() {
4588
+ if (!this.queueLoad) {
4589
+ const scope = this.scope;
4590
+ this.queueLoad = this.store.listQueue(`${scope}|`).then((queue) => {
4591
+ if (this.scope !== scope) return;
4592
+ this.queue = queue;
4593
+ this.patchStatus({ pending: queue.length });
4594
+ this.notifyQueue();
4595
+ }).catch(() => void 0);
4596
+ }
4597
+ return this.queueLoad;
4598
+ }
4599
+ enqueue(mutation) {
4600
+ const result = this.enqueueChain.then(async () => {
4601
+ await this.ensureQueueLoaded();
4602
+ if (mutation.type === "update") {
4603
+ const tail = this.queue[this.queue.length - 1];
4604
+ if (tail && tail.collection === mutation.collection && (tail.type === "create" || tail.type === "update") && tail.id === mutation.id) {
4605
+ tail.data = {
4606
+ ...tail.data,
4607
+ ...mutation.data,
4608
+ id: tail.id
4609
+ };
4610
+ await this.store.enqueue(this.queueKey(tail), tail);
4611
+ return;
4612
+ }
4613
+ }
4614
+ if (mutation.type === "delete") {
4615
+ if (this.queue.some((m) => m.collection === mutation.collection && m.type === "create" && m.id === mutation.id && m.generatedId === true)) {
4616
+ const doomed = this.queue.filter((m) => m.collection === mutation.collection && m.id === mutation.id && (m.type === "create" || m.type === "update"));
4617
+ for (const op of doomed) await this.store.dequeue(this.queueKey(op));
4618
+ this.queue = this.queue.filter((m) => !doomed.includes(m));
4619
+ this.afterQueueChange();
4620
+ return;
4621
+ }
4622
+ }
4623
+ const full = {
4624
+ ...mutation,
4625
+ mutationId: createMutationId(),
4626
+ queuedAt: Date.now()
4627
+ };
4628
+ await this.store.enqueue(this.queueKey(full), full);
4629
+ this.queue.push(full);
4630
+ this.afterQueueChange();
4631
+ });
4632
+ this.enqueueChain = result.catch(() => void 0);
4633
+ return result;
4634
+ }
4635
+ hasPending(slug, id) {
4636
+ const key = String(id);
4637
+ return this.queue.some((op) => {
4638
+ if (op.collection !== slug) return false;
4639
+ if (op.type === "createMany") return op.data?.some((r) => String(r.id) === key) ?? false;
4640
+ return op.id !== void 0 && String(op.id) === key;
4641
+ });
4642
+ }
4643
+ /** Is this row one the server has never been told about? */
4644
+ isLocallyCreated(slug, idKey) {
4645
+ return this.queue.some((op) => {
4646
+ if (op.collection !== slug) return false;
4647
+ if (op.type === "create") return op.id !== void 0 && String(op.id) === idKey;
4648
+ if (op.type === "createMany") return op.data?.some((r) => String(r.id) === idKey) ?? false;
4649
+ return false;
4650
+ });
4651
+ }
4652
+ /** How many rows the queue adds to (or removes from) a server-side count. */
4653
+ pendingDelta(slug, params) {
4654
+ if (!isExactlyEvaluable(params)) return 0;
4655
+ let delta = 0;
4656
+ for (const op of this.queue) {
4657
+ if (op.collection !== slug) continue;
4658
+ if (op.type === "create") {
4659
+ if (matchesParams(op.data, params)) delta++;
4660
+ } else if (op.type === "createMany") {
4661
+ for (const row of op.data ?? []) if (matchesParams(row, params)) delta++;
4662
+ } else if (op.type === "delete") {
4663
+ const before = op.rollback?.rows?.[String(op.id)];
4664
+ if (before && matchesParams(before, params)) delta--;
4665
+ }
4666
+ }
4667
+ return delta;
4668
+ }
4669
+ sync() {
4670
+ if (this.flushPromise) return this.flushPromise;
4671
+ this.flushPromise = this.withLock(() => this.flush()).finally(() => {
4672
+ this.flushPromise = void 0;
4673
+ });
4674
+ return this.flushPromise;
4675
+ }
4676
+ async flush() {
4677
+ await this.ensureQueueLoaded();
4678
+ await this.reloadQueue();
4679
+ if (this.queue.length === 0) return {
4680
+ flushed: 0,
4681
+ remaining: 0
4682
+ };
4683
+ this.patchStatus({ syncing: true });
4684
+ const touched = /* @__PURE__ */ new Set();
4685
+ const queuedAtStart = this.queue.length;
4686
+ let flushed = 0;
4687
+ try {
4688
+ while (this.queue.length > 0 && !this.disposed) {
4689
+ const op = this.queue[0];
4690
+ touched.add(op.collection);
4691
+ try {
4692
+ await this.replay(op);
4693
+ } catch (error) {
4694
+ if (isNetworkError(error)) {
4695
+ this.connectivity.markFailure();
4696
+ break;
4697
+ }
4698
+ op.attempts = (op.attempts ?? 0) + 1;
4699
+ op.lastError = error?.message ?? String(error);
4700
+ if (isRetryableError(error) && op.attempts < this.maxRetries) {
4701
+ await this.store.enqueue(this.queueKey(op), op).catch(() => void 0);
4702
+ this.connectivity.deferRetry();
4703
+ this.patchStatus({ lastError: op.lastError });
4704
+ break;
4705
+ }
4706
+ await this.rejectMutation(op, error);
4707
+ continue;
4708
+ }
4709
+ this.connectivity.markSuccess();
4710
+ await this.drop(op);
4711
+ flushed++;
4712
+ }
4713
+ } finally {
4714
+ this.patchStatus({ syncing: false });
4715
+ }
4716
+ if (this.queue.length !== queuedAtStart) {
4717
+ for (const slug of touched) {
4718
+ this.notifyCollection(slug);
4719
+ this.scheduleRefresh(slug);
4720
+ }
4721
+ this.broadcast({ type: "queue" });
4722
+ }
4723
+ if (this.queue.length === 0) this.patchStatus({ lastSyncedAt: Date.now() });
4724
+ return {
4725
+ flushed,
4726
+ remaining: this.queue.length
4727
+ };
4728
+ }
4729
+ async replay(op) {
4730
+ const inner = this.innerFor(op.collection);
4731
+ if (op.type === "create") {
4732
+ const row = await inner.create(op.data);
4733
+ await this.adoptServerRow(op, op.id, row);
4734
+ } else if (op.type === "createMany") {
4735
+ const queued = op.data ?? [];
4736
+ const rows = await inner.createMany(queued, op.upsert ? { upsert: true } : void 0);
4737
+ for (let i = 0; i < rows.length; i++) await this.adoptServerRow(op, queued[i]?.id, rows[i]);
4738
+ } else if (op.type === "update") {
4739
+ const row = await inner.update(op.id, op.data);
4740
+ await this.ingestReplaced(op, op.id, row);
4741
+ } else if (op.type === "delete") {
4742
+ await inner.delete(op.id);
4743
+ this.removeLocalRow(op.collection, op.id, true);
4744
+ }
4745
+ }
4746
+ /**
4747
+ * Take the server's version of a row the client created offline.
4748
+ *
4749
+ * The server may have assigned a different id — a serial column ignores
4750
+ * the id we invented — in which case every local trace of the temporary id
4751
+ * has to move with it, including queued writes that were made against it
4752
+ * before it was ever sent.
4753
+ */
4754
+ async adoptServerRow(op, localId, row) {
4755
+ if (!row) return;
4756
+ const slug = op.collection;
4757
+ const serverId = row.id;
4758
+ if (localId !== void 0 && serverId !== void 0 && String(serverId) !== String(localId)) {
4759
+ const oldKey = String(localId);
4760
+ this.removeLocalRow(slug, localId);
4761
+ for (const queued of this.queue) {
4762
+ if (queued.collection !== slug) continue;
4763
+ let dirty = false;
4764
+ if (queued.id !== void 0 && String(queued.id) === oldKey) {
4765
+ queued.id = serverId;
4766
+ if (queued.data && !Array.isArray(queued.data)) queued.data.id = serverId;
4767
+ dirty = true;
4768
+ }
4769
+ const rollbackRows = queued.rollback?.rows;
4770
+ if (rollbackRows && oldKey in rollbackRows) {
4771
+ rollbackRows[String(serverId)] = rollbackRows[oldKey];
4772
+ delete rollbackRows[oldKey];
4773
+ dirty = true;
4774
+ }
4775
+ if (dirty) await this.store.enqueue(this.queueKey(queued), queued).catch(() => void 0);
4776
+ }
4777
+ }
4778
+ await this.ingestReplaced(op, serverId ?? localId, row);
4779
+ }
4780
+ /**
4781
+ * Write a server row over the local one, ignoring the mutation that just
4782
+ * produced it — re-applying that would put the pre-server values back on
4783
+ * top of the server's answer — but keeping every write queued *after* it.
4784
+ * Those are still unsent, and dropping them here would make the row snap
4785
+ * back to the server's version in front of the user, only to change again
4786
+ * when they replay a moment later.
4787
+ */
4788
+ async ingestReplaced(op, id, row) {
4789
+ const slug = op.collection;
4790
+ const state = await this.ensureCollection(slug);
4791
+ const key = String(id);
4792
+ const merged = this.applyPendingToRow(slug, key, { ...row }, op.mutationId);
4793
+ if (merged === void 0) {
4794
+ this.removeLocalRow(slug, key);
4795
+ return;
4796
+ }
4797
+ const cachedAt = Date.now();
4798
+ state.rows.set(key, {
4799
+ row: merged,
4800
+ cachedAt,
4801
+ rev: ++this.revCounter
4802
+ });
4803
+ if (this.applyPendingToRow(slug, key, void 0, op.mutationId) === void 0) state.freshRows.add(key);
4804
+ this.writeCache(this.rowKey(slug, key), dehydrateRow(merged), cachedAt);
4805
+ }
4806
+ /**
4807
+ * The server refused a mutation. Put back what it changed, and discard the
4808
+ * queued writes that were built on top of it: an edit to a row whose
4809
+ * creation was rejected can only fail the same way, and applying it would
4810
+ * leave the local database claiming a row the server does not have.
4811
+ *
4812
+ * The cascade stops the moment a later write stops *depending* on the
4813
+ * rejected one. An `update` reads the row it edits, so it is doomed with
4814
+ * it; a `create` overwrites the row outright and a `delete` needs nothing
4815
+ * of it, so both stand on their own and are kept — dropping them would
4816
+ * silently lose writes the server would have accepted.
4817
+ */
4818
+ async rejectMutation(op, error) {
4819
+ const ids = new Set(Object.keys(op.rollback?.rows ?? {}));
4820
+ if (op.id !== void 0) ids.add(String(op.id));
4821
+ const doomed = [op];
4822
+ const orphaned = new Set(ids);
4823
+ const position = this.queue.indexOf(op);
4824
+ for (const later of this.queue.slice(position + 1)) {
4825
+ if (later.collection !== op.collection) continue;
4826
+ const hit = this.idsOf(later).filter((id) => orphaned.has(id));
4827
+ if (hit.length === 0) continue;
4828
+ if (later.type === "update") doomed.push(later);
4829
+ else for (const id of hit) orphaned.delete(id);
4830
+ }
4831
+ for (const dropped of doomed) await this.drop(dropped);
4832
+ for (const [idKey, previous] of Object.entries(op.rollback?.rows ?? {})) {
4833
+ const restored = this.applyPendingToRow(op.collection, idKey, previous ?? void 0);
4834
+ if (restored === void 0) this.removeLocalRow(op.collection, idKey);
4835
+ else this.setLocalRow(op.collection, idKey, restored);
4836
+ }
4837
+ this.patchStatus({ lastError: error.message });
4838
+ this.notifyCollection(op.collection);
4839
+ this.scheduleRefresh(op.collection);
4840
+ for (const dropped of doomed) this.onSyncError?.(error, dropped);
4841
+ }
4842
+ /** Every row id a mutation writes to. */
4843
+ idsOf(op) {
4844
+ if (op.type === "createMany") return (op.data ?? []).map((r) => String(r.id));
4845
+ return op.id === void 0 ? [] : [String(op.id)];
4846
+ }
4847
+ async drop(op) {
4848
+ await this.store.dequeue(this.queueKey(op)).catch(() => void 0);
4849
+ this.queue = this.queue.filter((m) => m.mutationId !== op.mutationId);
4850
+ this.afterQueueChange(false);
4851
+ }
4852
+ /** Replay uses unwrapped clients: a failure must never re-enqueue itself. */
4853
+ innerFor(slug) {
4854
+ let inner = this.inners.get(slug);
4855
+ if (!inner) {
4856
+ inner = this.createInner(slug);
4857
+ this.inners.set(slug, inner);
4858
+ }
4859
+ return inner;
4860
+ }
4861
+ async withLock(fn) {
4862
+ const locks = globalThis.navigator?.locks;
4863
+ if (!locks?.request) return fn();
4864
+ try {
4865
+ return await locks.request(`rebase-offline-sync:${this.scope}`, fn);
4866
+ } catch {
4867
+ return fn();
4868
+ }
4869
+ }
4870
+ broadcast(message) {
4871
+ if (!this.channel) return;
4872
+ try {
4873
+ this.channel.postMessage({
4874
+ ...message,
4875
+ scope: this.scope,
4876
+ sender: this.tabId
4877
+ });
4878
+ } catch {}
4879
+ }
4880
+ onBroadcast(message) {
4881
+ if (this.disposed || !message || typeof message !== "object") return;
4882
+ const msg = message;
4883
+ if (msg.sender === this.tabId || msg.scope !== this.scope) return;
4884
+ if (msg.type === "rows") for (const slug of msg.slugs ?? []) this.reloadCollection(slug);
4885
+ else if (msg.type === "queue") this.reloadQueue();
4886
+ }
4887
+ /** Re-read one collection from the store, replacing what is in memory. */
4888
+ async reloadCollection(slug) {
4889
+ const state = this.collections.get(slug);
4890
+ if (!state?.loaded) return;
4891
+ await this.reloadQueue();
4892
+ const scope = this.scope;
4893
+ const [rows, snapshots, absent] = await Promise.all([
4894
+ this.store.listCacheEntries(`${scope}|row|${slug}|`).catch(() => []),
4895
+ this.store.listCacheEntries(`${scope}|q|${slug}|`).catch(() => []),
4896
+ this.store.listCache(`${scope}|abs|${slug}|`).catch(() => [])
4897
+ ]);
4898
+ if (this.scope !== scope || this.collections.get(slug) !== state) return;
4899
+ const next = /* @__PURE__ */ new Map();
4900
+ for (const entry of rows) {
4901
+ const row = entry.value;
4902
+ if (!row || row.id === void 0 || row.id === null) continue;
4903
+ const key = String(row.id);
4904
+ const existing = state.rows.get(key);
4905
+ const hydrated = hydrateRow(row);
4906
+ const unchanged = existing && JSON.stringify(existing.row) === JSON.stringify(hydrated);
4907
+ next.set(key, {
4908
+ row: hydrated,
4909
+ cachedAt: entry.cachedAt,
4910
+ rev: unchanged ? existing.rev : ++this.revCounter
4911
+ });
4912
+ }
4913
+ state.rows = next;
4914
+ state.snapshots = /* @__PURE__ */ new Map();
4915
+ for (const entry of snapshots) {
4916
+ const key = entry.key.slice(`${scope}|q|${slug}|`.length);
4917
+ if (entry.value) state.snapshots.set(key, entry.value);
4918
+ }
4919
+ state.absent = new Set(absent.map((entry) => entry.key.slice(`${scope}|abs|${slug}|`.length)));
4920
+ this.notifyCollection(slug, false);
4921
+ }
4922
+ async reloadQueue() {
4923
+ const scope = this.scope;
4924
+ const queue = await this.store.listQueue(`${scope}|`).catch(() => void 0);
4925
+ if (!queue || this.scope !== scope) return;
4926
+ this.queue = queue;
4927
+ this.afterQueueChange(false);
4928
+ }
4929
+ afterQueueChange(broadcast = true) {
4930
+ this.patchStatus({ pending: this.queue.length });
4931
+ this.notifyQueue();
4932
+ if (broadcast) this.broadcast({ type: "queue" });
4933
+ }
4934
+ notifyQueue() {
4935
+ for (const listener of this.queueListeners) listener(this.queue.length);
4936
+ }
4937
+ patchStatus(patch) {
4938
+ let changed = false;
4939
+ for (const [key, value] of Object.entries(patch)) if (this.currentStatus[key] !== value) {
4940
+ this.currentStatus[key] = value;
4941
+ changed = true;
4942
+ }
4943
+ if (!changed) return;
4944
+ const snapshot = { ...this.currentStatus };
4945
+ for (const listener of this.statusListeners) listener(snapshot);
4946
+ }
4947
+ countKey(slug, params) {
4948
+ return `${this.scope}|count|${slug}|${buildQueryString(params)}`;
4949
+ }
4950
+ rowKey(slug, id) {
4951
+ return `${this.scope}|row|${slug}|${String(id)}`;
4952
+ }
4953
+ absentKey(slug, id) {
4954
+ return `${this.scope}|abs|${slug}|${String(id)}`;
4955
+ }
4956
+ queueKey(mutation) {
4957
+ return `${this.scope}|${mutation.mutationId}`;
4958
+ }
4959
+ async readCache(key) {
4960
+ try {
4961
+ return (await this.store.getCache(key))?.value;
4962
+ } catch {
4963
+ return;
4964
+ }
4965
+ }
4966
+ async writeCache(key, value, cachedAt = Date.now()) {
4967
+ try {
4968
+ await this.store.setCache(key, {
4969
+ value,
4970
+ cachedAt
4971
+ });
4972
+ } catch {}
4973
+ }
4974
+ async deleteCache(keys) {
4975
+ try {
4976
+ await this.store.deleteCache(keys);
4977
+ } catch {}
4978
+ }
4979
+ };
4980
+ //#endregion
2958
4981
  //#region src/index.ts
2959
4982
  /**
2960
4983
  * Derive a WebSocket URL from an HTTP base URL.
@@ -3079,10 +5102,20 @@ function createRebaseClient(options) {
3079
5102
  if (diffs <= 1) return key;
3080
5103
  }
3081
5104
  }
5105
+ const offlineManager = options.offline ? new OfflineManager(typeof options.offline === "object" ? options.offline : {}, (slug) => createCollectionClient(transport, slug)) : void 0;
5106
+ if (offlineManager) {
5107
+ offlineManager.setScope(auth.getSession()?.user?.uid);
5108
+ auth.onAuthStateChange((event, session) => {
5109
+ offlineManager.setScope(event === "SIGNED_OUT" ? void 0 : session?.user?.uid);
5110
+ });
5111
+ }
3082
5112
  const collectionClients = /* @__PURE__ */ new Map();
3083
5113
  let untypedWarned = false;
3084
5114
  function collection(slug) {
3085
- if (!collectionClients.has(slug)) collectionClients.set(slug, createCollectionClient(transport, slug, ws));
5115
+ if (!collectionClients.has(slug)) {
5116
+ const inner = createCollectionClient(transport, slug, ws);
5117
+ collectionClients.set(slug, offlineManager ? offlineManager.wrap(slug, inner) : inner);
5118
+ }
3086
5119
  return collectionClients.get(slug);
3087
5120
  }
3088
5121
  const dataProxy = new Proxy({ collection }, { get(_target, prop) {
@@ -3146,6 +5179,7 @@ channel: (name, options) => {
3146
5179
  for (const channel of realtimeChannels.values()) channel.leave();
3147
5180
  realtimeChannels.clear();
3148
5181
  ws?.disconnect(true);
5182
+ offlineManager?.dispose();
3149
5183
  },
3150
5184
  setToken: transport.setToken,
3151
5185
  setAuthTokenGetter: transport.setAuthTokenGetter,
@@ -3161,10 +5195,11 @@ channel: (name, options) => {
3161
5195
  });
3162
5196
  return res.data ?? res;
3163
5197
  },
3164
- data: dataProxy
5198
+ data: dataProxy,
5199
+ ...offlineManager ? { offline: offlineManager.api } : {}
3165
5200
  };
3166
5201
  }
3167
5202
  //#endregion
3168
- export { QueryBuilder, RebaseApiError, RebaseClientError, RebaseRealtimeChannel, RebaseWebSocketClient, and, cond, createBackups, createCookieStorage, createMemoryStorage, createRebaseClient, or };
5203
+ export { MemoryOfflineStore, QueryBuilder, RebaseApiError, RebaseClientError, RebaseRealtimeChannel, RebaseWebSocketClient, and, cond, createBackups, createCookieStorage, createMemoryStorage, createRebaseClient, isOfflineError, or };
3169
5204
 
3170
5205
  //# sourceMappingURL=index.es.js.map