@foretag/tanstack-db-surrealdb 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +20 -19
- package/dist/index.d.ts +20 -19
- package/dist/index.js +1947 -454
- package/dist/index.mjs +1945 -454
- package/package.json +2 -1
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,1779 @@
|
|
|
1
|
+
// node_modules/@tanstack/query-core/build/modern/subscribable.js
|
|
2
|
+
var Subscribable = class {
|
|
3
|
+
constructor() {
|
|
4
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
5
|
+
this.subscribe = this.subscribe.bind(this);
|
|
6
|
+
}
|
|
7
|
+
subscribe(listener) {
|
|
8
|
+
this.listeners.add(listener);
|
|
9
|
+
this.onSubscribe();
|
|
10
|
+
return () => {
|
|
11
|
+
this.listeners.delete(listener);
|
|
12
|
+
this.onUnsubscribe();
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
hasListeners() {
|
|
16
|
+
return this.listeners.size > 0;
|
|
17
|
+
}
|
|
18
|
+
onSubscribe() {
|
|
19
|
+
}
|
|
20
|
+
onUnsubscribe() {
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// node_modules/@tanstack/query-core/build/modern/timeoutManager.js
|
|
25
|
+
var defaultTimeoutProvider = {
|
|
26
|
+
// We need the wrapper function syntax below instead of direct references to
|
|
27
|
+
// global setTimeout etc.
|
|
28
|
+
//
|
|
29
|
+
// BAD: `setTimeout: setTimeout`
|
|
30
|
+
// GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`
|
|
31
|
+
//
|
|
32
|
+
// If we use direct references here, then anything that wants to spy on or
|
|
33
|
+
// replace the global setTimeout (like tests) won't work since we'll already
|
|
34
|
+
// have a hard reference to the original implementation at the time when this
|
|
35
|
+
// file was imported.
|
|
36
|
+
setTimeout: (callback, delay) => setTimeout(callback, delay),
|
|
37
|
+
clearTimeout: (timeoutId) => clearTimeout(timeoutId),
|
|
38
|
+
setInterval: (callback, delay) => setInterval(callback, delay),
|
|
39
|
+
clearInterval: (intervalId) => clearInterval(intervalId)
|
|
40
|
+
};
|
|
41
|
+
var TimeoutManager = class {
|
|
42
|
+
// We cannot have TimeoutManager<T> as we must instantiate it with a concrete
|
|
43
|
+
// type at app boot; and if we leave that type, then any new timer provider
|
|
44
|
+
// would need to support ReturnType<typeof setTimeout>, which is infeasible.
|
|
45
|
+
//
|
|
46
|
+
// We settle for type safety for the TimeoutProvider type, and accept that
|
|
47
|
+
// this class is unsafe internally to allow for extension.
|
|
48
|
+
#provider = defaultTimeoutProvider;
|
|
49
|
+
#providerCalled = false;
|
|
50
|
+
setTimeoutProvider(provider) {
|
|
51
|
+
if (process.env.NODE_ENV !== "production") {
|
|
52
|
+
if (this.#providerCalled && provider !== this.#provider) {
|
|
53
|
+
console.error(
|
|
54
|
+
`[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`,
|
|
55
|
+
{ previous: this.#provider, provider }
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
this.#provider = provider;
|
|
60
|
+
if (process.env.NODE_ENV !== "production") {
|
|
61
|
+
this.#providerCalled = false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
setTimeout(callback, delay) {
|
|
65
|
+
if (process.env.NODE_ENV !== "production") {
|
|
66
|
+
this.#providerCalled = true;
|
|
67
|
+
}
|
|
68
|
+
return this.#provider.setTimeout(callback, delay);
|
|
69
|
+
}
|
|
70
|
+
clearTimeout(timeoutId) {
|
|
71
|
+
this.#provider.clearTimeout(timeoutId);
|
|
72
|
+
}
|
|
73
|
+
setInterval(callback, delay) {
|
|
74
|
+
if (process.env.NODE_ENV !== "production") {
|
|
75
|
+
this.#providerCalled = true;
|
|
76
|
+
}
|
|
77
|
+
return this.#provider.setInterval(callback, delay);
|
|
78
|
+
}
|
|
79
|
+
clearInterval(intervalId) {
|
|
80
|
+
this.#provider.clearInterval(intervalId);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
var timeoutManager = new TimeoutManager();
|
|
84
|
+
function systemSetTimeoutZero(callback) {
|
|
85
|
+
setTimeout(callback, 0);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// node_modules/@tanstack/query-core/build/modern/utils.js
|
|
89
|
+
var isServer = typeof window === "undefined" || "Deno" in globalThis;
|
|
90
|
+
function noop() {
|
|
91
|
+
}
|
|
92
|
+
function isValidTimeout(value) {
|
|
93
|
+
return typeof value === "number" && value >= 0 && value !== Infinity;
|
|
94
|
+
}
|
|
95
|
+
function timeUntilStale(updatedAt, staleTime) {
|
|
96
|
+
return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
|
|
97
|
+
}
|
|
98
|
+
function resolveStaleTime(staleTime, query) {
|
|
99
|
+
return typeof staleTime === "function" ? staleTime(query) : staleTime;
|
|
100
|
+
}
|
|
101
|
+
function resolveEnabled(enabled, query) {
|
|
102
|
+
return typeof enabled === "function" ? enabled(query) : enabled;
|
|
103
|
+
}
|
|
104
|
+
function hashKey(queryKey) {
|
|
105
|
+
return JSON.stringify(
|
|
106
|
+
queryKey,
|
|
107
|
+
(_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
|
|
108
|
+
result[key] = val[key];
|
|
109
|
+
return result;
|
|
110
|
+
}, {}) : val
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
var hasOwn = Object.prototype.hasOwnProperty;
|
|
114
|
+
function replaceEqualDeep(a, b) {
|
|
115
|
+
if (a === b) {
|
|
116
|
+
return a;
|
|
117
|
+
}
|
|
118
|
+
const array = isPlainArray(a) && isPlainArray(b);
|
|
119
|
+
if (!array && !(isPlainObject(a) && isPlainObject(b))) return b;
|
|
120
|
+
const aItems = array ? a : Object.keys(a);
|
|
121
|
+
const aSize = aItems.length;
|
|
122
|
+
const bItems = array ? b : Object.keys(b);
|
|
123
|
+
const bSize = bItems.length;
|
|
124
|
+
const copy = array ? new Array(bSize) : {};
|
|
125
|
+
let equalItems = 0;
|
|
126
|
+
for (let i = 0; i < bSize; i++) {
|
|
127
|
+
const key = array ? i : bItems[i];
|
|
128
|
+
const aItem = a[key];
|
|
129
|
+
const bItem = b[key];
|
|
130
|
+
if (aItem === bItem) {
|
|
131
|
+
copy[key] = aItem;
|
|
132
|
+
if (array ? i < aSize : hasOwn.call(a, key)) equalItems++;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (aItem === null || bItem === null || typeof aItem !== "object" || typeof bItem !== "object") {
|
|
136
|
+
copy[key] = bItem;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const v = replaceEqualDeep(aItem, bItem);
|
|
140
|
+
copy[key] = v;
|
|
141
|
+
if (v === aItem) equalItems++;
|
|
142
|
+
}
|
|
143
|
+
return aSize === bSize && equalItems === aSize ? a : copy;
|
|
144
|
+
}
|
|
145
|
+
function shallowEqualObjects(a, b) {
|
|
146
|
+
if (!b || Object.keys(a).length !== Object.keys(b).length) {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
for (const key in a) {
|
|
150
|
+
if (a[key] !== b[key]) {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
function isPlainArray(value) {
|
|
157
|
+
return Array.isArray(value) && value.length === Object.keys(value).length;
|
|
158
|
+
}
|
|
159
|
+
function isPlainObject(o) {
|
|
160
|
+
if (!hasObjectPrototype(o)) {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
const ctor = o.constructor;
|
|
164
|
+
if (ctor === void 0) {
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
const prot = ctor.prototype;
|
|
168
|
+
if (!hasObjectPrototype(prot)) {
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
if (!prot.hasOwnProperty("isPrototypeOf")) {
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
if (Object.getPrototypeOf(o) !== Object.prototype) {
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
function hasObjectPrototype(o) {
|
|
180
|
+
return Object.prototype.toString.call(o) === "[object Object]";
|
|
181
|
+
}
|
|
182
|
+
function replaceData(prevData, data, options) {
|
|
183
|
+
if (typeof options.structuralSharing === "function") {
|
|
184
|
+
return options.structuralSharing(prevData, data);
|
|
185
|
+
} else if (options.structuralSharing !== false) {
|
|
186
|
+
if (process.env.NODE_ENV !== "production") {
|
|
187
|
+
try {
|
|
188
|
+
return replaceEqualDeep(prevData, data);
|
|
189
|
+
} catch (error) {
|
|
190
|
+
console.error(
|
|
191
|
+
`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`
|
|
192
|
+
);
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return replaceEqualDeep(prevData, data);
|
|
197
|
+
}
|
|
198
|
+
return data;
|
|
199
|
+
}
|
|
200
|
+
var skipToken = Symbol();
|
|
201
|
+
|
|
202
|
+
// node_modules/@tanstack/query-core/build/modern/focusManager.js
|
|
203
|
+
var FocusManager = class extends Subscribable {
|
|
204
|
+
#focused;
|
|
205
|
+
#cleanup;
|
|
206
|
+
#setup;
|
|
207
|
+
constructor() {
|
|
208
|
+
super();
|
|
209
|
+
this.#setup = (onFocus) => {
|
|
210
|
+
if (!isServer && window.addEventListener) {
|
|
211
|
+
const listener = () => onFocus();
|
|
212
|
+
window.addEventListener("visibilitychange", listener, false);
|
|
213
|
+
return () => {
|
|
214
|
+
window.removeEventListener("visibilitychange", listener);
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
return;
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
onSubscribe() {
|
|
221
|
+
if (!this.#cleanup) {
|
|
222
|
+
this.setEventListener(this.#setup);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
onUnsubscribe() {
|
|
226
|
+
if (!this.hasListeners()) {
|
|
227
|
+
this.#cleanup?.();
|
|
228
|
+
this.#cleanup = void 0;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
setEventListener(setup) {
|
|
232
|
+
this.#setup = setup;
|
|
233
|
+
this.#cleanup?.();
|
|
234
|
+
this.#cleanup = setup((focused) => {
|
|
235
|
+
if (typeof focused === "boolean") {
|
|
236
|
+
this.setFocused(focused);
|
|
237
|
+
} else {
|
|
238
|
+
this.onFocus();
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
setFocused(focused) {
|
|
243
|
+
const changed = this.#focused !== focused;
|
|
244
|
+
if (changed) {
|
|
245
|
+
this.#focused = focused;
|
|
246
|
+
this.onFocus();
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
onFocus() {
|
|
250
|
+
const isFocused = this.isFocused();
|
|
251
|
+
this.listeners.forEach((listener) => {
|
|
252
|
+
listener(isFocused);
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
isFocused() {
|
|
256
|
+
if (typeof this.#focused === "boolean") {
|
|
257
|
+
return this.#focused;
|
|
258
|
+
}
|
|
259
|
+
return globalThis.document?.visibilityState !== "hidden";
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
var focusManager = new FocusManager();
|
|
263
|
+
|
|
264
|
+
// node_modules/@tanstack/query-core/build/modern/thenable.js
|
|
265
|
+
function pendingThenable() {
|
|
266
|
+
let resolve;
|
|
267
|
+
let reject;
|
|
268
|
+
const thenable = new Promise((_resolve, _reject) => {
|
|
269
|
+
resolve = _resolve;
|
|
270
|
+
reject = _reject;
|
|
271
|
+
});
|
|
272
|
+
thenable.status = "pending";
|
|
273
|
+
thenable.catch(() => {
|
|
274
|
+
});
|
|
275
|
+
function finalize(data) {
|
|
276
|
+
Object.assign(thenable, data);
|
|
277
|
+
delete thenable.resolve;
|
|
278
|
+
delete thenable.reject;
|
|
279
|
+
}
|
|
280
|
+
thenable.resolve = (value) => {
|
|
281
|
+
finalize({
|
|
282
|
+
status: "fulfilled",
|
|
283
|
+
value
|
|
284
|
+
});
|
|
285
|
+
resolve(value);
|
|
286
|
+
};
|
|
287
|
+
thenable.reject = (reason) => {
|
|
288
|
+
finalize({
|
|
289
|
+
status: "rejected",
|
|
290
|
+
reason
|
|
291
|
+
});
|
|
292
|
+
reject(reason);
|
|
293
|
+
};
|
|
294
|
+
return thenable;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// node_modules/@tanstack/query-core/build/modern/notifyManager.js
|
|
298
|
+
var defaultScheduler = systemSetTimeoutZero;
|
|
299
|
+
function createNotifyManager() {
|
|
300
|
+
let queue = [];
|
|
301
|
+
let transactions = 0;
|
|
302
|
+
let notifyFn = (callback) => {
|
|
303
|
+
callback();
|
|
304
|
+
};
|
|
305
|
+
let batchNotifyFn = (callback) => {
|
|
306
|
+
callback();
|
|
307
|
+
};
|
|
308
|
+
let scheduleFn = defaultScheduler;
|
|
309
|
+
const schedule = (callback) => {
|
|
310
|
+
if (transactions) {
|
|
311
|
+
queue.push(callback);
|
|
312
|
+
} else {
|
|
313
|
+
scheduleFn(() => {
|
|
314
|
+
notifyFn(callback);
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
const flush = () => {
|
|
319
|
+
const originalQueue = queue;
|
|
320
|
+
queue = [];
|
|
321
|
+
if (originalQueue.length) {
|
|
322
|
+
scheduleFn(() => {
|
|
323
|
+
batchNotifyFn(() => {
|
|
324
|
+
originalQueue.forEach((callback) => {
|
|
325
|
+
notifyFn(callback);
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
return {
|
|
332
|
+
batch: (callback) => {
|
|
333
|
+
let result;
|
|
334
|
+
transactions++;
|
|
335
|
+
try {
|
|
336
|
+
result = callback();
|
|
337
|
+
} finally {
|
|
338
|
+
transactions--;
|
|
339
|
+
if (!transactions) {
|
|
340
|
+
flush();
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return result;
|
|
344
|
+
},
|
|
345
|
+
/**
|
|
346
|
+
* All calls to the wrapped function will be batched.
|
|
347
|
+
*/
|
|
348
|
+
batchCalls: (callback) => {
|
|
349
|
+
return (...args) => {
|
|
350
|
+
schedule(() => {
|
|
351
|
+
callback(...args);
|
|
352
|
+
});
|
|
353
|
+
};
|
|
354
|
+
},
|
|
355
|
+
schedule,
|
|
356
|
+
/**
|
|
357
|
+
* Use this method to set a custom notify function.
|
|
358
|
+
* This can be used to for example wrap notifications with `React.act` while running tests.
|
|
359
|
+
*/
|
|
360
|
+
setNotifyFunction: (fn) => {
|
|
361
|
+
notifyFn = fn;
|
|
362
|
+
},
|
|
363
|
+
/**
|
|
364
|
+
* Use this method to set a custom function to batch notifications together into a single tick.
|
|
365
|
+
* By default React Query will use the batch function provided by ReactDOM or React Native.
|
|
366
|
+
*/
|
|
367
|
+
setBatchNotifyFunction: (fn) => {
|
|
368
|
+
batchNotifyFn = fn;
|
|
369
|
+
},
|
|
370
|
+
setScheduler: (fn) => {
|
|
371
|
+
scheduleFn = fn;
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
var notifyManager = createNotifyManager();
|
|
376
|
+
|
|
377
|
+
// node_modules/@tanstack/query-core/build/modern/onlineManager.js
|
|
378
|
+
var OnlineManager = class extends Subscribable {
|
|
379
|
+
#online = true;
|
|
380
|
+
#cleanup;
|
|
381
|
+
#setup;
|
|
382
|
+
constructor() {
|
|
383
|
+
super();
|
|
384
|
+
this.#setup = (onOnline) => {
|
|
385
|
+
if (!isServer && window.addEventListener) {
|
|
386
|
+
const onlineListener = () => onOnline(true);
|
|
387
|
+
const offlineListener = () => onOnline(false);
|
|
388
|
+
window.addEventListener("online", onlineListener, false);
|
|
389
|
+
window.addEventListener("offline", offlineListener, false);
|
|
390
|
+
return () => {
|
|
391
|
+
window.removeEventListener("online", onlineListener);
|
|
392
|
+
window.removeEventListener("offline", offlineListener);
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
return;
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
onSubscribe() {
|
|
399
|
+
if (!this.#cleanup) {
|
|
400
|
+
this.setEventListener(this.#setup);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
onUnsubscribe() {
|
|
404
|
+
if (!this.hasListeners()) {
|
|
405
|
+
this.#cleanup?.();
|
|
406
|
+
this.#cleanup = void 0;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
setEventListener(setup) {
|
|
410
|
+
this.#setup = setup;
|
|
411
|
+
this.#cleanup?.();
|
|
412
|
+
this.#cleanup = setup(this.setOnline.bind(this));
|
|
413
|
+
}
|
|
414
|
+
setOnline(online) {
|
|
415
|
+
const changed = this.#online !== online;
|
|
416
|
+
if (changed) {
|
|
417
|
+
this.#online = online;
|
|
418
|
+
this.listeners.forEach((listener) => {
|
|
419
|
+
listener(online);
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
isOnline() {
|
|
424
|
+
return this.#online;
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
var onlineManager = new OnlineManager();
|
|
428
|
+
|
|
429
|
+
// node_modules/@tanstack/query-core/build/modern/retryer.js
|
|
430
|
+
function canFetch(networkMode) {
|
|
431
|
+
return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// node_modules/@tanstack/query-core/build/modern/query.js
|
|
435
|
+
function fetchState(data, options) {
|
|
436
|
+
return {
|
|
437
|
+
fetchFailureCount: 0,
|
|
438
|
+
fetchFailureReason: null,
|
|
439
|
+
fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused",
|
|
440
|
+
...data === void 0 && {
|
|
441
|
+
error: null,
|
|
442
|
+
status: "pending"
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// node_modules/@tanstack/query-core/build/modern/queryObserver.js
|
|
448
|
+
var QueryObserver = class extends Subscribable {
|
|
449
|
+
constructor(client, options) {
|
|
450
|
+
super();
|
|
451
|
+
this.options = options;
|
|
452
|
+
this.#client = client;
|
|
453
|
+
this.#selectError = null;
|
|
454
|
+
this.#currentThenable = pendingThenable();
|
|
455
|
+
this.bindMethods();
|
|
456
|
+
this.setOptions(options);
|
|
457
|
+
}
|
|
458
|
+
#client;
|
|
459
|
+
#currentQuery = void 0;
|
|
460
|
+
#currentQueryInitialState = void 0;
|
|
461
|
+
#currentResult = void 0;
|
|
462
|
+
#currentResultState;
|
|
463
|
+
#currentResultOptions;
|
|
464
|
+
#currentThenable;
|
|
465
|
+
#selectError;
|
|
466
|
+
#selectFn;
|
|
467
|
+
#selectResult;
|
|
468
|
+
// This property keeps track of the last query with defined data.
|
|
469
|
+
// It will be used to pass the previous data and query to the placeholder function between renders.
|
|
470
|
+
#lastQueryWithDefinedData;
|
|
471
|
+
#staleTimeoutId;
|
|
472
|
+
#refetchIntervalId;
|
|
473
|
+
#currentRefetchInterval;
|
|
474
|
+
#trackedProps = /* @__PURE__ */ new Set();
|
|
475
|
+
bindMethods() {
|
|
476
|
+
this.refetch = this.refetch.bind(this);
|
|
477
|
+
}
|
|
478
|
+
onSubscribe() {
|
|
479
|
+
if (this.listeners.size === 1) {
|
|
480
|
+
this.#currentQuery.addObserver(this);
|
|
481
|
+
if (shouldFetchOnMount(this.#currentQuery, this.options)) {
|
|
482
|
+
this.#executeFetch();
|
|
483
|
+
} else {
|
|
484
|
+
this.updateResult();
|
|
485
|
+
}
|
|
486
|
+
this.#updateTimers();
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
onUnsubscribe() {
|
|
490
|
+
if (!this.hasListeners()) {
|
|
491
|
+
this.destroy();
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
shouldFetchOnReconnect() {
|
|
495
|
+
return shouldFetchOn(
|
|
496
|
+
this.#currentQuery,
|
|
497
|
+
this.options,
|
|
498
|
+
this.options.refetchOnReconnect
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
shouldFetchOnWindowFocus() {
|
|
502
|
+
return shouldFetchOn(
|
|
503
|
+
this.#currentQuery,
|
|
504
|
+
this.options,
|
|
505
|
+
this.options.refetchOnWindowFocus
|
|
506
|
+
);
|
|
507
|
+
}
|
|
508
|
+
destroy() {
|
|
509
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
510
|
+
this.#clearStaleTimeout();
|
|
511
|
+
this.#clearRefetchInterval();
|
|
512
|
+
this.#currentQuery.removeObserver(this);
|
|
513
|
+
}
|
|
514
|
+
setOptions(options) {
|
|
515
|
+
const prevOptions = this.options;
|
|
516
|
+
const prevQuery = this.#currentQuery;
|
|
517
|
+
this.options = this.#client.defaultQueryOptions(options);
|
|
518
|
+
if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveEnabled(this.options.enabled, this.#currentQuery) !== "boolean") {
|
|
519
|
+
throw new Error(
|
|
520
|
+
"Expected enabled to be a boolean or a callback that returns a boolean"
|
|
521
|
+
);
|
|
522
|
+
}
|
|
523
|
+
this.#updateQuery();
|
|
524
|
+
this.#currentQuery.setOptions(this.options);
|
|
525
|
+
if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) {
|
|
526
|
+
this.#client.getQueryCache().notify({
|
|
527
|
+
type: "observerOptionsUpdated",
|
|
528
|
+
query: this.#currentQuery,
|
|
529
|
+
observer: this
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
const mounted = this.hasListeners();
|
|
533
|
+
if (mounted && shouldFetchOptionally(
|
|
534
|
+
this.#currentQuery,
|
|
535
|
+
prevQuery,
|
|
536
|
+
this.options,
|
|
537
|
+
prevOptions
|
|
538
|
+
)) {
|
|
539
|
+
this.#executeFetch();
|
|
540
|
+
}
|
|
541
|
+
this.updateResult();
|
|
542
|
+
if (mounted && (this.#currentQuery !== prevQuery || resolveEnabled(this.options.enabled, this.#currentQuery) !== resolveEnabled(prevOptions.enabled, this.#currentQuery) || resolveStaleTime(this.options.staleTime, this.#currentQuery) !== resolveStaleTime(prevOptions.staleTime, this.#currentQuery))) {
|
|
543
|
+
this.#updateStaleTimeout();
|
|
544
|
+
}
|
|
545
|
+
const nextRefetchInterval = this.#computeRefetchInterval();
|
|
546
|
+
if (mounted && (this.#currentQuery !== prevQuery || resolveEnabled(this.options.enabled, this.#currentQuery) !== resolveEnabled(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) {
|
|
547
|
+
this.#updateRefetchInterval(nextRefetchInterval);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
getOptimisticResult(options) {
|
|
551
|
+
const query = this.#client.getQueryCache().build(this.#client, options);
|
|
552
|
+
const result = this.createResult(query, options);
|
|
553
|
+
if (shouldAssignObserverCurrentProperties(this, result)) {
|
|
554
|
+
this.#currentResult = result;
|
|
555
|
+
this.#currentResultOptions = this.options;
|
|
556
|
+
this.#currentResultState = this.#currentQuery.state;
|
|
557
|
+
}
|
|
558
|
+
return result;
|
|
559
|
+
}
|
|
560
|
+
getCurrentResult() {
|
|
561
|
+
return this.#currentResult;
|
|
562
|
+
}
|
|
563
|
+
trackResult(result, onPropTracked) {
|
|
564
|
+
return new Proxy(result, {
|
|
565
|
+
get: (target, key) => {
|
|
566
|
+
this.trackProp(key);
|
|
567
|
+
onPropTracked?.(key);
|
|
568
|
+
if (key === "promise") {
|
|
569
|
+
this.trackProp("data");
|
|
570
|
+
if (!this.options.experimental_prefetchInRender && this.#currentThenable.status === "pending") {
|
|
571
|
+
this.#currentThenable.reject(
|
|
572
|
+
new Error(
|
|
573
|
+
"experimental_prefetchInRender feature flag is not enabled"
|
|
574
|
+
)
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
return Reflect.get(target, key);
|
|
579
|
+
}
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
trackProp(key) {
|
|
583
|
+
this.#trackedProps.add(key);
|
|
584
|
+
}
|
|
585
|
+
getCurrentQuery() {
|
|
586
|
+
return this.#currentQuery;
|
|
587
|
+
}
|
|
588
|
+
refetch({ ...options } = {}) {
|
|
589
|
+
return this.fetch({
|
|
590
|
+
...options
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
fetchOptimistic(options) {
|
|
594
|
+
const defaultedOptions = this.#client.defaultQueryOptions(options);
|
|
595
|
+
const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);
|
|
596
|
+
return query.fetch().then(() => this.createResult(query, defaultedOptions));
|
|
597
|
+
}
|
|
598
|
+
fetch(fetchOptions) {
|
|
599
|
+
return this.#executeFetch({
|
|
600
|
+
...fetchOptions,
|
|
601
|
+
cancelRefetch: fetchOptions.cancelRefetch ?? true
|
|
602
|
+
}).then(() => {
|
|
603
|
+
this.updateResult();
|
|
604
|
+
return this.#currentResult;
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
#executeFetch(fetchOptions) {
|
|
608
|
+
this.#updateQuery();
|
|
609
|
+
let promise = this.#currentQuery.fetch(
|
|
610
|
+
this.options,
|
|
611
|
+
fetchOptions
|
|
612
|
+
);
|
|
613
|
+
if (!fetchOptions?.throwOnError) {
|
|
614
|
+
promise = promise.catch(noop);
|
|
615
|
+
}
|
|
616
|
+
return promise;
|
|
617
|
+
}
|
|
618
|
+
#updateStaleTimeout() {
|
|
619
|
+
this.#clearStaleTimeout();
|
|
620
|
+
const staleTime = resolveStaleTime(
|
|
621
|
+
this.options.staleTime,
|
|
622
|
+
this.#currentQuery
|
|
623
|
+
);
|
|
624
|
+
if (isServer || this.#currentResult.isStale || !isValidTimeout(staleTime)) {
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime);
|
|
628
|
+
const timeout = time + 1;
|
|
629
|
+
this.#staleTimeoutId = timeoutManager.setTimeout(() => {
|
|
630
|
+
if (!this.#currentResult.isStale) {
|
|
631
|
+
this.updateResult();
|
|
632
|
+
}
|
|
633
|
+
}, timeout);
|
|
634
|
+
}
|
|
635
|
+
#computeRefetchInterval() {
|
|
636
|
+
return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(this.#currentQuery) : this.options.refetchInterval) ?? false;
|
|
637
|
+
}
|
|
638
|
+
#updateRefetchInterval(nextInterval) {
|
|
639
|
+
this.#clearRefetchInterval();
|
|
640
|
+
this.#currentRefetchInterval = nextInterval;
|
|
641
|
+
if (isServer || resolveEnabled(this.options.enabled, this.#currentQuery) === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
this.#refetchIntervalId = timeoutManager.setInterval(() => {
|
|
645
|
+
if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
|
|
646
|
+
this.#executeFetch();
|
|
647
|
+
}
|
|
648
|
+
}, this.#currentRefetchInterval);
|
|
649
|
+
}
|
|
650
|
+
#updateTimers() {
|
|
651
|
+
this.#updateStaleTimeout();
|
|
652
|
+
this.#updateRefetchInterval(this.#computeRefetchInterval());
|
|
653
|
+
}
|
|
654
|
+
#clearStaleTimeout() {
|
|
655
|
+
if (this.#staleTimeoutId) {
|
|
656
|
+
timeoutManager.clearTimeout(this.#staleTimeoutId);
|
|
657
|
+
this.#staleTimeoutId = void 0;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
#clearRefetchInterval() {
|
|
661
|
+
if (this.#refetchIntervalId) {
|
|
662
|
+
timeoutManager.clearInterval(this.#refetchIntervalId);
|
|
663
|
+
this.#refetchIntervalId = void 0;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
createResult(query, options) {
|
|
667
|
+
const prevQuery = this.#currentQuery;
|
|
668
|
+
const prevOptions = this.options;
|
|
669
|
+
const prevResult = this.#currentResult;
|
|
670
|
+
const prevResultState = this.#currentResultState;
|
|
671
|
+
const prevResultOptions = this.#currentResultOptions;
|
|
672
|
+
const queryChange = query !== prevQuery;
|
|
673
|
+
const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;
|
|
674
|
+
const { state } = query;
|
|
675
|
+
let newState = { ...state };
|
|
676
|
+
let isPlaceholderData = false;
|
|
677
|
+
let data;
|
|
678
|
+
if (options._optimisticResults) {
|
|
679
|
+
const mounted = this.hasListeners();
|
|
680
|
+
const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
|
|
681
|
+
const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
|
|
682
|
+
if (fetchOnMount || fetchOptionally) {
|
|
683
|
+
newState = {
|
|
684
|
+
...newState,
|
|
685
|
+
...fetchState(state.data, query.options)
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
if (options._optimisticResults === "isRestoring") {
|
|
689
|
+
newState.fetchStatus = "idle";
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
let { error, errorUpdatedAt, status } = newState;
|
|
693
|
+
data = newState.data;
|
|
694
|
+
let skipSelect = false;
|
|
695
|
+
if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
|
|
696
|
+
let placeholderData;
|
|
697
|
+
if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {
|
|
698
|
+
placeholderData = prevResult.data;
|
|
699
|
+
skipSelect = true;
|
|
700
|
+
} else {
|
|
701
|
+
placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
|
|
702
|
+
this.#lastQueryWithDefinedData?.state.data,
|
|
703
|
+
this.#lastQueryWithDefinedData
|
|
704
|
+
) : options.placeholderData;
|
|
705
|
+
}
|
|
706
|
+
if (placeholderData !== void 0) {
|
|
707
|
+
status = "success";
|
|
708
|
+
data = replaceData(
|
|
709
|
+
prevResult?.data,
|
|
710
|
+
placeholderData,
|
|
711
|
+
options
|
|
712
|
+
);
|
|
713
|
+
isPlaceholderData = true;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (options.select && data !== void 0 && !skipSelect) {
|
|
717
|
+
if (prevResult && data === prevResultState?.data && options.select === this.#selectFn) {
|
|
718
|
+
data = this.#selectResult;
|
|
719
|
+
} else {
|
|
720
|
+
try {
|
|
721
|
+
this.#selectFn = options.select;
|
|
722
|
+
data = options.select(data);
|
|
723
|
+
data = replaceData(prevResult?.data, data, options);
|
|
724
|
+
this.#selectResult = data;
|
|
725
|
+
this.#selectError = null;
|
|
726
|
+
} catch (selectError) {
|
|
727
|
+
this.#selectError = selectError;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
if (this.#selectError) {
|
|
732
|
+
error = this.#selectError;
|
|
733
|
+
data = this.#selectResult;
|
|
734
|
+
errorUpdatedAt = Date.now();
|
|
735
|
+
status = "error";
|
|
736
|
+
}
|
|
737
|
+
const isFetching = newState.fetchStatus === "fetching";
|
|
738
|
+
const isPending = status === "pending";
|
|
739
|
+
const isError = status === "error";
|
|
740
|
+
const isLoading = isPending && isFetching;
|
|
741
|
+
const hasData = data !== void 0;
|
|
742
|
+
const result = {
|
|
743
|
+
status,
|
|
744
|
+
fetchStatus: newState.fetchStatus,
|
|
745
|
+
isPending,
|
|
746
|
+
isSuccess: status === "success",
|
|
747
|
+
isError,
|
|
748
|
+
isInitialLoading: isLoading,
|
|
749
|
+
isLoading,
|
|
750
|
+
data,
|
|
751
|
+
dataUpdatedAt: newState.dataUpdatedAt,
|
|
752
|
+
error,
|
|
753
|
+
errorUpdatedAt,
|
|
754
|
+
failureCount: newState.fetchFailureCount,
|
|
755
|
+
failureReason: newState.fetchFailureReason,
|
|
756
|
+
errorUpdateCount: newState.errorUpdateCount,
|
|
757
|
+
isFetched: newState.dataUpdateCount > 0 || newState.errorUpdateCount > 0,
|
|
758
|
+
isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,
|
|
759
|
+
isFetching,
|
|
760
|
+
isRefetching: isFetching && !isPending,
|
|
761
|
+
isLoadingError: isError && !hasData,
|
|
762
|
+
isPaused: newState.fetchStatus === "paused",
|
|
763
|
+
isPlaceholderData,
|
|
764
|
+
isRefetchError: isError && hasData,
|
|
765
|
+
isStale: isStale(query, options),
|
|
766
|
+
refetch: this.refetch,
|
|
767
|
+
promise: this.#currentThenable,
|
|
768
|
+
isEnabled: resolveEnabled(options.enabled, query) !== false
|
|
769
|
+
};
|
|
770
|
+
const nextResult = result;
|
|
771
|
+
if (this.options.experimental_prefetchInRender) {
|
|
772
|
+
const finalizeThenableIfPossible = (thenable) => {
|
|
773
|
+
if (nextResult.status === "error") {
|
|
774
|
+
thenable.reject(nextResult.error);
|
|
775
|
+
} else if (nextResult.data !== void 0) {
|
|
776
|
+
thenable.resolve(nextResult.data);
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
const recreateThenable = () => {
|
|
780
|
+
const pending = this.#currentThenable = nextResult.promise = pendingThenable();
|
|
781
|
+
finalizeThenableIfPossible(pending);
|
|
782
|
+
};
|
|
783
|
+
const prevThenable = this.#currentThenable;
|
|
784
|
+
switch (prevThenable.status) {
|
|
785
|
+
case "pending":
|
|
786
|
+
if (query.queryHash === prevQuery.queryHash) {
|
|
787
|
+
finalizeThenableIfPossible(prevThenable);
|
|
788
|
+
}
|
|
789
|
+
break;
|
|
790
|
+
case "fulfilled":
|
|
791
|
+
if (nextResult.status === "error" || nextResult.data !== prevThenable.value) {
|
|
792
|
+
recreateThenable();
|
|
793
|
+
}
|
|
794
|
+
break;
|
|
795
|
+
case "rejected":
|
|
796
|
+
if (nextResult.status !== "error" || nextResult.error !== prevThenable.reason) {
|
|
797
|
+
recreateThenable();
|
|
798
|
+
}
|
|
799
|
+
break;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
return nextResult;
|
|
803
|
+
}
|
|
804
|
+
updateResult() {
|
|
805
|
+
const prevResult = this.#currentResult;
|
|
806
|
+
const nextResult = this.createResult(this.#currentQuery, this.options);
|
|
807
|
+
this.#currentResultState = this.#currentQuery.state;
|
|
808
|
+
this.#currentResultOptions = this.options;
|
|
809
|
+
if (this.#currentResultState.data !== void 0) {
|
|
810
|
+
this.#lastQueryWithDefinedData = this.#currentQuery;
|
|
811
|
+
}
|
|
812
|
+
if (shallowEqualObjects(nextResult, prevResult)) {
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
this.#currentResult = nextResult;
|
|
816
|
+
const shouldNotifyListeners = () => {
|
|
817
|
+
if (!prevResult) {
|
|
818
|
+
return true;
|
|
819
|
+
}
|
|
820
|
+
const { notifyOnChangeProps } = this.options;
|
|
821
|
+
const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
|
|
822
|
+
if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !this.#trackedProps.size) {
|
|
823
|
+
return true;
|
|
824
|
+
}
|
|
825
|
+
const includedProps = new Set(
|
|
826
|
+
notifyOnChangePropsValue ?? this.#trackedProps
|
|
827
|
+
);
|
|
828
|
+
if (this.options.throwOnError) {
|
|
829
|
+
includedProps.add("error");
|
|
830
|
+
}
|
|
831
|
+
return Object.keys(this.#currentResult).some((key) => {
|
|
832
|
+
const typedKey = key;
|
|
833
|
+
const changed = this.#currentResult[typedKey] !== prevResult[typedKey];
|
|
834
|
+
return changed && includedProps.has(typedKey);
|
|
835
|
+
});
|
|
836
|
+
};
|
|
837
|
+
this.#notify({ listeners: shouldNotifyListeners() });
|
|
838
|
+
}
|
|
839
|
+
#updateQuery() {
|
|
840
|
+
const query = this.#client.getQueryCache().build(this.#client, this.options);
|
|
841
|
+
if (query === this.#currentQuery) {
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
const prevQuery = this.#currentQuery;
|
|
845
|
+
this.#currentQuery = query;
|
|
846
|
+
this.#currentQueryInitialState = query.state;
|
|
847
|
+
if (this.hasListeners()) {
|
|
848
|
+
prevQuery?.removeObserver(this);
|
|
849
|
+
query.addObserver(this);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
onQueryUpdate() {
|
|
853
|
+
this.updateResult();
|
|
854
|
+
if (this.hasListeners()) {
|
|
855
|
+
this.#updateTimers();
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
#notify(notifyOptions) {
|
|
859
|
+
notifyManager.batch(() => {
|
|
860
|
+
if (notifyOptions.listeners) {
|
|
861
|
+
this.listeners.forEach((listener) => {
|
|
862
|
+
listener(this.#currentResult);
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
this.#client.getQueryCache().notify({
|
|
866
|
+
query: this.#currentQuery,
|
|
867
|
+
type: "observerResultsUpdated"
|
|
868
|
+
});
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
};
|
|
872
|
+
function shouldLoadOnMount(query, options) {
|
|
873
|
+
return resolveEnabled(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && options.retryOnMount === false);
|
|
874
|
+
}
|
|
875
|
+
function shouldFetchOnMount(query, options) {
|
|
876
|
+
return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);
|
|
877
|
+
}
|
|
878
|
+
function shouldFetchOn(query, options, field) {
|
|
879
|
+
if (resolveEnabled(options.enabled, query) !== false && resolveStaleTime(options.staleTime, query) !== "static") {
|
|
880
|
+
const value = typeof field === "function" ? field(query) : field;
|
|
881
|
+
return value === "always" || value !== false && isStale(query, options);
|
|
882
|
+
}
|
|
883
|
+
return false;
|
|
884
|
+
}
|
|
885
|
+
function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
|
|
886
|
+
return (query !== prevQuery || resolveEnabled(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
|
|
887
|
+
}
|
|
888
|
+
function isStale(query, options) {
|
|
889
|
+
return resolveEnabled(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query));
|
|
890
|
+
}
|
|
891
|
+
function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
|
|
892
|
+
if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {
|
|
893
|
+
return true;
|
|
894
|
+
}
|
|
895
|
+
return false;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
// node_modules/@tanstack/query-db-collection/dist/esm/query.js
|
|
899
|
+
import { deepEquals } from "@tanstack/db";
|
|
900
|
+
|
|
901
|
+
// node_modules/@tanstack/query-db-collection/dist/esm/errors.js
|
|
902
|
+
import { TanStackDBError } from "@tanstack/db";
|
|
903
|
+
var QueryCollectionError = class extends TanStackDBError {
|
|
904
|
+
constructor(message) {
|
|
905
|
+
super(message);
|
|
906
|
+
this.name = `QueryCollectionError`;
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
var QueryKeyRequiredError = class extends QueryCollectionError {
|
|
910
|
+
constructor() {
|
|
911
|
+
super(`[QueryCollection] queryKey must be provided.`);
|
|
912
|
+
this.name = `QueryKeyRequiredError`;
|
|
913
|
+
}
|
|
914
|
+
};
|
|
915
|
+
var QueryFnRequiredError = class extends QueryCollectionError {
|
|
916
|
+
constructor() {
|
|
917
|
+
super(`[QueryCollection] queryFn must be provided.`);
|
|
918
|
+
this.name = `QueryFnRequiredError`;
|
|
919
|
+
}
|
|
920
|
+
};
|
|
921
|
+
var QueryClientRequiredError = class extends QueryCollectionError {
|
|
922
|
+
constructor() {
|
|
923
|
+
super(`[QueryCollection] queryClient must be provided.`);
|
|
924
|
+
this.name = `QueryClientRequiredError`;
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
var GetKeyRequiredError = class extends QueryCollectionError {
|
|
928
|
+
constructor() {
|
|
929
|
+
super(`[QueryCollection] getKey must be provided.`);
|
|
930
|
+
this.name = `GetKeyRequiredError`;
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
var SyncNotInitializedError = class extends QueryCollectionError {
|
|
934
|
+
constructor() {
|
|
935
|
+
super(
|
|
936
|
+
`Collection must be in 'ready' state for manual sync operations. Sync not initialized yet.`
|
|
937
|
+
);
|
|
938
|
+
this.name = `SyncNotInitializedError`;
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
var DuplicateKeyInBatchError = class extends QueryCollectionError {
|
|
942
|
+
constructor(key) {
|
|
943
|
+
super(`Duplicate key '${key}' found within batch operations`);
|
|
944
|
+
this.name = `DuplicateKeyInBatchError`;
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
var UpdateOperationItemNotFoundError = class extends QueryCollectionError {
|
|
948
|
+
constructor(key) {
|
|
949
|
+
super(`Update operation: Item with key '${key}' does not exist`);
|
|
950
|
+
this.name = `UpdateOperationItemNotFoundError`;
|
|
951
|
+
}
|
|
952
|
+
};
|
|
953
|
+
var DeleteOperationItemNotFoundError = class extends QueryCollectionError {
|
|
954
|
+
constructor(key) {
|
|
955
|
+
super(`Delete operation: Item with key '${key}' does not exist`);
|
|
956
|
+
this.name = `DeleteOperationItemNotFoundError`;
|
|
957
|
+
}
|
|
958
|
+
};
|
|
959
|
+
|
|
960
|
+
// node_modules/@tanstack/query-db-collection/dist/esm/manual-sync.js
|
|
961
|
+
var activeBatchContexts = /* @__PURE__ */ new WeakMap();
|
|
962
|
+
function normalizeOperations(ops, ctx) {
|
|
963
|
+
const operations = Array.isArray(ops) ? ops : [ops];
|
|
964
|
+
const normalized = [];
|
|
965
|
+
for (const op of operations) {
|
|
966
|
+
if (op.type === `delete`) {
|
|
967
|
+
const keys = Array.isArray(op.key) ? op.key : [op.key];
|
|
968
|
+
for (const key of keys) {
|
|
969
|
+
normalized.push({ type: `delete`, key });
|
|
970
|
+
}
|
|
971
|
+
} else {
|
|
972
|
+
const items = Array.isArray(op.data) ? op.data : [op.data];
|
|
973
|
+
for (const item of items) {
|
|
974
|
+
let key;
|
|
975
|
+
if (op.type === `update`) {
|
|
976
|
+
key = ctx.getKey(item);
|
|
977
|
+
} else {
|
|
978
|
+
const resolved = ctx.collection.validateData(
|
|
979
|
+
item,
|
|
980
|
+
op.type === `upsert` ? `insert` : op.type
|
|
981
|
+
);
|
|
982
|
+
key = ctx.getKey(resolved);
|
|
983
|
+
}
|
|
984
|
+
normalized.push({ type: op.type, key, data: item });
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
return normalized;
|
|
989
|
+
}
|
|
990
|
+
function validateOperations(operations, ctx) {
|
|
991
|
+
const seenKeys = /* @__PURE__ */ new Set();
|
|
992
|
+
for (const op of operations) {
|
|
993
|
+
if (seenKeys.has(op.key)) {
|
|
994
|
+
throw new DuplicateKeyInBatchError(op.key);
|
|
995
|
+
}
|
|
996
|
+
seenKeys.add(op.key);
|
|
997
|
+
if (op.type === `update`) {
|
|
998
|
+
if (!ctx.collection._state.syncedData.has(op.key)) {
|
|
999
|
+
throw new UpdateOperationItemNotFoundError(op.key);
|
|
1000
|
+
}
|
|
1001
|
+
} else if (op.type === `delete`) {
|
|
1002
|
+
if (!ctx.collection._state.syncedData.has(op.key)) {
|
|
1003
|
+
throw new DeleteOperationItemNotFoundError(op.key);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
function performWriteOperations(operations, ctx) {
|
|
1009
|
+
const normalized = normalizeOperations(operations, ctx);
|
|
1010
|
+
validateOperations(normalized, ctx);
|
|
1011
|
+
ctx.begin();
|
|
1012
|
+
for (const op of normalized) {
|
|
1013
|
+
switch (op.type) {
|
|
1014
|
+
case `insert`: {
|
|
1015
|
+
const resolved = ctx.collection.validateData(op.data, `insert`);
|
|
1016
|
+
ctx.write({
|
|
1017
|
+
type: `insert`,
|
|
1018
|
+
value: resolved
|
|
1019
|
+
});
|
|
1020
|
+
break;
|
|
1021
|
+
}
|
|
1022
|
+
case `update`: {
|
|
1023
|
+
const currentItem = ctx.collection._state.syncedData.get(op.key);
|
|
1024
|
+
const updatedItem = {
|
|
1025
|
+
...currentItem,
|
|
1026
|
+
...op.data
|
|
1027
|
+
};
|
|
1028
|
+
const resolved = ctx.collection.validateData(
|
|
1029
|
+
updatedItem,
|
|
1030
|
+
`update`,
|
|
1031
|
+
op.key
|
|
1032
|
+
);
|
|
1033
|
+
ctx.write({
|
|
1034
|
+
type: `update`,
|
|
1035
|
+
value: resolved
|
|
1036
|
+
});
|
|
1037
|
+
break;
|
|
1038
|
+
}
|
|
1039
|
+
case `delete`: {
|
|
1040
|
+
const currentItem = ctx.collection._state.syncedData.get(op.key);
|
|
1041
|
+
ctx.write({
|
|
1042
|
+
type: `delete`,
|
|
1043
|
+
value: currentItem
|
|
1044
|
+
});
|
|
1045
|
+
break;
|
|
1046
|
+
}
|
|
1047
|
+
case `upsert`: {
|
|
1048
|
+
const existsInSyncedStore = ctx.collection._state.syncedData.has(op.key);
|
|
1049
|
+
const resolved = ctx.collection.validateData(
|
|
1050
|
+
op.data,
|
|
1051
|
+
existsInSyncedStore ? `update` : `insert`,
|
|
1052
|
+
op.key
|
|
1053
|
+
);
|
|
1054
|
+
if (existsInSyncedStore) {
|
|
1055
|
+
ctx.write({
|
|
1056
|
+
type: `update`,
|
|
1057
|
+
value: resolved
|
|
1058
|
+
});
|
|
1059
|
+
} else {
|
|
1060
|
+
ctx.write({
|
|
1061
|
+
type: `insert`,
|
|
1062
|
+
value: resolved
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
break;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
ctx.commit();
|
|
1070
|
+
const updatedData = Array.from(ctx.collection._state.syncedData.values());
|
|
1071
|
+
if (ctx.updateCacheData) {
|
|
1072
|
+
ctx.updateCacheData(updatedData);
|
|
1073
|
+
} else {
|
|
1074
|
+
ctx.queryClient.setQueryData(ctx.queryKey, updatedData);
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
function createWriteUtils(getContext) {
|
|
1078
|
+
function ensureContext() {
|
|
1079
|
+
const context = getContext();
|
|
1080
|
+
if (!context) {
|
|
1081
|
+
throw new SyncNotInitializedError();
|
|
1082
|
+
}
|
|
1083
|
+
return context;
|
|
1084
|
+
}
|
|
1085
|
+
return {
|
|
1086
|
+
writeInsert(data) {
|
|
1087
|
+
const operation = {
|
|
1088
|
+
type: `insert`,
|
|
1089
|
+
data
|
|
1090
|
+
};
|
|
1091
|
+
const ctx = ensureContext();
|
|
1092
|
+
const batchContext = activeBatchContexts.get(ctx);
|
|
1093
|
+
if (batchContext?.isActive) {
|
|
1094
|
+
batchContext.operations.push(operation);
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
performWriteOperations(operation, ctx);
|
|
1098
|
+
},
|
|
1099
|
+
writeUpdate(data) {
|
|
1100
|
+
const operation = {
|
|
1101
|
+
type: `update`,
|
|
1102
|
+
data
|
|
1103
|
+
};
|
|
1104
|
+
const ctx = ensureContext();
|
|
1105
|
+
const batchContext = activeBatchContexts.get(ctx);
|
|
1106
|
+
if (batchContext?.isActive) {
|
|
1107
|
+
batchContext.operations.push(operation);
|
|
1108
|
+
return;
|
|
1109
|
+
}
|
|
1110
|
+
performWriteOperations(operation, ctx);
|
|
1111
|
+
},
|
|
1112
|
+
writeDelete(key) {
|
|
1113
|
+
const operation = {
|
|
1114
|
+
type: `delete`,
|
|
1115
|
+
key
|
|
1116
|
+
};
|
|
1117
|
+
const ctx = ensureContext();
|
|
1118
|
+
const batchContext = activeBatchContexts.get(ctx);
|
|
1119
|
+
if (batchContext?.isActive) {
|
|
1120
|
+
batchContext.operations.push(operation);
|
|
1121
|
+
return;
|
|
1122
|
+
}
|
|
1123
|
+
performWriteOperations(operation, ctx);
|
|
1124
|
+
},
|
|
1125
|
+
writeUpsert(data) {
|
|
1126
|
+
const operation = {
|
|
1127
|
+
type: `upsert`,
|
|
1128
|
+
data
|
|
1129
|
+
};
|
|
1130
|
+
const ctx = ensureContext();
|
|
1131
|
+
const batchContext = activeBatchContexts.get(ctx);
|
|
1132
|
+
if (batchContext?.isActive) {
|
|
1133
|
+
batchContext.operations.push(operation);
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
performWriteOperations(operation, ctx);
|
|
1137
|
+
},
|
|
1138
|
+
writeBatch(callback) {
|
|
1139
|
+
const ctx = ensureContext();
|
|
1140
|
+
const existingBatch = activeBatchContexts.get(ctx);
|
|
1141
|
+
if (existingBatch?.isActive) {
|
|
1142
|
+
throw new Error(
|
|
1143
|
+
`Cannot nest writeBatch calls. Complete the current batch before starting a new one.`
|
|
1144
|
+
);
|
|
1145
|
+
}
|
|
1146
|
+
const batchContext = {
|
|
1147
|
+
operations: [],
|
|
1148
|
+
isActive: true
|
|
1149
|
+
};
|
|
1150
|
+
activeBatchContexts.set(ctx, batchContext);
|
|
1151
|
+
try {
|
|
1152
|
+
const result = callback();
|
|
1153
|
+
if (
|
|
1154
|
+
// @ts-expect-error - Runtime check for async callback, callback is typed as () => void but user might pass async
|
|
1155
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
1156
|
+
result && typeof result === `object` && `then` in result && // @ts-expect-error - Runtime check for async callback, callback is typed as () => void but user might pass async
|
|
1157
|
+
typeof result.then === `function`
|
|
1158
|
+
) {
|
|
1159
|
+
throw new Error(
|
|
1160
|
+
`writeBatch does not support async callbacks. The callback must be synchronous.`
|
|
1161
|
+
);
|
|
1162
|
+
}
|
|
1163
|
+
if (batchContext.operations.length > 0) {
|
|
1164
|
+
performWriteOperations(batchContext.operations, ctx);
|
|
1165
|
+
}
|
|
1166
|
+
} finally {
|
|
1167
|
+
batchContext.isActive = false;
|
|
1168
|
+
activeBatchContexts.delete(ctx);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// node_modules/@tanstack/query-db-collection/dist/esm/serialization.js
|
|
1175
|
+
function serializeLoadSubsetOptions(options) {
|
|
1176
|
+
if (!options) {
|
|
1177
|
+
return void 0;
|
|
1178
|
+
}
|
|
1179
|
+
const result = {};
|
|
1180
|
+
if (options.where) {
|
|
1181
|
+
result.where = serializeExpression(options.where);
|
|
1182
|
+
}
|
|
1183
|
+
if (options.orderBy?.length) {
|
|
1184
|
+
result.orderBy = options.orderBy.map((clause) => {
|
|
1185
|
+
const baseOrderBy = {
|
|
1186
|
+
expression: serializeExpression(clause.expression),
|
|
1187
|
+
direction: clause.compareOptions.direction,
|
|
1188
|
+
nulls: clause.compareOptions.nulls,
|
|
1189
|
+
stringSort: clause.compareOptions.stringSort
|
|
1190
|
+
};
|
|
1191
|
+
if (clause.compareOptions.stringSort === `locale`) {
|
|
1192
|
+
return {
|
|
1193
|
+
...baseOrderBy,
|
|
1194
|
+
locale: clause.compareOptions.locale,
|
|
1195
|
+
localeOptions: clause.compareOptions.localeOptions
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1198
|
+
return baseOrderBy;
|
|
1199
|
+
});
|
|
1200
|
+
}
|
|
1201
|
+
if (options.limit !== void 0) {
|
|
1202
|
+
result.limit = options.limit;
|
|
1203
|
+
}
|
|
1204
|
+
if (options.offset !== void 0) {
|
|
1205
|
+
result.offset = options.offset;
|
|
1206
|
+
}
|
|
1207
|
+
return Object.keys(result).length === 0 ? void 0 : JSON.stringify(result);
|
|
1208
|
+
}
|
|
1209
|
+
function serializeExpression(expr) {
|
|
1210
|
+
if (!expr) {
|
|
1211
|
+
return null;
|
|
1212
|
+
}
|
|
1213
|
+
switch (expr.type) {
|
|
1214
|
+
case `val`:
|
|
1215
|
+
return {
|
|
1216
|
+
type: `val`,
|
|
1217
|
+
value: serializeValue(expr.value)
|
|
1218
|
+
};
|
|
1219
|
+
case `ref`:
|
|
1220
|
+
return {
|
|
1221
|
+
type: `ref`,
|
|
1222
|
+
path: [...expr.path]
|
|
1223
|
+
};
|
|
1224
|
+
case `func`:
|
|
1225
|
+
return {
|
|
1226
|
+
type: `func`,
|
|
1227
|
+
name: expr.name,
|
|
1228
|
+
args: expr.args.map((arg) => serializeExpression(arg))
|
|
1229
|
+
};
|
|
1230
|
+
default:
|
|
1231
|
+
return null;
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
function serializeValue(value) {
|
|
1235
|
+
if (value === void 0) {
|
|
1236
|
+
return { __type: `undefined` };
|
|
1237
|
+
}
|
|
1238
|
+
if (typeof value === `number`) {
|
|
1239
|
+
if (Number.isNaN(value)) {
|
|
1240
|
+
return { __type: `nan` };
|
|
1241
|
+
}
|
|
1242
|
+
if (value === Number.POSITIVE_INFINITY) {
|
|
1243
|
+
return { __type: `infinity`, sign: 1 };
|
|
1244
|
+
}
|
|
1245
|
+
if (value === Number.NEGATIVE_INFINITY) {
|
|
1246
|
+
return { __type: `infinity`, sign: -1 };
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
if (value === null || typeof value === `string` || typeof value === `number` || typeof value === `boolean`) {
|
|
1250
|
+
return value;
|
|
1251
|
+
}
|
|
1252
|
+
if (value instanceof Date) {
|
|
1253
|
+
return { __type: `date`, value: value.toJSON() };
|
|
1254
|
+
}
|
|
1255
|
+
if (Array.isArray(value)) {
|
|
1256
|
+
return value.map((item) => serializeValue(item));
|
|
1257
|
+
}
|
|
1258
|
+
if (typeof value === `object`) {
|
|
1259
|
+
return Object.fromEntries(
|
|
1260
|
+
Object.entries(value).map(([key, val]) => [
|
|
1261
|
+
key,
|
|
1262
|
+
serializeValue(val)
|
|
1263
|
+
])
|
|
1264
|
+
);
|
|
1265
|
+
}
|
|
1266
|
+
return value;
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
// node_modules/@tanstack/query-db-collection/dist/esm/query.js
|
|
1270
|
+
var QueryCollectionUtilsImpl = class {
|
|
1271
|
+
constructor(state, refetch, writeUtils) {
|
|
1272
|
+
this.state = state;
|
|
1273
|
+
this.refetchFn = refetch;
|
|
1274
|
+
this.refetch = refetch;
|
|
1275
|
+
this.writeInsert = writeUtils.writeInsert;
|
|
1276
|
+
this.writeUpdate = writeUtils.writeUpdate;
|
|
1277
|
+
this.writeDelete = writeUtils.writeDelete;
|
|
1278
|
+
this.writeUpsert = writeUtils.writeUpsert;
|
|
1279
|
+
this.writeBatch = writeUtils.writeBatch;
|
|
1280
|
+
}
|
|
1281
|
+
async clearError() {
|
|
1282
|
+
this.state.lastError = void 0;
|
|
1283
|
+
this.state.errorCount = 0;
|
|
1284
|
+
this.state.lastErrorUpdatedAt = 0;
|
|
1285
|
+
await this.refetchFn({ throwOnError: true });
|
|
1286
|
+
}
|
|
1287
|
+
// Getters for error state
|
|
1288
|
+
get lastError() {
|
|
1289
|
+
return this.state.lastError;
|
|
1290
|
+
}
|
|
1291
|
+
get isError() {
|
|
1292
|
+
return !!this.state.lastError;
|
|
1293
|
+
}
|
|
1294
|
+
get errorCount() {
|
|
1295
|
+
return this.state.errorCount;
|
|
1296
|
+
}
|
|
1297
|
+
// Getters for QueryObserver state
|
|
1298
|
+
get isFetching() {
|
|
1299
|
+
return Array.from(this.state.observers.values()).some(
|
|
1300
|
+
(observer) => observer.getCurrentResult().isFetching
|
|
1301
|
+
);
|
|
1302
|
+
}
|
|
1303
|
+
get isRefetching() {
|
|
1304
|
+
return Array.from(this.state.observers.values()).some(
|
|
1305
|
+
(observer) => observer.getCurrentResult().isRefetching
|
|
1306
|
+
);
|
|
1307
|
+
}
|
|
1308
|
+
get isLoading() {
|
|
1309
|
+
return Array.from(this.state.observers.values()).some(
|
|
1310
|
+
(observer) => observer.getCurrentResult().isLoading
|
|
1311
|
+
);
|
|
1312
|
+
}
|
|
1313
|
+
get dataUpdatedAt() {
|
|
1314
|
+
return Math.max(
|
|
1315
|
+
0,
|
|
1316
|
+
...Array.from(this.state.observers.values()).map(
|
|
1317
|
+
(observer) => observer.getCurrentResult().dataUpdatedAt
|
|
1318
|
+
)
|
|
1319
|
+
);
|
|
1320
|
+
}
|
|
1321
|
+
get fetchStatus() {
|
|
1322
|
+
return Array.from(this.state.observers.values()).map(
|
|
1323
|
+
(observer) => observer.getCurrentResult().fetchStatus
|
|
1324
|
+
);
|
|
1325
|
+
}
|
|
1326
|
+
};
|
|
1327
|
+
function queryCollectionOptions(config) {
|
|
1328
|
+
const {
|
|
1329
|
+
queryKey,
|
|
1330
|
+
queryFn,
|
|
1331
|
+
select,
|
|
1332
|
+
queryClient,
|
|
1333
|
+
enabled,
|
|
1334
|
+
refetchInterval,
|
|
1335
|
+
retry,
|
|
1336
|
+
retryDelay,
|
|
1337
|
+
staleTime,
|
|
1338
|
+
getKey,
|
|
1339
|
+
onInsert,
|
|
1340
|
+
onUpdate,
|
|
1341
|
+
onDelete,
|
|
1342
|
+
meta,
|
|
1343
|
+
...baseCollectionConfig
|
|
1344
|
+
} = config;
|
|
1345
|
+
const syncMode = baseCollectionConfig.syncMode ?? `eager`;
|
|
1346
|
+
if (!queryKey) {
|
|
1347
|
+
throw new QueryKeyRequiredError();
|
|
1348
|
+
}
|
|
1349
|
+
if (!queryFn) {
|
|
1350
|
+
throw new QueryFnRequiredError();
|
|
1351
|
+
}
|
|
1352
|
+
if (!queryClient) {
|
|
1353
|
+
throw new QueryClientRequiredError();
|
|
1354
|
+
}
|
|
1355
|
+
if (!getKey) {
|
|
1356
|
+
throw new GetKeyRequiredError();
|
|
1357
|
+
}
|
|
1358
|
+
const state = {
|
|
1359
|
+
lastError: void 0,
|
|
1360
|
+
errorCount: 0,
|
|
1361
|
+
lastErrorUpdatedAt: 0,
|
|
1362
|
+
observers: /* @__PURE__ */ new Map()
|
|
1363
|
+
};
|
|
1364
|
+
const hashToQueryKey = /* @__PURE__ */ new Map();
|
|
1365
|
+
const queryToRows = /* @__PURE__ */ new Map();
|
|
1366
|
+
const rowToQueries = /* @__PURE__ */ new Map();
|
|
1367
|
+
const unsubscribes = /* @__PURE__ */ new Map();
|
|
1368
|
+
const queryRefCounts = /* @__PURE__ */ new Map();
|
|
1369
|
+
const addRow = (rowKey, hashedQueryKey) => {
|
|
1370
|
+
const rowToQueriesSet = rowToQueries.get(rowKey) || /* @__PURE__ */ new Set();
|
|
1371
|
+
rowToQueriesSet.add(hashedQueryKey);
|
|
1372
|
+
rowToQueries.set(rowKey, rowToQueriesSet);
|
|
1373
|
+
const queryToRowsSet = queryToRows.get(hashedQueryKey) || /* @__PURE__ */ new Set();
|
|
1374
|
+
queryToRowsSet.add(rowKey);
|
|
1375
|
+
queryToRows.set(hashedQueryKey, queryToRowsSet);
|
|
1376
|
+
};
|
|
1377
|
+
const removeRow = (rowKey, hashedQuerKey) => {
|
|
1378
|
+
const rowToQueriesSet = rowToQueries.get(rowKey) || /* @__PURE__ */ new Set();
|
|
1379
|
+
rowToQueriesSet.delete(hashedQuerKey);
|
|
1380
|
+
rowToQueries.set(rowKey, rowToQueriesSet);
|
|
1381
|
+
const queryToRowsSet = queryToRows.get(hashedQuerKey) || /* @__PURE__ */ new Set();
|
|
1382
|
+
queryToRowsSet.delete(rowKey);
|
|
1383
|
+
queryToRows.set(hashedQuerKey, queryToRowsSet);
|
|
1384
|
+
return rowToQueriesSet.size === 0;
|
|
1385
|
+
};
|
|
1386
|
+
const internalSync = (params) => {
|
|
1387
|
+
const { begin, write, commit, markReady, collection } = params;
|
|
1388
|
+
let syncStarted = false;
|
|
1389
|
+
const generateQueryKeyFromOptions = (opts) => {
|
|
1390
|
+
if (typeof queryKey === `function`) {
|
|
1391
|
+
return queryKey(opts);
|
|
1392
|
+
} else if (syncMode === `on-demand`) {
|
|
1393
|
+
const serialized = serializeLoadSubsetOptions(opts);
|
|
1394
|
+
return serialized !== void 0 ? [...queryKey, serialized] : queryKey;
|
|
1395
|
+
} else {
|
|
1396
|
+
return queryKey;
|
|
1397
|
+
}
|
|
1398
|
+
};
|
|
1399
|
+
const createQueryFromOpts = (opts = {}, queryFunction = queryFn) => {
|
|
1400
|
+
const key = generateQueryKeyFromOptions(opts);
|
|
1401
|
+
const hashedQueryKey = hashKey(key);
|
|
1402
|
+
const extendedMeta = { ...meta, loadSubsetOptions: opts };
|
|
1403
|
+
if (state.observers.has(hashedQueryKey)) {
|
|
1404
|
+
queryRefCounts.set(
|
|
1405
|
+
hashedQueryKey,
|
|
1406
|
+
(queryRefCounts.get(hashedQueryKey) || 0) + 1
|
|
1407
|
+
);
|
|
1408
|
+
const observer = state.observers.get(hashedQueryKey);
|
|
1409
|
+
const currentResult = observer.getCurrentResult();
|
|
1410
|
+
if (currentResult.isSuccess) {
|
|
1411
|
+
return true;
|
|
1412
|
+
} else if (currentResult.isError) {
|
|
1413
|
+
return Promise.reject(currentResult.error);
|
|
1414
|
+
} else {
|
|
1415
|
+
return new Promise((resolve, reject) => {
|
|
1416
|
+
const unsubscribe = observer.subscribe((result) => {
|
|
1417
|
+
queueMicrotask(() => {
|
|
1418
|
+
if (result.isSuccess) {
|
|
1419
|
+
unsubscribe();
|
|
1420
|
+
resolve();
|
|
1421
|
+
} else if (result.isError) {
|
|
1422
|
+
unsubscribe();
|
|
1423
|
+
reject(result.error);
|
|
1424
|
+
}
|
|
1425
|
+
});
|
|
1426
|
+
});
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
const observerOptions = {
|
|
1431
|
+
queryKey: key,
|
|
1432
|
+
queryFn: queryFunction,
|
|
1433
|
+
meta: extendedMeta,
|
|
1434
|
+
structuralSharing: true,
|
|
1435
|
+
notifyOnChangeProps: `all`,
|
|
1436
|
+
// Only include options that are explicitly defined to allow QueryClient defaultOptions to be used
|
|
1437
|
+
...enabled !== void 0 && { enabled },
|
|
1438
|
+
...refetchInterval !== void 0 && { refetchInterval },
|
|
1439
|
+
...retry !== void 0 && { retry },
|
|
1440
|
+
...retryDelay !== void 0 && { retryDelay },
|
|
1441
|
+
...staleTime !== void 0 && { staleTime }
|
|
1442
|
+
};
|
|
1443
|
+
const localObserver = new QueryObserver(queryClient, observerOptions);
|
|
1444
|
+
hashToQueryKey.set(hashedQueryKey, key);
|
|
1445
|
+
state.observers.set(hashedQueryKey, localObserver);
|
|
1446
|
+
queryRefCounts.set(
|
|
1447
|
+
hashedQueryKey,
|
|
1448
|
+
(queryRefCounts.get(hashedQueryKey) || 0) + 1
|
|
1449
|
+
);
|
|
1450
|
+
const readyPromise = new Promise((resolve, reject) => {
|
|
1451
|
+
const unsubscribe = localObserver.subscribe((result) => {
|
|
1452
|
+
queueMicrotask(() => {
|
|
1453
|
+
if (result.isSuccess) {
|
|
1454
|
+
unsubscribe();
|
|
1455
|
+
resolve();
|
|
1456
|
+
} else if (result.isError) {
|
|
1457
|
+
unsubscribe();
|
|
1458
|
+
reject(result.error);
|
|
1459
|
+
}
|
|
1460
|
+
});
|
|
1461
|
+
});
|
|
1462
|
+
});
|
|
1463
|
+
if (syncStarted || collection.subscriberCount > 0) {
|
|
1464
|
+
subscribeToQuery(localObserver, hashedQueryKey);
|
|
1465
|
+
}
|
|
1466
|
+
return readyPromise;
|
|
1467
|
+
};
|
|
1468
|
+
const makeQueryResultHandler = (queryKey2) => {
|
|
1469
|
+
const hashedQueryKey = hashKey(queryKey2);
|
|
1470
|
+
const handleQueryResult = (result) => {
|
|
1471
|
+
if (result.isSuccess) {
|
|
1472
|
+
state.lastError = void 0;
|
|
1473
|
+
state.errorCount = 0;
|
|
1474
|
+
const rawData = result.data;
|
|
1475
|
+
const newItemsArray = select ? select(rawData) : rawData;
|
|
1476
|
+
if (!Array.isArray(newItemsArray) || newItemsArray.some((item) => typeof item !== `object`)) {
|
|
1477
|
+
const errorMessage = select ? `@tanstack/query-db-collection: select() must return an array of objects. Got: ${typeof newItemsArray} for queryKey ${JSON.stringify(queryKey2)}` : `@tanstack/query-db-collection: queryFn must return an array of objects. Got: ${typeof newItemsArray} for queryKey ${JSON.stringify(queryKey2)}`;
|
|
1478
|
+
console.error(errorMessage);
|
|
1479
|
+
return;
|
|
1480
|
+
}
|
|
1481
|
+
const currentSyncedItems = new Map(
|
|
1482
|
+
collection._state.syncedData.entries()
|
|
1483
|
+
);
|
|
1484
|
+
const newItemsMap = /* @__PURE__ */ new Map();
|
|
1485
|
+
newItemsArray.forEach((item) => {
|
|
1486
|
+
const key = getKey(item);
|
|
1487
|
+
newItemsMap.set(key, item);
|
|
1488
|
+
});
|
|
1489
|
+
begin();
|
|
1490
|
+
currentSyncedItems.forEach((oldItem, key) => {
|
|
1491
|
+
const newItem = newItemsMap.get(key);
|
|
1492
|
+
if (!newItem) {
|
|
1493
|
+
const needToRemove = removeRow(key, hashedQueryKey);
|
|
1494
|
+
if (needToRemove) {
|
|
1495
|
+
write({ type: `delete`, value: oldItem });
|
|
1496
|
+
}
|
|
1497
|
+
} else if (!deepEquals(oldItem, newItem)) {
|
|
1498
|
+
write({ type: `update`, value: newItem });
|
|
1499
|
+
}
|
|
1500
|
+
});
|
|
1501
|
+
newItemsMap.forEach((newItem, key) => {
|
|
1502
|
+
addRow(key, hashedQueryKey);
|
|
1503
|
+
if (!currentSyncedItems.has(key)) {
|
|
1504
|
+
write({ type: `insert`, value: newItem });
|
|
1505
|
+
}
|
|
1506
|
+
});
|
|
1507
|
+
commit();
|
|
1508
|
+
markReady();
|
|
1509
|
+
} else if (result.isError) {
|
|
1510
|
+
if (result.errorUpdatedAt !== state.lastErrorUpdatedAt) {
|
|
1511
|
+
state.lastError = result.error;
|
|
1512
|
+
state.errorCount++;
|
|
1513
|
+
state.lastErrorUpdatedAt = result.errorUpdatedAt;
|
|
1514
|
+
}
|
|
1515
|
+
console.error(
|
|
1516
|
+
`[QueryCollection] Error observing query ${String(queryKey2)}:`,
|
|
1517
|
+
result.error
|
|
1518
|
+
);
|
|
1519
|
+
markReady();
|
|
1520
|
+
}
|
|
1521
|
+
};
|
|
1522
|
+
return handleQueryResult;
|
|
1523
|
+
};
|
|
1524
|
+
const isSubscribed = (hashedQueryKey) => {
|
|
1525
|
+
return unsubscribes.has(hashedQueryKey);
|
|
1526
|
+
};
|
|
1527
|
+
const subscribeToQuery = (observer, hashedQueryKey) => {
|
|
1528
|
+
if (!isSubscribed(hashedQueryKey)) {
|
|
1529
|
+
const cachedQueryKey = hashToQueryKey.get(hashedQueryKey);
|
|
1530
|
+
const handleQueryResult = makeQueryResultHandler(cachedQueryKey);
|
|
1531
|
+
const unsubscribeFn = observer.subscribe(handleQueryResult);
|
|
1532
|
+
unsubscribes.set(hashedQueryKey, unsubscribeFn);
|
|
1533
|
+
const currentResult = observer.getCurrentResult();
|
|
1534
|
+
if (currentResult.isSuccess || currentResult.isError) {
|
|
1535
|
+
handleQueryResult(currentResult);
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
};
|
|
1539
|
+
const subscribeToQueries = () => {
|
|
1540
|
+
state.observers.forEach(subscribeToQuery);
|
|
1541
|
+
};
|
|
1542
|
+
const unsubscribeFromQueries = () => {
|
|
1543
|
+
unsubscribes.forEach((unsubscribeFn) => {
|
|
1544
|
+
unsubscribeFn();
|
|
1545
|
+
});
|
|
1546
|
+
unsubscribes.clear();
|
|
1547
|
+
};
|
|
1548
|
+
syncStarted = true;
|
|
1549
|
+
const unsubscribeFromCollectionEvents = collection.on(
|
|
1550
|
+
`subscribers:change`,
|
|
1551
|
+
({ subscriberCount }) => {
|
|
1552
|
+
if (subscriberCount > 0) {
|
|
1553
|
+
subscribeToQueries();
|
|
1554
|
+
} else if (subscriberCount === 0) {
|
|
1555
|
+
unsubscribeFromQueries();
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
);
|
|
1559
|
+
if (syncMode === `eager`) {
|
|
1560
|
+
const initialResult = createQueryFromOpts({});
|
|
1561
|
+
if (initialResult instanceof Promise) {
|
|
1562
|
+
initialResult.catch(() => {
|
|
1563
|
+
});
|
|
1564
|
+
}
|
|
1565
|
+
} else {
|
|
1566
|
+
markReady();
|
|
1567
|
+
}
|
|
1568
|
+
subscribeToQueries();
|
|
1569
|
+
state.observers.forEach((observer, hashedQueryKey) => {
|
|
1570
|
+
const cachedQueryKey = hashToQueryKey.get(hashedQueryKey);
|
|
1571
|
+
const handleQueryResult = makeQueryResultHandler(cachedQueryKey);
|
|
1572
|
+
handleQueryResult(observer.getCurrentResult());
|
|
1573
|
+
});
|
|
1574
|
+
const cleanupQueryInternal = (hashedQueryKey) => {
|
|
1575
|
+
unsubscribes.get(hashedQueryKey)?.();
|
|
1576
|
+
unsubscribes.delete(hashedQueryKey);
|
|
1577
|
+
const rowKeys = queryToRows.get(hashedQueryKey) ?? /* @__PURE__ */ new Set();
|
|
1578
|
+
const rowsToDelete = [];
|
|
1579
|
+
rowKeys.forEach((rowKey) => {
|
|
1580
|
+
const queries = rowToQueries.get(rowKey);
|
|
1581
|
+
if (!queries) {
|
|
1582
|
+
return;
|
|
1583
|
+
}
|
|
1584
|
+
queries.delete(hashedQueryKey);
|
|
1585
|
+
if (queries.size === 0) {
|
|
1586
|
+
rowToQueries.delete(rowKey);
|
|
1587
|
+
if (collection.has(rowKey)) {
|
|
1588
|
+
rowsToDelete.push(collection.get(rowKey));
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
});
|
|
1592
|
+
if (rowsToDelete.length > 0) {
|
|
1593
|
+
begin();
|
|
1594
|
+
rowsToDelete.forEach((row) => {
|
|
1595
|
+
write({ type: `delete`, value: row });
|
|
1596
|
+
});
|
|
1597
|
+
commit();
|
|
1598
|
+
}
|
|
1599
|
+
state.observers.delete(hashedQueryKey);
|
|
1600
|
+
queryToRows.delete(hashedQueryKey);
|
|
1601
|
+
hashToQueryKey.delete(hashedQueryKey);
|
|
1602
|
+
queryRefCounts.delete(hashedQueryKey);
|
|
1603
|
+
};
|
|
1604
|
+
const cleanupQueryIfIdle = (hashedQueryKey) => {
|
|
1605
|
+
const refcount = queryRefCounts.get(hashedQueryKey) || 0;
|
|
1606
|
+
const observer = state.observers.get(hashedQueryKey);
|
|
1607
|
+
if (refcount <= 0) {
|
|
1608
|
+
unsubscribes.get(hashedQueryKey)?.();
|
|
1609
|
+
unsubscribes.delete(hashedQueryKey);
|
|
1610
|
+
}
|
|
1611
|
+
const hasListeners = observer?.hasListeners() ?? false;
|
|
1612
|
+
if (hasListeners) {
|
|
1613
|
+
queryRefCounts.set(hashedQueryKey, 0);
|
|
1614
|
+
return;
|
|
1615
|
+
}
|
|
1616
|
+
if (refcount > 0) {
|
|
1617
|
+
console.warn(
|
|
1618
|
+
`[cleanupQueryIfIdle] Invariant violation: refcount=${refcount} but no listeners. Cleaning up to prevent leak.`,
|
|
1619
|
+
{ hashedQueryKey }
|
|
1620
|
+
);
|
|
1621
|
+
}
|
|
1622
|
+
cleanupQueryInternal(hashedQueryKey);
|
|
1623
|
+
};
|
|
1624
|
+
const forceCleanupQuery = (hashedQueryKey) => {
|
|
1625
|
+
cleanupQueryInternal(hashedQueryKey);
|
|
1626
|
+
};
|
|
1627
|
+
const unsubscribeQueryCache = queryClient.getQueryCache().subscribe((event) => {
|
|
1628
|
+
const hashedKey = event.query.queryHash;
|
|
1629
|
+
if (event.type === `removed`) {
|
|
1630
|
+
if (hashToQueryKey.has(hashedKey)) {
|
|
1631
|
+
cleanupQueryIfIdle(hashedKey);
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
});
|
|
1635
|
+
const cleanup = async () => {
|
|
1636
|
+
unsubscribeFromCollectionEvents();
|
|
1637
|
+
unsubscribeFromQueries();
|
|
1638
|
+
const allQueryKeys = [...hashToQueryKey.values()];
|
|
1639
|
+
const allHashedKeys = [...state.observers.keys()];
|
|
1640
|
+
for (const hashedKey of allHashedKeys) {
|
|
1641
|
+
forceCleanupQuery(hashedKey);
|
|
1642
|
+
}
|
|
1643
|
+
unsubscribeQueryCache();
|
|
1644
|
+
await Promise.all(
|
|
1645
|
+
allQueryKeys.map(async (qKey) => {
|
|
1646
|
+
await queryClient.cancelQueries({ queryKey: qKey, exact: true });
|
|
1647
|
+
queryClient.removeQueries({ queryKey: qKey, exact: true });
|
|
1648
|
+
})
|
|
1649
|
+
);
|
|
1650
|
+
};
|
|
1651
|
+
const unloadSubset = (options) => {
|
|
1652
|
+
const key = generateQueryKeyFromOptions(options);
|
|
1653
|
+
const hashedQueryKey = hashKey(key);
|
|
1654
|
+
const currentCount = queryRefCounts.get(hashedQueryKey) || 0;
|
|
1655
|
+
const newCount = currentCount - 1;
|
|
1656
|
+
if (newCount <= 0) {
|
|
1657
|
+
queryRefCounts.set(hashedQueryKey, 0);
|
|
1658
|
+
cleanupQueryIfIdle(hashedQueryKey);
|
|
1659
|
+
} else {
|
|
1660
|
+
queryRefCounts.set(hashedQueryKey, newCount);
|
|
1661
|
+
}
|
|
1662
|
+
};
|
|
1663
|
+
const loadSubsetDedupe = syncMode === `eager` ? void 0 : createQueryFromOpts;
|
|
1664
|
+
return {
|
|
1665
|
+
loadSubset: loadSubsetDedupe,
|
|
1666
|
+
unloadSubset: syncMode === `eager` ? void 0 : unloadSubset,
|
|
1667
|
+
cleanup
|
|
1668
|
+
};
|
|
1669
|
+
};
|
|
1670
|
+
const refetch = async (opts) => {
|
|
1671
|
+
const allQueryKeys = [...hashToQueryKey.values()];
|
|
1672
|
+
const refetchPromises = allQueryKeys.map((qKey) => {
|
|
1673
|
+
const queryObserver = state.observers.get(hashKey(qKey));
|
|
1674
|
+
return queryObserver.refetch({
|
|
1675
|
+
throwOnError: opts?.throwOnError
|
|
1676
|
+
});
|
|
1677
|
+
});
|
|
1678
|
+
await Promise.all(refetchPromises);
|
|
1679
|
+
};
|
|
1680
|
+
const updateCacheData = (items) => {
|
|
1681
|
+
const key = typeof queryKey === `function` ? queryKey({}) : queryKey;
|
|
1682
|
+
if (select) {
|
|
1683
|
+
queryClient.setQueryData(key, (oldData) => {
|
|
1684
|
+
if (!oldData || typeof oldData !== `object`) {
|
|
1685
|
+
return oldData;
|
|
1686
|
+
}
|
|
1687
|
+
if (Array.isArray(oldData)) {
|
|
1688
|
+
return items;
|
|
1689
|
+
}
|
|
1690
|
+
const selectedArray = select(oldData);
|
|
1691
|
+
if (Array.isArray(selectedArray)) {
|
|
1692
|
+
for (const propKey of Object.keys(oldData)) {
|
|
1693
|
+
if (oldData[propKey] === selectedArray) {
|
|
1694
|
+
return { ...oldData, [propKey]: items };
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
if (Array.isArray(oldData.data)) {
|
|
1699
|
+
return { ...oldData, data: items };
|
|
1700
|
+
}
|
|
1701
|
+
if (Array.isArray(oldData.items)) {
|
|
1702
|
+
return { ...oldData, items };
|
|
1703
|
+
}
|
|
1704
|
+
if (Array.isArray(oldData.results)) {
|
|
1705
|
+
return { ...oldData, results: items };
|
|
1706
|
+
}
|
|
1707
|
+
for (const propKey of Object.keys(oldData)) {
|
|
1708
|
+
if (Array.isArray(oldData[propKey])) {
|
|
1709
|
+
return { ...oldData, [propKey]: items };
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
return oldData;
|
|
1713
|
+
});
|
|
1714
|
+
} else {
|
|
1715
|
+
queryClient.setQueryData(key, items);
|
|
1716
|
+
}
|
|
1717
|
+
};
|
|
1718
|
+
let writeContext = null;
|
|
1719
|
+
const enhancedInternalSync = (params) => {
|
|
1720
|
+
const { begin, write, commit, collection } = params;
|
|
1721
|
+
const contextQueryKey = typeof queryKey === `function` ? queryKey({}) : queryKey;
|
|
1722
|
+
writeContext = {
|
|
1723
|
+
collection,
|
|
1724
|
+
queryClient,
|
|
1725
|
+
queryKey: contextQueryKey,
|
|
1726
|
+
getKey,
|
|
1727
|
+
begin,
|
|
1728
|
+
write,
|
|
1729
|
+
commit,
|
|
1730
|
+
updateCacheData
|
|
1731
|
+
};
|
|
1732
|
+
return internalSync(params);
|
|
1733
|
+
};
|
|
1734
|
+
const writeUtils = createWriteUtils(
|
|
1735
|
+
() => writeContext
|
|
1736
|
+
);
|
|
1737
|
+
const wrappedOnInsert = onInsert ? async (params) => {
|
|
1738
|
+
const handlerResult = await onInsert(params) ?? {};
|
|
1739
|
+
const shouldRefetch = handlerResult.refetch !== false;
|
|
1740
|
+
if (shouldRefetch) {
|
|
1741
|
+
await refetch();
|
|
1742
|
+
}
|
|
1743
|
+
return handlerResult;
|
|
1744
|
+
} : void 0;
|
|
1745
|
+
const wrappedOnUpdate = onUpdate ? async (params) => {
|
|
1746
|
+
const handlerResult = await onUpdate(params) ?? {};
|
|
1747
|
+
const shouldRefetch = handlerResult.refetch !== false;
|
|
1748
|
+
if (shouldRefetch) {
|
|
1749
|
+
await refetch();
|
|
1750
|
+
}
|
|
1751
|
+
return handlerResult;
|
|
1752
|
+
} : void 0;
|
|
1753
|
+
const wrappedOnDelete = onDelete ? async (params) => {
|
|
1754
|
+
const handlerResult = await onDelete(params) ?? {};
|
|
1755
|
+
const shouldRefetch = handlerResult.refetch !== false;
|
|
1756
|
+
if (shouldRefetch) {
|
|
1757
|
+
await refetch();
|
|
1758
|
+
}
|
|
1759
|
+
return handlerResult;
|
|
1760
|
+
} : void 0;
|
|
1761
|
+
const utils = new QueryCollectionUtilsImpl(state, refetch, writeUtils);
|
|
1762
|
+
return {
|
|
1763
|
+
...baseCollectionConfig,
|
|
1764
|
+
getKey,
|
|
1765
|
+
syncMode,
|
|
1766
|
+
sync: { sync: enhancedInternalSync },
|
|
1767
|
+
onInsert: wrappedOnInsert,
|
|
1768
|
+
onUpdate: wrappedOnUpdate,
|
|
1769
|
+
onDelete: wrappedOnDelete,
|
|
1770
|
+
utils
|
|
1771
|
+
};
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
// node_modules/@tanstack/query-db-collection/dist/esm/index.js
|
|
1775
|
+
import { extractFieldPath, extractSimpleComparisons, extractValue, parseLoadSubsetOptions, parseOrderByExpression, parseWhereExpression, walkExpression } from "@tanstack/db";
|
|
1776
|
+
|
|
1
1777
|
// src/index.ts
|
|
2
1778
|
import { LoroDoc } from "loro-crdt";
|
|
3
1779
|
import { Features as Features2, RecordId } from "surrealdb";
|
|
@@ -9,101 +1785,48 @@ import {
|
|
|
9
1785
|
Features,
|
|
10
1786
|
Table
|
|
11
1787
|
} from "surrealdb";
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
const
|
|
22
|
-
const
|
|
23
|
-
for (const row of rows) cache.set(idKey(row.id), row);
|
|
24
|
-
};
|
|
25
|
-
const removeFromCache = (id) => {
|
|
26
|
-
cache.delete(idKey(id));
|
|
27
|
-
};
|
|
28
|
-
const listCached = () => Array.from(cache.values());
|
|
29
|
-
const buildWhere = () => {
|
|
1788
|
+
var normalizeFields = (raw) => {
|
|
1789
|
+
if (!raw || raw === "*") return ["*"];
|
|
1790
|
+
return raw;
|
|
1791
|
+
};
|
|
1792
|
+
var joinOrderBy = (o) => {
|
|
1793
|
+
if (!o) return void 0;
|
|
1794
|
+
return typeof o === "string" ? o : o.join(", ");
|
|
1795
|
+
};
|
|
1796
|
+
function manageTable(db, useLoro, { name, ...args }) {
|
|
1797
|
+
const fields = normalizeFields(args.fields);
|
|
1798
|
+
const baseWhere = () => {
|
|
30
1799
|
if (!useLoro) return args.where;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const applyPaging = (q, start, limit) => {
|
|
40
|
-
if (typeof start === "number" && q.start) q = q.start(start);
|
|
41
|
-
if (typeof limit === "number" && q.limit) q = q.limit(limit);
|
|
42
|
-
return q;
|
|
43
|
-
};
|
|
44
|
-
const fetchAll = async () => {
|
|
45
|
-
const rows = await buildQuery().fields(...fields);
|
|
46
|
-
upsertCache(rows);
|
|
47
|
-
fullyLoaded = true;
|
|
48
|
-
return rows;
|
|
49
|
-
};
|
|
50
|
-
const fetchPage = async (opts) => {
|
|
51
|
-
const q = applyPaging(
|
|
52
|
-
buildQuery(),
|
|
53
|
-
opts?.start ?? 0,
|
|
54
|
-
opts?.limit ?? pageSize
|
|
55
|
-
);
|
|
56
|
-
const rows = await q.fields(...fields);
|
|
57
|
-
upsertCache(rows);
|
|
58
|
-
if (rows.length < (opts?.limit ?? pageSize)) fullyLoaded = true;
|
|
59
|
-
return rows;
|
|
60
|
-
};
|
|
61
|
-
const fetchById = async (id) => {
|
|
62
|
-
const key = idKey(id);
|
|
63
|
-
const cached = cache.get(key);
|
|
64
|
-
if (cached) return cached;
|
|
65
|
-
const res = await db.select(id);
|
|
66
|
-
const row = Array.isArray(res) ? res[0] : res;
|
|
67
|
-
if (!row) return null;
|
|
68
|
-
if (useLoro && row.sync_deleted)
|
|
69
|
-
return null;
|
|
70
|
-
cache.set(key, row);
|
|
71
|
-
return row;
|
|
72
|
-
};
|
|
73
|
-
const loadMore = async (limit = pageSize) => {
|
|
74
|
-
if (fullyLoaded) return { rows: [], done: true };
|
|
75
|
-
const rows = await fetchPage({ start: cursor, limit });
|
|
76
|
-
cursor += rows.length;
|
|
77
|
-
const done = fullyLoaded || rows.length < limit;
|
|
78
|
-
args.onProgress?.({
|
|
1800
|
+
const alive = eq("sync_deleted", false);
|
|
1801
|
+
return args.where ? and(args.where, alive) : alive;
|
|
1802
|
+
};
|
|
1803
|
+
const listAll = async () => {
|
|
1804
|
+
const where = baseWhere();
|
|
1805
|
+
const whereSql = where ? " WHERE $where" : "";
|
|
1806
|
+
const sql = `SELECT ${fields.join(", ")} FROM type::table($table)${whereSql};`;
|
|
1807
|
+
const [res] = await db.query(sql, {
|
|
79
1808
|
table: name,
|
|
80
|
-
|
|
81
|
-
lastBatch: rows.length,
|
|
82
|
-
done
|
|
83
|
-
});
|
|
84
|
-
return { rows, done };
|
|
85
|
-
};
|
|
86
|
-
const startProgressive = () => {
|
|
87
|
-
if (progressiveTask || fullyLoaded) return;
|
|
88
|
-
progressiveTask = (async () => {
|
|
89
|
-
if (cache.size === 0) await loadMore(initialPageSize);
|
|
90
|
-
while (!fullyLoaded) {
|
|
91
|
-
const { done } = await loadMore(pageSize);
|
|
92
|
-
if (done) break;
|
|
93
|
-
}
|
|
94
|
-
})().finally(() => {
|
|
95
|
-
progressiveTask = null;
|
|
1809
|
+
where
|
|
96
1810
|
});
|
|
1811
|
+
return res ?? [];
|
|
97
1812
|
};
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
1813
|
+
const loadSubset = async (subset) => {
|
|
1814
|
+
const b = baseWhere();
|
|
1815
|
+
const w = subset?.where;
|
|
1816
|
+
const where = b && w ? and(b, w) : b ?? w;
|
|
1817
|
+
const whereSql = where ? " WHERE $where" : "";
|
|
1818
|
+
const order = joinOrderBy(subset?.orderBy);
|
|
1819
|
+
const orderSql = order ? ` ORDER BY ${order}` : "";
|
|
1820
|
+
const limitSql = typeof subset?.limit === "number" ? " LIMIT $limit" : "";
|
|
1821
|
+
const startSql = typeof subset?.offset === "number" ? " START $offset" : "";
|
|
1822
|
+
const sql = `SELECT ${fields.join(", ")} FROM type::table($table)${whereSql}${orderSql}${limitSql}${startSql};`;
|
|
1823
|
+
const [res] = await db.query(sql, {
|
|
1824
|
+
table: name,
|
|
1825
|
+
where,
|
|
1826
|
+
limit: subset?.limit,
|
|
1827
|
+
offset: subset?.offset
|
|
1828
|
+
});
|
|
1829
|
+
return res ?? [];
|
|
107
1830
|
};
|
|
108
1831
|
const create = async (data) => {
|
|
109
1832
|
await db.create(new Table(name)).content(data);
|
|
@@ -116,24 +1839,21 @@ function manageTable(db, useLoro, { name, ...args }, syncMode = "eager") {
|
|
|
116
1839
|
await db.update(id).merge({
|
|
117
1840
|
...data,
|
|
118
1841
|
sync_deleted: false,
|
|
119
|
-
updated_at:
|
|
1842
|
+
updated_at: Date.now()
|
|
120
1843
|
});
|
|
121
1844
|
};
|
|
122
1845
|
const remove = async (id) => {
|
|
123
1846
|
await db.delete(id);
|
|
124
|
-
removeFromCache(id);
|
|
125
1847
|
};
|
|
126
1848
|
const softDelete = async (id) => {
|
|
127
1849
|
if (!useLoro) {
|
|
128
1850
|
await db.delete(id);
|
|
129
|
-
removeFromCache(id);
|
|
130
1851
|
return;
|
|
131
1852
|
}
|
|
132
1853
|
await db.upsert(id).merge({
|
|
133
1854
|
sync_deleted: true,
|
|
134
|
-
updated_at:
|
|
1855
|
+
updated_at: Date.now()
|
|
135
1856
|
});
|
|
136
|
-
removeFromCache(id);
|
|
137
1857
|
};
|
|
138
1858
|
const subscribe = (cb) => {
|
|
139
1859
|
let killed = false;
|
|
@@ -141,25 +1861,10 @@ function manageTable(db, useLoro, { name, ...args }, syncMode = "eager") {
|
|
|
141
1861
|
const on = (msg) => {
|
|
142
1862
|
const { action, value } = msg;
|
|
143
1863
|
if (action === "KILLED") return;
|
|
144
|
-
if (action === "CREATE") {
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
return;
|
|
148
|
-
}
|
|
149
|
-
if (action === "UPDATE") {
|
|
150
|
-
if (useLoro && value.sync_deleted) {
|
|
151
|
-
removeFromCache(value.id);
|
|
152
|
-
cb({ type: "delete", row: { id: value.id } });
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
155
|
-
upsertCache([value]);
|
|
156
|
-
cb({ type: "update", row: value });
|
|
157
|
-
return;
|
|
158
|
-
}
|
|
159
|
-
if (action === "DELETE") {
|
|
160
|
-
removeFromCache(value.id);
|
|
1864
|
+
if (action === "CREATE") cb({ type: "insert", row: value });
|
|
1865
|
+
else if (action === "UPDATE") cb({ type: "update", row: value });
|
|
1866
|
+
else if (action === "DELETE")
|
|
161
1867
|
cb({ type: "delete", row: { id: value.id } });
|
|
162
|
-
}
|
|
163
1868
|
};
|
|
164
1869
|
const start = async () => {
|
|
165
1870
|
if (!db.isFeatureSupported(Features.LiveQueries)) return;
|
|
@@ -175,380 +1880,166 @@ function manageTable(db, useLoro, { name, ...args }, syncMode = "eager") {
|
|
|
175
1880
|
};
|
|
176
1881
|
return {
|
|
177
1882
|
listAll,
|
|
178
|
-
|
|
179
|
-
listCached,
|
|
180
|
-
fetchPage,
|
|
181
|
-
fetchById,
|
|
182
|
-
loadMore,
|
|
1883
|
+
loadSubset,
|
|
183
1884
|
create,
|
|
184
1885
|
update,
|
|
185
1886
|
remove,
|
|
186
1887
|
softDelete,
|
|
187
|
-
subscribe
|
|
188
|
-
get isFullyLoaded() {
|
|
189
|
-
return fullyLoaded;
|
|
190
|
-
},
|
|
191
|
-
get cachedCount() {
|
|
192
|
-
return cache.size;
|
|
193
|
-
}
|
|
1888
|
+
subscribe
|
|
194
1889
|
};
|
|
195
1890
|
}
|
|
196
1891
|
|
|
197
1892
|
// src/index.ts
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
if (typeof
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
return JSON.stringify(toJson(value));
|
|
217
|
-
};
|
|
218
|
-
var chunk = (arr, size) => {
|
|
219
|
-
const out = [];
|
|
220
|
-
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
|
|
221
|
-
return out;
|
|
222
|
-
};
|
|
1893
|
+
function toCleanup(res) {
|
|
1894
|
+
if (!res) return () => {
|
|
1895
|
+
};
|
|
1896
|
+
if (typeof res === "function") {
|
|
1897
|
+
return res;
|
|
1898
|
+
}
|
|
1899
|
+
if (typeof res === "object" && res !== null) {
|
|
1900
|
+
const r = res;
|
|
1901
|
+
const cleanup = r["cleanup"];
|
|
1902
|
+
if (typeof cleanup === "function") return cleanup;
|
|
1903
|
+
const unsubscribe = r["unsubscribe"];
|
|
1904
|
+
if (typeof unsubscribe === "function") return unsubscribe;
|
|
1905
|
+
const dispose = r["dispose"];
|
|
1906
|
+
if (typeof dispose === "function") return dispose;
|
|
1907
|
+
}
|
|
1908
|
+
return () => {
|
|
1909
|
+
};
|
|
1910
|
+
}
|
|
223
1911
|
function surrealCollectionOptions({
|
|
224
1912
|
id,
|
|
225
1913
|
useLoro = false,
|
|
226
1914
|
onError,
|
|
227
1915
|
db,
|
|
228
|
-
|
|
1916
|
+
queryClient,
|
|
1917
|
+
queryKey,
|
|
1918
|
+
syncMode = "eager",
|
|
229
1919
|
...config
|
|
230
1920
|
}) {
|
|
231
1921
|
let loro;
|
|
232
1922
|
if (useLoro) loro = { doc: new LoroDoc(), key: id };
|
|
1923
|
+
const table = manageTable(db, useLoro, config.table);
|
|
233
1924
|
const keyOf = (rid) => typeof rid === "string" ? rid : rid.toString();
|
|
234
1925
|
const getKey = (row) => keyOf(row.id);
|
|
235
1926
|
const loroKey = loro?.key ?? id ?? "surreal";
|
|
236
1927
|
const loroMap = useLoro ? loro?.doc?.getMap?.(loroKey) ?? null : null;
|
|
237
|
-
const
|
|
238
|
-
if (!loroMap) return
|
|
239
|
-
|
|
240
|
-
return Object.values(json);
|
|
241
|
-
};
|
|
242
|
-
const loroPutMany = (rows) => {
|
|
243
|
-
if (!loroMap || rows.length === 0) return;
|
|
244
|
-
for (const row of rows) loroMap.set(getKey(row), row);
|
|
1928
|
+
const loroPut = (row) => {
|
|
1929
|
+
if (!loroMap) return;
|
|
1930
|
+
loroMap.set(getKey(row), row);
|
|
245
1931
|
loro?.doc?.commit?.();
|
|
246
1932
|
};
|
|
247
|
-
const
|
|
248
|
-
if (!loroMap
|
|
249
|
-
|
|
1933
|
+
const loroRemove = (idStr) => {
|
|
1934
|
+
if (!loroMap) return;
|
|
1935
|
+
loroMap.delete(idStr);
|
|
250
1936
|
loro?.doc?.commit?.();
|
|
251
1937
|
};
|
|
252
|
-
const
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
const flushPushQueue = async () => {
|
|
259
|
-
if (!useLoro) return;
|
|
260
|
-
const ops = pushQueue.splice(0, pushQueue.length);
|
|
261
|
-
for (const op of ops) {
|
|
262
|
-
if (op.kind === "create") {
|
|
263
|
-
await table.create(op.row);
|
|
264
|
-
} else if (op.kind === "update") {
|
|
265
|
-
const rid = new RecordId(
|
|
266
|
-
config.table.name,
|
|
267
|
-
op.row.id.toString()
|
|
268
|
-
);
|
|
269
|
-
await table.update(rid, op.row);
|
|
270
|
-
} else {
|
|
271
|
-
const rid = new RecordId(config.table.name, op.id);
|
|
272
|
-
await table.softDelete(rid);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
};
|
|
276
|
-
const newer = (a, b) => (a?.getTime() ?? -1) > (b?.getTime() ?? -1);
|
|
277
|
-
const fetchServerByLocalIds = async (ids) => {
|
|
278
|
-
if (ids.length === 0) return [];
|
|
279
|
-
const tableName = config.table.name;
|
|
280
|
-
const parts = chunk(ids, LOCAL_ID_VERIFY_CHUNK);
|
|
1938
|
+
const mergeLocalOverServer = (serverRows) => {
|
|
1939
|
+
if (!useLoro || !loroMap) return serverRows;
|
|
1940
|
+
const localJson = loroMap.toJSON?.() ?? {};
|
|
1941
|
+
const localById = new Map(
|
|
1942
|
+
Object.values(localJson).map((r) => [getKey(r), r])
|
|
1943
|
+
);
|
|
281
1944
|
const out = [];
|
|
282
|
-
for (const
|
|
283
|
-
const
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
}
|
|
289
|
-
);
|
|
290
|
-
if (res) out.push(...res);
|
|
291
|
-
}
|
|
292
|
-
return out;
|
|
293
|
-
};
|
|
294
|
-
const dedupeById = (rows) => {
|
|
295
|
-
const m = /* @__PURE__ */ new Map();
|
|
296
|
-
for (const r of rows) m.set(getKey(r), r);
|
|
297
|
-
return Array.from(m.values());
|
|
298
|
-
};
|
|
299
|
-
let prevById = /* @__PURE__ */ new Map();
|
|
300
|
-
const buildMap = (rows) => new Map(rows.map((r) => [getKey(r), r]));
|
|
301
|
-
const same = (a, b) => {
|
|
302
|
-
if (useLoro) {
|
|
303
|
-
return (a.sync_deleted ?? false) === (b.sync_deleted ?? false) && (a.updated_at?.getTime() ?? 0) === (b.updated_at?.getTime() ?? 0);
|
|
304
|
-
}
|
|
305
|
-
return stableStringify(a) === stableStringify(b);
|
|
306
|
-
};
|
|
307
|
-
const diffAndEmit = (currentRows, write) => {
|
|
308
|
-
const currById = buildMap(currentRows);
|
|
309
|
-
for (const [id2, row] of currById) {
|
|
310
|
-
const prev = prevById.get(id2);
|
|
311
|
-
if (!prev) write({ type: "insert", value: row });
|
|
312
|
-
else if (!same(prev, row)) write({ type: "update", value: row });
|
|
313
|
-
}
|
|
314
|
-
for (const [id2, prev] of prevById) {
|
|
315
|
-
if (!currById.has(id2)) write({ type: "delete", value: prev });
|
|
316
|
-
}
|
|
317
|
-
prevById = currById;
|
|
318
|
-
};
|
|
319
|
-
const reconcileBoot = (serverRows, write) => {
|
|
320
|
-
const localRows = loroToArray();
|
|
321
|
-
const serverById = new Map(serverRows.map((r) => [getKey(r), r]));
|
|
322
|
-
const localById = new Map(localRows.map((r) => [getKey(r), r]));
|
|
323
|
-
const ids = /* @__PURE__ */ new Set([...serverById.keys(), ...localById.keys()]);
|
|
324
|
-
const current = [];
|
|
325
|
-
const toRemove = [];
|
|
326
|
-
const toPut = [];
|
|
327
|
-
const applyLocal = (row) => {
|
|
328
|
-
if (!row) return;
|
|
329
|
-
if (row.sync_deleted) toRemove.push(getKey(row));
|
|
330
|
-
else toPut.push(row);
|
|
331
|
-
};
|
|
332
|
-
for (const id2 of ids) {
|
|
333
|
-
const s = serverById.get(id2);
|
|
334
|
-
const l = localById.get(id2);
|
|
335
|
-
if (s && l) {
|
|
336
|
-
const sDeleted = s.sync_deleted ?? false;
|
|
337
|
-
const lDeleted = l.sync_deleted ?? false;
|
|
338
|
-
const sUpdated = s.updated_at;
|
|
339
|
-
const lUpdated = l.updated_at;
|
|
340
|
-
if (sDeleted && lDeleted) {
|
|
341
|
-
applyLocal(s);
|
|
342
|
-
current.push(s);
|
|
343
|
-
} else if (sDeleted && !lDeleted) {
|
|
344
|
-
applyLocal(s);
|
|
345
|
-
current.push(s);
|
|
346
|
-
} else if (!sDeleted && lDeleted) {
|
|
347
|
-
if (newer(lUpdated, sUpdated)) {
|
|
348
|
-
enqueuePush({
|
|
349
|
-
kind: "delete",
|
|
350
|
-
id: id2,
|
|
351
|
-
updated_at: lUpdated ?? /* @__PURE__ */ new Date()
|
|
352
|
-
});
|
|
353
|
-
applyLocal(l);
|
|
354
|
-
current.push(l);
|
|
355
|
-
} else {
|
|
356
|
-
applyLocal(s);
|
|
357
|
-
current.push(s);
|
|
358
|
-
}
|
|
359
|
-
} else {
|
|
360
|
-
if (newer(lUpdated, sUpdated)) {
|
|
361
|
-
enqueuePush({ kind: "update", row: l });
|
|
362
|
-
applyLocal(l);
|
|
363
|
-
current.push(l);
|
|
364
|
-
} else {
|
|
365
|
-
applyLocal(s);
|
|
366
|
-
current.push(s);
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
} else if (s && !l) {
|
|
370
|
-
applyLocal(s);
|
|
371
|
-
current.push(s);
|
|
372
|
-
} else if (!s && l) {
|
|
373
|
-
const lDeleted = l.sync_deleted ?? false;
|
|
374
|
-
const lUpdated = l.updated_at;
|
|
375
|
-
if (lDeleted) {
|
|
376
|
-
enqueuePush({
|
|
377
|
-
kind: "delete",
|
|
378
|
-
id: id2,
|
|
379
|
-
updated_at: lUpdated ?? /* @__PURE__ */ new Date()
|
|
380
|
-
});
|
|
381
|
-
applyLocal(l);
|
|
382
|
-
current.push(l);
|
|
383
|
-
} else {
|
|
384
|
-
enqueuePush({ kind: "create", row: l });
|
|
385
|
-
applyLocal(l);
|
|
386
|
-
current.push(l);
|
|
387
|
-
}
|
|
1945
|
+
for (const s of serverRows) {
|
|
1946
|
+
const idStr = getKey(s);
|
|
1947
|
+
const l = localById.get(idStr);
|
|
1948
|
+
if (!l) {
|
|
1949
|
+
out.push(s);
|
|
1950
|
+
continue;
|
|
388
1951
|
}
|
|
1952
|
+
const lDeleted = (l.sync_deleted ?? false) === true;
|
|
1953
|
+
if (lDeleted) continue;
|
|
1954
|
+
out.push(l);
|
|
389
1955
|
}
|
|
390
|
-
|
|
391
|
-
loroPutMany(toPut);
|
|
392
|
-
diffAndEmit(current, write);
|
|
1956
|
+
return out;
|
|
393
1957
|
};
|
|
394
|
-
const
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
markReady
|
|
401
|
-
}) => {
|
|
402
|
-
if (!db.isFeatureSupported(Features2.LiveQueries)) {
|
|
403
|
-
markReady();
|
|
404
|
-
return () => {
|
|
405
|
-
};
|
|
406
|
-
}
|
|
407
|
-
let offLive = null;
|
|
408
|
-
let work = Promise.resolve();
|
|
409
|
-
const enqueueWork = (fn) => {
|
|
410
|
-
work = work.then(fn).catch((e) => onError?.(e));
|
|
411
|
-
return work;
|
|
412
|
-
};
|
|
413
|
-
const makeTombstone = (id2) => ({
|
|
414
|
-
id: new RecordId(config.table.name, id2).toString(),
|
|
415
|
-
updated_at: now(),
|
|
416
|
-
sync_deleted: true
|
|
417
|
-
});
|
|
418
|
-
const start = async () => {
|
|
1958
|
+
const base = queryCollectionOptions({
|
|
1959
|
+
getKey: (row) => getKey(row),
|
|
1960
|
+
queryKey,
|
|
1961
|
+
queryClient,
|
|
1962
|
+
syncMode,
|
|
1963
|
+
queryFn: async ({ meta }) => {
|
|
419
1964
|
try {
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
} else if (syncMode === "progressive") {
|
|
424
|
-
const first = await table.loadMore(
|
|
425
|
-
config.table.initialPageSize ?? DEFAULT_INITIAL_PAGE_SIZE
|
|
426
|
-
);
|
|
427
|
-
serverRows = first.rows;
|
|
428
|
-
} else {
|
|
429
|
-
serverRows = await table.listActive();
|
|
430
|
-
}
|
|
431
|
-
await enqueueWork(async () => {
|
|
432
|
-
begin();
|
|
433
|
-
if (useLoro) {
|
|
434
|
-
const localIds = loroToArray().map(getKey);
|
|
435
|
-
const verifiedServerRows = syncMode === "eager" ? serverRows : dedupeById([
|
|
436
|
-
...serverRows,
|
|
437
|
-
...await fetchServerByLocalIds(
|
|
438
|
-
localIds
|
|
439
|
-
)
|
|
440
|
-
]);
|
|
441
|
-
reconcileBoot(verifiedServerRows, write);
|
|
442
|
-
} else {
|
|
443
|
-
diffAndEmit(serverRows, write);
|
|
444
|
-
}
|
|
445
|
-
commit();
|
|
446
|
-
markReady();
|
|
447
|
-
});
|
|
448
|
-
if (syncMode === "progressive") {
|
|
449
|
-
void (async () => {
|
|
450
|
-
while (!table.isFullyLoaded) {
|
|
451
|
-
const { rows } = await table.loadMore();
|
|
452
|
-
if (rows.length === 0) break;
|
|
453
|
-
await enqueueWork(async () => {
|
|
454
|
-
begin();
|
|
455
|
-
try {
|
|
456
|
-
if (useLoro) loroPutMany(rows);
|
|
457
|
-
diffAndEmit(rows, write);
|
|
458
|
-
} finally {
|
|
459
|
-
commit();
|
|
460
|
-
}
|
|
461
|
-
});
|
|
462
|
-
}
|
|
463
|
-
})().catch((e) => onError?.(e));
|
|
464
|
-
}
|
|
465
|
-
await flushPushQueue();
|
|
466
|
-
offLive = table.subscribe((evt) => {
|
|
467
|
-
void enqueueWork(async () => {
|
|
468
|
-
begin();
|
|
469
|
-
try {
|
|
470
|
-
if (evt.type === "insert" || evt.type === "update") {
|
|
471
|
-
const row = evt.row;
|
|
472
|
-
const deleted = useLoro ? row.sync_deleted ?? false : false;
|
|
473
|
-
if (deleted) {
|
|
474
|
-
if (useLoro) loroRemove(getKey(row));
|
|
475
|
-
const prev = prevById.get(getKey(row)) ?? makeTombstone(getKey(row));
|
|
476
|
-
write({ type: "delete", value: prev });
|
|
477
|
-
prevById.delete(getKey(row));
|
|
478
|
-
} else {
|
|
479
|
-
if (useLoro) loroPutMany([row]);
|
|
480
|
-
const had = prevById.has(getKey(row));
|
|
481
|
-
write({
|
|
482
|
-
type: had ? "update" : "insert",
|
|
483
|
-
value: row
|
|
484
|
-
});
|
|
485
|
-
prevById.set(getKey(row), row);
|
|
486
|
-
}
|
|
487
|
-
} else {
|
|
488
|
-
const rid = getKey(evt.row);
|
|
489
|
-
if (useLoro) loroRemove(rid);
|
|
490
|
-
const prev = prevById.get(rid) ?? makeTombstone(rid);
|
|
491
|
-
write({ type: "delete", value: prev });
|
|
492
|
-
prevById.delete(rid);
|
|
493
|
-
}
|
|
494
|
-
} finally {
|
|
495
|
-
commit();
|
|
496
|
-
}
|
|
497
|
-
});
|
|
498
|
-
});
|
|
1965
|
+
const subset = syncMode === "on-demand" ? meta["surrealSubset"] : void 0;
|
|
1966
|
+
const rows = syncMode === "eager" ? await table.listAll() : await table.loadSubset(subset);
|
|
1967
|
+
return mergeLocalOverServer(rows);
|
|
499
1968
|
} catch (e) {
|
|
500
1969
|
onError?.(e);
|
|
501
|
-
|
|
1970
|
+
return [];
|
|
502
1971
|
}
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
const
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
1972
|
+
},
|
|
1973
|
+
onInsert: (async (p) => {
|
|
1974
|
+
const now = () => /* @__PURE__ */ new Date();
|
|
1975
|
+
const resultRows = [];
|
|
1976
|
+
for (const m of p.transaction.mutations) {
|
|
1977
|
+
if (m.type !== "insert") continue;
|
|
1978
|
+
const baseRow = { ...m.modified };
|
|
1979
|
+
const row = useLoro ? {
|
|
1980
|
+
...baseRow,
|
|
1981
|
+
updated_at: now(),
|
|
1982
|
+
sync_deleted: false
|
|
1983
|
+
} : baseRow;
|
|
1984
|
+
if (useLoro) loroPut(row);
|
|
1985
|
+
await table.create(row);
|
|
1986
|
+
resultRows.push(row);
|
|
1987
|
+
}
|
|
1988
|
+
return resultRows;
|
|
1989
|
+
}),
|
|
1990
|
+
onUpdate: (async (p) => {
|
|
1991
|
+
const now = () => /* @__PURE__ */ new Date();
|
|
1992
|
+
const resultRows = [];
|
|
1993
|
+
for (const m of p.transaction.mutations) {
|
|
1994
|
+
if (m.type !== "update") continue;
|
|
1995
|
+
const idKey = m.key;
|
|
1996
|
+
const baseRow = { ...m.modified, id: idKey };
|
|
1997
|
+
const row = useLoro ? { ...baseRow, updated_at: now() } : baseRow;
|
|
1998
|
+
if (useLoro) loroPut(row);
|
|
1999
|
+
await table.update(
|
|
2000
|
+
new RecordId(config.table.name, keyOf(idKey)),
|
|
2001
|
+
row
|
|
2002
|
+
);
|
|
2003
|
+
resultRows.push(row);
|
|
2004
|
+
}
|
|
2005
|
+
return resultRows;
|
|
2006
|
+
}),
|
|
2007
|
+
onDelete: (async (p) => {
|
|
2008
|
+
for (const m of p.transaction.mutations) {
|
|
2009
|
+
if (m.type !== "delete") continue;
|
|
2010
|
+
const idKey = m.key;
|
|
2011
|
+
if (useLoro) loroRemove(keyOf(idKey));
|
|
2012
|
+
await table.softDelete(
|
|
2013
|
+
new RecordId(config.table.name, keyOf(idKey))
|
|
2014
|
+
);
|
|
2015
|
+
}
|
|
2016
|
+
return [];
|
|
2017
|
+
})
|
|
2018
|
+
});
|
|
2019
|
+
const baseSync = base.sync?.sync;
|
|
2020
|
+
const sync = baseSync ? {
|
|
2021
|
+
sync: (ctx) => {
|
|
2022
|
+
const offBase = baseSync(ctx);
|
|
2023
|
+
if (!db.isFeatureSupported(Features2.LiveQueries))
|
|
2024
|
+
return offBase;
|
|
2025
|
+
const offLive = table.subscribe((evt) => {
|
|
2026
|
+
if (useLoro) {
|
|
2027
|
+
if (evt.type === "delete")
|
|
2028
|
+
loroRemove(getKey(evt.row));
|
|
2029
|
+
else loroPut(evt.row);
|
|
2030
|
+
}
|
|
2031
|
+
void queryClient.invalidateQueries({ queryKey, exact: false }).catch((e) => onError?.(e));
|
|
2032
|
+
});
|
|
2033
|
+
const baseCleanup = toCleanup(baseSync(ctx));
|
|
2034
|
+
return () => {
|
|
2035
|
+
offLive();
|
|
2036
|
+
baseCleanup();
|
|
2037
|
+
};
|
|
2038
|
+
}
|
|
2039
|
+
} : void 0;
|
|
545
2040
|
return {
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
sync: { sync },
|
|
549
|
-
onInsert,
|
|
550
|
-
onDelete,
|
|
551
|
-
onUpdate
|
|
2041
|
+
...base,
|
|
2042
|
+
sync: sync ?? base.sync
|
|
552
2043
|
};
|
|
553
2044
|
}
|
|
554
2045
|
export {
|