@zveltio/sdk 2.0.8 → 3.0.0-beta.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -4
- package/dist/build/index.d.ts +77 -0
- package/dist/build/index.d.ts.map +1 -0
- package/dist/build/index.js +157 -0
- package/dist/client.d.ts +103 -7
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +129 -28
- package/dist/core.d.ts.map +1 -1
- package/dist/core.js +21 -3
- package/dist/crdt.d.ts.map +1 -1
- package/dist/crdt.js +11 -2
- package/dist/ddl/index.d.ts +173 -0
- package/dist/ddl/index.d.ts.map +1 -0
- package/dist/ddl/index.js +33 -0
- package/dist/errors.d.ts +58 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +124 -0
- package/dist/extension/action-refusal.d.ts +27 -0
- package/dist/extension/action-refusal.d.ts.map +1 -0
- package/dist/extension/action-refusal.js +29 -0
- package/dist/extension/capabilities.d.ts +71 -0
- package/dist/extension/capabilities.d.ts.map +1 -0
- package/dist/extension/capabilities.js +79 -0
- package/dist/extension/dates.d.ts +7 -0
- package/dist/extension/dates.d.ts.map +1 -0
- package/dist/extension/dates.js +14 -0
- package/dist/extension/index.d.ts +1570 -10
- package/dist/extension/index.d.ts.map +1 -1
- package/dist/extension/index.js +17 -1
- package/dist/extension/jsonb.d.ts +62 -0
- package/dist/extension/jsonb.d.ts.map +1 -0
- package/dist/extension/jsonb.js +64 -0
- package/dist/extension/multipart.d.ts +58 -0
- package/dist/extension/multipart.d.ts.map +1 -0
- package/dist/extension/multipart.js +61 -0
- package/dist/extension/numeric.d.ts +94 -0
- package/dist/extension/numeric.d.ts.map +1 -0
- package/dist/extension/numeric.js +162 -0
- package/dist/extension/permission-gate.d.ts +52 -0
- package/dist/extension/permission-gate.d.ts.map +1 -0
- package/dist/extension/permission-gate.js +125 -0
- package/dist/extension/reserved-paths.d.ts +10 -0
- package/dist/extension/reserved-paths.d.ts.map +1 -0
- package/dist/extension/reserved-paths.js +23 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/local-store.d.ts +14 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-store.js +93 -16
- package/dist/offline/index.d.ts +75 -0
- package/dist/offline/index.d.ts.map +1 -0
- package/dist/offline/index.js +251 -0
- package/dist/publish/index.d.ts +94 -0
- package/dist/publish/index.d.ts.map +1 -0
- package/dist/publish/index.js +153 -0
- package/dist/realtime.d.ts +25 -1
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +53 -5
- package/dist/rpc/index.d.ts +68 -0
- package/dist/rpc/index.d.ts.map +1 -0
- package/dist/rpc/index.js +63 -0
- package/dist/schema-codegen.d.ts +84 -0
- package/dist/schema-codegen.d.ts.map +1 -0
- package/dist/schema-codegen.js +503 -0
- package/dist/schema-watcher.d.ts +10 -2
- package/dist/schema-watcher.d.ts.map +1 -1
- package/dist/schema-watcher.js +26 -13
- package/dist/studio/index.d.ts +85 -0
- package/dist/studio/index.d.ts.map +1 -0
- package/dist/studio/index.js +183 -0
- package/dist/studio/slot-owner-registry.d.ts +13 -0
- package/dist/studio/slot-owner-registry.d.ts.map +1 -0
- package/dist/studio/slot-owner-registry.js +21 -0
- package/dist/svelte.d.ts +1 -1
- package/dist/svelte.d.ts.map +1 -1
- package/dist/svelte.js +4 -2
- package/dist/sync-manager.d.ts +49 -4
- package/dist/sync-manager.d.ts.map +1 -1
- package/dist/sync-manager.js +175 -24
- package/dist/testing/index.d.ts +121 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +305 -0
- package/dist/testing/with-test-db.d.ts +119 -0
- package/dist/testing/with-test-db.d.ts.map +1 -0
- package/dist/testing/with-test-db.js +320 -0
- package/dist/tests/action-refusal.test.d.ts +2 -0
- package/dist/tests/action-refusal.test.d.ts.map +1 -0
- package/dist/tests/action-refusal.test.js +13 -0
- package/dist/tests/client.test.d.ts +2 -0
- package/dist/tests/client.test.d.ts.map +1 -0
- package/dist/tests/client.test.js +164 -0
- package/dist/tests/crdt-orset.test.d.ts +2 -0
- package/dist/tests/crdt-orset.test.d.ts.map +1 -0
- package/dist/tests/crdt-orset.test.js +23 -0
- package/dist/tests/local-store.test.js +44 -0
- package/dist/tests/migration-parse.test.d.ts +2 -0
- package/dist/tests/migration-parse.test.d.ts.map +1 -0
- package/dist/tests/migration-parse.test.js +17 -0
- package/dist/tests/multipart.test.d.ts +2 -0
- package/dist/tests/multipart.test.d.ts.map +1 -0
- package/dist/tests/multipart.test.js +37 -0
- package/dist/tests/offline-provider-crdt.test.d.ts +2 -0
- package/dist/tests/offline-provider-crdt.test.d.ts.map +1 -0
- package/dist/tests/offline-provider-crdt.test.js +206 -0
- package/dist/tests/realtime.test.d.ts +2 -0
- package/dist/tests/realtime.test.d.ts.map +1 -0
- package/dist/tests/realtime.test.js +220 -0
- package/dist/tests/reserved-paths.test.d.ts +2 -0
- package/dist/tests/reserved-paths.test.d.ts.map +1 -0
- package/dist/tests/reserved-paths.test.js +21 -0
- package/dist/tests/sync-manager.test.d.ts +2 -0
- package/dist/tests/sync-manager.test.d.ts.map +1 -0
- package/dist/tests/sync-manager.test.js +123 -0
- package/dist/tests/today-in.test.d.ts +2 -0
- package/dist/tests/today-in.test.d.ts.map +1 -0
- package/dist/tests/today-in.test.js +14 -0
- package/dist/tests/validate-manifest-actions.test.d.ts +2 -0
- package/dist/tests/validate-manifest-actions.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-actions.test.js +82 -0
- package/dist/tests/validate-manifest-dependencies.test.d.ts +2 -0
- package/dist/tests/validate-manifest-dependencies.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-dependencies.test.js +27 -0
- package/dist/tests/validate-manifest-forward-credentials.test.d.ts +2 -0
- package/dist/tests/validate-manifest-forward-credentials.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-forward-credentials.test.js +35 -0
- package/dist/tests/validate-sdui-data-endpoints.test.d.ts +2 -0
- package/dist/tests/validate-sdui-data-endpoints.test.d.ts.map +1 -0
- package/dist/tests/validate-sdui-data-endpoints.test.js +41 -0
- package/dist/tests/with-test-db.test.d.ts +2 -0
- package/dist/tests/with-test-db.test.d.ts.map +1 -0
- package/dist/tests/with-test-db.test.js +57 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +3 -1
- package/dist/validate/index.d.ts +148 -0
- package/dist/validate/index.d.ts.map +1 -0
- package/dist/validate/index.js +887 -0
- package/dist/validate/migration-parse.d.ts +22 -0
- package/dist/validate/migration-parse.d.ts.map +1 -0
- package/dist/validate/migration-parse.js +11 -0
- package/dist/validate/shared-message-keys.d.ts +16 -0
- package/dist/validate/shared-message-keys.d.ts.map +1 -0
- package/dist/validate/shared-message-keys.js +227 -0
- package/package.json +56 -4
- package/dist/client/Auth.d.ts +0 -19
- package/dist/client/Auth.d.ts.map +0 -1
- package/dist/client/Auth.js +0 -45
- package/dist/client/QueryBuilder.d.ts +0 -17
- package/dist/client/QueryBuilder.d.ts.map +0 -1
- package/dist/client/QueryBuilder.js +0 -76
- package/dist/client/RealtimeClient.d.ts +0 -22
- package/dist/client/RealtimeClient.d.ts.map +0 -1
- package/dist/client/RealtimeClient.js +0 -96
- package/dist/client/ZveltioClient.d.ts +0 -20
- package/dist/client/ZveltioClient.d.ts.map +0 -1
- package/dist/client/ZveltioClient.js +0 -78
package/dist/sync-manager.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { LocalStore } from './local-store.js';
|
|
2
2
|
import { mergeLWW, fromDocument } from './crdt.js';
|
|
3
3
|
import { generateUUID } from './utils.js';
|
|
4
|
+
import { ZveltioApiError } from './errors.js';
|
|
5
|
+
/** Local-store meta key holding `/api/sync/pull` positions, per table. */
|
|
6
|
+
const PULL_CURSORS = 'sync_pull_cursors';
|
|
4
7
|
export class SyncManager {
|
|
5
8
|
store;
|
|
6
9
|
client;
|
|
@@ -9,6 +12,16 @@ export class SyncManager {
|
|
|
9
12
|
syncTimer = null;
|
|
10
13
|
isOnline = true;
|
|
11
14
|
isSyncing = false;
|
|
15
|
+
/** Set by `stop()`; `start()` checks it after every await it makes. */
|
|
16
|
+
stopped = false;
|
|
17
|
+
onOnline = () => {
|
|
18
|
+
this.isOnline = true;
|
|
19
|
+
this.syncNow(); // Sync immediately on reconnect
|
|
20
|
+
};
|
|
21
|
+
onOffline = () => {
|
|
22
|
+
this.isOnline = false;
|
|
23
|
+
};
|
|
24
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
12
25
|
listeners = new Map();
|
|
13
26
|
constructor(client, config = {}) {
|
|
14
27
|
this.store = new LocalStore();
|
|
@@ -22,21 +35,24 @@ export class SyncManager {
|
|
|
22
35
|
};
|
|
23
36
|
}
|
|
24
37
|
async start(realtimeUrl) {
|
|
38
|
+
this.stopped = false;
|
|
25
39
|
await this.store.open();
|
|
40
|
+
// A caller that unmounts before `start()` settles calls `stop()` first — a
|
|
41
|
+
// React effect cleanup, and StrictMode runs one on every mount in
|
|
42
|
+
// development. Arming the timer and socket after that leaked both forever.
|
|
43
|
+
if (this.stopped)
|
|
44
|
+
return this.store.close();
|
|
26
45
|
// Online/offline detection
|
|
27
46
|
if (typeof window !== 'undefined') {
|
|
28
|
-
window.addEventListener('online',
|
|
29
|
-
|
|
30
|
-
this.syncNow(); // Sync immediately on reconnect
|
|
31
|
-
});
|
|
32
|
-
window.addEventListener('offline', () => {
|
|
33
|
-
this.isOnline = false;
|
|
34
|
-
});
|
|
47
|
+
window.addEventListener('online', this.onOnline);
|
|
48
|
+
window.addEventListener('offline', this.onOffline);
|
|
35
49
|
this.isOnline = navigator.onLine;
|
|
36
50
|
}
|
|
37
51
|
// Realtime: receives push updates from server
|
|
38
52
|
if (realtimeUrl) {
|
|
39
53
|
const { ZveltioRealtime } = await import('./realtime.js');
|
|
54
|
+
if (this.stopped)
|
|
55
|
+
return;
|
|
40
56
|
this.realtime = new ZveltioRealtime(realtimeUrl);
|
|
41
57
|
this.realtime.connect();
|
|
42
58
|
// Subscriptions are per-collection via collection()
|
|
@@ -75,6 +91,7 @@ export class SyncManager {
|
|
|
75
91
|
};
|
|
76
92
|
},
|
|
77
93
|
/** Create — writes LOCAL + queues sync */
|
|
94
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
78
95
|
create: async (data) => {
|
|
79
96
|
const id = data.id || generateUUID();
|
|
80
97
|
const record = await this.store.put(name, id, data);
|
|
@@ -87,6 +104,7 @@ export class SyncManager {
|
|
|
87
104
|
};
|
|
88
105
|
},
|
|
89
106
|
/** Update — writes LOCAL + queues sync */
|
|
107
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
90
108
|
update: async (id, data) => {
|
|
91
109
|
const existing = await this.store.get(name, id);
|
|
92
110
|
const merged = { ...(existing?.data || {}), ...data };
|
|
@@ -106,6 +124,7 @@ export class SyncManager {
|
|
|
106
124
|
this.syncNow();
|
|
107
125
|
},
|
|
108
126
|
/** Subscribe la changes (realtime + local writes) */
|
|
127
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
109
128
|
subscribe: (callback) => {
|
|
110
129
|
if (!this.listeners.has(name))
|
|
111
130
|
this.listeners.set(name, new Set());
|
|
@@ -114,22 +133,24 @@ export class SyncManager {
|
|
|
114
133
|
let unsubRealtime;
|
|
115
134
|
if (this.realtime) {
|
|
116
135
|
unsubRealtime = this.realtime.subscribe(name, async (event) => {
|
|
117
|
-
// Apply update from server to local store
|
|
118
|
-
|
|
119
|
-
|
|
136
|
+
// Apply update from server to local store. The engine's socket
|
|
137
|
+
// sends `{ type: 'event', event: 'insert'|'update'|'delete', data }`
|
|
138
|
+
// (routes/ws.ts `broadcastEvent`); the id lives on `data`.
|
|
139
|
+
const id = event.data?.id;
|
|
140
|
+
if (event.type !== 'event' || !id)
|
|
141
|
+
return;
|
|
142
|
+
if (event.event === 'insert' || event.event === 'update') {
|
|
120
143
|
try {
|
|
121
|
-
const serverRecord = await this.client
|
|
122
|
-
|
|
123
|
-
.get(event.record_id);
|
|
124
|
-
await this.store.applyServerUpdate(name, event.record_id, serverRecord, Date.now());
|
|
144
|
+
const serverRecord = await this.client.collection(name).get(id);
|
|
145
|
+
await this.store.applyServerUpdate(name, id, serverRecord, Date.now());
|
|
125
146
|
this.notifyListeners(name);
|
|
126
147
|
}
|
|
127
148
|
catch {
|
|
128
149
|
/* offline or error — ignore, periodic sync will resolve */
|
|
129
150
|
}
|
|
130
151
|
}
|
|
131
|
-
else if (event.event === '
|
|
132
|
-
await this.store.
|
|
152
|
+
else if (event.event === 'delete') {
|
|
153
|
+
await this.store.applyServerDelete(name, id);
|
|
133
154
|
this.notifyListeners(name);
|
|
134
155
|
}
|
|
135
156
|
});
|
|
@@ -153,6 +174,7 @@ export class SyncManager {
|
|
|
153
174
|
return this.store.getConflicts(name);
|
|
154
175
|
},
|
|
155
176
|
/** Resolve a conflict manually */
|
|
177
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
156
178
|
resolveConflict: async (id, resolvedData) => {
|
|
157
179
|
await this.store.resolveConflict(name, id, resolvedData);
|
|
158
180
|
this.notifyListeners(name);
|
|
@@ -173,6 +195,7 @@ export class SyncManager {
|
|
|
173
195
|
const file = new File([blobItem.blob], `offline_${blobItem.id}`, {
|
|
174
196
|
type: blobItem.blob.type,
|
|
175
197
|
});
|
|
198
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
176
199
|
const result = (await this.client.storage.upload(file));
|
|
177
200
|
const url = result?.url || result?.publicUrl || result?.path || '';
|
|
178
201
|
if (!url)
|
|
@@ -209,9 +232,7 @@ export class SyncManager {
|
|
|
209
232
|
.create({ id: op.recordId, ...crdtPayload });
|
|
210
233
|
break;
|
|
211
234
|
case 'update':
|
|
212
|
-
await this.client
|
|
213
|
-
.collection(op.collection)
|
|
214
|
-
.update(op.recordId, crdtPayload);
|
|
235
|
+
await this.client.collection(op.collection).update(op.recordId, crdtPayload);
|
|
215
236
|
break;
|
|
216
237
|
case 'delete':
|
|
217
238
|
await this.client.collection(op.collection).delete(op.recordId);
|
|
@@ -219,27 +240,34 @@ export class SyncManager {
|
|
|
219
240
|
}
|
|
220
241
|
await this.store.markSynced(op.id, op.collection, op.recordId, serverVersion);
|
|
221
242
|
this.notifyListeners(op.collection);
|
|
243
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
222
244
|
}
|
|
223
245
|
catch (err) {
|
|
224
246
|
// Conflict from server (409) — apply conflict resolution
|
|
225
247
|
if (err.message?.includes('409')) {
|
|
226
248
|
try {
|
|
227
|
-
const serverRecord = await this.client
|
|
228
|
-
.collection(op.collection)
|
|
229
|
-
.get(op.recordId);
|
|
249
|
+
const serverRecord = await this.client.collection(op.collection).get(op.recordId);
|
|
230
250
|
const localRecord = await this.store.get(op.collection, op.recordId);
|
|
231
251
|
// CRDT LWW merge if both sides have CRDT docs and strategy is 'lww'
|
|
232
252
|
if (this.config.conflictResolution === 'lww' &&
|
|
233
253
|
localRecord?._crdtDoc &&
|
|
254
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
234
255
|
serverRecord.__crdt) {
|
|
256
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
235
257
|
const merged = mergeLWW(localRecord._crdtDoc, serverRecord.__crdt);
|
|
236
|
-
|
|
237
|
-
await this.store.resolveConflict(op.collection, op.recordId, resolvedData);
|
|
258
|
+
await this.store.resolveConflict(op.collection, op.recordId, fromDocument(merged));
|
|
238
259
|
}
|
|
239
260
|
else {
|
|
240
261
|
const resolved = this.config.onConflict(localRecord?.data, serverRecord);
|
|
241
262
|
await this.store.resolveConflict(op.collection, op.recordId, resolved);
|
|
242
263
|
}
|
|
264
|
+
// The operation the server just rejected stayed in the queue with
|
|
265
|
+
// its original payload and its attempt count untouched, so the next
|
|
266
|
+
// tick sent the same payload, took the same 409 and resolved the
|
|
267
|
+
// same conflict again — every `syncInterval`, with no end. Count
|
|
268
|
+
// the attempt so `maxRetries` retires it; the resolved row is
|
|
269
|
+
// queued by `resolveConflict` as its own operation.
|
|
270
|
+
await this.store.markFailed(op.id, 'rejected with 409 — resolved locally');
|
|
243
271
|
}
|
|
244
272
|
catch {
|
|
245
273
|
/* fallback: server wins — ignore error */
|
|
@@ -275,6 +303,109 @@ export class SyncManager {
|
|
|
275
303
|
}
|
|
276
304
|
});
|
|
277
305
|
}
|
|
306
|
+
/**
|
|
307
|
+
* Open the local store without starting background sync.
|
|
308
|
+
*
|
|
309
|
+
* `start()` opens the store, attaches online/offline listeners, connects
|
|
310
|
+
* realtime and installs a periodic timer. A caller driving `pull()` and
|
|
311
|
+
* `push()` explicitly — the `OfflineProvider` contract in `offline/` — wants
|
|
312
|
+
* the store and none of the rest, and a timer firing `syncNow()` underneath it
|
|
313
|
+
* makes "how many operations did that push send" unanswerable.
|
|
314
|
+
*/
|
|
315
|
+
async open() {
|
|
316
|
+
await this.store.open();
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Pull rows for the named collections from the server into the local store.
|
|
320
|
+
*
|
|
321
|
+
* There was no way to do this. Records reached the local store only through
|
|
322
|
+
* realtime events, one at a time, which means a client that was offline while
|
|
323
|
+
* a row was created never learns it exists: it missed the event and nothing
|
|
324
|
+
* ever asks the server what it has. `syncNow()` is push-only despite the name.
|
|
325
|
+
*
|
|
326
|
+
* Reads `POST /api/sync/pull`, which returns what changed since the cursors
|
|
327
|
+
* kept in the local store, deletes included. Paging `list()` instead — what
|
|
328
|
+
* this did before — never removed anything: a row deleted on the server
|
|
329
|
+
* stayed in every local store that had pulled it.
|
|
330
|
+
*
|
|
331
|
+
* A collection pulled for the first time, or one the server answers with
|
|
332
|
+
* `resync`, loses its synced local rows before the page is applied; local
|
|
333
|
+
* edits not yet pushed stay. `/api/sync` takes sessions only, so a client
|
|
334
|
+
* authenticated by an API key (403) falls back to paging `list()`, without
|
|
335
|
+
* deletes.
|
|
336
|
+
*/
|
|
337
|
+
async pull(collections, pageSize = 200) {
|
|
338
|
+
let applied = 0;
|
|
339
|
+
// The server takes at most 20 collections per pull.
|
|
340
|
+
for (let i = 0; i < collections.length; i += 20) {
|
|
341
|
+
const names = collections.slice(i, i + 20);
|
|
342
|
+
try {
|
|
343
|
+
applied += await this.pullChanges(names);
|
|
344
|
+
}
|
|
345
|
+
catch (err) {
|
|
346
|
+
if (!(err instanceof ZveltioApiError && err.status === 403))
|
|
347
|
+
throw err;
|
|
348
|
+
applied += await this.pullPages(names, pageSize);
|
|
349
|
+
}
|
|
350
|
+
for (const name of names)
|
|
351
|
+
await this.notifyListeners(name);
|
|
352
|
+
}
|
|
353
|
+
return applied;
|
|
354
|
+
}
|
|
355
|
+
async pullChanges(names) {
|
|
356
|
+
const byTable = new Map(names.map((n) => [n.startsWith('zvd_') ? n : `zvd_${n}`, n]));
|
|
357
|
+
const cursors = (await this.store.getMeta(PULL_CURSORS)) ?? {};
|
|
358
|
+
for (const [table, name] of byTable) {
|
|
359
|
+
if (!cursors[table])
|
|
360
|
+
await this.store.dropSynced(name);
|
|
361
|
+
}
|
|
362
|
+
let applied = 0;
|
|
363
|
+
for (;;) {
|
|
364
|
+
const res = await this.client.post('/api/sync/pull', { collections: [...byTable.keys()], cursors });
|
|
365
|
+
for (const [table, flag] of Object.entries(res.resync ?? {})) {
|
|
366
|
+
const name = byTable.get(table);
|
|
367
|
+
if (flag && name)
|
|
368
|
+
await this.store.dropSynced(name);
|
|
369
|
+
}
|
|
370
|
+
for (const ch of res.changes) {
|
|
371
|
+
const name = byTable.get(ch.collection) ?? ch.collection;
|
|
372
|
+
if (ch.operation === 'delete')
|
|
373
|
+
await this.store.applyServerDelete(name, ch.id);
|
|
374
|
+
else
|
|
375
|
+
await this.store.applyServerUpdate(name, ch.id, ch.data ?? {}, Date.now());
|
|
376
|
+
applied++;
|
|
377
|
+
}
|
|
378
|
+
// Saved only after the page is applied: a pull cut short resumes here.
|
|
379
|
+
Object.assign(cursors, res.cursors);
|
|
380
|
+
await this.store.setMeta(PULL_CURSORS, cursors);
|
|
381
|
+
if (!res.hasMore)
|
|
382
|
+
return applied;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/** Pages through `list()`; stops on the first page that comes back short. */
|
|
386
|
+
async pullPages(collections, pageSize) {
|
|
387
|
+
let applied = 0;
|
|
388
|
+
for (const name of collections) {
|
|
389
|
+
for (let page = 1;; page++) {
|
|
390
|
+
const result = await this.client.collection(name).list({ page, limit: pageSize });
|
|
391
|
+
const rows = result?.records ?? [];
|
|
392
|
+
for (const row of rows) {
|
|
393
|
+
const id = row.id;
|
|
394
|
+
if (!id)
|
|
395
|
+
continue;
|
|
396
|
+
// `Date.now()` as the server version: the collections API does not
|
|
397
|
+
// return a version column, and the local store only compares versions
|
|
398
|
+
// to decide whether an incoming row is newer than one it already has.
|
|
399
|
+
// A server row arriving now IS newer than anything already local.
|
|
400
|
+
await this.store.applyServerUpdate(name, id, row, Date.now());
|
|
401
|
+
applied++;
|
|
402
|
+
}
|
|
403
|
+
if (rows.length < pageSize)
|
|
404
|
+
break;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return applied;
|
|
408
|
+
}
|
|
278
409
|
/** Status: pending operations count, conflicts count */
|
|
279
410
|
async getStatus() {
|
|
280
411
|
const pending = await this.store.getPendingOps();
|
|
@@ -285,10 +416,30 @@ export class SyncManager {
|
|
|
285
416
|
isOnline: this.isOnline,
|
|
286
417
|
};
|
|
287
418
|
}
|
|
419
|
+
/**
|
|
420
|
+
* Delete everything the local store holds — records, pending writes, blobs,
|
|
421
|
+
* pull positions — so the next user of this browser neither sees this user's
|
|
422
|
+
* data nor sends this user's queued writes under their own session. Call it
|
|
423
|
+
* after sign-out (a sync started then is refused and stores nothing); call
|
|
424
|
+
* `syncNow()` before sign-out to push what is pending, which is lost otherwise.
|
|
425
|
+
*/
|
|
426
|
+
async clearLocalData() {
|
|
427
|
+
// ponytail: polls the in-flight sync; a stored promise if it ever matters.
|
|
428
|
+
while (this.isSyncing)
|
|
429
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
430
|
+
await this.store.clear();
|
|
431
|
+
}
|
|
288
432
|
async stop() {
|
|
433
|
+
this.stopped = true;
|
|
289
434
|
if (this.syncTimer)
|
|
290
435
|
clearInterval(this.syncTimer);
|
|
436
|
+
this.syncTimer = null;
|
|
437
|
+
if (typeof window !== 'undefined') {
|
|
438
|
+
window.removeEventListener('online', this.onOnline);
|
|
439
|
+
window.removeEventListener('offline', this.onOffline);
|
|
440
|
+
}
|
|
291
441
|
this.realtime?.disconnect();
|
|
442
|
+
this.realtime = null;
|
|
292
443
|
await this.store.close();
|
|
293
444
|
}
|
|
294
445
|
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Testing helpers for Zveltio extensions (S4-06).
|
|
3
|
+
*
|
|
4
|
+
* Goal: give extension authors a one-liner to spin up a fake
|
|
5
|
+
* `ExtensionContext` and a Hono test app, so unit tests run without a
|
|
6
|
+
* real database or auth setup. For integration tests against a real
|
|
7
|
+
* Postgres + engine, use Bun's `testcontainers` directly — this module
|
|
8
|
+
* is the offline-fast path.
|
|
9
|
+
*
|
|
10
|
+
* Three primitives:
|
|
11
|
+
* - `createTestContext(overrides?)` — minimal `ExtensionContext` with
|
|
12
|
+
* no-op stubs for everything (db, auth, events, services,
|
|
13
|
+
* queryAlter, entityAccess, registerPublicRoute). Override per-test.
|
|
14
|
+
* - `createTestApp(extension, ctx?)` — runs `extension.register()`
|
|
15
|
+
* against a fresh Hono and returns the app, ready for `.request()`.
|
|
16
|
+
* - `mockDb(presets?)` — records query-builder calls; returns presets
|
|
17
|
+
* when an `.execute()` / `.executeTakeFirst()` lands. Enough to
|
|
18
|
+
* fake CRUD paths; falls back to empty arrays / undefined.
|
|
19
|
+
*/
|
|
20
|
+
import { Hono } from 'hono';
|
|
21
|
+
import type { ZveltioExtension, ExtensionContext } from '../extension/index.js';
|
|
22
|
+
export interface MockCall {
|
|
23
|
+
/** Method name chain, e.g. `'selectFrom.where.execute'`. */
|
|
24
|
+
chain: string;
|
|
25
|
+
/** Args of the terminal call. */
|
|
26
|
+
args: unknown[];
|
|
27
|
+
}
|
|
28
|
+
export interface MockDbPresets {
|
|
29
|
+
/**
|
|
30
|
+
* Preset a return value for a specific chain. Match is by suffix —
|
|
31
|
+
* `'selectFrom.zvd_users.execute'` matches the chain ending in that.
|
|
32
|
+
* Use exact chains for precision.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* mockDb({
|
|
36
|
+
* 'selectFrom.zvd_users.selectAll.execute': [{ id: '1', name: 'A' }],
|
|
37
|
+
* 'selectFrom.zvd_users.executeTakeFirst': { id: '1', name: 'A' },
|
|
38
|
+
* })
|
|
39
|
+
*/
|
|
40
|
+
[chain: string]: unknown;
|
|
41
|
+
}
|
|
42
|
+
export interface MockDb {
|
|
43
|
+
/** Recorded calls, oldest first. Reset between tests. */
|
|
44
|
+
readonly calls: MockCall[];
|
|
45
|
+
/** Reset call history (presets stay). */
|
|
46
|
+
reset(): void;
|
|
47
|
+
/** Add or override a preset after construction. */
|
|
48
|
+
preset(chain: string, value: unknown): void;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Build a recording mock Kysely-shaped object. Any method chain is
|
|
52
|
+
* accepted; the terminal `.execute()` / `.executeTakeFirst()` /
|
|
53
|
+
* `.executeTakeFirstOrThrow()` returns a preset if matched, otherwise
|
|
54
|
+
* an empty list (for execute) or undefined.
|
|
55
|
+
*/
|
|
56
|
+
export declare function mockDb(presets?: MockDbPresets): any & MockDb;
|
|
57
|
+
export interface MockEventBus {
|
|
58
|
+
emit(event: string, payload: unknown): void;
|
|
59
|
+
on(event: string, handler: (payload: any) => void): () => void;
|
|
60
|
+
onBefore(event: string, handler: (payload: any) => any): () => void;
|
|
61
|
+
runBefore(event: string, seed: Record<string, unknown>): Promise<any>;
|
|
62
|
+
/** Recorded emits, oldest first. */
|
|
63
|
+
readonly emitted: Array<{
|
|
64
|
+
event: string;
|
|
65
|
+
payload: unknown;
|
|
66
|
+
}>;
|
|
67
|
+
/** Reset emit log. */
|
|
68
|
+
reset(): void;
|
|
69
|
+
}
|
|
70
|
+
export declare function mockEventBus(): MockEventBus;
|
|
71
|
+
export declare function mockServiceRegistry(): {
|
|
72
|
+
register(name: string, value: unknown): void;
|
|
73
|
+
unregister(name: string): void;
|
|
74
|
+
get<T = unknown>(name: string): T | null;
|
|
75
|
+
has(name: string): boolean;
|
|
76
|
+
list(): string[];
|
|
77
|
+
waitFor<T = unknown>(name: string, timeoutMs?: number): Promise<T>;
|
|
78
|
+
};
|
|
79
|
+
export interface MockAuthOptions {
|
|
80
|
+
/** If set, getSession returns `{ user: this }`. If null, getSession returns null. */
|
|
81
|
+
user?: {
|
|
82
|
+
id: string;
|
|
83
|
+
email?: string;
|
|
84
|
+
name?: string;
|
|
85
|
+
roles?: string[];
|
|
86
|
+
} | null;
|
|
87
|
+
}
|
|
88
|
+
export declare function mockAuth(opts?: MockAuthOptions): any;
|
|
89
|
+
export interface CreateTestContextOptions {
|
|
90
|
+
/** Override the mocked db. Default: `mockDb()`. */
|
|
91
|
+
db?: any;
|
|
92
|
+
/** Override the mocked auth. Default: signed-in test user. */
|
|
93
|
+
auth?: any;
|
|
94
|
+
/** Override the mocked event bus. Default: in-memory. */
|
|
95
|
+
events?: MockEventBus;
|
|
96
|
+
/** Provide additional fields. They go onto the returned ctx as-is. */
|
|
97
|
+
extra?: Partial<ExtensionContext<any>>;
|
|
98
|
+
}
|
|
99
|
+
export declare function createTestContext(opts?: CreateTestContextOptions): ExtensionContext<any>;
|
|
100
|
+
export interface CreateTestAppOptions {
|
|
101
|
+
/** Override the context handed to register(). Default: `createTestContext()`. */
|
|
102
|
+
ctx?: ExtensionContext<any>;
|
|
103
|
+
/**
|
|
104
|
+
* When the extension uses `mountStrategy: 'subapp'`, the engine normally
|
|
105
|
+
* mounts the sub-app at `/ext/<name>`. For tests we replicate that so
|
|
106
|
+
* `.request('/ext/<name>/...')` works. Pass `false` to skip the wrapper
|
|
107
|
+
* and mount the sub-app at root for cleaner test URLs.
|
|
108
|
+
*/
|
|
109
|
+
mountSubappAt?: string | false;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Spin up a Hono test app with the extension's routes registered. Returns
|
|
113
|
+
* the outer Hono so callers can use `.request(path, init)` for assertions.
|
|
114
|
+
*
|
|
115
|
+
* Honors the extension's `mountStrategy`. For `'subapp'`, the outer app
|
|
116
|
+
* mounts the sub-app at `/ext/<extension.name>` by default — same shape
|
|
117
|
+
* the engine produces in production.
|
|
118
|
+
*/
|
|
119
|
+
export declare function createTestApp(extension: ZveltioExtension<any>, opts?: CreateTestAppOptions): Promise<Hono>;
|
|
120
|
+
export { withTestDb, startTestDb, applyMigrationStrings, applyMigrationFiles, stopReusedTestDb, splitStatements, type TestDb, type WithTestDbOptions, } from './with-test-db.js';
|
|
121
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAIhF,MAAM,WAAW,QAAQ;IACvB,4DAA4D;IAC5D,KAAK,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,IAAI,EAAE,OAAO,EAAE,CAAC;CACjB;AAED,MAAM,WAAW,aAAa;IAC5B;;;;;;;;;;OAUG;IACH,CAAC,KAAK,EAAE,MAAM,GAA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