@rebasepro/server 0.10.0 → 0.10.1-canary.31c773c
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 +1959 -14
- package/dist/index.es.js.map +1 -1
- package/package.json +5 -5
package/dist/index.es.js
CHANGED
|
@@ -13,7 +13,7 @@ import path, { join } from "path";
|
|
|
13
13
|
import { pathToFileURL } from "url";
|
|
14
14
|
import { Hono } from "hono";
|
|
15
15
|
import { promisify } from "util";
|
|
16
|
-
import * as crypto from "crypto";
|
|
16
|
+
import * as crypto$1 from "crypto";
|
|
17
17
|
import { createCipheriv, createDecipheriv, createHash as createHash$1, createHmac, randomBytes as randomBytes$1, randomUUID as randomUUID$1, scrypt, timingSafeEqual } from "crypto";
|
|
18
18
|
import { bodyLimit } from "hono/body-limit";
|
|
19
19
|
import { csrf } from "hono/csrf";
|
|
@@ -1007,7 +1007,7 @@ function deepClone(value) {
|
|
|
1007
1007
|
function isObject$1(item) {
|
|
1008
1008
|
return !!item && typeof item === "object" && !Array.isArray(item);
|
|
1009
1009
|
}
|
|
1010
|
-
function isPlainObject$
|
|
1010
|
+
function isPlainObject$2(obj) {
|
|
1011
1011
|
if (typeof obj !== "object" || obj === null || Array.isArray(obj)) return false;
|
|
1012
1012
|
return Object.getPrototypeOf(obj) === Object.prototype;
|
|
1013
1013
|
}
|
|
@@ -1022,7 +1022,7 @@ function mergeDeep(target, source, ignoreUndefined = false) {
|
|
|
1022
1022
|
const outputValue = output[key];
|
|
1023
1023
|
if (ignoreUndefined && sourceValue === void 0) continue;
|
|
1024
1024
|
if (sourceValue instanceof Date) output[key] = new Date(sourceValue.getTime());
|
|
1025
|
-
else if (Array.isArray(sourceValue)) if (Array.isArray(outputValue)) if (!(sourceValue.some(isPlainObject$
|
|
1025
|
+
else if (Array.isArray(sourceValue)) if (Array.isArray(outputValue)) if (!(sourceValue.some(isPlainObject$2) || outputValue.some(isPlainObject$2))) output[key] = [...sourceValue];
|
|
1026
1026
|
else {
|
|
1027
1027
|
const newArray = [];
|
|
1028
1028
|
const maxLength = Math.max(outputValue.length, sourceValue.length);
|
|
@@ -1032,13 +1032,13 @@ function mergeDeep(target, source, ignoreUndefined = false) {
|
|
|
1032
1032
|
if (i >= sourceValue.length) newArray[i] = targetItem;
|
|
1033
1033
|
else if (i >= outputValue.length) newArray[i] = sourceItem;
|
|
1034
1034
|
else if (sourceItem === null) newArray[i] = targetItem;
|
|
1035
|
-
else if (isPlainObject$
|
|
1035
|
+
else if (isPlainObject$2(sourceItem) && isPlainObject$2(targetItem)) newArray[i] = mergeDeep(targetItem, sourceItem, ignoreUndefined);
|
|
1036
1036
|
else newArray[i] = sourceItem;
|
|
1037
1037
|
}
|
|
1038
1038
|
output[key] = newArray;
|
|
1039
1039
|
}
|
|
1040
1040
|
else output[key] = [...sourceValue];
|
|
1041
|
-
else if (isPlainObject$
|
|
1041
|
+
else if (isPlainObject$2(sourceValue)) if (isPlainObject$2(outputValue)) output[key] = mergeDeep(outputValue, sourceValue, ignoreUndefined);
|
|
1042
1042
|
else output[key] = sourceValue;
|
|
1043
1043
|
else if (isObject$1(sourceValue)) output[key] = sourceValue;
|
|
1044
1044
|
else output[key] = sourceValue;
|
|
@@ -1051,7 +1051,7 @@ function removeFunctions(o) {
|
|
|
1051
1051
|
if (o === null) return null;
|
|
1052
1052
|
if (typeof o === "object") {
|
|
1053
1053
|
if (Array.isArray(o)) return o.map((v) => removeFunctions(v));
|
|
1054
|
-
if (!isPlainObject$
|
|
1054
|
+
if (!isPlainObject$2(o)) return o;
|
|
1055
1055
|
return Object.entries(o).filter(([_, value]) => typeof value !== "function").map(([key, value]) => {
|
|
1056
1056
|
if (Array.isArray(value)) return { [key]: value.map((v) => removeFunctions(v)) };
|
|
1057
1057
|
else if (typeof value === "object") return { [key]: removeFunctions(value) };
|
|
@@ -6114,7 +6114,7 @@ var allowsEval = /* @__PURE__*/ cached(() => {
|
|
|
6114
6114
|
return false;
|
|
6115
6115
|
}
|
|
6116
6116
|
});
|
|
6117
|
-
function isPlainObject(o) {
|
|
6117
|
+
function isPlainObject$1(o) {
|
|
6118
6118
|
if (isObject(o) === false) return false;
|
|
6119
6119
|
const ctor = o.constructor;
|
|
6120
6120
|
if (ctor === void 0) return true;
|
|
@@ -6125,7 +6125,7 @@ function isPlainObject(o) {
|
|
|
6125
6125
|
return true;
|
|
6126
6126
|
}
|
|
6127
6127
|
function shallowClone(o) {
|
|
6128
|
-
if (isPlainObject(o)) return { ...o };
|
|
6128
|
+
if (isPlainObject$1(o)) return { ...o };
|
|
6129
6129
|
if (Array.isArray(o)) return [...o];
|
|
6130
6130
|
if (o instanceof Map) return new Map(o);
|
|
6131
6131
|
if (o instanceof Set) return new Set(o);
|
|
@@ -6202,7 +6202,7 @@ function omit(schema, mask) {
|
|
|
6202
6202
|
}));
|
|
6203
6203
|
}
|
|
6204
6204
|
function extend(schema, shape) {
|
|
6205
|
-
if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
|
|
6205
|
+
if (!isPlainObject$1(shape)) throw new Error("Invalid input to extend: expected a plain object");
|
|
6206
6206
|
const checks = schema._zod.def.checks;
|
|
6207
6207
|
if (checks && checks.length > 0) {
|
|
6208
6208
|
const existingShape = schema._zod.def.shape;
|
|
@@ -6218,7 +6218,7 @@ function extend(schema, shape) {
|
|
|
6218
6218
|
} }));
|
|
6219
6219
|
}
|
|
6220
6220
|
function safeExtend(schema, shape) {
|
|
6221
|
-
if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
|
|
6221
|
+
if (!isPlainObject$1(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
|
|
6222
6222
|
return clone(schema, mergeDefs(schema._zod.def, { get shape() {
|
|
6223
6223
|
const _shape = {
|
|
6224
6224
|
...schema._zod.def.shape,
|
|
@@ -7569,7 +7569,7 @@ function mergeValues(a, b) {
|
|
|
7569
7569
|
valid: true,
|
|
7570
7570
|
data: a
|
|
7571
7571
|
};
|
|
7572
|
-
if (isPlainObject(a) && isPlainObject(b)) {
|
|
7572
|
+
if (isPlainObject$1(a) && isPlainObject$1(b)) {
|
|
7573
7573
|
const bKeys = Object.keys(b);
|
|
7574
7574
|
const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
|
|
7575
7575
|
const newObj = {
|
|
@@ -15833,6 +15833,44 @@ function createCollectionClient(transport, slug, ws) {
|
|
|
15833
15833
|
});
|
|
15834
15834
|
return (await transport.request(basePath + "/count" + qs, { method: "GET" })).count ?? 0;
|
|
15835
15835
|
},
|
|
15836
|
+
observe(params, onResult, onError, options) {
|
|
15837
|
+
let closed = false;
|
|
15838
|
+
const emit = (result) => {
|
|
15839
|
+
if (closed) return;
|
|
15840
|
+
onResult({
|
|
15841
|
+
...result,
|
|
15842
|
+
fromCache: false,
|
|
15843
|
+
hasPendingWrites: false,
|
|
15844
|
+
partial: false
|
|
15845
|
+
});
|
|
15846
|
+
};
|
|
15847
|
+
client.find(params).then(emit).catch((error) => {
|
|
15848
|
+
if (!closed) onError?.(error);
|
|
15849
|
+
});
|
|
15850
|
+
const live = options?.realtime !== false && client.listen ? client.listen(params, emit, onError) : void 0;
|
|
15851
|
+
return () => {
|
|
15852
|
+
closed = true;
|
|
15853
|
+
live?.();
|
|
15854
|
+
};
|
|
15855
|
+
},
|
|
15856
|
+
observeById(id, onResult, onError, options) {
|
|
15857
|
+
let closed = false;
|
|
15858
|
+
const emit = (row) => {
|
|
15859
|
+
if (closed) return;
|
|
15860
|
+
onResult(row, {
|
|
15861
|
+
fromCache: false,
|
|
15862
|
+
hasPendingWrites: false
|
|
15863
|
+
});
|
|
15864
|
+
};
|
|
15865
|
+
client.findById(id).then(emit).catch((error) => {
|
|
15866
|
+
if (!closed) onError?.(error);
|
|
15867
|
+
});
|
|
15868
|
+
const live = options?.realtime !== false && client.listenById ? client.listenById(id, emit, onError) : void 0;
|
|
15869
|
+
return () => {
|
|
15870
|
+
closed = true;
|
|
15871
|
+
live?.();
|
|
15872
|
+
};
|
|
15873
|
+
},
|
|
15836
15874
|
where(columnOrCondition, operator, value) {
|
|
15837
15875
|
const builder = new SDKQueryBuilder(client);
|
|
15838
15876
|
if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
|
|
@@ -17633,6 +17671,1901 @@ var RebaseRealtimeChannel = class {
|
|
|
17633
17671
|
}
|
|
17634
17672
|
};
|
|
17635
17673
|
/**
|
|
17674
|
+
* Lossless round-tripping of rows through the offline store.
|
|
17675
|
+
*
|
|
17676
|
+
* Both persistence backends move values by structured clone, which keeps
|
|
17677
|
+
* `Date` but flattens every class instance to a plain object. For
|
|
17678
|
+
* `EntityReference`/`EntityRelation` that is harmless — they carry their own
|
|
17679
|
+
* `__type` discriminator, so the JSON reviver can rebuild them — but
|
|
17680
|
+
* `GeoPoint` and `Vector` do not, and would come back out of the cache as
|
|
17681
|
+
* anonymous `{ latitude, longitude }` / `{ value }` bags. A row read from the
|
|
17682
|
+
* cache must be indistinguishable from the same row read from the network, so
|
|
17683
|
+
* those two are tagged on the way in and revived on the way out.
|
|
17684
|
+
*
|
|
17685
|
+
* Type tests here are structural rather than `instanceof`, because a structured
|
|
17686
|
+
* clone can arrive from another realm — an iframe, a worker, or the polyfill
|
|
17687
|
+
* the tests run against — where the constructor identity differs but the value
|
|
17688
|
+
* is the real thing. Only *plain* objects are walked; anything else is passed
|
|
17689
|
+
* through whole, so a class instance is never quietly reduced to `{}`.
|
|
17690
|
+
*/
|
|
17691
|
+
function isDate(value) {
|
|
17692
|
+
return Object.prototype.toString.call(value) === "[object Date]";
|
|
17693
|
+
}
|
|
17694
|
+
/** An object literal — not a Date, RegExp, Map, or any class instance. */
|
|
17695
|
+
function isPlainObject(value) {
|
|
17696
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
17697
|
+
const proto = Object.getPrototypeOf(value);
|
|
17698
|
+
if (proto === null || proto === Object.prototype) return true;
|
|
17699
|
+
return proto.constructor?.name === "Object";
|
|
17700
|
+
}
|
|
17701
|
+
function dehydrateValue(value) {
|
|
17702
|
+
if (value === null || value === void 0) return value;
|
|
17703
|
+
if (value instanceof GeoPoint) return {
|
|
17704
|
+
__type: "GeoPoint",
|
|
17705
|
+
latitude: value.latitude,
|
|
17706
|
+
longitude: value.longitude
|
|
17707
|
+
};
|
|
17708
|
+
if (value instanceof Vector) return {
|
|
17709
|
+
__type: "Vector",
|
|
17710
|
+
value: [...value.value]
|
|
17711
|
+
};
|
|
17712
|
+
if (value instanceof EntityReference || value instanceof EntityRelation) return value;
|
|
17713
|
+
if (Array.isArray(value)) return value.map(dehydrateValue);
|
|
17714
|
+
if (isPlainObject(value)) {
|
|
17715
|
+
const out = {};
|
|
17716
|
+
for (const [key, inner] of Object.entries(value)) out[key] = dehydrateValue(inner);
|
|
17717
|
+
return out;
|
|
17718
|
+
}
|
|
17719
|
+
return value;
|
|
17720
|
+
}
|
|
17721
|
+
function hydrateValue(value) {
|
|
17722
|
+
if (value === null || value === void 0 || isDate(value)) return value;
|
|
17723
|
+
if (Array.isArray(value)) return value.map(hydrateValue);
|
|
17724
|
+
if (typeof value === "object") {
|
|
17725
|
+
const revived = rebaseReviver("", value);
|
|
17726
|
+
if (revived !== value) return revived;
|
|
17727
|
+
if (!isPlainObject(value)) return value;
|
|
17728
|
+
const out = {};
|
|
17729
|
+
for (const [key, inner] of Object.entries(value)) out[key] = hydrateValue(inner);
|
|
17730
|
+
return out;
|
|
17731
|
+
}
|
|
17732
|
+
return value;
|
|
17733
|
+
}
|
|
17734
|
+
/** Prepare a row for the store. */
|
|
17735
|
+
function dehydrateRow(row) {
|
|
17736
|
+
return dehydrateValue(row);
|
|
17737
|
+
}
|
|
17738
|
+
/** Restore a row read back from the store. */
|
|
17739
|
+
function hydrateRow(row) {
|
|
17740
|
+
return hydrateValue(row);
|
|
17741
|
+
}
|
|
17742
|
+
/**
|
|
17743
|
+
* Whether the network is worth trying, and when to try again after it wasn't.
|
|
17744
|
+
*
|
|
17745
|
+
* `navigator.onLine` is necessary but not sufficient: it reports the state of
|
|
17746
|
+
* the network interface, so it stays `true` behind a captive portal, on a
|
|
17747
|
+
* connection that resolves DNS but reaches nothing, and while the API itself
|
|
17748
|
+
* is down. This tracks what actually happened to requests as well, so the
|
|
17749
|
+
* first failure is the only one an app pays for — everything after it inside
|
|
17750
|
+
* the backoff window skips the doomed round trip and answers from the local
|
|
17751
|
+
* store immediately, which is the difference between an app that freezes when
|
|
17752
|
+
* the wifi drops and one that does not.
|
|
17753
|
+
*/
|
|
17754
|
+
/** The request never reached the server, so nothing was decided by it. */
|
|
17755
|
+
function isNetworkError(error) {
|
|
17756
|
+
if (error instanceof RebaseApiError) return error.status === 0;
|
|
17757
|
+
if (error instanceof TypeError) return true;
|
|
17758
|
+
const name = error?.name;
|
|
17759
|
+
return name === "AbortError" || name === "TimeoutError" || name === "NetworkError";
|
|
17760
|
+
}
|
|
17761
|
+
/**
|
|
17762
|
+
* Statuses that mean "not now" rather than "not ever": a queued write that
|
|
17763
|
+
* gets one of these is worth replaying, while a 400 or a 403 never will be.
|
|
17764
|
+
* 500 is deliberately absent — an unhandled server error is far more often a
|
|
17765
|
+
* bug the same payload will hit again than a blip, and retrying it forever
|
|
17766
|
+
* jams every write behind it.
|
|
17767
|
+
*/
|
|
17768
|
+
var RETRYABLE_STATUSES = new Set([
|
|
17769
|
+
408,
|
|
17770
|
+
425,
|
|
17771
|
+
429,
|
|
17772
|
+
502,
|
|
17773
|
+
503,
|
|
17774
|
+
504
|
|
17775
|
+
]);
|
|
17776
|
+
/** Is this failure worth another attempt later? */
|
|
17777
|
+
function isRetryableError(error) {
|
|
17778
|
+
if (isNetworkError(error)) return true;
|
|
17779
|
+
if (error instanceof RebaseApiError) return error.status !== void 0 && RETRYABLE_STATUSES.has(error.status);
|
|
17780
|
+
return false;
|
|
17781
|
+
}
|
|
17782
|
+
var ConnectivityMonitor = class {
|
|
17783
|
+
state = "online";
|
|
17784
|
+
backoffMs;
|
|
17785
|
+
initialBackoffMs;
|
|
17786
|
+
maxBackoffMs;
|
|
17787
|
+
retryAt = 0;
|
|
17788
|
+
timer;
|
|
17789
|
+
listeners = /* @__PURE__ */ new Set();
|
|
17790
|
+
respectBackoff;
|
|
17791
|
+
now;
|
|
17792
|
+
setTimer;
|
|
17793
|
+
clearTimer;
|
|
17794
|
+
/** Called when the backoff window expires, to drive an automatic retry. */
|
|
17795
|
+
onRetryDue;
|
|
17796
|
+
handleOnline = () => {
|
|
17797
|
+
this.retryAt = 0;
|
|
17798
|
+
this.backoffMs = this.initialBackoffMs;
|
|
17799
|
+
this.clearPendingTimer();
|
|
17800
|
+
this.setState("online");
|
|
17801
|
+
this.onRetryDue?.();
|
|
17802
|
+
};
|
|
17803
|
+
handleOffline = () => {
|
|
17804
|
+
this.setState("offline");
|
|
17805
|
+
};
|
|
17806
|
+
constructor(options = {}) {
|
|
17807
|
+
this.initialBackoffMs = options.initialBackoffMs ?? 1e3;
|
|
17808
|
+
this.maxBackoffMs = Math.max(this.initialBackoffMs, options.maxBackoffMs ?? 6e4);
|
|
17809
|
+
this.backoffMs = this.initialBackoffMs;
|
|
17810
|
+
this.respectBackoff = options.respectBackoff ?? true;
|
|
17811
|
+
this.now = options.now ?? (() => Date.now());
|
|
17812
|
+
this.setTimer = options.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
|
|
17813
|
+
this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle));
|
|
17814
|
+
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
|
|
17815
|
+
window.addEventListener("online", this.handleOnline);
|
|
17816
|
+
window.addEventListener("offline", this.handleOffline);
|
|
17817
|
+
}
|
|
17818
|
+
if (typeof navigator !== "undefined" && navigator.onLine === false) this.state = "offline";
|
|
17819
|
+
}
|
|
17820
|
+
/** What the app should be told: are we connected? */
|
|
17821
|
+
isOnline() {
|
|
17822
|
+
if (typeof navigator !== "undefined" && navigator.onLine === false) return false;
|
|
17823
|
+
return this.state === "online";
|
|
17824
|
+
}
|
|
17825
|
+
/**
|
|
17826
|
+
* Should this request even be sent? False means "answer from the local
|
|
17827
|
+
* store instead" — the request would only burn a timeout to reach the same
|
|
17828
|
+
* conclusion the last one already did.
|
|
17829
|
+
*/
|
|
17830
|
+
shouldAttempt() {
|
|
17831
|
+
if (typeof navigator !== "undefined" && navigator.onLine === false) return false;
|
|
17832
|
+
if (this.state === "online" || !this.respectBackoff) return true;
|
|
17833
|
+
return this.now() >= this.retryAt;
|
|
17834
|
+
}
|
|
17835
|
+
/** A request reached the server. */
|
|
17836
|
+
markSuccess() {
|
|
17837
|
+
this.backoffMs = this.initialBackoffMs;
|
|
17838
|
+
this.retryAt = 0;
|
|
17839
|
+
this.clearPendingTimer();
|
|
17840
|
+
this.setState("online");
|
|
17841
|
+
}
|
|
17842
|
+
/** A request did not reach the server: we are offline until proven otherwise. */
|
|
17843
|
+
markFailure() {
|
|
17844
|
+
this.deferRetry();
|
|
17845
|
+
this.setState("offline");
|
|
17846
|
+
}
|
|
17847
|
+
/**
|
|
17848
|
+
* Back off and try again later without claiming the connection is gone.
|
|
17849
|
+
* This is what a 429 or a 503 deserves — the server answered, so the app
|
|
17850
|
+
* is demonstrably online; it just should not hammer.
|
|
17851
|
+
*/
|
|
17852
|
+
deferRetry() {
|
|
17853
|
+
const jitter = .8 + Math.random() * .4;
|
|
17854
|
+
this.retryAt = this.now() + this.backoffMs * jitter;
|
|
17855
|
+
const delay = Math.max(0, this.retryAt - this.now());
|
|
17856
|
+
this.backoffMs = Math.min(this.maxBackoffMs, this.backoffMs * 2);
|
|
17857
|
+
this.scheduleRetry(delay);
|
|
17858
|
+
}
|
|
17859
|
+
/** Milliseconds until the next attempt is allowed; 0 when one is allowed now. */
|
|
17860
|
+
msUntilRetry() {
|
|
17861
|
+
if (this.state === "online") return 0;
|
|
17862
|
+
return Math.max(0, this.retryAt - this.now());
|
|
17863
|
+
}
|
|
17864
|
+
onChange(listener) {
|
|
17865
|
+
this.listeners.add(listener);
|
|
17866
|
+
return () => this.listeners.delete(listener);
|
|
17867
|
+
}
|
|
17868
|
+
dispose() {
|
|
17869
|
+
if (typeof window !== "undefined" && typeof window.removeEventListener === "function") {
|
|
17870
|
+
window.removeEventListener("online", this.handleOnline);
|
|
17871
|
+
window.removeEventListener("offline", this.handleOffline);
|
|
17872
|
+
}
|
|
17873
|
+
this.clearPendingTimer();
|
|
17874
|
+
this.listeners.clear();
|
|
17875
|
+
this.onRetryDue = void 0;
|
|
17876
|
+
}
|
|
17877
|
+
scheduleRetry(delay) {
|
|
17878
|
+
this.clearPendingTimer();
|
|
17879
|
+
if (!this.onRetryDue) return;
|
|
17880
|
+
this.timer = this.setTimer(() => {
|
|
17881
|
+
this.timer = void 0;
|
|
17882
|
+
this.onRetryDue?.();
|
|
17883
|
+
}, delay);
|
|
17884
|
+
this.timer.unref?.();
|
|
17885
|
+
}
|
|
17886
|
+
clearPendingTimer() {
|
|
17887
|
+
if (this.timer !== void 0) {
|
|
17888
|
+
this.clearTimer(this.timer);
|
|
17889
|
+
this.timer = void 0;
|
|
17890
|
+
}
|
|
17891
|
+
}
|
|
17892
|
+
setState(next) {
|
|
17893
|
+
if (this.state === next) return;
|
|
17894
|
+
this.state = next;
|
|
17895
|
+
const online = this.isOnline();
|
|
17896
|
+
for (const listener of this.listeners) listener(online);
|
|
17897
|
+
}
|
|
17898
|
+
};
|
|
17899
|
+
/**
|
|
17900
|
+
* Monotonic within a tab, unique across tabs, and sortable as a plain string:
|
|
17901
|
+
* `<ms base36, padded>-<counter>-<random>`. The padding is what keeps
|
|
17902
|
+
* lexicographic order equal to chronological order, and the random suffix is
|
|
17903
|
+
* what stops two tabs from writing the same queue key in the same millisecond
|
|
17904
|
+
* — which would silently drop one of the two writes.
|
|
17905
|
+
*/
|
|
17906
|
+
var mutationCounter = 0;
|
|
17907
|
+
function createMutationId(now = Date.now()) {
|
|
17908
|
+
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")}`;
|
|
17909
|
+
}
|
|
17910
|
+
/**
|
|
17911
|
+
* In-memory store: the default outside the browser and the workhorse of the
|
|
17912
|
+
* test suite. Values are deep-copied on the way in and out so a caller
|
|
17913
|
+
* mutating a returned row cannot silently edit the "persisted" copy — the
|
|
17914
|
+
* IndexedDB implementation gets the same guarantee for free from structured
|
|
17915
|
+
* cloning, and the two must not differ in aliasing behaviour.
|
|
17916
|
+
*/
|
|
17917
|
+
var MemoryOfflineStore = class {
|
|
17918
|
+
cache = /* @__PURE__ */ new Map();
|
|
17919
|
+
queue = /* @__PURE__ */ new Map();
|
|
17920
|
+
async getCache(key) {
|
|
17921
|
+
const entry = this.cache.get(key);
|
|
17922
|
+
return entry ? structuredClone(entry) : void 0;
|
|
17923
|
+
}
|
|
17924
|
+
async setCache(key, entry) {
|
|
17925
|
+
this.cache.set(key, structuredClone(entry));
|
|
17926
|
+
}
|
|
17927
|
+
async setCacheMany(entries) {
|
|
17928
|
+
for (const { key, entry } of entries) this.cache.set(key, structuredClone(entry));
|
|
17929
|
+
}
|
|
17930
|
+
async deleteCache(keys) {
|
|
17931
|
+
for (const key of keys) this.cache.delete(key);
|
|
17932
|
+
}
|
|
17933
|
+
async listCache(prefix) {
|
|
17934
|
+
const out = [];
|
|
17935
|
+
for (const [key, entry] of this.cache) if (key.startsWith(prefix)) out.push({
|
|
17936
|
+
key,
|
|
17937
|
+
cachedAt: entry.cachedAt
|
|
17938
|
+
});
|
|
17939
|
+
return out;
|
|
17940
|
+
}
|
|
17941
|
+
async listCacheEntries(prefix) {
|
|
17942
|
+
const out = [];
|
|
17943
|
+
for (const [key, entry] of this.cache) if (key.startsWith(prefix)) out.push({
|
|
17944
|
+
key,
|
|
17945
|
+
...structuredClone(entry)
|
|
17946
|
+
});
|
|
17947
|
+
out.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
17948
|
+
return out;
|
|
17949
|
+
}
|
|
17950
|
+
async enqueue(key, mutation) {
|
|
17951
|
+
this.queue.set(key, structuredClone(mutation));
|
|
17952
|
+
}
|
|
17953
|
+
async dequeue(key) {
|
|
17954
|
+
this.queue.delete(key);
|
|
17955
|
+
}
|
|
17956
|
+
async listQueue(prefix) {
|
|
17957
|
+
return [...this.queue.entries()].filter(([key]) => key.startsWith(prefix)).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, mutation]) => structuredClone(mutation));
|
|
17958
|
+
}
|
|
17959
|
+
async clear(prefix) {
|
|
17960
|
+
for (const key of [...this.cache.keys()]) if (key.startsWith(prefix)) this.cache.delete(key);
|
|
17961
|
+
for (const key of [...this.queue.keys()]) if (key.startsWith(prefix)) this.queue.delete(key);
|
|
17962
|
+
}
|
|
17963
|
+
};
|
|
17964
|
+
var IDB_NAME = "rebase-offline";
|
|
17965
|
+
/**
|
|
17966
|
+
* v2 introduced the normalized row cache and string mutation ids. A v1
|
|
17967
|
+
* database holds whole-response blobs under keys this version cannot read and
|
|
17968
|
+
* queue entries ordered by a numeric `seq` this version no longer writes, so
|
|
17969
|
+
* the upgrade drops both stores rather than trying to translate them. Offline
|
|
17970
|
+
* support had not shipped in a release when v2 landed, so nothing in the wild
|
|
17971
|
+
* loses a queued write to this.
|
|
17972
|
+
*/
|
|
17973
|
+
var IDB_VERSION = 2;
|
|
17974
|
+
var CACHE_STORE = "cache";
|
|
17975
|
+
var QUEUE_STORE = "queue";
|
|
17976
|
+
/** The exclusive upper bound of an IDBKeyRange covering every key under `prefix`. */
|
|
17977
|
+
function prefixRange(prefix) {
|
|
17978
|
+
return IDBKeyRange.bound(prefix, prefix + "", false, false);
|
|
17979
|
+
}
|
|
17980
|
+
function requestToPromise(request) {
|
|
17981
|
+
return new Promise((resolve, reject) => {
|
|
17982
|
+
request.onsuccess = () => resolve(request.result);
|
|
17983
|
+
request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB request failed"));
|
|
17984
|
+
});
|
|
17985
|
+
}
|
|
17986
|
+
/** Resolve when the whole transaction commits, not just when the last request returns. */
|
|
17987
|
+
function transactionDone(tx) {
|
|
17988
|
+
return new Promise((resolve, reject) => {
|
|
17989
|
+
tx.oncomplete = () => resolve();
|
|
17990
|
+
tx.onabort = tx.onerror = () => reject(tx.error ?? /* @__PURE__ */ new Error("IndexedDB transaction failed"));
|
|
17991
|
+
});
|
|
17992
|
+
}
|
|
17993
|
+
/**
|
|
17994
|
+
* IndexedDB-backed store — the browser default, so cached rows and queued
|
|
17995
|
+
* writes survive a reload or a browser restart. Everything lives in one
|
|
17996
|
+
* database with two object stores; keys are the manager's full prefixed
|
|
17997
|
+
* strings, so multiple users (scopes) share the database without ever
|
|
17998
|
+
* sharing entries.
|
|
17999
|
+
*/
|
|
18000
|
+
var IndexedDBOfflineStore = class {
|
|
18001
|
+
dbPromise;
|
|
18002
|
+
open() {
|
|
18003
|
+
if (!this.dbPromise) this.dbPromise = new Promise((resolve, reject) => {
|
|
18004
|
+
const request = indexedDB.open(IDB_NAME, IDB_VERSION);
|
|
18005
|
+
request.onupgradeneeded = (event) => {
|
|
18006
|
+
const db = request.result;
|
|
18007
|
+
if (event.oldVersion > 0 && event.oldVersion < 2) {
|
|
18008
|
+
if (db.objectStoreNames.contains(CACHE_STORE)) db.deleteObjectStore(CACHE_STORE);
|
|
18009
|
+
if (db.objectStoreNames.contains(QUEUE_STORE)) db.deleteObjectStore(QUEUE_STORE);
|
|
18010
|
+
}
|
|
18011
|
+
if (!db.objectStoreNames.contains(CACHE_STORE)) db.createObjectStore(CACHE_STORE);
|
|
18012
|
+
if (!db.objectStoreNames.contains(QUEUE_STORE)) db.createObjectStore(QUEUE_STORE);
|
|
18013
|
+
};
|
|
18014
|
+
request.onsuccess = () => {
|
|
18015
|
+
const db = request.result;
|
|
18016
|
+
db.onversionchange = () => {
|
|
18017
|
+
db.close();
|
|
18018
|
+
this.dbPromise = void 0;
|
|
18019
|
+
};
|
|
18020
|
+
resolve(db);
|
|
18021
|
+
};
|
|
18022
|
+
request.onerror = () => {
|
|
18023
|
+
this.dbPromise = void 0;
|
|
18024
|
+
reject(request.error ?? /* @__PURE__ */ new Error("Failed to open IndexedDB"));
|
|
18025
|
+
};
|
|
18026
|
+
request.onblocked = () => {
|
|
18027
|
+
this.dbPromise = void 0;
|
|
18028
|
+
reject(/* @__PURE__ */ new Error("IndexedDB upgrade blocked by another tab"));
|
|
18029
|
+
};
|
|
18030
|
+
});
|
|
18031
|
+
return this.dbPromise;
|
|
18032
|
+
}
|
|
18033
|
+
async store(name, mode) {
|
|
18034
|
+
return (await this.open()).transaction(name, mode).objectStore(name);
|
|
18035
|
+
}
|
|
18036
|
+
async getCache(key) {
|
|
18037
|
+
return await requestToPromise((await this.store(CACHE_STORE, "readonly")).get(key));
|
|
18038
|
+
}
|
|
18039
|
+
async setCache(key, entry) {
|
|
18040
|
+
await requestToPromise((await this.store(CACHE_STORE, "readwrite")).put(entry, key));
|
|
18041
|
+
}
|
|
18042
|
+
async setCacheMany(entries) {
|
|
18043
|
+
if (entries.length === 0) return;
|
|
18044
|
+
const store = await this.store(CACHE_STORE, "readwrite");
|
|
18045
|
+
for (const { key, entry } of entries) store.put(entry, key);
|
|
18046
|
+
await transactionDone(store.transaction);
|
|
18047
|
+
}
|
|
18048
|
+
async deleteCache(keys) {
|
|
18049
|
+
if (keys.length === 0) return;
|
|
18050
|
+
const store = await this.store(CACHE_STORE, "readwrite");
|
|
18051
|
+
for (const key of keys) store.delete(key);
|
|
18052
|
+
await transactionDone(store.transaction);
|
|
18053
|
+
}
|
|
18054
|
+
async listCache(prefix) {
|
|
18055
|
+
const store = await this.store(CACHE_STORE, "readonly");
|
|
18056
|
+
const [keys, entries] = await Promise.all([requestToPromise(store.getAllKeys(prefixRange(prefix))), requestToPromise(store.getAll(prefixRange(prefix)))]);
|
|
18057
|
+
return keys.map((key, i) => ({
|
|
18058
|
+
key: String(key),
|
|
18059
|
+
cachedAt: entries[i]?.cachedAt ?? 0
|
|
18060
|
+
}));
|
|
18061
|
+
}
|
|
18062
|
+
async listCacheEntries(prefix) {
|
|
18063
|
+
const store = await this.store(CACHE_STORE, "readonly");
|
|
18064
|
+
const [keys, entries] = await Promise.all([requestToPromise(store.getAllKeys(prefixRange(prefix))), requestToPromise(store.getAll(prefixRange(prefix)))]);
|
|
18065
|
+
return keys.map((key, i) => {
|
|
18066
|
+
const entry = entries[i];
|
|
18067
|
+
return {
|
|
18068
|
+
key: String(key),
|
|
18069
|
+
value: entry?.value,
|
|
18070
|
+
cachedAt: entry?.cachedAt ?? 0
|
|
18071
|
+
};
|
|
18072
|
+
});
|
|
18073
|
+
}
|
|
18074
|
+
async enqueue(key, mutation) {
|
|
18075
|
+
await requestToPromise((await this.store(QUEUE_STORE, "readwrite")).put(mutation, key));
|
|
18076
|
+
}
|
|
18077
|
+
async dequeue(key) {
|
|
18078
|
+
await requestToPromise((await this.store(QUEUE_STORE, "readwrite")).delete(key));
|
|
18079
|
+
}
|
|
18080
|
+
async listQueue(prefix) {
|
|
18081
|
+
return await requestToPromise((await this.store(QUEUE_STORE, "readonly")).getAll(prefixRange(prefix)));
|
|
18082
|
+
}
|
|
18083
|
+
async clear(prefix) {
|
|
18084
|
+
await requestToPromise((await this.store(CACHE_STORE, "readwrite")).delete(prefixRange(prefix)));
|
|
18085
|
+
await requestToPromise((await this.store(QUEUE_STORE, "readwrite")).delete(prefixRange(prefix)));
|
|
18086
|
+
}
|
|
18087
|
+
};
|
|
18088
|
+
/**
|
|
18089
|
+
* A local evaluator for `FindParams`, so cached rows can answer a query the
|
|
18090
|
+
* client has never sent to the server — and so a row written offline shows up
|
|
18091
|
+
* in every filtered list it belongs to, not just in unfiltered ones.
|
|
18092
|
+
*
|
|
18093
|
+
* This mirrors the Postgres driver's semantics rather than JavaScript's:
|
|
18094
|
+
*
|
|
18095
|
+
* - Comparing against NULL is *unknown*, not false-or-true. `status != "done"`
|
|
18096
|
+
* excludes rows where `status` is null, exactly as SQL does — a JS `!==`
|
|
18097
|
+
* would have included them.
|
|
18098
|
+
* - `ORDER BY` puts nulls last ascending and first descending, which is the
|
|
18099
|
+
* Postgres default.
|
|
18100
|
+
* - The wire format carries no types, so values arriving as strings are
|
|
18101
|
+
* compared numerically against numeric columns and as instants against
|
|
18102
|
+
* date columns. `["==", "3"]` matches the number `3`, as it does server-side.
|
|
18103
|
+
*
|
|
18104
|
+
* Two things it deliberately approximates, both flagged by
|
|
18105
|
+
* {@link isExactlyEvaluable}: `searchString` becomes a case-insensitive
|
|
18106
|
+
* substring scan over the row's string fields (the server runs real full-text
|
|
18107
|
+
* search over the collection's configured columns), and `include` cannot be
|
|
18108
|
+
* evaluated at all, because the related rows live in collections this query
|
|
18109
|
+
* knows nothing about.
|
|
18110
|
+
*/
|
|
18111
|
+
var collator = typeof Intl !== "undefined" && typeof Intl.Collator === "function" ? new Intl.Collator(void 0, {
|
|
18112
|
+
numeric: false,
|
|
18113
|
+
sensitivity: "variant"
|
|
18114
|
+
}) : void 0;
|
|
18115
|
+
function isNullish(value) {
|
|
18116
|
+
return value === null || value === void 0;
|
|
18117
|
+
}
|
|
18118
|
+
/**
|
|
18119
|
+
* Reduce a value to something comparable. Relations compare by the id they
|
|
18120
|
+
* point at — the column holds a foreign key, so that is what the server
|
|
18121
|
+
* compares too.
|
|
18122
|
+
*/
|
|
18123
|
+
function toComparable(value) {
|
|
18124
|
+
if (value instanceof Date) return value.getTime();
|
|
18125
|
+
if (value instanceof EntityRelation) return value.id;
|
|
18126
|
+
if (value && typeof value === "object") {
|
|
18127
|
+
const record = value;
|
|
18128
|
+
if (typeof record.__type === "string" && "id" in record) return record.id;
|
|
18129
|
+
}
|
|
18130
|
+
return value;
|
|
18131
|
+
}
|
|
18132
|
+
/**
|
|
18133
|
+
* Three-way compare with SQL's type coercion but not its collation. Returns
|
|
18134
|
+
* `undefined` when the two values are not ordered relative to each other,
|
|
18135
|
+
* which is how NULL propagates through a comparison.
|
|
18136
|
+
*/
|
|
18137
|
+
function compareValues(a, b) {
|
|
18138
|
+
const left = toComparable(a);
|
|
18139
|
+
const right = toComparable(b);
|
|
18140
|
+
if (isNullish(left) || isNullish(right)) return void 0;
|
|
18141
|
+
if (typeof left === "boolean" || typeof right === "boolean") return (left === true || left === "true" || left === 1 ? 1 : 0) - (right === true || right === "true" || right === 1 ? 1 : 0);
|
|
18142
|
+
const leftNum = typeof left === "number" ? left : numericOrNaN(left);
|
|
18143
|
+
const rightNum = typeof right === "number" ? right : numericOrNaN(right);
|
|
18144
|
+
if (!Number.isNaN(leftNum) && !Number.isNaN(rightNum)) return leftNum < rightNum ? -1 : leftNum > rightNum ? 1 : 0;
|
|
18145
|
+
if (typeof left === "number" || typeof right === "number") {
|
|
18146
|
+
const leftTime = toTime(left);
|
|
18147
|
+
const rightTime = toTime(right);
|
|
18148
|
+
if (leftTime !== void 0 && rightTime !== void 0) return leftTime < rightTime ? -1 : leftTime > rightTime ? 1 : 0;
|
|
18149
|
+
}
|
|
18150
|
+
const leftStr = String(left);
|
|
18151
|
+
const rightStr = String(right);
|
|
18152
|
+
if (collator) return collator.compare(leftStr, rightStr);
|
|
18153
|
+
return leftStr < rightStr ? -1 : leftStr > rightStr ? 1 : 0;
|
|
18154
|
+
}
|
|
18155
|
+
function numericOrNaN(value) {
|
|
18156
|
+
if (typeof value === "number") return value;
|
|
18157
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
18158
|
+
const n = Number(value);
|
|
18159
|
+
return Number.isNaN(n) ? NaN : n;
|
|
18160
|
+
}
|
|
18161
|
+
if (typeof value === "bigint") return Number(value);
|
|
18162
|
+
return NaN;
|
|
18163
|
+
}
|
|
18164
|
+
function toTime(value) {
|
|
18165
|
+
if (typeof value === "number") return value;
|
|
18166
|
+
if (typeof value === "string") {
|
|
18167
|
+
const t = Date.parse(value);
|
|
18168
|
+
return Number.isNaN(t) ? void 0 : t;
|
|
18169
|
+
}
|
|
18170
|
+
}
|
|
18171
|
+
/** Equality with the wire's type erasure allowed for, but never across NULL. */
|
|
18172
|
+
function looseEquals(a, b) {
|
|
18173
|
+
const left = toComparable(a);
|
|
18174
|
+
const right = toComparable(b);
|
|
18175
|
+
if (isNullish(left) || isNullish(right)) return isNullish(left) && isNullish(right);
|
|
18176
|
+
if (left === right) return true;
|
|
18177
|
+
return compareValues(left, right) === 0;
|
|
18178
|
+
}
|
|
18179
|
+
/**
|
|
18180
|
+
* Translate a SQL `LIKE` pattern to an anchored regular expression.
|
|
18181
|
+
* `%` matches any run of characters, `_` exactly one, and a backslash escapes
|
|
18182
|
+
* either of them.
|
|
18183
|
+
*/
|
|
18184
|
+
function likeToRegExp(pattern, caseInsensitive) {
|
|
18185
|
+
let source = "^";
|
|
18186
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
18187
|
+
const char = pattern[i];
|
|
18188
|
+
if (char === "\\" && i + 1 < pattern.length) {
|
|
18189
|
+
source += pattern[i + 1].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
18190
|
+
i++;
|
|
18191
|
+
} else if (char === "%") source += "[\\s\\S]*";
|
|
18192
|
+
else if (char === "_") source += "[\\s\\S]";
|
|
18193
|
+
else source += char.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
18194
|
+
}
|
|
18195
|
+
return new RegExp(source + "$", caseInsensitive ? "i" : "");
|
|
18196
|
+
}
|
|
18197
|
+
function asArray(value) {
|
|
18198
|
+
if (Array.isArray(value)) return value;
|
|
18199
|
+
if (value === void 0) return [];
|
|
18200
|
+
return [value];
|
|
18201
|
+
}
|
|
18202
|
+
/** Evaluate one canonical operator against one row value. */
|
|
18203
|
+
function matchesOperator(rowValue, op, filterValue) {
|
|
18204
|
+
switch (op) {
|
|
18205
|
+
case "is-null": return isNullish(rowValue);
|
|
18206
|
+
case "is-not-null": return !isNullish(rowValue);
|
|
18207
|
+
case "==": return looseEquals(rowValue, filterValue);
|
|
18208
|
+
case "!=":
|
|
18209
|
+
if (isNullish(rowValue)) return false;
|
|
18210
|
+
return !looseEquals(rowValue, filterValue);
|
|
18211
|
+
case "<":
|
|
18212
|
+
case "<=":
|
|
18213
|
+
case ">":
|
|
18214
|
+
case ">=": {
|
|
18215
|
+
const cmp = compareValues(rowValue, filterValue);
|
|
18216
|
+
if (cmp === void 0) return false;
|
|
18217
|
+
if (op === "<") return cmp < 0;
|
|
18218
|
+
if (op === "<=") return cmp <= 0;
|
|
18219
|
+
if (op === ">") return cmp > 0;
|
|
18220
|
+
return cmp >= 0;
|
|
18221
|
+
}
|
|
18222
|
+
case "in":
|
|
18223
|
+
if (isNullish(rowValue)) return false;
|
|
18224
|
+
return asArray(filterValue).some((v) => looseEquals(rowValue, v));
|
|
18225
|
+
case "not-in":
|
|
18226
|
+
if (isNullish(rowValue)) return false;
|
|
18227
|
+
return !asArray(filterValue).some((v) => looseEquals(rowValue, v));
|
|
18228
|
+
case "array-contains":
|
|
18229
|
+
if (!Array.isArray(rowValue)) return false;
|
|
18230
|
+
return rowValue.some((v) => looseEquals(v, filterValue));
|
|
18231
|
+
case "array-contains-any": {
|
|
18232
|
+
if (!Array.isArray(rowValue)) return false;
|
|
18233
|
+
const wanted = asArray(filterValue);
|
|
18234
|
+
return rowValue.some((v) => wanted.some((w) => looseEquals(v, w)));
|
|
18235
|
+
}
|
|
18236
|
+
case "like":
|
|
18237
|
+
case "not-like":
|
|
18238
|
+
case "ilike":
|
|
18239
|
+
case "not-ilike": {
|
|
18240
|
+
if (isNullish(rowValue)) return false;
|
|
18241
|
+
const insensitive = op === "ilike" || op === "not-ilike";
|
|
18242
|
+
const negated = op === "not-like" || op === "not-ilike";
|
|
18243
|
+
const matched = likeToRegExp(String(filterValue), insensitive).test(String(rowValue));
|
|
18244
|
+
return negated ? !matched : matched;
|
|
18245
|
+
}
|
|
18246
|
+
default: return true;
|
|
18247
|
+
}
|
|
18248
|
+
}
|
|
18249
|
+
function isTuple(value) {
|
|
18250
|
+
return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && toCanonicalOp(value[0]) !== void 0;
|
|
18251
|
+
}
|
|
18252
|
+
/** Evaluate a `where` clause: every field, and every tuple on a field, AND-ed. */
|
|
18253
|
+
function matchesWhere(row, where) {
|
|
18254
|
+
if (!where) return true;
|
|
18255
|
+
for (const [field, condition] of Object.entries(where)) {
|
|
18256
|
+
if (condition === void 0) continue;
|
|
18257
|
+
const tuples = isTuple(condition) ? [condition] : Array.isArray(condition) ? condition.filter(isTuple) : [];
|
|
18258
|
+
for (const [rawOp, value] of tuples) {
|
|
18259
|
+
const op = toCanonicalOp(rawOp) ?? rawOp;
|
|
18260
|
+
if (!matchesOperator(row[field], op, value)) return false;
|
|
18261
|
+
}
|
|
18262
|
+
}
|
|
18263
|
+
return true;
|
|
18264
|
+
}
|
|
18265
|
+
/** Evaluate a nested and/or tree. */
|
|
18266
|
+
function matchesLogical(row, condition) {
|
|
18267
|
+
if (!condition) return true;
|
|
18268
|
+
if ("type" in condition) {
|
|
18269
|
+
const children = condition.conditions ?? [];
|
|
18270
|
+
if (children.length === 0) return true;
|
|
18271
|
+
return condition.type === "or" ? children.some((c) => matchesLogical(row, c)) : children.every((c) => matchesLogical(row, c));
|
|
18272
|
+
}
|
|
18273
|
+
const op = toCanonicalOp(condition.operator) ?? condition.operator;
|
|
18274
|
+
return matchesOperator(row[condition.column], op, condition.value);
|
|
18275
|
+
}
|
|
18276
|
+
/**
|
|
18277
|
+
* Approximate the server's full-text search with a case-insensitive substring
|
|
18278
|
+
* scan over the row's own string fields. Narrower than the real thing (no
|
|
18279
|
+
* stemming, no configured search columns), and it never matches a field the
|
|
18280
|
+
* cached row does not carry — a local list may therefore be missing rows the
|
|
18281
|
+
* server would have returned, which is why {@link isExactlyEvaluable} refuses
|
|
18282
|
+
* to call a search query exact.
|
|
18283
|
+
*/
|
|
18284
|
+
function matchesSearch(row, searchString) {
|
|
18285
|
+
if (!searchString) return true;
|
|
18286
|
+
const needle = searchString.trim().toLowerCase();
|
|
18287
|
+
if (!needle) return true;
|
|
18288
|
+
for (const value of Object.values(row)) {
|
|
18289
|
+
if (typeof value === "string" && value.toLowerCase().includes(needle)) return true;
|
|
18290
|
+
if (typeof value === "number" && String(value).includes(needle)) return true;
|
|
18291
|
+
}
|
|
18292
|
+
return false;
|
|
18293
|
+
}
|
|
18294
|
+
/** Does this row belong in the result set for `params`, ignoring pagination? */
|
|
18295
|
+
function matchesParams(row, params) {
|
|
18296
|
+
if (!params) return true;
|
|
18297
|
+
return matchesWhere(row, params.where) && matchesLogical(row, params.logical) && matchesSearch(row, params.searchString);
|
|
18298
|
+
}
|
|
18299
|
+
/**
|
|
18300
|
+
* Sort in place, Postgres-style: nulls last ascending, first descending, with
|
|
18301
|
+
* the row id as a tiebreak so paging through an unsorted-but-equal run does
|
|
18302
|
+
* not shuffle rows between pages.
|
|
18303
|
+
*/
|
|
18304
|
+
function sortRows(rows, orderBy) {
|
|
18305
|
+
if (!orderBy) return rows;
|
|
18306
|
+
const [field, direction = "asc"] = orderBy;
|
|
18307
|
+
const sign = direction === "desc" ? -1 : 1;
|
|
18308
|
+
return rows.sort((a, b) => {
|
|
18309
|
+
const av = a[field];
|
|
18310
|
+
const bv = b[field];
|
|
18311
|
+
const aNull = isNullish(toComparable(av));
|
|
18312
|
+
const bNull = isNullish(toComparable(bv));
|
|
18313
|
+
if (aNull || bNull) {
|
|
18314
|
+
if (aNull && bNull) return tiebreak(a, b);
|
|
18315
|
+
return (aNull ? 1 : -1) * (direction === "desc" ? -1 : 1);
|
|
18316
|
+
}
|
|
18317
|
+
const cmp = compareValues(av, bv);
|
|
18318
|
+
if (cmp === void 0 || cmp === 0) return tiebreak(a, b);
|
|
18319
|
+
return cmp * sign;
|
|
18320
|
+
});
|
|
18321
|
+
}
|
|
18322
|
+
function tiebreak(a, b) {
|
|
18323
|
+
return compareValues(a.id, b.id) ?? 0;
|
|
18324
|
+
}
|
|
18325
|
+
/** Resolve `page`/`offset`/`limit` the way the server does. */
|
|
18326
|
+
function resolvePagination(params) {
|
|
18327
|
+
const limit = params?.limit ?? 20;
|
|
18328
|
+
return {
|
|
18329
|
+
limit,
|
|
18330
|
+
offset: params?.page != null ? Math.max(0, (params.page - 1) * limit) : params?.offset ?? 0
|
|
18331
|
+
};
|
|
18332
|
+
}
|
|
18333
|
+
/**
|
|
18334
|
+
* Can a locally evaluated answer to `params` be trusted to match the server's,
|
|
18335
|
+
* assuming the cache holds every row of the collection?
|
|
18336
|
+
*
|
|
18337
|
+
* `include` pulls in rows from other collections that this evaluator never
|
|
18338
|
+
* sees, and `searchString` is only approximated — both make the local answer a
|
|
18339
|
+
* best effort rather than an equivalent one.
|
|
18340
|
+
*/
|
|
18341
|
+
function isExactlyEvaluable(params) {
|
|
18342
|
+
if (!params) return true;
|
|
18343
|
+
if (params.include && params.include.length > 0) return false;
|
|
18344
|
+
if (params.searchString) return false;
|
|
18345
|
+
return true;
|
|
18346
|
+
}
|
|
18347
|
+
/** Run a full query — filter, sort, paginate — over a set of rows. */
|
|
18348
|
+
function runLocalQuery(rows, params) {
|
|
18349
|
+
const matched = rows.filter((row) => matchesParams(row, params));
|
|
18350
|
+
sortRows(matched, params?.orderBy);
|
|
18351
|
+
const { limit, offset } = resolvePagination(params);
|
|
18352
|
+
const page = matched.slice(offset, offset + limit);
|
|
18353
|
+
return {
|
|
18354
|
+
data: page,
|
|
18355
|
+
meta: {
|
|
18356
|
+
total: matched.length,
|
|
18357
|
+
limit,
|
|
18358
|
+
offset,
|
|
18359
|
+
hasMore: offset + page.length < matched.length
|
|
18360
|
+
}
|
|
18361
|
+
};
|
|
18362
|
+
}
|
|
18363
|
+
function offlineError(message) {
|
|
18364
|
+
return new RebaseApiError(message, {
|
|
18365
|
+
status: 0,
|
|
18366
|
+
code: "offline"
|
|
18367
|
+
});
|
|
18368
|
+
}
|
|
18369
|
+
function generateOfflineId() {
|
|
18370
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
|
18371
|
+
return `off-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
18372
|
+
}
|
|
18373
|
+
var MISSING = "\0missing";
|
|
18374
|
+
var OfflineManager = class {
|
|
18375
|
+
store;
|
|
18376
|
+
maxCachedQueries;
|
|
18377
|
+
maxCachedRows;
|
|
18378
|
+
maxRetries;
|
|
18379
|
+
onSyncError;
|
|
18380
|
+
createInner;
|
|
18381
|
+
inners = /* @__PURE__ */ new Map();
|
|
18382
|
+
connectivity;
|
|
18383
|
+
scope = "anon";
|
|
18384
|
+
/** The local database: normalized rows and query snapshots per collection. */
|
|
18385
|
+
collections = /* @__PURE__ */ new Map();
|
|
18386
|
+
/** In-memory mirror of the current scope's queue, in replay order. */
|
|
18387
|
+
queue = [];
|
|
18388
|
+
queueLoad;
|
|
18389
|
+
/** Serializes enqueues so concurrent writes keep the order the app made them. */
|
|
18390
|
+
enqueueChain = Promise.resolve();
|
|
18391
|
+
flushPromise;
|
|
18392
|
+
queueListeners = /* @__PURE__ */ new Set();
|
|
18393
|
+
statusListeners = /* @__PURE__ */ new Set();
|
|
18394
|
+
observers = /* @__PURE__ */ new Map();
|
|
18395
|
+
refreshPending = /* @__PURE__ */ new Set();
|
|
18396
|
+
revCounter = 0;
|
|
18397
|
+
disposed = false;
|
|
18398
|
+
currentStatus = {
|
|
18399
|
+
online: true,
|
|
18400
|
+
syncing: false,
|
|
18401
|
+
pending: 0
|
|
18402
|
+
};
|
|
18403
|
+
channel;
|
|
18404
|
+
tabId = createMutationId();
|
|
18405
|
+
api;
|
|
18406
|
+
constructor(config, createInner) {
|
|
18407
|
+
this.store = config.store ?? (typeof indexedDB !== "undefined" ? new IndexedDBOfflineStore() : new MemoryOfflineStore());
|
|
18408
|
+
this.maxCachedQueries = config.maxCachedQueriesPerCollection ?? 50;
|
|
18409
|
+
this.maxCachedRows = config.maxCachedRowsPerCollection ?? 5e3;
|
|
18410
|
+
this.maxRetries = config.maxRetries ?? 5;
|
|
18411
|
+
this.onSyncError = config.onSyncError;
|
|
18412
|
+
this.createInner = createInner;
|
|
18413
|
+
const maxBackoffMs = config.syncIntervalMs ?? 6e4;
|
|
18414
|
+
this.connectivity = new ConnectivityMonitor({
|
|
18415
|
+
maxBackoffMs: Math.max(1e3, maxBackoffMs),
|
|
18416
|
+
respectBackoff: maxBackoffMs > 0
|
|
18417
|
+
});
|
|
18418
|
+
if (maxBackoffMs > 0) this.connectivity.onRetryDue = () => {
|
|
18419
|
+
this.sync().catch(() => void 0);
|
|
18420
|
+
};
|
|
18421
|
+
this.connectivity.onChange((online) => {
|
|
18422
|
+
this.patchStatus({ online });
|
|
18423
|
+
if (online) this.revalidateAll();
|
|
18424
|
+
});
|
|
18425
|
+
this.currentStatus.online = this.connectivity.isOnline();
|
|
18426
|
+
if ((config.crossTab ?? this.store instanceof IndexedDBOfflineStore) && typeof BroadcastChannel !== "undefined") try {
|
|
18427
|
+
this.channel = new BroadcastChannel("rebase-offline");
|
|
18428
|
+
this.channel.onmessage = (event) => this.onBroadcast(event.data);
|
|
18429
|
+
this.channel.unref?.();
|
|
18430
|
+
} catch {}
|
|
18431
|
+
this.api = {
|
|
18432
|
+
sync: () => this.sync(),
|
|
18433
|
+
pending: async () => {
|
|
18434
|
+
await this.ensureQueueLoaded();
|
|
18435
|
+
return this.queue.map((m) => structuredClone(m));
|
|
18436
|
+
},
|
|
18437
|
+
status: () => ({ ...this.currentStatus }),
|
|
18438
|
+
onStatusChange: (listener) => {
|
|
18439
|
+
this.statusListeners.add(listener);
|
|
18440
|
+
return () => this.statusListeners.delete(listener);
|
|
18441
|
+
},
|
|
18442
|
+
clear: async () => {
|
|
18443
|
+
await this.store.clear(`${this.scope}|`);
|
|
18444
|
+
this.queue = [];
|
|
18445
|
+
this.resetCollections();
|
|
18446
|
+
this.patchStatus({
|
|
18447
|
+
pending: 0,
|
|
18448
|
+
lastError: void 0
|
|
18449
|
+
});
|
|
18450
|
+
this.notifyQueue();
|
|
18451
|
+
for (const slug of this.observers.keys()) this.notifyCollection(slug, false);
|
|
18452
|
+
},
|
|
18453
|
+
onQueueChange: (listener) => {
|
|
18454
|
+
this.queueListeners.add(listener);
|
|
18455
|
+
return () => this.queueListeners.delete(listener);
|
|
18456
|
+
}
|
|
18457
|
+
};
|
|
18458
|
+
}
|
|
18459
|
+
/**
|
|
18460
|
+
* Cache and queue are partitioned per signed-in user: cached rows are
|
|
18461
|
+
* RLS-filtered for the user who fetched them, and queued writes must
|
|
18462
|
+
* replay under the credentials that made them — so neither may ever leak
|
|
18463
|
+
* across a sign-out/sign-in on a shared browser.
|
|
18464
|
+
*/
|
|
18465
|
+
setScope(uid) {
|
|
18466
|
+
const next = uid || "anon";
|
|
18467
|
+
if (next === this.scope) return;
|
|
18468
|
+
this.scope = next;
|
|
18469
|
+
this.queueLoad = void 0;
|
|
18470
|
+
this.queue = [];
|
|
18471
|
+
this.resetCollections();
|
|
18472
|
+
this.patchStatus({
|
|
18473
|
+
pending: 0,
|
|
18474
|
+
lastError: void 0
|
|
18475
|
+
});
|
|
18476
|
+
this.notifyQueue();
|
|
18477
|
+
for (const slug of this.observers.keys()) this.notifyCollection(slug, false);
|
|
18478
|
+
this.revalidateAll();
|
|
18479
|
+
this.sync().catch(() => void 0);
|
|
18480
|
+
}
|
|
18481
|
+
/**
|
|
18482
|
+
* Throw away every local row, for a scope change or an explicit clear.
|
|
18483
|
+
*
|
|
18484
|
+
* The state objects are replaced rather than emptied, so a load still in
|
|
18485
|
+
* flight for the previous user fails its identity check and discards what
|
|
18486
|
+
* it read instead of grafting it onto the new one. The replacements are
|
|
18487
|
+
* marked ready: nothing needs loading until something asks, and observers
|
|
18488
|
+
* have to be told *now* that the rows they are showing are gone.
|
|
18489
|
+
*/
|
|
18490
|
+
resetCollections() {
|
|
18491
|
+
const slugs = [...this.collections.keys()];
|
|
18492
|
+
this.collections = /* @__PURE__ */ new Map();
|
|
18493
|
+
for (const slug of slugs) this.collections.set(slug, {
|
|
18494
|
+
rows: /* @__PURE__ */ new Map(),
|
|
18495
|
+
snapshots: /* @__PURE__ */ new Map(),
|
|
18496
|
+
absent: /* @__PURE__ */ new Set(),
|
|
18497
|
+
ready: true
|
|
18498
|
+
});
|
|
18499
|
+
}
|
|
18500
|
+
/** Release listeners, timers and the cross-tab channel (client.close()). */
|
|
18501
|
+
dispose() {
|
|
18502
|
+
this.disposed = true;
|
|
18503
|
+
this.connectivity.dispose();
|
|
18504
|
+
try {
|
|
18505
|
+
this.channel?.close();
|
|
18506
|
+
} catch {}
|
|
18507
|
+
this.observers.clear();
|
|
18508
|
+
this.queueListeners.clear();
|
|
18509
|
+
this.statusListeners.clear();
|
|
18510
|
+
}
|
|
18511
|
+
wrap(slug, inner) {
|
|
18512
|
+
this.inners.set(slug, inner);
|
|
18513
|
+
const wrapped = {
|
|
18514
|
+
find: async (params) => {
|
|
18515
|
+
const state = await this.ensureCollection(slug);
|
|
18516
|
+
if (this.connectivity.shouldAttempt()) try {
|
|
18517
|
+
const res = await inner.find(params);
|
|
18518
|
+
this.connectivity.markSuccess();
|
|
18519
|
+
await this.ingest(slug, res.data ?? []);
|
|
18520
|
+
const snapshot = this.recordSnapshot(slug, params, res);
|
|
18521
|
+
const answer = this.answer(slug, params, snapshot);
|
|
18522
|
+
this.notifyCollection(slug, false);
|
|
18523
|
+
return {
|
|
18524
|
+
data: answer.data,
|
|
18525
|
+
meta: answer.meta
|
|
18526
|
+
};
|
|
18527
|
+
} catch (error) {
|
|
18528
|
+
if (!isNetworkError(error)) {
|
|
18529
|
+
if (isRetryableError(error) && this.hasLocalAnswer(state, slug, params)) {
|
|
18530
|
+
const answer = this.answer(slug, params, this.snapshotFor(slug, params));
|
|
18531
|
+
return {
|
|
18532
|
+
data: answer.data,
|
|
18533
|
+
meta: answer.meta
|
|
18534
|
+
};
|
|
18535
|
+
}
|
|
18536
|
+
throw error;
|
|
18537
|
+
}
|
|
18538
|
+
this.connectivity.markFailure();
|
|
18539
|
+
}
|
|
18540
|
+
const answer = this.localFind(slug, params);
|
|
18541
|
+
return {
|
|
18542
|
+
data: answer.data,
|
|
18543
|
+
meta: answer.meta
|
|
18544
|
+
};
|
|
18545
|
+
},
|
|
18546
|
+
findById: async (id) => {
|
|
18547
|
+
await this.ensureCollection(slug);
|
|
18548
|
+
if (this.connectivity.shouldAttempt()) try {
|
|
18549
|
+
const row = await inner.findById(id);
|
|
18550
|
+
this.connectivity.markSuccess();
|
|
18551
|
+
if (row !== void 0) await this.ingest(slug, [row]);
|
|
18552
|
+
else if (!this.hasPending(slug, id)) this.removeLocalRow(slug, id, true);
|
|
18553
|
+
this.notifyCollection(slug, false);
|
|
18554
|
+
return this.localRow(slug, id);
|
|
18555
|
+
} catch (error) {
|
|
18556
|
+
if (!isNetworkError(error)) throw error;
|
|
18557
|
+
this.connectivity.markFailure();
|
|
18558
|
+
}
|
|
18559
|
+
const local = this.localRow(slug, id);
|
|
18560
|
+
if (local !== void 0 || this.hasPending(slug, id)) return local;
|
|
18561
|
+
if (this.collections.get(slug)?.absent.has(String(id))) return void 0;
|
|
18562
|
+
throw offlineError(`Offline: "${slug}" row ${String(id)} is not in the local database.`);
|
|
18563
|
+
},
|
|
18564
|
+
create: async (data, id) => {
|
|
18565
|
+
await this.ensureCollection(slug);
|
|
18566
|
+
if (this.connectivity.shouldAttempt()) try {
|
|
18567
|
+
const row = await inner.create(data, id);
|
|
18568
|
+
this.connectivity.markSuccess();
|
|
18569
|
+
await this.ingest(slug, [row]);
|
|
18570
|
+
this.notifyCollection(slug);
|
|
18571
|
+
this.scheduleRefresh(slug);
|
|
18572
|
+
return row;
|
|
18573
|
+
} catch (error) {
|
|
18574
|
+
if (!isNetworkError(error)) throw error;
|
|
18575
|
+
this.connectivity.markFailure();
|
|
18576
|
+
}
|
|
18577
|
+
const providedId = id ?? data.id;
|
|
18578
|
+
const rowId = providedId ?? generateOfflineId();
|
|
18579
|
+
const row = {
|
|
18580
|
+
...data,
|
|
18581
|
+
id: rowId
|
|
18582
|
+
};
|
|
18583
|
+
await this.enqueue({
|
|
18584
|
+
collection: slug,
|
|
18585
|
+
type: "create",
|
|
18586
|
+
id: rowId,
|
|
18587
|
+
data: row,
|
|
18588
|
+
generatedId: providedId === void 0,
|
|
18589
|
+
rollback: { rows: { [String(rowId)]: this.rawLocalRow(slug, rowId) ?? null } }
|
|
18590
|
+
});
|
|
18591
|
+
this.setLocalRow(slug, rowId, row);
|
|
18592
|
+
this.notifyCollection(slug);
|
|
18593
|
+
return row;
|
|
18594
|
+
},
|
|
18595
|
+
createMany: async (data, options) => {
|
|
18596
|
+
await this.ensureCollection(slug);
|
|
18597
|
+
if (!Array.isArray(data)) throw new TypeError("createMany expects an array of records.");
|
|
18598
|
+
if (data.length === 0) return [];
|
|
18599
|
+
if (this.connectivity.shouldAttempt()) try {
|
|
18600
|
+
const rows = await inner.createMany(data, options);
|
|
18601
|
+
this.connectivity.markSuccess();
|
|
18602
|
+
await this.ingest(slug, rows);
|
|
18603
|
+
this.notifyCollection(slug);
|
|
18604
|
+
this.scheduleRefresh(slug);
|
|
18605
|
+
return rows;
|
|
18606
|
+
} catch (error) {
|
|
18607
|
+
if (!isNetworkError(error)) throw error;
|
|
18608
|
+
this.connectivity.markFailure();
|
|
18609
|
+
}
|
|
18610
|
+
const rows = data.map((r) => ({
|
|
18611
|
+
...r,
|
|
18612
|
+
id: r.id ?? generateOfflineId()
|
|
18613
|
+
}));
|
|
18614
|
+
const rollback = {};
|
|
18615
|
+
for (const row of rows) {
|
|
18616
|
+
const key = String(row.id);
|
|
18617
|
+
rollback[key] = this.rawLocalRow(slug, row.id) ?? null;
|
|
18618
|
+
}
|
|
18619
|
+
await this.enqueue({
|
|
18620
|
+
collection: slug,
|
|
18621
|
+
type: "createMany",
|
|
18622
|
+
data: rows,
|
|
18623
|
+
upsert: options?.upsert,
|
|
18624
|
+
rollback: { rows: rollback }
|
|
18625
|
+
});
|
|
18626
|
+
for (const row of rows) this.setLocalRow(slug, row.id, row);
|
|
18627
|
+
this.notifyCollection(slug);
|
|
18628
|
+
return rows;
|
|
18629
|
+
},
|
|
18630
|
+
update: async (id, data) => {
|
|
18631
|
+
await this.ensureCollection(slug);
|
|
18632
|
+
if (this.connectivity.shouldAttempt()) try {
|
|
18633
|
+
const row = await inner.update(id, data);
|
|
18634
|
+
this.connectivity.markSuccess();
|
|
18635
|
+
await this.ingest(slug, [row]);
|
|
18636
|
+
this.notifyCollection(slug);
|
|
18637
|
+
return row;
|
|
18638
|
+
} catch (error) {
|
|
18639
|
+
if (!isNetworkError(error)) throw error;
|
|
18640
|
+
this.connectivity.markFailure();
|
|
18641
|
+
}
|
|
18642
|
+
const base = this.rawLocalRow(slug, id);
|
|
18643
|
+
await this.enqueue({
|
|
18644
|
+
collection: slug,
|
|
18645
|
+
type: "update",
|
|
18646
|
+
id,
|
|
18647
|
+
data,
|
|
18648
|
+
rollback: { rows: { [String(id)]: base ?? null } }
|
|
18649
|
+
});
|
|
18650
|
+
const optimistic = {
|
|
18651
|
+
...base ?? {},
|
|
18652
|
+
...data,
|
|
18653
|
+
id
|
|
18654
|
+
};
|
|
18655
|
+
this.setLocalRow(slug, id, optimistic);
|
|
18656
|
+
this.notifyCollection(slug);
|
|
18657
|
+
return optimistic;
|
|
18658
|
+
},
|
|
18659
|
+
delete: async (id) => {
|
|
18660
|
+
await this.ensureCollection(slug);
|
|
18661
|
+
if (this.connectivity.shouldAttempt()) try {
|
|
18662
|
+
await inner.delete(id);
|
|
18663
|
+
this.connectivity.markSuccess();
|
|
18664
|
+
this.removeLocalRow(slug, id, true);
|
|
18665
|
+
this.notifyCollection(slug);
|
|
18666
|
+
this.scheduleRefresh(slug);
|
|
18667
|
+
return;
|
|
18668
|
+
} catch (error) {
|
|
18669
|
+
if (!isNetworkError(error)) throw error;
|
|
18670
|
+
this.connectivity.markFailure();
|
|
18671
|
+
}
|
|
18672
|
+
await this.enqueue({
|
|
18673
|
+
collection: slug,
|
|
18674
|
+
type: "delete",
|
|
18675
|
+
id,
|
|
18676
|
+
rollback: { rows: { [String(id)]: this.rawLocalRow(slug, id) ?? null } }
|
|
18677
|
+
});
|
|
18678
|
+
this.removeLocalRow(slug, id);
|
|
18679
|
+
this.notifyCollection(slug);
|
|
18680
|
+
},
|
|
18681
|
+
count: async (params) => {
|
|
18682
|
+
await this.ensureCollection(slug);
|
|
18683
|
+
if (this.connectivity.shouldAttempt()) try {
|
|
18684
|
+
const n = await inner.count(params);
|
|
18685
|
+
this.connectivity.markSuccess();
|
|
18686
|
+
this.writeCache(this.countKey(slug, params), n);
|
|
18687
|
+
return Math.max(0, n + this.pendingDelta(slug, params));
|
|
18688
|
+
} catch (error) {
|
|
18689
|
+
if (!isNetworkError(error)) throw error;
|
|
18690
|
+
this.connectivity.markFailure();
|
|
18691
|
+
}
|
|
18692
|
+
const cached = await this.readCache(this.countKey(slug, params));
|
|
18693
|
+
if (cached !== void 0) return Math.max(0, cached + this.pendingDelta(slug, params));
|
|
18694
|
+
const state = this.collections.get(slug);
|
|
18695
|
+
if (state && state.rows.size > 0) return runLocalQuery([...state.rows.values()].map((e) => e.row), params).meta.total;
|
|
18696
|
+
throw offlineError(`Offline: no cached count for "${slug}".`);
|
|
18697
|
+
},
|
|
18698
|
+
observe: (params, onResult, onError, options) => this.observe(slug, wrapped, inner, params, onResult, onError, options),
|
|
18699
|
+
observeById: (id, onResult, onError, options) => this.observeById(slug, wrapped, inner, id, onResult, onError, options),
|
|
18700
|
+
where(columnOrCondition, operator, value) {
|
|
18701
|
+
const builder = new SDKQueryBuilder(wrapped);
|
|
18702
|
+
if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
|
|
18703
|
+
return builder.where(columnOrCondition, operator, value);
|
|
18704
|
+
},
|
|
18705
|
+
orderBy: (column, direction) => new SDKQueryBuilder(wrapped).orderBy(column, direction),
|
|
18706
|
+
limit: (count) => new SDKQueryBuilder(wrapped).limit(count),
|
|
18707
|
+
offset: (count) => new SDKQueryBuilder(wrapped).offset(count),
|
|
18708
|
+
search: (searchString) => new SDKQueryBuilder(wrapped).search(searchString),
|
|
18709
|
+
include: (...relations) => new SDKQueryBuilder(wrapped).include(...relations)
|
|
18710
|
+
};
|
|
18711
|
+
if (inner.listen) wrapped.listen = (params, onUpdate, onError) => inner.listen(params, (response) => {
|
|
18712
|
+
this.ingest(slug, response.data ?? []).then(() => this.notifyCollection(slug, false));
|
|
18713
|
+
onUpdate(response);
|
|
18714
|
+
}, onError);
|
|
18715
|
+
if (inner.listenById) wrapped.listenById = (id, onUpdate, onError) => inner.listenById(id, (row) => {
|
|
18716
|
+
if (row) this.ingest(slug, [row]).then(() => this.notifyCollection(slug, false));
|
|
18717
|
+
onUpdate(row);
|
|
18718
|
+
}, onError);
|
|
18719
|
+
return wrapped;
|
|
18720
|
+
}
|
|
18721
|
+
observe(slug, wrapped, inner, params, onResult, onError, options) {
|
|
18722
|
+
let closed = false;
|
|
18723
|
+
let unlisten;
|
|
18724
|
+
const observer = {
|
|
18725
|
+
slug,
|
|
18726
|
+
params,
|
|
18727
|
+
settled: false,
|
|
18728
|
+
refresh: () => wrapped.find(params).catch(() => void 0),
|
|
18729
|
+
emit: () => {
|
|
18730
|
+
if (closed || !this.collections.get(slug)?.ready) return;
|
|
18731
|
+
const result = this.answer(slug, params, this.snapshotFor(slug, params));
|
|
18732
|
+
const signature = this.signature(slug, result.data, result.meta.total);
|
|
18733
|
+
if (observer.settled && signature === observer.signature) return;
|
|
18734
|
+
observer.signature = signature;
|
|
18735
|
+
observer.settled = true;
|
|
18736
|
+
onResult(observer.error ? {
|
|
18737
|
+
...result,
|
|
18738
|
+
error: observer.error
|
|
18739
|
+
} : result);
|
|
18740
|
+
}
|
|
18741
|
+
};
|
|
18742
|
+
this.observersFor(slug).add(observer);
|
|
18743
|
+
(async () => {
|
|
18744
|
+
await this.ensureCollection(slug);
|
|
18745
|
+
if (closed) return;
|
|
18746
|
+
if (this.hasLocalAnswer(this.collections.get(slug), slug, params)) observer.emit();
|
|
18747
|
+
try {
|
|
18748
|
+
await wrapped.find(params);
|
|
18749
|
+
observer.error = void 0;
|
|
18750
|
+
} catch (error) {
|
|
18751
|
+
observer.error = error;
|
|
18752
|
+
if (closed) return;
|
|
18753
|
+
if (!observer.settled) {
|
|
18754
|
+
onError?.(error);
|
|
18755
|
+
return;
|
|
18756
|
+
}
|
|
18757
|
+
}
|
|
18758
|
+
if (!closed) observer.emit();
|
|
18759
|
+
})();
|
|
18760
|
+
if (options?.realtime !== false && inner.listen) unlisten = inner.listen(params, (response) => {
|
|
18761
|
+
this.ingest(slug, response.data ?? []).then(() => {
|
|
18762
|
+
this.recordSnapshot(slug, params, response);
|
|
18763
|
+
this.notifyCollection(slug, false);
|
|
18764
|
+
});
|
|
18765
|
+
}, onError);
|
|
18766
|
+
return () => {
|
|
18767
|
+
closed = true;
|
|
18768
|
+
this.observersFor(slug).delete(observer);
|
|
18769
|
+
unlisten?.();
|
|
18770
|
+
};
|
|
18771
|
+
}
|
|
18772
|
+
observeById(slug, wrapped, inner, id, onResult, onError, options) {
|
|
18773
|
+
let closed = false;
|
|
18774
|
+
let unlisten;
|
|
18775
|
+
const observer = {
|
|
18776
|
+
slug,
|
|
18777
|
+
id,
|
|
18778
|
+
settled: false,
|
|
18779
|
+
refresh: () => wrapped.findById(id).catch(() => void 0),
|
|
18780
|
+
emit: () => {
|
|
18781
|
+
if (closed || !this.collections.get(slug)?.ready) return;
|
|
18782
|
+
const row = this.localRow(slug, id);
|
|
18783
|
+
const entry = this.collections.get(slug)?.rows.get(String(id));
|
|
18784
|
+
const signature = row === void 0 ? MISSING : `${String(id)}:${entry?.rev ?? 0}`;
|
|
18785
|
+
if (observer.settled && signature === observer.signature) return;
|
|
18786
|
+
observer.signature = signature;
|
|
18787
|
+
observer.settled = true;
|
|
18788
|
+
onResult(row, {
|
|
18789
|
+
fromCache: true,
|
|
18790
|
+
hasPendingWrites: this.hasPending(slug, id)
|
|
18791
|
+
});
|
|
18792
|
+
}
|
|
18793
|
+
};
|
|
18794
|
+
this.observersFor(slug).add(observer);
|
|
18795
|
+
(async () => {
|
|
18796
|
+
await this.ensureCollection(slug);
|
|
18797
|
+
if (closed) return;
|
|
18798
|
+
if (this.localRow(slug, id) !== void 0) observer.emit();
|
|
18799
|
+
try {
|
|
18800
|
+
await wrapped.findById(id);
|
|
18801
|
+
} catch (error) {
|
|
18802
|
+
if (closed) return;
|
|
18803
|
+
if (!observer.settled) {
|
|
18804
|
+
onError?.(error);
|
|
18805
|
+
return;
|
|
18806
|
+
}
|
|
18807
|
+
}
|
|
18808
|
+
if (!closed) observer.emit();
|
|
18809
|
+
})();
|
|
18810
|
+
if (options?.realtime !== false && inner.listenById) unlisten = inner.listenById(id, (row) => {
|
|
18811
|
+
if (!row) {
|
|
18812
|
+
if (!this.hasPending(slug, id)) this.removeLocalRow(slug, id, true);
|
|
18813
|
+
this.notifyCollection(slug, false);
|
|
18814
|
+
return;
|
|
18815
|
+
}
|
|
18816
|
+
this.ingest(slug, [row]).then(() => this.notifyCollection(slug, false));
|
|
18817
|
+
}, onError);
|
|
18818
|
+
return () => {
|
|
18819
|
+
closed = true;
|
|
18820
|
+
this.observersFor(slug).delete(observer);
|
|
18821
|
+
unlisten?.();
|
|
18822
|
+
};
|
|
18823
|
+
}
|
|
18824
|
+
observersFor(slug) {
|
|
18825
|
+
let set = this.observers.get(slug);
|
|
18826
|
+
if (!set) {
|
|
18827
|
+
set = /* @__PURE__ */ new Set();
|
|
18828
|
+
this.observers.set(slug, set);
|
|
18829
|
+
}
|
|
18830
|
+
return set;
|
|
18831
|
+
}
|
|
18832
|
+
/** Cheap change detection: which rows, in what order, at which revision. */
|
|
18833
|
+
signature(slug, rows, total) {
|
|
18834
|
+
const state = this.collections.get(slug);
|
|
18835
|
+
return `${total}|${rows.map((row) => {
|
|
18836
|
+
const key = String(row.id);
|
|
18837
|
+
return `${key}:${state?.rows.get(key)?.rev ?? 0}`;
|
|
18838
|
+
}).join(",")}`;
|
|
18839
|
+
}
|
|
18840
|
+
notifyCollection(slug, broadcast = true) {
|
|
18841
|
+
const set = this.observers.get(slug);
|
|
18842
|
+
if (set) for (const observer of [...set]) observer.emit();
|
|
18843
|
+
if (broadcast) this.broadcast({
|
|
18844
|
+
type: "rows",
|
|
18845
|
+
slugs: [slug]
|
|
18846
|
+
});
|
|
18847
|
+
}
|
|
18848
|
+
/** Connectivity came back (or the user changed): re-read everything live. */
|
|
18849
|
+
revalidateAll() {
|
|
18850
|
+
for (const slug of this.observers.keys()) {
|
|
18851
|
+
this.notifyCollection(slug, false);
|
|
18852
|
+
this.scheduleRefresh(slug);
|
|
18853
|
+
}
|
|
18854
|
+
}
|
|
18855
|
+
collectionState(slug) {
|
|
18856
|
+
let state = this.collections.get(slug);
|
|
18857
|
+
if (!state) {
|
|
18858
|
+
state = {
|
|
18859
|
+
rows: /* @__PURE__ */ new Map(),
|
|
18860
|
+
snapshots: /* @__PURE__ */ new Map(),
|
|
18861
|
+
absent: /* @__PURE__ */ new Set(),
|
|
18862
|
+
ready: false
|
|
18863
|
+
};
|
|
18864
|
+
this.collections.set(slug, state);
|
|
18865
|
+
}
|
|
18866
|
+
return state;
|
|
18867
|
+
}
|
|
18868
|
+
ensureCollection(slug) {
|
|
18869
|
+
const state = this.collectionState(slug);
|
|
18870
|
+
if (!state.loaded) {
|
|
18871
|
+
const scope = this.scope;
|
|
18872
|
+
state.loaded = (async () => {
|
|
18873
|
+
await this.ensureQueueLoaded();
|
|
18874
|
+
const [rows, snapshots, absent] = await Promise.all([
|
|
18875
|
+
this.store.listCacheEntries(`${scope}|row|${slug}|`).catch(() => []),
|
|
18876
|
+
this.store.listCacheEntries(`${scope}|q|${slug}|`).catch(() => []),
|
|
18877
|
+
this.store.listCache(`${scope}|abs|${slug}|`).catch(() => [])
|
|
18878
|
+
]);
|
|
18879
|
+
if (this.scope !== scope || this.collections.get(slug) !== state) return;
|
|
18880
|
+
for (const entry of rows) {
|
|
18881
|
+
const row = entry.value;
|
|
18882
|
+
if (!row || row.id === void 0 || row.id === null) continue;
|
|
18883
|
+
state.rows.set(String(row.id), {
|
|
18884
|
+
row: hydrateRow(row),
|
|
18885
|
+
cachedAt: entry.cachedAt,
|
|
18886
|
+
rev: ++this.revCounter
|
|
18887
|
+
});
|
|
18888
|
+
}
|
|
18889
|
+
for (const entry of snapshots) {
|
|
18890
|
+
const key = entry.key.slice(`${scope}|q|${slug}|`.length);
|
|
18891
|
+
if (entry.value) state.snapshots.set(key, entry.value);
|
|
18892
|
+
}
|
|
18893
|
+
for (const entry of absent) state.absent.add(entry.key.slice(`${scope}|abs|${slug}|`.length));
|
|
18894
|
+
})().catch(() => void 0).finally(() => {
|
|
18895
|
+
state.ready = true;
|
|
18896
|
+
});
|
|
18897
|
+
}
|
|
18898
|
+
return state.loaded.then(() => state);
|
|
18899
|
+
}
|
|
18900
|
+
snapshotFor(slug, params) {
|
|
18901
|
+
return this.collections.get(slug)?.snapshots.get(buildQueryString(params));
|
|
18902
|
+
}
|
|
18903
|
+
hasLocalAnswer(state, slug, params) {
|
|
18904
|
+
if (!state) return false;
|
|
18905
|
+
return state.snapshots.has(buildQueryString(params)) || state.rows.size > 0;
|
|
18906
|
+
}
|
|
18907
|
+
/**
|
|
18908
|
+
* Answer a query from the local database.
|
|
18909
|
+
*
|
|
18910
|
+
* With a snapshot, the server's own page — its ids, order and total — is
|
|
18911
|
+
* the skeleton, and the local rows fill it in: rows deleted locally drop
|
|
18912
|
+
* out, rows edited locally show the edit, and rows *created* locally join
|
|
18913
|
+
* the first page if they match. Without one, the query is evaluated
|
|
18914
|
+
* outright over every cached row, which is the best that can be done for a
|
|
18915
|
+
* query the server has never answered here.
|
|
18916
|
+
*/
|
|
18917
|
+
answer(slug, params, snapshot) {
|
|
18918
|
+
const state = this.collections.get(slug);
|
|
18919
|
+
const exact = isExactlyEvaluable(params);
|
|
18920
|
+
if (!state) return {
|
|
18921
|
+
data: [],
|
|
18922
|
+
meta: {
|
|
18923
|
+
total: 0,
|
|
18924
|
+
limit: params?.limit ?? 20,
|
|
18925
|
+
offset: params?.offset ?? 0,
|
|
18926
|
+
hasMore: false
|
|
18927
|
+
},
|
|
18928
|
+
fromCache: true,
|
|
18929
|
+
hasPendingWrites: false,
|
|
18930
|
+
partial: true
|
|
18931
|
+
};
|
|
18932
|
+
if (!snapshot) {
|
|
18933
|
+
const local = runLocalQuery([...state.rows.values()].map((e) => e.row), params);
|
|
18934
|
+
return {
|
|
18935
|
+
...local,
|
|
18936
|
+
fromCache: true,
|
|
18937
|
+
hasPendingWrites: local.data.some((row) => this.hasPending(slug, row.id)),
|
|
18938
|
+
partial: true
|
|
18939
|
+
};
|
|
18940
|
+
}
|
|
18941
|
+
const rows = [];
|
|
18942
|
+
const seen = /* @__PURE__ */ new Set();
|
|
18943
|
+
/** Rows the server counted that we know are no longer in the result. */
|
|
18944
|
+
let removed = 0;
|
|
18945
|
+
for (const id of snapshot.ids) {
|
|
18946
|
+
const key = String(id);
|
|
18947
|
+
const entry = state.rows.get(key);
|
|
18948
|
+
if (!entry) {
|
|
18949
|
+
if (state.absent.has(key) || this.hasPending(slug, key)) removed++;
|
|
18950
|
+
continue;
|
|
18951
|
+
}
|
|
18952
|
+
if (exact && this.hasPending(slug, key) && !matchesParams(entry.row, params)) {
|
|
18953
|
+
removed++;
|
|
18954
|
+
continue;
|
|
18955
|
+
}
|
|
18956
|
+
rows.push(entry.row);
|
|
18957
|
+
seen.add(key);
|
|
18958
|
+
}
|
|
18959
|
+
let added = 0;
|
|
18960
|
+
const offset = snapshot.offset ?? 0;
|
|
18961
|
+
if (exact && offset === 0) {
|
|
18962
|
+
for (const [key, entry] of state.rows) {
|
|
18963
|
+
if (seen.has(key) || !this.hasPending(slug, key)) continue;
|
|
18964
|
+
if (!this.isLocallyCreated(slug, key)) continue;
|
|
18965
|
+
if (!matchesParams(entry.row, params)) continue;
|
|
18966
|
+
rows.push(entry.row);
|
|
18967
|
+
added++;
|
|
18968
|
+
}
|
|
18969
|
+
if (added > 0 && params?.orderBy) sortRows(rows, params.orderBy);
|
|
18970
|
+
}
|
|
18971
|
+
return {
|
|
18972
|
+
data: rows,
|
|
18973
|
+
meta: {
|
|
18974
|
+
total: Math.max(rows.length, snapshot.total - removed + added),
|
|
18975
|
+
limit: snapshot.limit,
|
|
18976
|
+
offset,
|
|
18977
|
+
hasMore: snapshot.hasMore
|
|
18978
|
+
},
|
|
18979
|
+
fromCache: true,
|
|
18980
|
+
hasPendingWrites: rows.some((row) => this.hasPending(slug, row.id)),
|
|
18981
|
+
partial: !exact
|
|
18982
|
+
};
|
|
18983
|
+
}
|
|
18984
|
+
localFind(slug, params) {
|
|
18985
|
+
const state = this.collections.get(slug);
|
|
18986
|
+
const snapshot = this.snapshotFor(slug, params);
|
|
18987
|
+
if (!snapshot && (!state || state.rows.size === 0)) throw offlineError(`Offline: no cached data for "${slug}".`);
|
|
18988
|
+
const answer = this.answer(slug, params, snapshot);
|
|
18989
|
+
return snapshot ? answer : {
|
|
18990
|
+
...answer,
|
|
18991
|
+
partial: true
|
|
18992
|
+
};
|
|
18993
|
+
}
|
|
18994
|
+
rawLocalRow(slug, id) {
|
|
18995
|
+
const entry = this.collections.get(slug)?.rows.get(String(id));
|
|
18996
|
+
return entry ? { ...entry.row } : void 0;
|
|
18997
|
+
}
|
|
18998
|
+
localRow(slug, id) {
|
|
18999
|
+
return this.collections.get(slug)?.rows.get(String(id))?.row;
|
|
19000
|
+
}
|
|
19001
|
+
setLocalRow(slug, id, row) {
|
|
19002
|
+
const state = this.collectionState(slug);
|
|
19003
|
+
const key = String(id);
|
|
19004
|
+
const cachedAt = Date.now();
|
|
19005
|
+
state.rows.set(key, {
|
|
19006
|
+
row: { ...row },
|
|
19007
|
+
cachedAt,
|
|
19008
|
+
rev: ++this.revCounter
|
|
19009
|
+
});
|
|
19010
|
+
this.forgetTombstone(slug, key);
|
|
19011
|
+
this.writeCache(this.rowKey(slug, key), dehydrateRow(row), cachedAt);
|
|
19012
|
+
this.evictRows(slug);
|
|
19013
|
+
}
|
|
19014
|
+
/**
|
|
19015
|
+
* Drop a row and, when the server is the one saying it is gone, remember
|
|
19016
|
+
* that. "I looked it up and it does not exist" is real knowledge: without
|
|
19017
|
+
* it, opening a deleted row while offline would report a missing local
|
|
19018
|
+
* database instead of a missing row.
|
|
19019
|
+
*/
|
|
19020
|
+
removeLocalRow(slug, id, known = false) {
|
|
19021
|
+
const state = this.collectionState(slug);
|
|
19022
|
+
const key = String(id);
|
|
19023
|
+
const existed = state.rows.delete(key);
|
|
19024
|
+
if (known) {
|
|
19025
|
+
state.absent.add(key);
|
|
19026
|
+
this.writeCache(this.absentKey(slug, key), true);
|
|
19027
|
+
}
|
|
19028
|
+
if (existed) this.deleteCache([this.rowKey(slug, key)]);
|
|
19029
|
+
}
|
|
19030
|
+
forgetTombstone(slug, key) {
|
|
19031
|
+
if (!this.collectionState(slug).absent.delete(key)) return;
|
|
19032
|
+
this.deleteCache([this.absentKey(slug, key)]);
|
|
19033
|
+
}
|
|
19034
|
+
/**
|
|
19035
|
+
* Merge server rows into the local database. A row with unsynced local
|
|
19036
|
+
* writes keeps them: the server's copy is the base the queued mutations
|
|
19037
|
+
* are re-applied to, not a replacement for what the user did.
|
|
19038
|
+
*
|
|
19039
|
+
* Rows that came back unchanged keep their identity and revision, so a
|
|
19040
|
+
* refetch that changed nothing does not re-render every live query that
|
|
19041
|
+
* touches them — or rewrite them all to disk.
|
|
19042
|
+
*/
|
|
19043
|
+
async ingest(slug, rows) {
|
|
19044
|
+
if (rows.length === 0) return;
|
|
19045
|
+
const state = await this.ensureCollection(slug);
|
|
19046
|
+
const cachedAt = Date.now();
|
|
19047
|
+
const writes = [];
|
|
19048
|
+
const deletes = [];
|
|
19049
|
+
for (const raw of rows) {
|
|
19050
|
+
if (!raw || raw.id === void 0 || raw.id === null) continue;
|
|
19051
|
+
const key = String(raw.id);
|
|
19052
|
+
const merged = this.hasPending(slug, key) ? this.applyPendingToRow(slug, key, { ...raw }) : { ...raw };
|
|
19053
|
+
if (merged === void 0) {
|
|
19054
|
+
state.rows.delete(key);
|
|
19055
|
+
deletes.push(this.rowKey(slug, key));
|
|
19056
|
+
continue;
|
|
19057
|
+
}
|
|
19058
|
+
this.forgetTombstone(slug, key);
|
|
19059
|
+
const existing = state.rows.get(key);
|
|
19060
|
+
if (existing && JSON.stringify(existing.row) === JSON.stringify(merged)) {
|
|
19061
|
+
existing.cachedAt = cachedAt;
|
|
19062
|
+
continue;
|
|
19063
|
+
}
|
|
19064
|
+
state.rows.set(key, {
|
|
19065
|
+
row: merged,
|
|
19066
|
+
cachedAt,
|
|
19067
|
+
rev: ++this.revCounter
|
|
19068
|
+
});
|
|
19069
|
+
writes.push({
|
|
19070
|
+
key: this.rowKey(slug, key),
|
|
19071
|
+
entry: {
|
|
19072
|
+
value: dehydrateRow(merged),
|
|
19073
|
+
cachedAt
|
|
19074
|
+
}
|
|
19075
|
+
});
|
|
19076
|
+
}
|
|
19077
|
+
if (writes.length > 0) this.store.setCacheMany(writes).catch(() => void 0);
|
|
19078
|
+
if (deletes.length > 0) this.deleteCache(deletes);
|
|
19079
|
+
this.evictRows(slug);
|
|
19080
|
+
}
|
|
19081
|
+
/**
|
|
19082
|
+
* Fold the queued mutations for one row over a base, newest last.
|
|
19083
|
+
* `afterMutationId` skips everything up to and including that mutation,
|
|
19084
|
+
* which is how a just-replayed write avoids being applied on top of the
|
|
19085
|
+
* server's response to it.
|
|
19086
|
+
*/
|
|
19087
|
+
applyPendingToRow(slug, idKey, base, afterMutationId) {
|
|
19088
|
+
let row = base;
|
|
19089
|
+
let skipping = afterMutationId !== void 0;
|
|
19090
|
+
for (const op of this.queue) {
|
|
19091
|
+
if (skipping) {
|
|
19092
|
+
if (op.mutationId === afterMutationId) skipping = false;
|
|
19093
|
+
continue;
|
|
19094
|
+
}
|
|
19095
|
+
if (op.collection !== slug) continue;
|
|
19096
|
+
if (op.type === "createMany") {
|
|
19097
|
+
const match = op.data?.find((r) => String(r.id) === idKey);
|
|
19098
|
+
if (match) row = { ...match };
|
|
19099
|
+
continue;
|
|
19100
|
+
}
|
|
19101
|
+
if (op.id === void 0 || String(op.id) !== idKey) continue;
|
|
19102
|
+
if (op.type === "create") row = { ...op.data };
|
|
19103
|
+
else if (op.type === "update") row = {
|
|
19104
|
+
...row ?? {},
|
|
19105
|
+
...op.data,
|
|
19106
|
+
id: op.id
|
|
19107
|
+
};
|
|
19108
|
+
else if (op.type === "delete") row = void 0;
|
|
19109
|
+
}
|
|
19110
|
+
return row;
|
|
19111
|
+
}
|
|
19112
|
+
recordSnapshot(slug, params, result) {
|
|
19113
|
+
const meta = result.meta ?? {
|
|
19114
|
+
total: result.data?.length ?? 0,
|
|
19115
|
+
limit: 20,
|
|
19116
|
+
offset: 0,
|
|
19117
|
+
hasMore: false
|
|
19118
|
+
};
|
|
19119
|
+
const snapshot = {
|
|
19120
|
+
ids: (result.data ?? []).map((row) => row.id).filter((id) => id !== void 0),
|
|
19121
|
+
total: meta.total ?? result.data?.length ?? 0,
|
|
19122
|
+
limit: meta.limit ?? params?.limit ?? 20,
|
|
19123
|
+
offset: meta.offset ?? params?.offset ?? 0,
|
|
19124
|
+
hasMore: meta.hasMore ?? false
|
|
19125
|
+
};
|
|
19126
|
+
const state = this.collectionState(slug);
|
|
19127
|
+
const key = buildQueryString(params);
|
|
19128
|
+
state.snapshots.set(key, snapshot);
|
|
19129
|
+
this.writeCache(`${this.scope}|q|${slug}|${key}`, snapshot);
|
|
19130
|
+
this.evictSnapshots(slug);
|
|
19131
|
+
return snapshot;
|
|
19132
|
+
}
|
|
19133
|
+
/**
|
|
19134
|
+
* A write changed which rows belong in a list, and only the server can say
|
|
19135
|
+
* how — a row it generated is in no cached page, and the totals moved.
|
|
19136
|
+
* Re-run every live query on the collection; queries nobody is watching
|
|
19137
|
+
* are corrected by their next `find`.
|
|
19138
|
+
*
|
|
19139
|
+
* Coalesced per microtask so a burst of writes costs one round trip, and
|
|
19140
|
+
* skipped entirely while offline, where the local database is already the
|
|
19141
|
+
* best answer available.
|
|
19142
|
+
*/
|
|
19143
|
+
scheduleRefresh(slug) {
|
|
19144
|
+
if (this.refreshPending.has(slug)) return;
|
|
19145
|
+
const observers = this.observers.get(slug);
|
|
19146
|
+
if (!observers || observers.size === 0) return;
|
|
19147
|
+
this.refreshPending.add(slug);
|
|
19148
|
+
Promise.resolve().then(() => {
|
|
19149
|
+
this.refreshPending.delete(slug);
|
|
19150
|
+
if (this.disposed || !this.connectivity.shouldAttempt()) return;
|
|
19151
|
+
for (const observer of [...this.observers.get(slug) ?? []]) observer.refresh();
|
|
19152
|
+
});
|
|
19153
|
+
}
|
|
19154
|
+
evictRows(slug) {
|
|
19155
|
+
const state = this.collections.get(slug);
|
|
19156
|
+
if (!state || state.rows.size <= this.maxCachedRows) return;
|
|
19157
|
+
const evictable = [...state.rows.entries()].filter(([key]) => !this.hasPending(slug, key)).sort((a, b) => a[1].cachedAt - b[1].cachedAt);
|
|
19158
|
+
const excess = state.rows.size - this.maxCachedRows;
|
|
19159
|
+
const doomed = evictable.slice(0, excess);
|
|
19160
|
+
for (const [key] of doomed) state.rows.delete(key);
|
|
19161
|
+
if (doomed.length > 0) this.deleteCache(doomed.map(([key]) => this.rowKey(slug, key)));
|
|
19162
|
+
if (state.absent.size > this.maxCachedRows) {
|
|
19163
|
+
const stale = [...state.absent].slice(0, state.absent.size - this.maxCachedRows);
|
|
19164
|
+
for (const key of stale) state.absent.delete(key);
|
|
19165
|
+
this.deleteCache(stale.map((key) => this.absentKey(slug, key)));
|
|
19166
|
+
}
|
|
19167
|
+
}
|
|
19168
|
+
evictSnapshots(slug) {
|
|
19169
|
+
const state = this.collections.get(slug);
|
|
19170
|
+
if (!state || state.snapshots.size <= this.maxCachedQueries) return;
|
|
19171
|
+
const excess = state.snapshots.size - this.maxCachedQueries;
|
|
19172
|
+
const doomed = [...state.snapshots.keys()].slice(0, excess);
|
|
19173
|
+
for (const key of doomed) state.snapshots.delete(key);
|
|
19174
|
+
this.deleteCache(doomed.map((key) => `${this.scope}|q|${slug}|${key}`));
|
|
19175
|
+
}
|
|
19176
|
+
ensureQueueLoaded() {
|
|
19177
|
+
if (!this.queueLoad) {
|
|
19178
|
+
const scope = this.scope;
|
|
19179
|
+
this.queueLoad = this.store.listQueue(`${scope}|`).then((queue) => {
|
|
19180
|
+
if (this.scope !== scope) return;
|
|
19181
|
+
this.queue = queue;
|
|
19182
|
+
this.patchStatus({ pending: queue.length });
|
|
19183
|
+
this.notifyQueue();
|
|
19184
|
+
}).catch(() => void 0);
|
|
19185
|
+
}
|
|
19186
|
+
return this.queueLoad;
|
|
19187
|
+
}
|
|
19188
|
+
enqueue(mutation) {
|
|
19189
|
+
const result = this.enqueueChain.then(async () => {
|
|
19190
|
+
await this.ensureQueueLoaded();
|
|
19191
|
+
if (mutation.type === "update") {
|
|
19192
|
+
const tail = this.queue[this.queue.length - 1];
|
|
19193
|
+
if (tail && tail.collection === mutation.collection && (tail.type === "create" || tail.type === "update") && tail.id === mutation.id) {
|
|
19194
|
+
tail.data = {
|
|
19195
|
+
...tail.data,
|
|
19196
|
+
...mutation.data,
|
|
19197
|
+
id: tail.id
|
|
19198
|
+
};
|
|
19199
|
+
await this.store.enqueue(this.queueKey(tail), tail);
|
|
19200
|
+
return;
|
|
19201
|
+
}
|
|
19202
|
+
}
|
|
19203
|
+
if (mutation.type === "delete") {
|
|
19204
|
+
if (this.queue.some((m) => m.collection === mutation.collection && m.type === "create" && m.id === mutation.id && m.generatedId === true)) {
|
|
19205
|
+
const doomed = this.queue.filter((m) => m.collection === mutation.collection && m.id === mutation.id && (m.type === "create" || m.type === "update"));
|
|
19206
|
+
for (const op of doomed) await this.store.dequeue(this.queueKey(op));
|
|
19207
|
+
this.queue = this.queue.filter((m) => !doomed.includes(m));
|
|
19208
|
+
this.afterQueueChange();
|
|
19209
|
+
return;
|
|
19210
|
+
}
|
|
19211
|
+
}
|
|
19212
|
+
const full = {
|
|
19213
|
+
...mutation,
|
|
19214
|
+
mutationId: createMutationId(),
|
|
19215
|
+
queuedAt: Date.now()
|
|
19216
|
+
};
|
|
19217
|
+
await this.store.enqueue(this.queueKey(full), full);
|
|
19218
|
+
this.queue.push(full);
|
|
19219
|
+
this.afterQueueChange();
|
|
19220
|
+
});
|
|
19221
|
+
this.enqueueChain = result.catch(() => void 0);
|
|
19222
|
+
return result;
|
|
19223
|
+
}
|
|
19224
|
+
hasPending(slug, id) {
|
|
19225
|
+
const key = String(id);
|
|
19226
|
+
return this.queue.some((op) => {
|
|
19227
|
+
if (op.collection !== slug) return false;
|
|
19228
|
+
if (op.type === "createMany") return op.data?.some((r) => String(r.id) === key) ?? false;
|
|
19229
|
+
return op.id !== void 0 && String(op.id) === key;
|
|
19230
|
+
});
|
|
19231
|
+
}
|
|
19232
|
+
/** Is this row one the server has never been told about? */
|
|
19233
|
+
isLocallyCreated(slug, idKey) {
|
|
19234
|
+
return this.queue.some((op) => {
|
|
19235
|
+
if (op.collection !== slug) return false;
|
|
19236
|
+
if (op.type === "create") return op.id !== void 0 && String(op.id) === idKey;
|
|
19237
|
+
if (op.type === "createMany") return op.data?.some((r) => String(r.id) === idKey) ?? false;
|
|
19238
|
+
return false;
|
|
19239
|
+
});
|
|
19240
|
+
}
|
|
19241
|
+
/** How many rows the queue adds to (or removes from) a server-side count. */
|
|
19242
|
+
pendingDelta(slug, params) {
|
|
19243
|
+
if (!isExactlyEvaluable(params)) return 0;
|
|
19244
|
+
let delta = 0;
|
|
19245
|
+
for (const op of this.queue) {
|
|
19246
|
+
if (op.collection !== slug) continue;
|
|
19247
|
+
if (op.type === "create") {
|
|
19248
|
+
if (matchesParams(op.data, params)) delta++;
|
|
19249
|
+
} else if (op.type === "createMany") {
|
|
19250
|
+
for (const row of op.data ?? []) if (matchesParams(row, params)) delta++;
|
|
19251
|
+
} else if (op.type === "delete") {
|
|
19252
|
+
const before = op.rollback?.rows?.[String(op.id)];
|
|
19253
|
+
if (before && matchesParams(before, params)) delta--;
|
|
19254
|
+
}
|
|
19255
|
+
}
|
|
19256
|
+
return delta;
|
|
19257
|
+
}
|
|
19258
|
+
sync() {
|
|
19259
|
+
if (this.flushPromise) return this.flushPromise;
|
|
19260
|
+
this.flushPromise = this.withLock(() => this.flush()).finally(() => {
|
|
19261
|
+
this.flushPromise = void 0;
|
|
19262
|
+
});
|
|
19263
|
+
return this.flushPromise;
|
|
19264
|
+
}
|
|
19265
|
+
async flush() {
|
|
19266
|
+
await this.ensureQueueLoaded();
|
|
19267
|
+
await this.reloadQueue();
|
|
19268
|
+
if (this.queue.length === 0) return {
|
|
19269
|
+
flushed: 0,
|
|
19270
|
+
remaining: 0
|
|
19271
|
+
};
|
|
19272
|
+
this.patchStatus({ syncing: true });
|
|
19273
|
+
const touched = /* @__PURE__ */ new Set();
|
|
19274
|
+
const queuedAtStart = this.queue.length;
|
|
19275
|
+
let flushed = 0;
|
|
19276
|
+
try {
|
|
19277
|
+
while (this.queue.length > 0 && !this.disposed) {
|
|
19278
|
+
const op = this.queue[0];
|
|
19279
|
+
touched.add(op.collection);
|
|
19280
|
+
try {
|
|
19281
|
+
await this.replay(op);
|
|
19282
|
+
} catch (error) {
|
|
19283
|
+
if (isNetworkError(error)) {
|
|
19284
|
+
this.connectivity.markFailure();
|
|
19285
|
+
break;
|
|
19286
|
+
}
|
|
19287
|
+
op.attempts = (op.attempts ?? 0) + 1;
|
|
19288
|
+
op.lastError = error?.message ?? String(error);
|
|
19289
|
+
if (isRetryableError(error) && op.attempts < this.maxRetries) {
|
|
19290
|
+
await this.store.enqueue(this.queueKey(op), op).catch(() => void 0);
|
|
19291
|
+
this.connectivity.deferRetry();
|
|
19292
|
+
this.patchStatus({ lastError: op.lastError });
|
|
19293
|
+
break;
|
|
19294
|
+
}
|
|
19295
|
+
await this.rejectMutation(op, error);
|
|
19296
|
+
continue;
|
|
19297
|
+
}
|
|
19298
|
+
this.connectivity.markSuccess();
|
|
19299
|
+
await this.drop(op);
|
|
19300
|
+
flushed++;
|
|
19301
|
+
}
|
|
19302
|
+
} finally {
|
|
19303
|
+
this.patchStatus({ syncing: false });
|
|
19304
|
+
}
|
|
19305
|
+
if (this.queue.length !== queuedAtStart) {
|
|
19306
|
+
for (const slug of touched) {
|
|
19307
|
+
this.notifyCollection(slug);
|
|
19308
|
+
this.scheduleRefresh(slug);
|
|
19309
|
+
}
|
|
19310
|
+
this.broadcast({ type: "queue" });
|
|
19311
|
+
}
|
|
19312
|
+
if (this.queue.length === 0) this.patchStatus({ lastSyncedAt: Date.now() });
|
|
19313
|
+
return {
|
|
19314
|
+
flushed,
|
|
19315
|
+
remaining: this.queue.length
|
|
19316
|
+
};
|
|
19317
|
+
}
|
|
19318
|
+
async replay(op) {
|
|
19319
|
+
const inner = this.innerFor(op.collection);
|
|
19320
|
+
if (op.type === "create") {
|
|
19321
|
+
const row = await inner.create(op.data);
|
|
19322
|
+
await this.adoptServerRow(op, op.id, row);
|
|
19323
|
+
} else if (op.type === "createMany") {
|
|
19324
|
+
const queued = op.data ?? [];
|
|
19325
|
+
const rows = await inner.createMany(queued, op.upsert ? { upsert: true } : void 0);
|
|
19326
|
+
for (let i = 0; i < rows.length; i++) await this.adoptServerRow(op, queued[i]?.id, rows[i]);
|
|
19327
|
+
} else if (op.type === "update") {
|
|
19328
|
+
const row = await inner.update(op.id, op.data);
|
|
19329
|
+
await this.ingestReplaced(op, op.id, row);
|
|
19330
|
+
} else if (op.type === "delete") {
|
|
19331
|
+
await inner.delete(op.id);
|
|
19332
|
+
this.removeLocalRow(op.collection, op.id, true);
|
|
19333
|
+
}
|
|
19334
|
+
}
|
|
19335
|
+
/**
|
|
19336
|
+
* Take the server's version of a row the client created offline.
|
|
19337
|
+
*
|
|
19338
|
+
* The server may have assigned a different id — a serial column ignores
|
|
19339
|
+
* the id we invented — in which case every local trace of the temporary id
|
|
19340
|
+
* has to move with it, including queued writes that were made against it
|
|
19341
|
+
* before it was ever sent.
|
|
19342
|
+
*/
|
|
19343
|
+
async adoptServerRow(op, localId, row) {
|
|
19344
|
+
if (!row) return;
|
|
19345
|
+
const slug = op.collection;
|
|
19346
|
+
const serverId = row.id;
|
|
19347
|
+
if (localId !== void 0 && serverId !== void 0 && String(serverId) !== String(localId)) {
|
|
19348
|
+
const oldKey = String(localId);
|
|
19349
|
+
this.removeLocalRow(slug, localId);
|
|
19350
|
+
for (const queued of this.queue) {
|
|
19351
|
+
if (queued.collection !== slug) continue;
|
|
19352
|
+
let dirty = false;
|
|
19353
|
+
if (queued.id !== void 0 && String(queued.id) === oldKey) {
|
|
19354
|
+
queued.id = serverId;
|
|
19355
|
+
if (queued.data && !Array.isArray(queued.data)) queued.data.id = serverId;
|
|
19356
|
+
dirty = true;
|
|
19357
|
+
}
|
|
19358
|
+
const rollbackRows = queued.rollback?.rows;
|
|
19359
|
+
if (rollbackRows && oldKey in rollbackRows) {
|
|
19360
|
+
rollbackRows[String(serverId)] = rollbackRows[oldKey];
|
|
19361
|
+
delete rollbackRows[oldKey];
|
|
19362
|
+
dirty = true;
|
|
19363
|
+
}
|
|
19364
|
+
if (dirty) await this.store.enqueue(this.queueKey(queued), queued).catch(() => void 0);
|
|
19365
|
+
}
|
|
19366
|
+
}
|
|
19367
|
+
await this.ingestReplaced(op, serverId ?? localId, row);
|
|
19368
|
+
}
|
|
19369
|
+
/**
|
|
19370
|
+
* Write a server row over the local one, ignoring the mutation that just
|
|
19371
|
+
* produced it — re-applying that would put the pre-server values back on
|
|
19372
|
+
* top of the server's answer — but keeping every write queued *after* it.
|
|
19373
|
+
* Those are still unsent, and dropping them here would make the row snap
|
|
19374
|
+
* back to the server's version in front of the user, only to change again
|
|
19375
|
+
* when they replay a moment later.
|
|
19376
|
+
*/
|
|
19377
|
+
async ingestReplaced(op, id, row) {
|
|
19378
|
+
const slug = op.collection;
|
|
19379
|
+
const state = await this.ensureCollection(slug);
|
|
19380
|
+
const key = String(id);
|
|
19381
|
+
const merged = this.applyPendingToRow(slug, key, { ...row }, op.mutationId);
|
|
19382
|
+
if (merged === void 0) {
|
|
19383
|
+
this.removeLocalRow(slug, key);
|
|
19384
|
+
return;
|
|
19385
|
+
}
|
|
19386
|
+
const cachedAt = Date.now();
|
|
19387
|
+
state.rows.set(key, {
|
|
19388
|
+
row: merged,
|
|
19389
|
+
cachedAt,
|
|
19390
|
+
rev: ++this.revCounter
|
|
19391
|
+
});
|
|
19392
|
+
this.writeCache(this.rowKey(slug, key), dehydrateRow(merged), cachedAt);
|
|
19393
|
+
}
|
|
19394
|
+
/**
|
|
19395
|
+
* The server refused a mutation. Put back what it changed, and discard the
|
|
19396
|
+
* queued writes that were built on top of it: an edit to a row whose
|
|
19397
|
+
* creation was rejected can only fail the same way, and applying it would
|
|
19398
|
+
* leave the local database claiming a row the server does not have.
|
|
19399
|
+
*
|
|
19400
|
+
* The cascade stops the moment a later write stops *depending* on the
|
|
19401
|
+
* rejected one. An `update` reads the row it edits, so it is doomed with
|
|
19402
|
+
* it; a `create` overwrites the row outright and a `delete` needs nothing
|
|
19403
|
+
* of it, so both stand on their own and are kept — dropping them would
|
|
19404
|
+
* silently lose writes the server would have accepted.
|
|
19405
|
+
*/
|
|
19406
|
+
async rejectMutation(op, error) {
|
|
19407
|
+
const ids = new Set(Object.keys(op.rollback?.rows ?? {}));
|
|
19408
|
+
if (op.id !== void 0) ids.add(String(op.id));
|
|
19409
|
+
const doomed = [op];
|
|
19410
|
+
const orphaned = new Set(ids);
|
|
19411
|
+
const position = this.queue.indexOf(op);
|
|
19412
|
+
for (const later of this.queue.slice(position + 1)) {
|
|
19413
|
+
if (later.collection !== op.collection) continue;
|
|
19414
|
+
const hit = this.idsOf(later).filter((id) => orphaned.has(id));
|
|
19415
|
+
if (hit.length === 0) continue;
|
|
19416
|
+
if (later.type === "update") doomed.push(later);
|
|
19417
|
+
else for (const id of hit) orphaned.delete(id);
|
|
19418
|
+
}
|
|
19419
|
+
for (const dropped of doomed) await this.drop(dropped);
|
|
19420
|
+
for (const [idKey, previous] of Object.entries(op.rollback?.rows ?? {})) {
|
|
19421
|
+
const restored = this.applyPendingToRow(op.collection, idKey, previous ?? void 0);
|
|
19422
|
+
if (restored === void 0) this.removeLocalRow(op.collection, idKey);
|
|
19423
|
+
else this.setLocalRow(op.collection, idKey, restored);
|
|
19424
|
+
}
|
|
19425
|
+
this.patchStatus({ lastError: error.message });
|
|
19426
|
+
this.notifyCollection(op.collection);
|
|
19427
|
+
this.scheduleRefresh(op.collection);
|
|
19428
|
+
for (const dropped of doomed) this.onSyncError?.(error, dropped);
|
|
19429
|
+
}
|
|
19430
|
+
/** Every row id a mutation writes to. */
|
|
19431
|
+
idsOf(op) {
|
|
19432
|
+
if (op.type === "createMany") return (op.data ?? []).map((r) => String(r.id));
|
|
19433
|
+
return op.id === void 0 ? [] : [String(op.id)];
|
|
19434
|
+
}
|
|
19435
|
+
async drop(op) {
|
|
19436
|
+
await this.store.dequeue(this.queueKey(op)).catch(() => void 0);
|
|
19437
|
+
this.queue = this.queue.filter((m) => m.mutationId !== op.mutationId);
|
|
19438
|
+
this.afterQueueChange(false);
|
|
19439
|
+
}
|
|
19440
|
+
/** Replay uses unwrapped clients: a failure must never re-enqueue itself. */
|
|
19441
|
+
innerFor(slug) {
|
|
19442
|
+
let inner = this.inners.get(slug);
|
|
19443
|
+
if (!inner) {
|
|
19444
|
+
inner = this.createInner(slug);
|
|
19445
|
+
this.inners.set(slug, inner);
|
|
19446
|
+
}
|
|
19447
|
+
return inner;
|
|
19448
|
+
}
|
|
19449
|
+
async withLock(fn) {
|
|
19450
|
+
const locks = globalThis.navigator?.locks;
|
|
19451
|
+
if (!locks?.request) return fn();
|
|
19452
|
+
try {
|
|
19453
|
+
return await locks.request(`rebase-offline-sync:${this.scope}`, fn);
|
|
19454
|
+
} catch {
|
|
19455
|
+
return fn();
|
|
19456
|
+
}
|
|
19457
|
+
}
|
|
19458
|
+
broadcast(message) {
|
|
19459
|
+
if (!this.channel) return;
|
|
19460
|
+
try {
|
|
19461
|
+
this.channel.postMessage({
|
|
19462
|
+
...message,
|
|
19463
|
+
scope: this.scope,
|
|
19464
|
+
sender: this.tabId
|
|
19465
|
+
});
|
|
19466
|
+
} catch {}
|
|
19467
|
+
}
|
|
19468
|
+
onBroadcast(message) {
|
|
19469
|
+
if (this.disposed || !message || typeof message !== "object") return;
|
|
19470
|
+
const msg = message;
|
|
19471
|
+
if (msg.sender === this.tabId || msg.scope !== this.scope) return;
|
|
19472
|
+
if (msg.type === "rows") for (const slug of msg.slugs ?? []) this.reloadCollection(slug);
|
|
19473
|
+
else if (msg.type === "queue") this.reloadQueue();
|
|
19474
|
+
}
|
|
19475
|
+
/** Re-read one collection from the store, replacing what is in memory. */
|
|
19476
|
+
async reloadCollection(slug) {
|
|
19477
|
+
const state = this.collections.get(slug);
|
|
19478
|
+
if (!state?.loaded) return;
|
|
19479
|
+
await this.reloadQueue();
|
|
19480
|
+
const scope = this.scope;
|
|
19481
|
+
const [rows, snapshots, absent] = await Promise.all([
|
|
19482
|
+
this.store.listCacheEntries(`${scope}|row|${slug}|`).catch(() => []),
|
|
19483
|
+
this.store.listCacheEntries(`${scope}|q|${slug}|`).catch(() => []),
|
|
19484
|
+
this.store.listCache(`${scope}|abs|${slug}|`).catch(() => [])
|
|
19485
|
+
]);
|
|
19486
|
+
if (this.scope !== scope || this.collections.get(slug) !== state) return;
|
|
19487
|
+
const next = /* @__PURE__ */ new Map();
|
|
19488
|
+
for (const entry of rows) {
|
|
19489
|
+
const row = entry.value;
|
|
19490
|
+
if (!row || row.id === void 0 || row.id === null) continue;
|
|
19491
|
+
const key = String(row.id);
|
|
19492
|
+
const existing = state.rows.get(key);
|
|
19493
|
+
const hydrated = hydrateRow(row);
|
|
19494
|
+
const unchanged = existing && JSON.stringify(existing.row) === JSON.stringify(hydrated);
|
|
19495
|
+
next.set(key, {
|
|
19496
|
+
row: hydrated,
|
|
19497
|
+
cachedAt: entry.cachedAt,
|
|
19498
|
+
rev: unchanged ? existing.rev : ++this.revCounter
|
|
19499
|
+
});
|
|
19500
|
+
}
|
|
19501
|
+
state.rows = next;
|
|
19502
|
+
state.snapshots = /* @__PURE__ */ new Map();
|
|
19503
|
+
for (const entry of snapshots) {
|
|
19504
|
+
const key = entry.key.slice(`${scope}|q|${slug}|`.length);
|
|
19505
|
+
if (entry.value) state.snapshots.set(key, entry.value);
|
|
19506
|
+
}
|
|
19507
|
+
state.absent = new Set(absent.map((entry) => entry.key.slice(`${scope}|abs|${slug}|`.length)));
|
|
19508
|
+
this.notifyCollection(slug, false);
|
|
19509
|
+
}
|
|
19510
|
+
async reloadQueue() {
|
|
19511
|
+
const scope = this.scope;
|
|
19512
|
+
const queue = await this.store.listQueue(`${scope}|`).catch(() => void 0);
|
|
19513
|
+
if (!queue || this.scope !== scope) return;
|
|
19514
|
+
this.queue = queue;
|
|
19515
|
+
this.afterQueueChange(false);
|
|
19516
|
+
}
|
|
19517
|
+
afterQueueChange(broadcast = true) {
|
|
19518
|
+
this.patchStatus({ pending: this.queue.length });
|
|
19519
|
+
this.notifyQueue();
|
|
19520
|
+
if (broadcast) this.broadcast({ type: "queue" });
|
|
19521
|
+
}
|
|
19522
|
+
notifyQueue() {
|
|
19523
|
+
for (const listener of this.queueListeners) listener(this.queue.length);
|
|
19524
|
+
}
|
|
19525
|
+
patchStatus(patch) {
|
|
19526
|
+
let changed = false;
|
|
19527
|
+
for (const [key, value] of Object.entries(patch)) if (this.currentStatus[key] !== value) {
|
|
19528
|
+
this.currentStatus[key] = value;
|
|
19529
|
+
changed = true;
|
|
19530
|
+
}
|
|
19531
|
+
if (!changed) return;
|
|
19532
|
+
const snapshot = { ...this.currentStatus };
|
|
19533
|
+
for (const listener of this.statusListeners) listener(snapshot);
|
|
19534
|
+
}
|
|
19535
|
+
countKey(slug, params) {
|
|
19536
|
+
return `${this.scope}|count|${slug}|${buildQueryString(params)}`;
|
|
19537
|
+
}
|
|
19538
|
+
rowKey(slug, id) {
|
|
19539
|
+
return `${this.scope}|row|${slug}|${String(id)}`;
|
|
19540
|
+
}
|
|
19541
|
+
absentKey(slug, id) {
|
|
19542
|
+
return `${this.scope}|abs|${slug}|${String(id)}`;
|
|
19543
|
+
}
|
|
19544
|
+
queueKey(mutation) {
|
|
19545
|
+
return `${this.scope}|${mutation.mutationId}`;
|
|
19546
|
+
}
|
|
19547
|
+
async readCache(key) {
|
|
19548
|
+
try {
|
|
19549
|
+
return (await this.store.getCache(key))?.value;
|
|
19550
|
+
} catch {
|
|
19551
|
+
return;
|
|
19552
|
+
}
|
|
19553
|
+
}
|
|
19554
|
+
async writeCache(key, value, cachedAt = Date.now()) {
|
|
19555
|
+
try {
|
|
19556
|
+
await this.store.setCache(key, {
|
|
19557
|
+
value,
|
|
19558
|
+
cachedAt
|
|
19559
|
+
});
|
|
19560
|
+
} catch {}
|
|
19561
|
+
}
|
|
19562
|
+
async deleteCache(keys) {
|
|
19563
|
+
try {
|
|
19564
|
+
await this.store.deleteCache(keys);
|
|
19565
|
+
} catch {}
|
|
19566
|
+
}
|
|
19567
|
+
};
|
|
19568
|
+
/**
|
|
17636
19569
|
* Derive a WebSocket URL from an HTTP base URL.
|
|
17637
19570
|
* `http://` → `ws://`, `https://` → `wss://`.
|
|
17638
19571
|
*/
|
|
@@ -17755,10 +19688,20 @@ function createRebaseClient(options) {
|
|
|
17755
19688
|
if (diffs <= 1) return key;
|
|
17756
19689
|
}
|
|
17757
19690
|
}
|
|
19691
|
+
const offlineManager = options.offline ? new OfflineManager(typeof options.offline === "object" ? options.offline : {}, (slug) => createCollectionClient(transport, slug)) : void 0;
|
|
19692
|
+
if (offlineManager) {
|
|
19693
|
+
offlineManager.setScope(auth.getSession()?.user?.uid);
|
|
19694
|
+
auth.onAuthStateChange((event, session) => {
|
|
19695
|
+
offlineManager.setScope(event === "SIGNED_OUT" ? void 0 : session?.user?.uid);
|
|
19696
|
+
});
|
|
19697
|
+
}
|
|
17758
19698
|
const collectionClients = /* @__PURE__ */ new Map();
|
|
17759
19699
|
let untypedWarned = false;
|
|
17760
19700
|
function collection(slug) {
|
|
17761
|
-
if (!collectionClients.has(slug))
|
|
19701
|
+
if (!collectionClients.has(slug)) {
|
|
19702
|
+
const inner = createCollectionClient(transport, slug, ws);
|
|
19703
|
+
collectionClients.set(slug, offlineManager ? offlineManager.wrap(slug, inner) : inner);
|
|
19704
|
+
}
|
|
17762
19705
|
return collectionClients.get(slug);
|
|
17763
19706
|
}
|
|
17764
19707
|
const dataProxy = new Proxy({ collection }, { get(_target, prop) {
|
|
@@ -17822,6 +19765,7 @@ channel: (name, options) => {
|
|
|
17822
19765
|
for (const channel of realtimeChannels.values()) channel.leave();
|
|
17823
19766
|
realtimeChannels.clear();
|
|
17824
19767
|
ws?.disconnect(true);
|
|
19768
|
+
offlineManager?.dispose();
|
|
17825
19769
|
},
|
|
17826
19770
|
setToken: transport.setToken,
|
|
17827
19771
|
setAuthTokenGetter: transport.setAuthTokenGetter,
|
|
@@ -17837,7 +19781,8 @@ channel: (name, options) => {
|
|
|
17837
19781
|
});
|
|
17838
19782
|
return res.data ?? res;
|
|
17839
19783
|
},
|
|
17840
|
-
data: dataProxy
|
|
19784
|
+
data: dataProxy,
|
|
19785
|
+
...offlineManager ? { offline: offlineManager.api } : {}
|
|
17841
19786
|
};
|
|
17842
19787
|
}
|
|
17843
19788
|
//#endregion
|
|
@@ -19779,7 +21724,7 @@ var authJwt = () => {
|
|
|
19779
21724
|
* avoids the need for hardcoded dev secrets.
|
|
19780
21725
|
*/
|
|
19781
21726
|
function generateSecret(bytes = 48) {
|
|
19782
|
-
return crypto.randomBytes(bytes).toString("hex");
|
|
21727
|
+
return crypto$1.randomBytes(bytes).toString("hex");
|
|
19783
21728
|
}
|
|
19784
21729
|
/**
|
|
19785
21730
|
* Zod coercion helper: transforms `"true"` → `true`, everything else → `false`.
|