@marktiderman/genesis-core 2.9.0 → 2.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -1
- package/dist/{chunk-LGTXQTHA.js → chunk-2VJQVAJD.js} +3 -3
- package/dist/{chunk-LGTXQTHA.js.map → chunk-2VJQVAJD.js.map} +1 -1
- package/dist/chunk-2WS4LGYU.js +47 -0
- package/dist/chunk-2WS4LGYU.js.map +1 -0
- package/dist/{chunk-X6EVE7W4.js → chunk-3B5O36DU.js} +112 -19
- package/dist/chunk-3B5O36DU.js.map +1 -0
- package/dist/{chunk-EHFYSJJA.js → chunk-42QPCDQF.js} +3 -3
- package/dist/{chunk-EHFYSJJA.js.map → chunk-42QPCDQF.js.map} +1 -1
- package/dist/{chunk-RK365SO2.js → chunk-AKF2RAGX.js} +8 -5
- package/dist/chunk-AKF2RAGX.js.map +1 -0
- package/dist/{chunk-4ZR7472O.js → chunk-LOJGHR5O.js} +4 -4
- package/dist/{chunk-4ZR7472O.js.map → chunk-LOJGHR5O.js.map} +1 -1
- package/dist/{chunk-ON2V4RXX.js → chunk-OC4OGB2K.js} +19 -11
- package/dist/chunk-OC4OGB2K.js.map +1 -0
- package/dist/{chunk-HQAVDVIH.js → chunk-POMTRNAL.js} +4 -4
- package/dist/{chunk-HQAVDVIH.js.map → chunk-POMTRNAL.js.map} +1 -1
- package/dist/{chunk-VDEW4AOS.js → chunk-PSFKIG27.js} +55 -6
- package/dist/chunk-PSFKIG27.js.map +1 -0
- package/dist/{chunk-37RWGNIO.js → chunk-VFT6QKZW.js} +114 -5
- package/dist/chunk-VFT6QKZW.js.map +1 -0
- package/dist/{chunk-IQVIHN7C.js → chunk-VJGU6E4U.js} +19 -13
- package/dist/chunk-VJGU6E4U.js.map +1 -0
- package/dist/{chunk-ZCE3CHPX.js → chunk-XVRIWP7B.js} +3 -3
- package/dist/{chunk-ZCE3CHPX.js.map → chunk-XVRIWP7B.js.map} +1 -1
- package/dist/{chunk-7FVTGKTX.js → chunk-YDMKMNDS.js} +2 -2
- package/dist/{chunk-7FVTGKTX.js.map → chunk-YDMKMNDS.js.map} +1 -1
- package/dist/{chunk-6WV6ST67.js → chunk-YNXLPOAB.js} +97 -10
- package/dist/chunk-YNXLPOAB.js.map +1 -0
- package/dist/{chunk-7GW3QR63.js → chunk-ZHC3MDCS.js} +101 -18
- package/dist/chunk-ZHC3MDCS.js.map +1 -0
- package/dist/conversation/index.d.ts +195 -0
- package/dist/conversation/index.js +110 -0
- package/dist/conversation/index.js.map +1 -0
- package/dist/csv.d.ts +1 -1
- package/dist/errors.js +1 -2
- package/dist/form-types.d.ts +1 -1
- package/dist/gallery/index.d.ts +79 -0
- package/dist/gallery/index.js +64 -0
- package/dist/gallery/index.js.map +1 -0
- package/dist/hooks/index.d.ts +5 -4
- package/dist/hooks/index.js +18 -18
- package/dist/hooks/mutation-mode.d.ts +29 -2
- package/dist/hooks/mutation-mode.js +9 -4
- package/dist/hooks/related-keys.d.ts +1 -1
- package/dist/hooks/use-capabilities.d.ts +1 -1
- package/dist/hooks/use-capabilities.js +2 -2
- package/dist/hooks/use-infinite-resource.d.ts +1 -1
- package/dist/hooks/use-infinite-resource.js +4 -4
- package/dist/hooks/use-link-options.d.ts +10 -2
- package/dist/hooks/use-link-options.js +6 -6
- package/dist/hooks/use-live.d.ts +1 -1
- package/dist/hooks/use-live.js +3 -3
- package/dist/hooks/use-one.d.ts +1 -1
- package/dist/hooks/use-one.js +4 -4
- package/dist/hooks/use-relation-label.d.ts +1 -1
- package/dist/hooks/use-relation-label.js +2 -2
- package/dist/hooks/use-resource-form.d.ts +20 -1
- package/dist/hooks/use-resource-form.js +12 -9
- package/dist/hooks/use-resource.d.ts +17 -3
- package/dist/hooks/use-resource.js +12 -8
- package/dist/hooks/use-write.d.ts +1 -1
- package/dist/index.d.ts +8 -6
- package/dist/index.js +21 -21
- package/dist/offline/index.d.ts +84 -0
- package/dist/offline/index.js +413 -0
- package/dist/offline/index.js.map +1 -0
- package/dist/provider/index.d.ts +60 -7
- package/dist/provider/index.js +3 -3
- package/dist/resource-view/index.d.ts +113 -4
- package/dist/resource-view/index.js +183 -25
- package/dist/resource-view/index.js.map +1 -1
- package/dist/schema/index.d.ts +4 -3
- package/dist/schema/index.js +2 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/{types-r_Rlw7BB.d.ts → types-BzLv8yOm.d.ts} +22 -0
- package/dist/types-CsKSAKqs.d.ts +143 -0
- package/dist/{viewer-scope-bthEYSOB.d.ts → viewer-scope-Dx0N9AYk.d.ts} +3 -2
- package/dist/workspaces.d.ts +1 -1
- package/dist/{write-outcome-BWV34wh5.d.ts → write-outcome-DC5hORz-.d.ts} +1 -1
- package/dist/write-state-DVC4Yq9T.d.ts +58 -0
- package/package.json +15 -2
- package/dist/chunk-37RWGNIO.js.map +0 -1
- package/dist/chunk-6WV6ST67.js.map +0 -1
- package/dist/chunk-7GW3QR63.js.map +0 -1
- package/dist/chunk-IQVIHN7C.js.map +0 -1
- package/dist/chunk-ON2V4RXX.js.map +0 -1
- package/dist/chunk-PA6WJE5E.js +0 -115
- package/dist/chunk-PA6WJE5E.js.map +0 -1
- package/dist/chunk-RK365SO2.js.map +0 -1
- package/dist/chunk-VDEW4AOS.js.map +0 -1
- package/dist/chunk-X6EVE7W4.js.map +0 -1
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
// src/offline/types.ts
|
|
2
|
+
var userPrefix = (user) => `u:${user}|`;
|
|
3
|
+
function assertScope(scope) {
|
|
4
|
+
if (!/^u:[^|]+\|/.test(scope)) {
|
|
5
|
+
throw new Error(`[genesis offline] "${scope}" isn't a person's cache scope: build it with cacheScope(userId, workspace).`);
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
function cacheScope(userId, workspace = "none") {
|
|
9
|
+
if (!userId) throw new Error("[genesis offline] cacheScope needs the signed-in user's id.");
|
|
10
|
+
return `${userPrefix(userId)}${workspace}`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// src/offline/memory.ts
|
|
14
|
+
var rowKey = (resource, id) => `${resource}\0${id}`;
|
|
15
|
+
function apply(bucket, op) {
|
|
16
|
+
if (op.kind === "row") {
|
|
17
|
+
const k = rowKey(op.row.resource, op.row.id);
|
|
18
|
+
const stored = bucket.rows.get(k);
|
|
19
|
+
if (!stored || stored.fetchedAt <= op.row.fetchedAt) bucket.rows.set(k, op.row);
|
|
20
|
+
} else if (op.kind === "query") bucket.queries.set(op.query.key, op.query);
|
|
21
|
+
else if (op.kind === "forget") {
|
|
22
|
+
const stored = bucket.queries.get(op.key);
|
|
23
|
+
if (stored && (op.before === void 0 || stored.fetchedAt < op.before)) bucket.queries.delete(op.key);
|
|
24
|
+
} else if (op.kind === "drop") bucket.rows.delete(rowKey(op.resource, op.id));
|
|
25
|
+
else {
|
|
26
|
+
const keep = new Set(op.keep);
|
|
27
|
+
for (const [k, row] of bucket.rows) if (row.resource === op.resource && !keep.has(row.id) && row.fetchedAt < op.before) bucket.rows.delete(k);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function memoryLocalCache() {
|
|
31
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
32
|
+
const bucket = (scope) => {
|
|
33
|
+
let b = buckets.get(scope);
|
|
34
|
+
if (!b) buckets.set(scope, b = { rows: /* @__PURE__ */ new Map(), queries: /* @__PURE__ */ new Map() });
|
|
35
|
+
return b;
|
|
36
|
+
};
|
|
37
|
+
return {
|
|
38
|
+
async readQueries(scope) {
|
|
39
|
+
assertScope(scope);
|
|
40
|
+
return [...buckets.get(scope)?.queries.values() ?? []];
|
|
41
|
+
},
|
|
42
|
+
async readRows(scope, resource, ids) {
|
|
43
|
+
assertScope(scope);
|
|
44
|
+
const b = buckets.get(scope);
|
|
45
|
+
if (!b) return [];
|
|
46
|
+
return ids.map((id) => b.rows.get(rowKey(resource, id))).filter((r) => !!r);
|
|
47
|
+
},
|
|
48
|
+
async write(scope, ops) {
|
|
49
|
+
assertScope(scope);
|
|
50
|
+
const current = bucket(scope);
|
|
51
|
+
const next = { rows: new Map(current.rows), queries: new Map(current.queries) };
|
|
52
|
+
for (const op of ops) apply(next, op);
|
|
53
|
+
buckets.set(scope, next);
|
|
54
|
+
},
|
|
55
|
+
async clear(target) {
|
|
56
|
+
if (!target) {
|
|
57
|
+
buckets.clear();
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if ("scope" in target) {
|
|
61
|
+
buckets.delete(target.scope);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const mine = (scope) => scope.startsWith(userPrefix("user" in target ? target.user : target.except));
|
|
65
|
+
for (const scope of [...buckets.keys()]) if (mine(scope) === "user" in target) buckets.delete(scope);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// src/offline/indexeddb.ts
|
|
71
|
+
var VERSION = 1;
|
|
72
|
+
var done = (request) => new Promise((resolve, reject) => {
|
|
73
|
+
request.onsuccess = () => resolve(request.result);
|
|
74
|
+
request.onerror = () => reject(request.error);
|
|
75
|
+
});
|
|
76
|
+
var finished = (tx) => new Promise((resolve, reject) => {
|
|
77
|
+
tx.oncomplete = () => resolve();
|
|
78
|
+
tx.onabort = () => reject(tx.error ?? new Error("[genesis offline] IndexedDB transaction aborted"));
|
|
79
|
+
tx.onerror = () => reject(tx.error);
|
|
80
|
+
});
|
|
81
|
+
function indexedDbLocalCache(options = {}) {
|
|
82
|
+
const name = options.name ?? "genesis-offline";
|
|
83
|
+
const factory = options.indexedDB ?? globalThis.indexedDB;
|
|
84
|
+
let opening = null;
|
|
85
|
+
const open = () => {
|
|
86
|
+
if (opening) return opening;
|
|
87
|
+
if (!factory) return Promise.reject(new Error("[genesis offline] IndexedDB isn't available here."));
|
|
88
|
+
if (options.persist === true) {
|
|
89
|
+
const storage = globalThis.navigator?.storage;
|
|
90
|
+
void storage?.persist?.().catch(() => false);
|
|
91
|
+
}
|
|
92
|
+
const request = factory.open(name, VERSION);
|
|
93
|
+
request.onblocked = () => void 0;
|
|
94
|
+
request.onupgradeneeded = () => {
|
|
95
|
+
const db = request.result;
|
|
96
|
+
if (!db.objectStoreNames.contains("rows")) {
|
|
97
|
+
db.createObjectStore("rows", { keyPath: ["scope", "resource", "id"] }).createIndex("scope", "scope");
|
|
98
|
+
}
|
|
99
|
+
if (!db.objectStoreNames.contains("queries")) {
|
|
100
|
+
db.createObjectStore("queries", { keyPath: ["scope", "key"] }).createIndex("scope", "scope");
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
opening = done(request).then((db) => {
|
|
104
|
+
db.onversionchange = () => {
|
|
105
|
+
db.close();
|
|
106
|
+
opening = null;
|
|
107
|
+
};
|
|
108
|
+
return db;
|
|
109
|
+
});
|
|
110
|
+
opening.catch(() => {
|
|
111
|
+
opening = null;
|
|
112
|
+
});
|
|
113
|
+
return opening;
|
|
114
|
+
};
|
|
115
|
+
const scopeRange = (scope) => IDBKeyRange.bound([scope], [scope, []]);
|
|
116
|
+
const personRange = (user) => IDBKeyRange.bound([userPrefix(user)], [`${userPrefix(user)}\uFFFF`]);
|
|
117
|
+
return {
|
|
118
|
+
async readQueries(scope) {
|
|
119
|
+
assertScope(scope);
|
|
120
|
+
const db = await open();
|
|
121
|
+
const records = await done(db.transaction("queries").objectStore("queries").index("scope").getAll(IDBKeyRange.only(scope)));
|
|
122
|
+
return records.map(({ scope: _s, ...query }) => query);
|
|
123
|
+
},
|
|
124
|
+
async readRows(scope, resource, ids) {
|
|
125
|
+
assertScope(scope);
|
|
126
|
+
if (ids.length === 0) return [];
|
|
127
|
+
const db = await open();
|
|
128
|
+
const store = db.transaction("rows").objectStore("rows");
|
|
129
|
+
const found = await Promise.all(ids.map((id) => done(store.get([scope, resource, id]))));
|
|
130
|
+
return found.filter((r) => !!r).map(({ scope: _s, ...row }) => row);
|
|
131
|
+
},
|
|
132
|
+
async write(scope, ops) {
|
|
133
|
+
assertScope(scope);
|
|
134
|
+
if (ops.length === 0) return;
|
|
135
|
+
const db = await open();
|
|
136
|
+
const tx = db.transaction(["rows", "queries"], "readwrite");
|
|
137
|
+
const rows = tx.objectStore("rows");
|
|
138
|
+
const queries = tx.objectStore("queries");
|
|
139
|
+
const newest = /* @__PURE__ */ new Map();
|
|
140
|
+
for (const op of ops) {
|
|
141
|
+
if (op.kind !== "row") continue;
|
|
142
|
+
const k = JSON.stringify([op.row.resource, op.row.id]);
|
|
143
|
+
const seen = newest.get(k);
|
|
144
|
+
if (!seen || seen.fetchedAt <= op.row.fetchedAt) newest.set(k, op.row);
|
|
145
|
+
}
|
|
146
|
+
const olderThan = (store, key, before, then) => {
|
|
147
|
+
const get = store.get(key);
|
|
148
|
+
get.onsuccess = () => {
|
|
149
|
+
const stored = get.result;
|
|
150
|
+
if (stored && stored.fetchedAt < before) then();
|
|
151
|
+
};
|
|
152
|
+
};
|
|
153
|
+
for (const op of ops) {
|
|
154
|
+
if (op.kind === "row") {
|
|
155
|
+
const row = newest.get(JSON.stringify([op.row.resource, op.row.id]));
|
|
156
|
+
if (row !== op.row) continue;
|
|
157
|
+
const get = rows.get([scope, row.resource, row.id]);
|
|
158
|
+
get.onsuccess = () => {
|
|
159
|
+
const stored = get.result;
|
|
160
|
+
if (!stored || stored.fetchedAt <= row.fetchedAt) rows.put({ ...row, scope });
|
|
161
|
+
};
|
|
162
|
+
} else if (op.kind === "query") queries.put({ ...op.query, scope });
|
|
163
|
+
else if (op.kind === "forget") {
|
|
164
|
+
if (op.before === void 0) queries.delete([scope, op.key]);
|
|
165
|
+
else olderThan(queries, [scope, op.key], op.before, () => queries.delete([scope, op.key]));
|
|
166
|
+
} else if (op.kind === "drop") rows.delete([scope, op.resource, op.id]);
|
|
167
|
+
else {
|
|
168
|
+
const keep = new Set(op.keep);
|
|
169
|
+
const cursor = rows.openCursor(IDBKeyRange.bound([scope, op.resource], [scope, op.resource, []]));
|
|
170
|
+
cursor.onsuccess = () => {
|
|
171
|
+
const c = cursor.result;
|
|
172
|
+
if (!c) return;
|
|
173
|
+
const stored = c.value;
|
|
174
|
+
if (!keep.has(stored.id) && stored.fetchedAt < op.before) c.delete();
|
|
175
|
+
c.continue();
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
await finished(tx);
|
|
180
|
+
},
|
|
181
|
+
async clear(target) {
|
|
182
|
+
const db = await open();
|
|
183
|
+
const tx = db.transaction(["rows", "queries"], "readwrite");
|
|
184
|
+
for (const store of [tx.objectStore("rows"), tx.objectStore("queries")]) {
|
|
185
|
+
if (!target) store.clear();
|
|
186
|
+
else if ("scope" in target) store.delete(scopeRange(target.scope));
|
|
187
|
+
else if ("user" in target) store.delete(personRange(target.user));
|
|
188
|
+
else {
|
|
189
|
+
store.delete(IDBKeyRange.upperBound([userPrefix(target.except)], true));
|
|
190
|
+
store.delete(IDBKeyRange.lowerBound([`${userPrefix(target.except)}\uFFFF`]));
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
await finished(tx);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// src/offline/persist.ts
|
|
199
|
+
var DAY = 24 * 60 * 60 * 1e3;
|
|
200
|
+
var META = "__genesis_offline_meta__";
|
|
201
|
+
var KINDS = /* @__PURE__ */ new Set(["list", "detail", "infinite"]);
|
|
202
|
+
var isRef = (v) => !!v && typeof v === "object" && typeof v.$row === "string" && Object.keys(v).length === 1;
|
|
203
|
+
var isRow = (v) => !!v && typeof v === "object" && !Array.isArray(v) && v.id != null;
|
|
204
|
+
var keyText = (key) => JSON.stringify(
|
|
205
|
+
key,
|
|
206
|
+
(_k, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : v
|
|
207
|
+
);
|
|
208
|
+
var toScope = (scope) => !scope ? null : scope.startsWith("u:") ? /^u:[^|]+\|/.test(scope) ? scope : null : `${userPrefix(scope)}none`;
|
|
209
|
+
function split(kind, select, data, rows) {
|
|
210
|
+
if (select !== void 0) return kind === "infinite" && !(data && typeof data === "object" && Array.isArray(data.pages)) ? null : data;
|
|
211
|
+
const list = (page) => {
|
|
212
|
+
if (!page || typeof page !== "object" || !Array.isArray(page.data)) return page;
|
|
213
|
+
const p = page;
|
|
214
|
+
return { ...p, data: p.data.map((r) => isRow(r) ? (rows.push(r), { $row: String(r.id) }) : r) };
|
|
215
|
+
};
|
|
216
|
+
if (kind === "list") return list(data);
|
|
217
|
+
if (kind === "infinite") {
|
|
218
|
+
if (!data || typeof data !== "object" || !Array.isArray(data.pages)) return null;
|
|
219
|
+
const d = data;
|
|
220
|
+
return { ...d, pages: d.pages.map(list) };
|
|
221
|
+
}
|
|
222
|
+
if (isRow(data)) {
|
|
223
|
+
rows.push(data);
|
|
224
|
+
return { $row: String(data.id) };
|
|
225
|
+
}
|
|
226
|
+
return data;
|
|
227
|
+
}
|
|
228
|
+
function refsIn(value, out) {
|
|
229
|
+
if (isRef(value)) out.add(value.$row);
|
|
230
|
+
else if (Array.isArray(value)) for (const v of value) refsIn(v, out);
|
|
231
|
+
else if (value && typeof value === "object") for (const v of Object.values(value)) refsIn(v, out);
|
|
232
|
+
}
|
|
233
|
+
function join(value, rows) {
|
|
234
|
+
if (isRef(value)) return rows.get(value.$row);
|
|
235
|
+
if (Array.isArray(value)) {
|
|
236
|
+
const out = value.map((v) => join(v, rows));
|
|
237
|
+
return out.some((v, i) => v === void 0 && value[i] !== void 0) ? void 0 : out;
|
|
238
|
+
}
|
|
239
|
+
if (value && typeof value === "object") {
|
|
240
|
+
const out = {};
|
|
241
|
+
for (const [k, v] of Object.entries(value)) {
|
|
242
|
+
const joined = join(v, rows);
|
|
243
|
+
if (joined === void 0 && v !== void 0) return void 0;
|
|
244
|
+
out[k] = joined;
|
|
245
|
+
}
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
248
|
+
return value;
|
|
249
|
+
}
|
|
250
|
+
function persistOffline(options) {
|
|
251
|
+
const { cache, buster, maxAge = 7 * DAY, throttleMs = 500, maxReads = 200 } = options;
|
|
252
|
+
const kept = new Set(options.resources);
|
|
253
|
+
return (queryClient) => {
|
|
254
|
+
let restores = 0;
|
|
255
|
+
let saves = 0;
|
|
256
|
+
const fetched = /* @__PURE__ */ new WeakMap();
|
|
257
|
+
queryClient.getQueryCache().subscribe((event) => {
|
|
258
|
+
if (event.type !== "updated") return;
|
|
259
|
+
const action = event.action;
|
|
260
|
+
if (action.type !== "success" || action.manual) return;
|
|
261
|
+
fetched.set(event.query, { data: event.query.state.data, fetchedAt: event.query.state.dataUpdatedAt });
|
|
262
|
+
});
|
|
263
|
+
const people = /* @__PURE__ */ new Set();
|
|
264
|
+
const meta = () => ({ kind: "query", query: { key: META, queryKey: [META], resource: META, data: { buster }, fetchedAt: Date.now() } });
|
|
265
|
+
const keptQuery = (query) => {
|
|
266
|
+
const [resource, kind] = query.queryKey;
|
|
267
|
+
return typeof resource === "string" && kept.has(resource) && typeof kind === "string" && KINDS.has(kind);
|
|
268
|
+
};
|
|
269
|
+
const restore = async (raw, signal) => {
|
|
270
|
+
if (raw === "") {
|
|
271
|
+
restores += 1;
|
|
272
|
+
saves += 1;
|
|
273
|
+
people.clear();
|
|
274
|
+
await cache.clear().catch(() => void 0);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
const scope = toScope(raw);
|
|
278
|
+
if (!scope) return;
|
|
279
|
+
const mine = ++restores;
|
|
280
|
+
const user = scope.slice(2, scope.indexOf("|"));
|
|
281
|
+
people.add(user);
|
|
282
|
+
const stale = () => mine !== restores || signal?.aborted === true;
|
|
283
|
+
const startedAt = Date.now();
|
|
284
|
+
try {
|
|
285
|
+
await cache.clear({ except: user });
|
|
286
|
+
const stored = await cache.readQueries(scope);
|
|
287
|
+
if (stale()) return;
|
|
288
|
+
const found = stored.find((q) => q.key === META);
|
|
289
|
+
if (!found || found.data?.buster !== buster) {
|
|
290
|
+
const fresh2 = stored.filter((q) => q.key !== META).map((q) => ({ kind: "forget", key: q.key, before: startedAt }));
|
|
291
|
+
for (const resource of /* @__PURE__ */ new Set([...stored.filter((q) => q.key !== META).map((q) => q.resource), ...kept])) {
|
|
292
|
+
fresh2.push({ kind: "prune", resource, keep: [], before: startedAt });
|
|
293
|
+
}
|
|
294
|
+
await cache.write(scope, [...fresh2, meta()]);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const reads = stored.filter((q) => q.key !== META);
|
|
298
|
+
const fresh = reads.filter((q) => Date.now() - q.fetchedAt <= maxAge && kept.has(q.resource)).sort((a, b) => b.fetchedAt - a.fetchedAt).slice(0, maxReads);
|
|
299
|
+
const wanted = /* @__PURE__ */ new Map();
|
|
300
|
+
for (const q of reads) if (!wanted.has(q.resource)) wanted.set(q.resource, /* @__PURE__ */ new Set());
|
|
301
|
+
for (const q of fresh) refsIn(q.data, wanted.get(q.resource));
|
|
302
|
+
const rowsOf = /* @__PURE__ */ new Map();
|
|
303
|
+
for (const [resource, ids] of wanted) {
|
|
304
|
+
if (ids.size === 0) continue;
|
|
305
|
+
const rows = await cache.readRows(scope, resource, [...ids]);
|
|
306
|
+
rowsOf.set(resource, new Map(rows.map((r) => [r.id, r.row])));
|
|
307
|
+
}
|
|
308
|
+
if (stale()) return;
|
|
309
|
+
for (const q of fresh) {
|
|
310
|
+
const data = join(q.data, rowsOf.get(q.resource) ?? /* @__PURE__ */ new Map());
|
|
311
|
+
if (data === void 0) continue;
|
|
312
|
+
const existing = queryClient.getQueryState(q.queryKey);
|
|
313
|
+
if (existing?.data !== void 0 && existing.dataUpdatedAt >= q.fetchedAt) continue;
|
|
314
|
+
queryClient.setQueryData(q.queryKey, data, { updatedAt: q.fetchedAt });
|
|
315
|
+
}
|
|
316
|
+
const sweep = reads.filter((q) => !fresh.includes(q)).map((q) => ({ kind: "forget", key: q.key, before: startedAt }));
|
|
317
|
+
for (const [resource, ids] of wanted) sweep.push({ kind: "prune", resource, keep: [...ids], before: startedAt });
|
|
318
|
+
if (sweep.length) await cache.write(scope, sweep);
|
|
319
|
+
} catch {
|
|
320
|
+
await cache.clear({ scope }).catch(() => void 0);
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
const subscribe = (raw, options2 = {}) => {
|
|
324
|
+
const scope = toScope(raw);
|
|
325
|
+
if (!scope) return () => {
|
|
326
|
+
};
|
|
327
|
+
const mine = ++saves;
|
|
328
|
+
people.add(scope.slice(2, scope.indexOf("|")));
|
|
329
|
+
const pending = /* @__PURE__ */ new Map();
|
|
330
|
+
if (options2.refresh) {
|
|
331
|
+
for (const query of queryClient.getQueryCache().getAll()) {
|
|
332
|
+
if (keptQuery(query) && query.state.fetchStatus === "fetching") void query.cancel({ revert: true });
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const before = options2.adopt ? /* @__PURE__ */ new Set() : new Set(queryClient.getQueryCache().getAll().filter((q) => q.state.fetchStatus === "fetching").map((q) => q.queryHash));
|
|
336
|
+
let timer;
|
|
337
|
+
let first = true;
|
|
338
|
+
const flush = () => {
|
|
339
|
+
timer = void 0;
|
|
340
|
+
if (mine !== saves || pending.size === 0) return;
|
|
341
|
+
const ops = first ? [meta()] : [];
|
|
342
|
+
const newest = /* @__PURE__ */ new Map();
|
|
343
|
+
first = false;
|
|
344
|
+
for (const read of pending.values()) {
|
|
345
|
+
if (queryClient.getQueryCache().get(read.query.queryHash) !== read.query) continue;
|
|
346
|
+
const [resource, kind, params, detailSelect] = read.queryKey;
|
|
347
|
+
const select = kind === "detail" ? detailSelect : params?.select;
|
|
348
|
+
const key = keyText(read.queryKey);
|
|
349
|
+
if (kind === "detail" && read.data == null) {
|
|
350
|
+
const id = read.queryKey[2];
|
|
351
|
+
ops.push({ kind: "forget", key });
|
|
352
|
+
if (select === void 0 && id != null) ops.push({ kind: "drop", resource, id: String(id) });
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
const rows = [];
|
|
356
|
+
const data = split(kind, select, read.data, rows);
|
|
357
|
+
if (data === null) continue;
|
|
358
|
+
for (const row of rows) {
|
|
359
|
+
const k = `${resource}\0${String(row.id)}`;
|
|
360
|
+
const seen = newest.get(k);
|
|
361
|
+
if (!seen || seen.fetchedAt <= read.fetchedAt) newest.set(k, { resource, id: String(row.id), row, fetchedAt: read.fetchedAt });
|
|
362
|
+
}
|
|
363
|
+
ops.push({ kind: "query", query: { key, queryKey: read.queryKey, resource, data, fetchedAt: read.fetchedAt } });
|
|
364
|
+
}
|
|
365
|
+
pending.clear();
|
|
366
|
+
for (const row of newest.values()) ops.push({ kind: "row", row });
|
|
367
|
+
if (ops.length) void cache.write(scope, ops).catch(() => void 0);
|
|
368
|
+
};
|
|
369
|
+
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
|
370
|
+
if (event.type !== "updated" || mine !== saves) return;
|
|
371
|
+
const action = event.action;
|
|
372
|
+
if (action.type !== "success" || action.manual) return;
|
|
373
|
+
if (queryClient.getQueryCache().get(event.query.queryHash) !== event.query) return;
|
|
374
|
+
if (before.delete(event.query.queryHash)) return;
|
|
375
|
+
if (!keptQuery(event.query)) return;
|
|
376
|
+
const { data, dataUpdatedAt } = event.query.state;
|
|
377
|
+
pending.set(event.query.queryHash, { query: event.query, queryKey: event.query.queryKey, data, fetchedAt: dataUpdatedAt });
|
|
378
|
+
timer ??= setTimeout(flush, throttleMs);
|
|
379
|
+
});
|
|
380
|
+
if (options2.refresh) {
|
|
381
|
+
const infinite = (query) => keptQuery(query) && query.queryKey[1] === "infinite";
|
|
382
|
+
void queryClient.resetQueries({ predicate: infinite }).catch(() => void 0);
|
|
383
|
+
void queryClient.invalidateQueries({ predicate: (query) => keptQuery(query) && !infinite(query) }).catch(() => void 0);
|
|
384
|
+
}
|
|
385
|
+
if (options2.adopt) {
|
|
386
|
+
for (const query of queryClient.getQueryCache().getAll()) {
|
|
387
|
+
const read = fetched.get(query);
|
|
388
|
+
if (!read || read.data === void 0 || !keptQuery(query)) continue;
|
|
389
|
+
pending.set(query.queryHash, { query, queryKey: query.queryKey, data: read.data, fetchedAt: read.fetchedAt });
|
|
390
|
+
}
|
|
391
|
+
if (pending.size) timer ??= setTimeout(flush, throttleMs);
|
|
392
|
+
}
|
|
393
|
+
return () => {
|
|
394
|
+
unsubscribe();
|
|
395
|
+
if (timer) clearTimeout(timer);
|
|
396
|
+
flush();
|
|
397
|
+
};
|
|
398
|
+
};
|
|
399
|
+
const clear = async () => {
|
|
400
|
+
restores += 1;
|
|
401
|
+
saves += 1;
|
|
402
|
+
const everyone = [...people];
|
|
403
|
+
people.clear();
|
|
404
|
+
if (everyone.length === 0) await cache.clear();
|
|
405
|
+
else for (const user of everyone) await cache.clear({ user });
|
|
406
|
+
};
|
|
407
|
+
return { restore, subscribe, clear };
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export { cacheScope, indexedDbLocalCache, memoryLocalCache, persistOffline };
|
|
412
|
+
//# sourceMappingURL=index.js.map
|
|
413
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/offline/types.ts","../../src/offline/memory.ts","../../src/offline/indexeddb.ts","../../src/offline/persist.ts"],"names":["fresh","options"],"mappings":";AA6HO,IAAM,UAAA,GAAa,CAAC,IAAA,KAAiB,CAAA,EAAA,EAAK,IAAI,CAAA,CAAA,CAAA;AAG9C,SAAS,YAAY,KAAA,EAAyB;AACnD,EAAA,IAAI,CAAC,YAAA,CAAa,IAAA,CAAK,KAAK,CAAA,EAAG;AAC7B,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,mBAAA,EAAsB,KAAK,CAAA,4EAAA,CAA8E,CAAA;AAAA,EAC3H;AACF;AAYO,SAAS,UAAA,CAAW,MAAA,EAAgB,SAAA,GAAY,MAAA,EAAoB;AACzE,EAAA,IAAI,CAAC,MAAA,EAAQ,MAAM,IAAI,MAAM,6DAA6D,CAAA;AAC1F,EAAA,OAAO,CAAA,EAAG,UAAA,CAAW,MAA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ACA,MAAA,IAAIA,SAAQ,KAAA,EAAO;AAGjB,QAAA,KAAA,MAAW,KAAA,IAAS,WAAA,CAAY,aAAA,EAAc,CAAE,QAAO,EAAG;AACxD,UAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,KAAK,CAAA;AAC9B,UAAA,IAAI,CAAC,QAAQ,IAAA,CAAK,IAAA,KAAS,UAAa,CAAC,SAAA,CAAU,KAAK,CAAA,EAAG;AAC3D,UAAA,OAAA,CAAQ,GAAA,CAAI,KAAA,CAAM,SAAA,EAAW,EAAE,OAAO,QAAA,EAAU,KAAA,CAAM,QAAA,EAAU,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,SAAA,EAAW,IAAA,CAAK,WAAW,CAAA;AAAA,QAC9G;AACA,QAAA,IAAI,OAAA,CAAQ,IAAA,EAAM,KAAA,KAAU,UAAA,CAAW,OAAO,UAAU,CAAA;AAAA,MAC1D;AACA,MAAA,OAAO,MAAM;AACX,QAAA,WAAA,EAAY;AACZ,QAAA,IAAI,KAAA,eAAoB,KAAK,CAAA;AAC7B,QAAA,KAAA,EAAM;AAAA,MACR,CAAA;AAAA,IACF,CAAA;AAEA,IAAA,MAAM,QAAQ,YAAY;AACxB,MAAA,QAAA,IAAY,CAAA;AACZ,MAAA,KAAA,IAAS,CAAA;AACT,MAAA,MAAM,QAAA,GAAW,CAAC,GAAG,MAAM,CAAA;AAC3B,MAAA,MAAA,CAAO,KAAA,EAAM;AACb,MAAA,IAAI,QAAA,CAAS,MAAA,KAAW,CAAA,EAAG,MAAM,MAAM,KAAA,EAAM;AAAA,WACxC,KAAA,MAAW,QAAQ,QAAA,EAAU,MAAM,MAAM,KAAA,CAAM,EAAE,MAAM,CAAA;AAAA,IAC9D,CAAA;AAEA,IAAA,OAAO,EAAE,OAAA,EAAS,SAAA,EAAW,KAAA,EAAM;AAAA,EACrC,CAAA;AACF","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// The device cache's contract (ADR 0010, slice 1: \"lists open instantly\")\n//\n// A local cache keeps the reads a person already made, per record and per\n// query, so a list or a record opens from the device before the network\n// answers and is then refreshed. It can always be rebuilt from the server:\n// a wipe loses nothing but speed. Every row in it came from a normal read by\n// this person, through the provider and so through RLS.\n// ---------------------------------------------------------------------------\n\n/**\n * Whose cache a write belongs to: always a person's. `u:<userId>|<workspace>`,\n * from `cacheScope`. An adapter refuses a scope without the `u:` prefix, so\n * `clear({ user })` reaches every bucket a person has.\n */\nexport type CacheScope = string;\n\n/** One record as it was read: stored once, whatever lists hold it. */\nexport interface StoredRow {\n readonly resource: string;\n /** `String(row.id)`. */\n readonly id: string;\n /**\n * The row as last read whole (a list or a record read without `select`). A\n * newer read replaces it, so a field the server stops returning is gone; an\n * older one never does.\n */\n readonly row: Readonly<Record<string, unknown>>;\n readonly fetchedAt: number;\n}\n\n/**\n * One cached read (a list, an infinite list or a record), its rows replaced by\n * references (`{ $row: id }`) into the row store.\n */\nexport interface StoredQuery {\n /** The query key as text, the query's identity in the store. */\n readonly key: string;\n readonly queryKey: readonly unknown[];\n readonly resource: string;\n readonly data: unknown;\n readonly fetchedAt: number;\n}\n\n/** One change to the store. A `write` applies all of its ops together, or none. */\nexport type CacheOp =\n | { readonly kind: \"row\"; readonly row: StoredRow }\n | { readonly kind: \"query\"; readonly query: StoredQuery }\n /** Deletes a stored read; with `before`, only if it was fetched before then (a newer save stays). */\n | { readonly kind: \"forget\"; readonly key: string; readonly before?: number }\n /** Deletes one stored row (the record came back empty: deleted, or no longer readable). */\n | { readonly kind: \"drop\"; readonly resource: string; readonly id: string }\n /**\n * Deletes every stored row of `resource` that isn't in `keep` and was fetched before `before`:\n * the rows no kept read refers to, never one saved since the sweep started.\n */\n | { readonly kind: \"prune\"; readonly resource: string; readonly keep: readonly string[]; readonly before: number };\n\n/**\n * The device cache. `memoryLocalCache` (tests), `indexedDbLocalCache` (the\n * web) and genesis-native's `sqliteLocalCache` (the phone) implement it; one\n * contract suite tests every adapter.\n *\n * @stability Beta\n */\nexport interface LocalCache {\n /** Every stored read for `scope`. */\n readQueries(scope: CacheScope): Promise<StoredQuery[]>;\n /** The stored rows of `resource` with these ids; missing ones are left out. */\n readRows(scope: CacheScope, resource: string, ids: readonly string[]): Promise<StoredRow[]>;\n /**\n * Applies `ops` in order, in one transaction. A row op replaces the stored row unless the\n * stored one was fetched later (an older read never overwrites a newer one).\n */\n write(scope: CacheScope, ops: readonly CacheOp[]): Promise<void>;\n /**\n * Deletes one scope's bucket, every bucket of one person, every bucket except one person's\n * (`except`: a device is one person's), or everything.\n */\n clear(target?: { readonly scope: CacheScope } | { readonly user: string } | { readonly except: string }): Promise<void>;\n}\n\n/**\n * Loads saved reads into a QueryClient and saves new ones: what\n * `GenesisNativeApp`'s and `GenesisProvider`'s `persist` take.\n *\n * @stability Beta\n */\nexport interface QueryPersistence {\n /**\n * Load the saved reads for `scope` into the client. Once `signal` aborts (the\n * person signed out, or the scope changed), nothing more is loaded.\n */\n restore(scope: string, signal?: AbortSignal): Promise<void>;\n /**\n * Saves settled reads for `scope` as they arrive; returns the unsubscribe.\n * `restore(\"\")` (nobody signed in) deletes every saved read on the device.\n */\n subscribe(scope: string, options?: SubscribeOptions): () => void;\n /** Delete the saved reads of every person this persistence restored or saved for (else everything). */\n clear(): Promise<void>;\n}\n\n/** Options for `QueryPersistence.subscribe`. */\nexport interface SubscribeOptions {\n /**\n * The reads already made are this scope's: save what each kept query last fetched (never a\n * value the client set since), and the reads still on their way. Only where the client can\n * hold nothing of anyone else's: `GenesisNativeApp`, which empties it whenever the person\n * changes and starts saving only once the session is known.\n *\n * @internal For `GenesisNativeApp`. Elsewhere, use `refresh`: a client that outlived another\n * person's session would have their reads adopted.\n */\n adopt?: boolean;\n /**\n * Nothing already in the client, or on its way, is trusted to be this scope's (the session was\n * still loading, or the client outlived another person's session): every kept read in flight is\n * called off, and the kept queries are fetched again, so everything saved was read once the\n * scope was known. What `GenesisProvider` does when a scope arrives after `undefined`.\n */\n refresh?: boolean;\n}\n\n/** The scope prefix every bucket of `user` starts with. */\nexport const userPrefix = (user: string) => `u:${user}|`;\n\n/** Refuses a scope that doesn't belong to a person. */\nexport function assertScope(scope: CacheScope): void {\n if (!/^u:[^|]+\\|/.test(scope)) {\n throw new Error(`[genesis offline] \"${scope}\" isn't a person's cache scope: build it with cacheScope(userId, workspace).`);\n }\n}\n\n/**\n * A person's cache scope: their user id plus the workspace they're in\n * (`WorkspaceScope`'s `<kind>:<id>`), `all` for a roll-up, or `none` outside\n * any workspace.\n *\n * cacheScope(user.id) // \"u:<id>|none\"\n * cacheScope(user.id, \"org:acme\") // \"u:<id>|org:acme\"\n *\n * @stability Beta\n */\nexport function cacheScope(userId: string, workspace = \"none\"): CacheScope {\n if (!userId) throw new Error(\"[genesis offline] cacheScope needs the signed-in user's id.\");\n return `${userPrefix(userId)}${workspace}`;\n}\n","import { assertScope, userPrefix, type CacheOp, type CacheScope, type LocalCache, type StoredQuery, type StoredRow } from \"./types\";\n\ninterface Bucket {\n rows: Map<string, StoredRow>;\n queries: Map<string, StoredQuery>;\n}\n\nconst rowKey = (resource: string, id: string) => `${resource}\\u0000${id}`;\n\n/** Applies one op to a bucket (shared with the other adapters' tests through behaviour, not code). */\nfunction apply(bucket: Bucket, op: CacheOp): void {\n if (op.kind === \"row\") {\n const k = rowKey(op.row.resource, op.row.id);\n const stored = bucket.rows.get(k);\n if (!stored || stored.fetchedAt <= op.row.fetchedAt) bucket.rows.set(k, op.row);\n } else if (op.kind === \"query\") bucket.queries.set(op.query.key, op.query);\n else if (op.kind === \"forget\") {\n const stored = bucket.queries.get(op.key);\n if (stored && (op.before === undefined || stored.fetchedAt < op.before)) bucket.queries.delete(op.key);\n } else if (op.kind === \"drop\") bucket.rows.delete(rowKey(op.resource, op.id));\n else {\n const keep = new Set(op.keep);\n for (const [k, row] of bucket.rows) if (row.resource === op.resource && !keep.has(row.id) && row.fetchedAt < op.before) bucket.rows.delete(k);\n }\n}\n\n/**\n * A `LocalCache` in memory: for tests, and for a screen that wants the\n * contract without a device store. Nothing survives a reload.\n *\n * @stability Beta\n */\nexport function memoryLocalCache(): LocalCache {\n const buckets = new Map<CacheScope, Bucket>();\n const bucket = (scope: CacheScope) => {\n let b = buckets.get(scope);\n if (!b) buckets.set(scope, (b = { rows: new Map(), queries: new Map() }));\n return b;\n };\n return {\n async readQueries(scope) {\n assertScope(scope);\n return [...(buckets.get(scope)?.queries.values() ?? [])];\n },\n async readRows(scope, resource, ids) {\n assertScope(scope);\n const b = buckets.get(scope);\n if (!b) return [];\n return ids.map((id) => b.rows.get(rowKey(resource, id))).filter((r): r is StoredRow => !!r);\n },\n async write(scope, ops) {\n assertScope(scope);\n // All or nothing: apply to a copy, then swap it in.\n const current = bucket(scope);\n const next: Bucket = { rows: new Map(current.rows), queries: new Map(current.queries) };\n for (const op of ops) apply(next, op);\n buckets.set(scope, next);\n },\n async clear(target) {\n if (!target) {\n buckets.clear();\n return;\n }\n if (\"scope\" in target) {\n buckets.delete(target.scope);\n return;\n }\n // A person's buckets, or (`except`) everyone else's.\n const mine = (scope: CacheScope) => scope.startsWith(userPrefix(\"user\" in target ? target.user : target.except));\n for (const scope of [...buckets.keys()]) if (mine(scope) === (\"user\" in target)) buckets.delete(scope);\n },\n };\n}\n","import { assertScope, userPrefix, type CacheOp, type LocalCache, type StoredQuery, type StoredRow } from \"./types\";\n\n/** Options for {@link indexedDbLocalCache}. */\nexport interface IndexedDbLocalCacheOptions {\n /** The database name. Default `\"genesis-offline\"`. */\n name?: string;\n /** The IndexedDB factory. Default `globalThis.indexedDB`. */\n indexedDB?: IDBFactory;\n /**\n * Ask the browser to keep this origin's storage (`navigator.storage.persist()`).\n * Default false: some browsers ask the person, and kept storage outlives a\n * shared machine's session longer. Without it the browser may evict the\n * cache under pressure; it's rebuilt from the server.\n */\n persist?: boolean;\n}\n\nconst VERSION = 1;\ntype RowRecord = StoredRow & { scope: string };\ntype QueryRecord = StoredQuery & { scope: string };\n\nconst done = <T>(request: IDBRequest<T>) =>\n new Promise<T>((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n\nconst finished = (tx: IDBTransaction) =>\n new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onabort = () => reject(tx.error ?? new Error(\"[genesis offline] IndexedDB transaction aborted\"));\n tx.onerror = () => reject(tx.error);\n });\n\n/**\n * A `LocalCache` in IndexedDB, for the web: plain IndexedDB, no dependency.\n * Rows and queries are separate object stores keyed by scope, so one row is\n * stored once whatever lists hold it, and a write is one transaction. A newer\n * version of the database opened in another tab closes this one, which then\n * reopens on its next use, instead of blocking the upgrade.\n *\n * @stability Beta\n */\nexport function indexedDbLocalCache(options: IndexedDbLocalCacheOptions = {}): LocalCache {\n const name = options.name ?? \"genesis-offline\";\n const factory = options.indexedDB ?? (globalThis as { indexedDB?: IDBFactory }).indexedDB;\n let opening: Promise<IDBDatabase> | null = null;\n\n const open = (): Promise<IDBDatabase> => {\n if (opening) return opening;\n if (!factory) return Promise.reject(new Error(\"[genesis offline] IndexedDB isn't available here.\"));\n if (options.persist === true) {\n const storage = (globalThis as { navigator?: { storage?: { persist?: () => Promise<boolean> } } }).navigator?.storage;\n void storage?.persist?.().catch(() => false);\n }\n const request = factory.open(name, VERSION);\n // Another tab holds an older version open: it closes on its versionchange, then this opens.\n request.onblocked = () => undefined;\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains(\"rows\")) {\n db.createObjectStore(\"rows\", { keyPath: [\"scope\", \"resource\", \"id\"] }).createIndex(\"scope\", \"scope\");\n }\n if (!db.objectStoreNames.contains(\"queries\")) {\n db.createObjectStore(\"queries\", { keyPath: [\"scope\", \"key\"] }).createIndex(\"scope\", \"scope\");\n }\n };\n opening = done(request).then((db) => {\n db.onversionchange = () => {\n db.close();\n opening = null;\n };\n return db;\n });\n opening.catch(() => {\n opening = null;\n });\n return opening;\n };\n\n // Every key starts with its scope, so a scope's (or a person's) records are one key range: an\n // array key sorts after any shorter array it starts with, and an array element sorts after a\n // string, so `[scope, []]` is above every `[scope, ...]`.\n const scopeRange = (scope: string) => IDBKeyRange.bound([scope], [scope, []]);\n const personRange = (user: string) => IDBKeyRange.bound([userPrefix(user)], [`${userPrefix(user)}\\uffff`]);\n\n return {\n async readQueries(scope) {\n assertScope(scope);\n const db = await open();\n const records = (await done(db.transaction(\"queries\").objectStore(\"queries\").index(\"scope\").getAll(IDBKeyRange.only(scope)))) as QueryRecord[];\n return records.map(({ scope: _s, ...query }) => query);\n },\n async readRows(scope, resource, ids) {\n assertScope(scope);\n if (ids.length === 0) return [];\n const db = await open();\n const store = db.transaction(\"rows\").objectStore(\"rows\");\n const found = await Promise.all(ids.map((id) => done(store.get([scope, resource, id])) as Promise<RowRecord | undefined>));\n return found.filter((r): r is RowRecord => !!r).map(({ scope: _s, ...row }) => row);\n },\n async write(scope, ops: readonly CacheOp[]) {\n assertScope(scope);\n if (ops.length === 0) return;\n const db = await open();\n const tx = db.transaction([\"rows\", \"queries\"], \"readwrite\");\n const rows = tx.objectStore(\"rows\");\n const queries = tx.objectStore(\"queries\");\n // Requests in one transaction run in the order they're made, so the ops apply in order. A row\n // is written only if the stored one isn't newer: read first, then put (one row op per key, the\n // newest, so two reads of one row in one write can't race).\n const newest = new Map<string, StoredRow>();\n for (const op of ops) {\n if (op.kind !== \"row\") continue;\n const k = JSON.stringify([op.row.resource, op.row.id]);\n const seen = newest.get(k);\n if (!seen || seen.fetchedAt <= op.row.fetchedAt) newest.set(k, op.row);\n }\n const olderThan = (store: IDBObjectStore, key: IDBValidKey, before: number, then: () => void) => {\n const get = store.get(key);\n get.onsuccess = () => {\n const stored = get.result as { fetchedAt: number } | undefined;\n if (stored && stored.fetchedAt < before) then();\n };\n };\n for (const op of ops) {\n if (op.kind === \"row\") {\n const row = newest.get(JSON.stringify([op.row.resource, op.row.id]));\n if (row !== op.row) continue;\n const get = rows.get([scope, row.resource, row.id]);\n get.onsuccess = () => {\n const stored = get.result as RowRecord | undefined;\n if (!stored || stored.fetchedAt <= row.fetchedAt) rows.put({ ...row, scope } satisfies RowRecord);\n };\n } else if (op.kind === \"query\") queries.put({ ...op.query, scope } satisfies QueryRecord);\n else if (op.kind === \"forget\") {\n if (op.before === undefined) queries.delete([scope, op.key]);\n else olderThan(queries, [scope, op.key], op.before, () => queries.delete([scope, op.key]));\n } else if (op.kind === \"drop\") rows.delete([scope, op.resource, op.id]);\n else {\n const keep = new Set(op.keep);\n const cursor = rows.openCursor(IDBKeyRange.bound([scope, op.resource], [scope, op.resource, []]));\n cursor.onsuccess = () => {\n const c = cursor.result;\n if (!c) return;\n const stored = c.value as RowRecord;\n if (!keep.has(stored.id) && stored.fetchedAt < op.before) c.delete();\n c.continue();\n };\n }\n }\n await finished(tx);\n },\n async clear(target) {\n const db = await open();\n const tx = db.transaction([\"rows\", \"queries\"], \"readwrite\");\n for (const store of [tx.objectStore(\"rows\"), tx.objectStore(\"queries\")]) {\n if (!target) store.clear();\n else if (\"scope\" in target) store.delete(scopeRange(target.scope));\n else if (\"user\" in target) store.delete(personRange(target.user));\n else {\n // Everyone else: the keys below this person's range, and those above it.\n store.delete(IDBKeyRange.upperBound([userPrefix(target.except)], true));\n store.delete(IDBKeyRange.lowerBound([`${userPrefix(target.except)}\\uffff`]));\n }\n }\n await finished(tx);\n },\n };\n}\n","import type { Query, QueryCacheNotifyEvent, QueryClient } from \"@tanstack/react-query\";\nimport { userPrefix, type CacheOp, type CacheScope, type LocalCache, type QueryPersistence, type StoredQuery, type StoredRow, type SubscribeOptions } from \"./types\";\n\n/** Options for {@link persistOffline}. */\nexport interface PersistOfflineOptions {\n /** Where reads are kept: `indexedDbLocalCache()` on the web, `sqliteLocalCache({ db })` on the phone. */\n cache: LocalCache;\n /**\n * The resources whose reads are kept on the device: the one opt-in switch.\n * Keeping data on a device is a decision, so nothing else is written. Leave\n * out a resource whose rows shouldn't sit on a phone unencrypted.\n */\n resources: readonly string[];\n /** Your app's version: a different value discards what was kept. */\n buster: string;\n /** How old a kept read may be when restored. Default 7 days. */\n maxAge?: number;\n /** Save at most this often. Default 500 ms. */\n throttleMs?: number;\n /** The most reads kept per person and workspace; the least recently fetched go first. Default 200. */\n maxReads?: number;\n}\n\nconst DAY = 24 * 60 * 60 * 1000;\nconst META = \"__genesis_offline_meta__\";\nconst KINDS = new Set([\"list\", \"detail\", \"infinite\"]);\n\ntype Row = Record<string, unknown>;\ntype Ref = { $row: string };\nconst isRef = (v: unknown): v is Ref => !!v && typeof v === \"object\" && typeof (v as Ref).$row === \"string\" && Object.keys(v).length === 1;\nconst isRow = (v: unknown): v is Row => !!v && typeof v === \"object\" && !Array.isArray(v) && (v as Row).id != null;\n\n/** A query's key as text: its identity in the store. */\nconst keyText = (key: readonly unknown[]) =>\n JSON.stringify(key, (_k, v: unknown) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(Object.entries(v as Row).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n : v,\n );\n\n/** A person's scope from what the app shell hands over: a user id, or a scope `cacheScope` built. */\nconst toScope = (scope: string): CacheScope | null =>\n !scope ? null : scope.startsWith(\"u:\") ? (/^u:[^|]+\\|/.test(scope) ? scope : null) : `${userPrefix(scope)}none`;\n\n/**\n * Replaces the rows in a read with references, and collects them. Only a read of whole rows (no\n * `select`) is split, so every stored row has one shape; a projection is kept as it came. Null:\n * not a shape this keeps.\n */\nfunction split(kind: string, select: unknown, data: unknown, rows: Row[]): unknown {\n if (select !== undefined) return kind === \"infinite\" && !(data && typeof data === \"object\" && Array.isArray((data as { pages?: unknown }).pages)) ? null : data;\n const list = (page: unknown) => {\n if (!page || typeof page !== \"object\" || !Array.isArray((page as { data?: unknown }).data)) return page;\n const p = page as { data: unknown[] };\n return { ...p, data: p.data.map((r) => (isRow(r) ? (rows.push(r), { $row: String(r.id) }) : r)) };\n };\n if (kind === \"list\") return list(data);\n if (kind === \"infinite\") {\n if (!data || typeof data !== \"object\" || !Array.isArray((data as { pages?: unknown }).pages)) return null;\n const d = data as { pages: unknown[] };\n return { ...d, pages: d.pages.map(list) };\n }\n // A record read whole is a row.\n if (isRow(data)) {\n rows.push(data);\n return { $row: String(data.id) };\n }\n return data;\n}\n\n/** Collects the ids a stored read refers to. */\nfunction refsIn(value: unknown, out: Set<string>): void {\n if (isRef(value)) out.add(value.$row);\n else if (Array.isArray(value)) for (const v of value) refsIn(v, out);\n else if (value && typeof value === \"object\") for (const v of Object.values(value)) refsIn(v, out);\n}\n\n/** Puts the rows back; undefined when a row it needs is missing. */\nfunction join(value: unknown, rows: Map<string, Row>): unknown {\n if (isRef(value)) return rows.get(value.$row);\n if (Array.isArray(value)) {\n const out = value.map((v) => join(v, rows));\n return out.some((v, i) => v === undefined && value[i] !== undefined) ? undefined : out;\n }\n if (value && typeof value === \"object\") {\n const out: Row = {};\n for (const [k, v] of Object.entries(value)) {\n const joined = join(v, rows);\n if (joined === undefined && v !== undefined) return undefined;\n out[k] = joined;\n }\n return out;\n }\n return value;\n}\n\n/**\n * Keeps the reads of the listed resources on the device, per record, and\n * puts them back into the QueryClient on the next start, so lists and records\n * open at once and then refresh as usual. What `GenesisNativeApp`'s and\n * `GenesisProvider`'s `persist` take.\n *\n * persist={persistOffline({ cache: indexedDbLocalCache(), resources: [\"tasks\", \"people\"], buster: version })}\n *\n * - Only reads that came back from the provider are kept (never an optimistic\n * change that hasn't been saved), in the bucket of the person and workspace\n * they were read in.\n * - A restored read is marked as fetched when it was, so a screen refetches it\n * once it's stale (the client's `staleTime`), as with any cached read. It\n * never replaces a newer read already in the client.\n * - A newer read replaces a stored row, so a field the server stops returning\n * goes; a record that comes back empty is deleted from the device. Each start\n * deletes reads older than `maxAge` and the rows no kept read refers to.\n * - A device is one person's: restoring someone deletes every other person's\n * reads first, and `restore(\"\")` (nobody signed in) deletes them all, so a\n * session that ended outside the app leaves nothing behind.\n * - A sign-out, a change of person or workspace, or `clear()` stops every save\n * and restore still in flight from landing in the new bucket.\n *\n * @stability Beta\n */\nexport function persistOffline(options: PersistOfflineOptions): (queryClient: QueryClient) => QueryPersistence {\n const { cache, buster, maxAge = 7 * DAY, throttleMs = 500, maxReads = 200 } = options;\n const kept = new Set(options.resources);\n\n return (queryClient) => {\n // Generations: a save or a restore started before a newer one (or a clear) is dropped, so\n // nothing lands in another person's or workspace's bucket.\n // Restores and saves count apart, so starting to save doesn't cancel a restore still reading.\n let restores = 0;\n let saves = 0;\n // Each query's last fetched result, recorded from the start whatever the scope: what adopting\n // saves, so a value the client changed since (setQueryData) is never taken for a read.\n const fetched = new WeakMap<Query, { data: unknown; fetchedAt: number }>();\n queryClient.getQueryCache().subscribe((event: QueryCacheNotifyEvent) => {\n if (event.type !== \"updated\") return;\n const action = event.action as { type?: string; manual?: boolean };\n if (action.type !== \"success\" || action.manual) return;\n fetched.set(event.query, { data: event.query.state.data, fetchedAt: event.query.state.dataUpdatedAt });\n });\n // Everyone this persistence restored or saved for: `clear` deletes all of their reads.\n const people = new Set<string>();\n const meta = (): CacheOp => ({ kind: \"query\", query: { key: META, queryKey: [META], resource: META, data: { buster }, fetchedAt: Date.now() } });\n\n const keptQuery = (query: Query) => {\n const [resource, kind] = query.queryKey as readonly unknown[];\n return typeof resource === \"string\" && kept.has(resource) && typeof kind === \"string\" && KINDS.has(kind);\n };\n\n const restore = async (raw: string, signal?: AbortSignal) => {\n if (raw === \"\") {\n // Nobody is signed in: nothing of anyone's stays on the device.\n restores += 1;\n saves += 1;\n people.clear();\n await cache.clear().catch(() => undefined);\n return;\n }\n const scope = toScope(raw);\n if (!scope) return;\n const mine = ++restores;\n const user = scope.slice(2, scope.indexOf(\"|\"));\n people.add(user);\n const stale = () => mine !== restores || signal?.aborted === true;\n // Reads saved from here on are newer than this restore: the sweep below never deletes them.\n const startedAt = Date.now();\n try {\n // A device is one person's: whoever used it before (a session that ended outside the app,\n // by expiry or a sign-out elsewhere) leaves nothing here for this person to sit beside.\n await cache.clear({ except: user });\n const stored = await cache.readQueries(scope);\n if (stale()) return;\n const found = stored.find((q) => q.key === META);\n if (!found || (found.data as { buster?: unknown })?.buster !== buster) {\n // A different app version, or nothing kept yet: start this bucket afresh, deleting what an\n // earlier version kept but never a read saved since this restore started (saving runs\n // alongside it).\n const fresh: CacheOp[] = stored.filter((q) => q.key !== META).map((q) => ({ kind: \"forget\", key: q.key, before: startedAt }));\n for (const resource of new Set([...stored.filter((q) => q.key !== META).map((q) => q.resource), ...kept])) {\n fresh.push({ kind: \"prune\", resource, keep: [], before: startedAt });\n }\n await cache.write(scope, [...fresh, meta()]);\n return;\n }\n const reads = stored.filter((q) => q.key !== META);\n const fresh = reads\n .filter((q) => Date.now() - q.fetchedAt <= maxAge && kept.has(q.resource))\n .sort((a, b) => b.fetchedAt - a.fetchedAt)\n .slice(0, maxReads);\n // The rows each resource's reads refer to, read once per resource.\n const wanted = new Map<string, Set<string>>();\n for (const q of reads) if (!wanted.has(q.resource)) wanted.set(q.resource, new Set());\n for (const q of fresh) refsIn(q.data, wanted.get(q.resource)!);\n const rowsOf = new Map<string, Map<string, Row>>();\n for (const [resource, ids] of wanted) {\n if (ids.size === 0) continue;\n const rows = await cache.readRows(scope, resource, [...ids]);\n rowsOf.set(resource, new Map(rows.map((r) => [r.id, r.row as Row])));\n }\n if (stale()) return;\n for (const q of fresh) {\n const data = join(q.data, rowsOf.get(q.resource) ?? new Map());\n if (data === undefined) continue; // A row it needs is gone: the screen reads it again.\n const existing = queryClient.getQueryState(q.queryKey);\n if (existing?.data !== undefined && existing.dataUpdatedAt >= q.fetchedAt) continue;\n queryClient.setQueryData(q.queryKey, data, { updatedAt: q.fetchedAt });\n }\n // Keep the device to what can still be restored: expired reads, reads past `maxReads`,\n // reads of resources no longer kept, and rows nothing refers to are deleted, unless saved\n // since this restore started.\n const sweep: CacheOp[] = reads.filter((q) => !fresh.includes(q)).map((q) => ({ kind: \"forget\", key: q.key, before: startedAt }));\n for (const [resource, ids] of wanted) sweep.push({ kind: \"prune\", resource, keep: [...ids], before: startedAt });\n if (sweep.length) await cache.write(scope, sweep);\n } catch {\n // An unreadable bucket is no reason to fail the start: the screens read from the server.\n // Dropped, so it doesn't fail every start after this one.\n await cache.clear({ scope }).catch(() => undefined);\n }\n };\n\n const subscribe = (raw: string, options: SubscribeOptions = {}) => {\n const scope = toScope(raw);\n if (!scope) return () => {};\n const mine = ++saves;\n people.add(scope.slice(2, scope.indexOf(\"|\")));\n // What each read was when it came back: saved later, but never what the client changed since.\n const pending = new Map<string, { query: Query; queryKey: readonly unknown[]; data: unknown; fetchedAt: number }>();\n // `refresh`: no kept read already made or on its way is trusted to be this scope's. The ones in\n // flight are called off (so they never come back as a success), and the kept queries are\n // fetched again below, once this subscription is listening.\n if (options.refresh) {\n for (const query of queryClient.getQueryCache().getAll()) {\n if (keptQuery(query) && query.state.fetchStatus === \"fetching\") void query.cancel({ revert: true });\n }\n }\n // Reads already on their way when this started belong to the scope before: never saved here,\n // unless they're this scope's (`adopt`).\n const before = options.adopt\n ? new Set<string>()\n : new Set(queryClient.getQueryCache().getAll().filter((q) => q.state.fetchStatus === \"fetching\").map((q) => q.queryHash));\n let timer: ReturnType<typeof setTimeout> | undefined;\n let first = true;\n\n const flush = () => {\n timer = undefined;\n if (mine !== saves || pending.size === 0) return;\n // The bucket's app version, so the next start keeps what this saves.\n const ops: CacheOp[] = first ? [meta()] : [];\n const newest = new Map<string, StoredRow>();\n first = false;\n for (const read of pending.values()) {\n // A query the client let go of before this save ran (the person changed) isn't saved.\n if (queryClient.getQueryCache().get(read.query.queryHash) !== read.query) continue;\n const [resource, kind, params, detailSelect] = read.queryKey;\n // A record's projection is its key's fourth part; a list's is in its params.\n const select = kind === \"detail\" ? detailSelect : (params as { select?: unknown } | undefined)?.select;\n const key = keyText(read.queryKey);\n if (kind === \"detail\" && read.data == null) {\n // The record came back empty (deleted, or no longer readable): forget it here too.\n const id = read.queryKey[2];\n ops.push({ kind: \"forget\", key });\n if (select === undefined && id != null) ops.push({ kind: \"drop\", resource: resource as string, id: String(id) });\n continue;\n }\n const rows: Row[] = [];\n const data = split(kind as string, select, read.data, rows);\n if (data === null) continue;\n for (const row of rows) {\n // One row per record per save, the most recently fetched (a list, then the record,\n // then the list again leave the newest copy, whatever order they're saved in).\n const k = `${resource as string}\\u0000${String(row.id)}`;\n const seen = newest.get(k);\n if (!seen || seen.fetchedAt <= read.fetchedAt) newest.set(k, { resource: resource as string, id: String(row.id), row, fetchedAt: read.fetchedAt });\n }\n ops.push({ kind: \"query\", query: { key, queryKey: read.queryKey, resource: resource as string, data, fetchedAt: read.fetchedAt } satisfies StoredQuery });\n }\n pending.clear();\n for (const row of newest.values()) ops.push({ kind: \"row\", row });\n if (ops.length) void cache.write(scope, ops).catch(() => undefined);\n };\n\n const unsubscribe = queryClient.getQueryCache().subscribe((event: QueryCacheNotifyEvent) => {\n if (event.type !== \"updated\" || mine !== saves) return;\n const action = event.action as { type?: string; manual?: boolean };\n // A fetch that came back; never a change made in the client (an optimistic patch, a live\n // hint's merge, a restore), which the next fetch confirms or undoes.\n if (action.type !== \"success\" || action.manual) return;\n // A query no longer in the client (cleared when the person changed) finishing its fetch\n // belongs to whoever was signed in before: never saved.\n if (queryClient.getQueryCache().get(event.query.queryHash) !== event.query) return;\n if (before.delete(event.query.queryHash)) return;\n if (!keptQuery(event.query)) return;\n const { data, dataUpdatedAt } = event.query.state;\n pending.set(event.query.queryHash, { query: event.query, queryKey: event.query.queryKey, data, fetchedAt: dataUpdatedAt });\n timer ??= setTimeout(flush, throttleMs);\n });\n if (options.refresh) {\n // Fetched again under this scope: the screens on show read now, the rest when they show.\n // An infinite list is reset (its pages dropped) rather than refetched: a next page fetched\n // onto pages read before the scope (a fetchNextPage that cancels or outlives the refetch)\n // would be saved as this scope's, with the earlier session's pages in it.\n const infinite = (query: Query) => keptQuery(query) && (query.queryKey as readonly unknown[])[1] === \"infinite\";\n void queryClient.resetQueries({ predicate: infinite }).catch(() => undefined);\n void queryClient.invalidateQueries({ predicate: (query) => keptQuery(query) && !infinite(query) }).catch(() => undefined);\n }\n if (options.adopt) {\n // The reads this scope made before saving started: each query's last fetched result, as it\n // came back. A value the client set or changed since (setQueryData) is never adopted.\n for (const query of queryClient.getQueryCache().getAll()) {\n const read = fetched.get(query);\n if (!read || read.data === undefined || !keptQuery(query)) continue;\n pending.set(query.queryHash, { query, queryKey: query.queryKey, data: read.data, fetchedAt: read.fetchedAt });\n }\n if (pending.size) timer ??= setTimeout(flush, throttleMs);\n }\n return () => {\n unsubscribe();\n if (timer) clearTimeout(timer);\n flush();\n };\n };\n\n const clear = async () => {\n restores += 1;\n saves += 1;\n const everyone = [...people];\n people.clear();\n if (everyone.length === 0) await cache.clear();\n else for (const user of everyone) await cache.clear({ user });\n };\n\n return { restore, subscribe, clear };\n };\n}\n"]}
|