@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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"offline-provider-crdt.test.d.ts","sourceRoot":"","sources":["../../src/tests/offline-provider-crdt.test.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,CAAC"}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import './setup';
|
|
2
|
+
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
|
|
3
|
+
import { LocalStore } from '../local-store.js';
|
|
4
|
+
import { createOfflineProvider } from '../offline/index.js';
|
|
5
|
+
/**
|
|
6
|
+
* The CRDT provider is the DEFAULT (`config.provider ?? 'crdt'`) and it did
|
|
7
|
+
* nothing at all: `pull()` was an empty body, `subscribe()` returned an
|
|
8
|
+
* unsubscribe for nothing, and `push()` returned `0` — which reads as "there
|
|
9
|
+
* was nothing to send" rather than "I did not look". An application that called
|
|
10
|
+
* `createOfflineProvider({ engineUrl })` and pushed on a timer got a clean run
|
|
11
|
+
* and an empty server, forever, with nothing in any log.
|
|
12
|
+
*
|
|
13
|
+
* The test that existed asserted exactly that: `await expect(p.push())
|
|
14
|
+
* .resolves.toBe(0)`, under the title "builds a working stub". It passed for the
|
|
15
|
+
* whole life of the defect.
|
|
16
|
+
*
|
|
17
|
+
* So these assert the crossing — what ends up in the local store, and what the
|
|
18
|
+
* count means — rather than that the methods are callable.
|
|
19
|
+
*/
|
|
20
|
+
const ENGINE = 'http://engine.test';
|
|
21
|
+
/** Rows the fake engine holds, by collection. */
|
|
22
|
+
let served = {};
|
|
23
|
+
/** Ids the fake engine reports deleted (tombstones), by collection. */
|
|
24
|
+
let tombstones = {};
|
|
25
|
+
/** Collections the next pull answers with `resync`. */
|
|
26
|
+
let resync = {};
|
|
27
|
+
/** `/api/sync/pull` answers 403, as it does to an API key. */
|
|
28
|
+
let pullForbidden = false;
|
|
29
|
+
/** Bodies `/api/sync/pull` received. */
|
|
30
|
+
let pullBodies = [];
|
|
31
|
+
/** Every request the provider made, so "did it even ask" is answerable. */
|
|
32
|
+
let requests = [];
|
|
33
|
+
const realFetch = globalThis.fetch;
|
|
34
|
+
function json(body, status = 200) {
|
|
35
|
+
return new Response(JSON.stringify(body), {
|
|
36
|
+
status,
|
|
37
|
+
headers: { 'content-type': 'application/json' },
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
beforeEach(async () => {
|
|
41
|
+
served = {};
|
|
42
|
+
tombstones = {};
|
|
43
|
+
resync = {};
|
|
44
|
+
pullForbidden = false;
|
|
45
|
+
pullBodies = [];
|
|
46
|
+
requests = [];
|
|
47
|
+
globalThis.fetch = (async (input, init) => {
|
|
48
|
+
const url = typeof input === 'string' ? input : input.toString();
|
|
49
|
+
requests.push(`${init?.method ?? 'GET'} ${url.replace(ENGINE, '')}`);
|
|
50
|
+
if (url.endsWith('/api/sync/pull')) {
|
|
51
|
+
if (pullForbidden)
|
|
52
|
+
return json({ error: 'Session required' }, 403);
|
|
53
|
+
const body = JSON.parse(String(init?.body));
|
|
54
|
+
pullBodies.push(body);
|
|
55
|
+
const changes = [];
|
|
56
|
+
const cursors = {};
|
|
57
|
+
for (const table of body.collections) {
|
|
58
|
+
const name = table.replace(/^zvd_/, '');
|
|
59
|
+
// A cursor means rows already sent: only tombstones follow it, unless
|
|
60
|
+
// the collection restarts (`resync`) or has none.
|
|
61
|
+
if (body.cursors?.[table] && !resync[table]) {
|
|
62
|
+
for (const id of tombstones[name] ?? []) {
|
|
63
|
+
changes.push({ collection: table, id, data: null, operation: 'delete' });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
for (const row of served[name] ?? []) {
|
|
68
|
+
changes.push({ collection: table, id: row.id, data: row, operation: 'upsert' });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
cursors[table] = `pos-${pullBodies.length}`;
|
|
72
|
+
}
|
|
73
|
+
const answer = { changes, hasMore: false, cursors, resync };
|
|
74
|
+
resync = {};
|
|
75
|
+
return json(answer);
|
|
76
|
+
}
|
|
77
|
+
const match = url.match(/\/api\/data\/([^/?]+)/);
|
|
78
|
+
const name = match?.[1] ?? '';
|
|
79
|
+
const page = Number(new URL(url).searchParams.get('page') ?? '1');
|
|
80
|
+
// One page only: page 2 comes back empty, which is how `pull` stops.
|
|
81
|
+
// The shape `listRecords` sends. This fake answered `{ data, … }`, the shape
|
|
82
|
+
// the SDK's type wrongly declared, so the test agreed with the bug.
|
|
83
|
+
const records = page === 1 ? (served[name] ?? []) : [];
|
|
84
|
+
return json({ records, pagination: { total: records.length, page, limit: 200 } });
|
|
85
|
+
});
|
|
86
|
+
const store = new LocalStore();
|
|
87
|
+
await store.open();
|
|
88
|
+
await store.clear();
|
|
89
|
+
await store.close();
|
|
90
|
+
});
|
|
91
|
+
afterEach(() => {
|
|
92
|
+
globalThis.fetch = realFetch;
|
|
93
|
+
});
|
|
94
|
+
async function localRows(collection) {
|
|
95
|
+
const store = new LocalStore();
|
|
96
|
+
await store.open();
|
|
97
|
+
const rows = await store.list(collection);
|
|
98
|
+
await store.close();
|
|
99
|
+
return rows;
|
|
100
|
+
}
|
|
101
|
+
describe('createOfflineProvider — the crdt path actually syncs', () => {
|
|
102
|
+
it('is the default provider, which is why the no-op mattered', async () => {
|
|
103
|
+
const p = await createOfflineProvider({ engineUrl: ENGINE });
|
|
104
|
+
expect(p.kind).toBe('crdt');
|
|
105
|
+
await p.close();
|
|
106
|
+
});
|
|
107
|
+
it('pull writes the server rows into the local store', async () => {
|
|
108
|
+
served.orders = [
|
|
109
|
+
{ id: 'o-1', total: 10, status: 'new' },
|
|
110
|
+
{ id: 'o-2', total: 20, status: 'paid' },
|
|
111
|
+
];
|
|
112
|
+
const p = await createOfflineProvider({ engineUrl: ENGINE, tables: ['orders'] });
|
|
113
|
+
await p.pull();
|
|
114
|
+
await p.close();
|
|
115
|
+
const rows = await localRows('orders');
|
|
116
|
+
expect(rows.map((r) => r.id).sort()).toEqual(['o-1', 'o-2']);
|
|
117
|
+
expect(rows.find((r) => r.id === 'o-1')?.data.total).toBe(10);
|
|
118
|
+
// The old implementation made no request at all. This is the assertion that
|
|
119
|
+
// would have caught it.
|
|
120
|
+
expect(requests).toContain('POST /api/sync/pull');
|
|
121
|
+
});
|
|
122
|
+
it('pull refuses an empty table list instead of quietly doing nothing', async () => {
|
|
123
|
+
// Silence here is exactly what the no-op was. A provider asked to replicate
|
|
124
|
+
// nothing is a configuration mistake, and an empty local database looks the
|
|
125
|
+
// same as an empty server.
|
|
126
|
+
const p = await createOfflineProvider({ engineUrl: ENGINE });
|
|
127
|
+
await expect(p.pull()).rejects.toThrow(/tables.*is empty/i);
|
|
128
|
+
await p.close();
|
|
129
|
+
});
|
|
130
|
+
it('push reports how many queued operations it actually sent', async () => {
|
|
131
|
+
const p = await createOfflineProvider({ engineUrl: ENGINE, tables: ['orders'] });
|
|
132
|
+
// Queue two local writes the way an offline application does.
|
|
133
|
+
const store = new LocalStore();
|
|
134
|
+
await store.open();
|
|
135
|
+
await store.put('orders', 'o-9', { total: 99 });
|
|
136
|
+
await store.put('orders', 'o-10', { total: 100 });
|
|
137
|
+
const queued = await store.getPendingOps();
|
|
138
|
+
await store.close();
|
|
139
|
+
expect(queued.length).toBe(2);
|
|
140
|
+
const sent = await p.push();
|
|
141
|
+
await p.close();
|
|
142
|
+
expect(sent).toBe(2);
|
|
143
|
+
// Not just a number: the writes have to have left the machine.
|
|
144
|
+
expect(requests.filter((r) => r.startsWith('POST /api/data/orders')).length).toBe(2);
|
|
145
|
+
});
|
|
146
|
+
it('subscribe delivers the local rows, and the unsubscribe stops delivery', async () => {
|
|
147
|
+
served.orders = [{ id: 'o-1', total: 10 }];
|
|
148
|
+
const p = await createOfflineProvider({ engineUrl: ENGINE, tables: ['orders'] });
|
|
149
|
+
await p.pull();
|
|
150
|
+
const seen = [];
|
|
151
|
+
const off = p.subscribe('orders', (rows) => seen.push(rows));
|
|
152
|
+
await Bun.sleep(20);
|
|
153
|
+
expect(seen.length).toBeGreaterThan(0);
|
|
154
|
+
expect(seen.at(-1).map((r) => r.id)).toEqual(['o-1']);
|
|
155
|
+
off();
|
|
156
|
+
const countAtUnsubscribe = seen.length;
|
|
157
|
+
// A second pull notifies listeners; an unsubscribed callback must not hear it.
|
|
158
|
+
await p.pull();
|
|
159
|
+
await Bun.sleep(20);
|
|
160
|
+
expect(seen.length).toBe(countAtUnsubscribe);
|
|
161
|
+
await p.close();
|
|
162
|
+
});
|
|
163
|
+
it('a row deleted on the server leaves the local store on the next pull', async () => {
|
|
164
|
+
served.orders = [
|
|
165
|
+
{ id: 'o-1', total: 10 },
|
|
166
|
+
{ id: 'o-2', total: 20 },
|
|
167
|
+
];
|
|
168
|
+
const p = await createOfflineProvider({ engineUrl: ENGINE, tables: ['orders'] });
|
|
169
|
+
await p.pull();
|
|
170
|
+
served.orders = [];
|
|
171
|
+
tombstones.orders = ['o-2'];
|
|
172
|
+
await p.pull();
|
|
173
|
+
await p.close();
|
|
174
|
+
// The second pull resumed from the cursor the first one saved.
|
|
175
|
+
expect(pullBodies[1]?.cursors).toEqual({ zvd_orders: 'pos-1' });
|
|
176
|
+
expect((await localRows('orders')).map((r) => r.id)).toEqual(['o-1']);
|
|
177
|
+
});
|
|
178
|
+
it('resync drops synced rows the server no longer sends, keeping unpushed edits', async () => {
|
|
179
|
+
served.orders = [
|
|
180
|
+
{ id: 'o-1', total: 10 },
|
|
181
|
+
{ id: 'o-2', total: 20 },
|
|
182
|
+
];
|
|
183
|
+
const p = await createOfflineProvider({ engineUrl: ENGINE, tables: ['orders'] });
|
|
184
|
+
await p.pull();
|
|
185
|
+
const store = new LocalStore();
|
|
186
|
+
await store.open();
|
|
187
|
+
await store.put('orders', 'o-local', { total: 1 });
|
|
188
|
+
await store.close();
|
|
189
|
+
served.orders = [{ id: 'o-1', total: 11 }];
|
|
190
|
+
resync = { zvd_orders: true };
|
|
191
|
+
await p.pull();
|
|
192
|
+
await p.close();
|
|
193
|
+
const rows = await localRows('orders');
|
|
194
|
+
expect(rows.map((r) => r.id).sort()).toEqual(['o-1', 'o-local']);
|
|
195
|
+
expect(rows.find((r) => r.id === 'o-1')?.data.total).toBe(11);
|
|
196
|
+
});
|
|
197
|
+
it('a client the sync endpoint refuses (API key, 403) still pulls through the data API', async () => {
|
|
198
|
+
served.orders = [{ id: 'o-1', total: 10 }];
|
|
199
|
+
pullForbidden = true;
|
|
200
|
+
const p = await createOfflineProvider({ engineUrl: ENGINE, tables: ['orders'] });
|
|
201
|
+
await p.pull();
|
|
202
|
+
await p.close();
|
|
203
|
+
expect((await localRows('orders')).map((r) => r.id)).toEqual(['o-1']);
|
|
204
|
+
expect(requests.some((r) => r.startsWith('GET /api/data/orders'))).toBe(true);
|
|
205
|
+
});
|
|
206
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"realtime.test.d.ts","sourceRoot":"","sources":["../../src/tests/realtime.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { describe, it, expect, afterEach, jest, spyOn } from 'bun:test';
|
|
2
|
+
import { rm } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { ZveltioRealtime } from '../realtime.js';
|
|
5
|
+
import { watchSchema } from '../schema-watcher.js';
|
|
6
|
+
const RealWebSocket = globalThis.WebSocket;
|
|
7
|
+
afterEach(() => {
|
|
8
|
+
globalThis.WebSocket = RealWebSocket;
|
|
9
|
+
});
|
|
10
|
+
/** Records the constructor arguments instead of dialling out. */
|
|
11
|
+
function captureSockets() {
|
|
12
|
+
const calls = [];
|
|
13
|
+
globalThis.WebSocket = class {
|
|
14
|
+
static OPEN = 1;
|
|
15
|
+
readyState = 0;
|
|
16
|
+
constructor(...args) {
|
|
17
|
+
calls.push(args);
|
|
18
|
+
}
|
|
19
|
+
close() { }
|
|
20
|
+
send() { }
|
|
21
|
+
};
|
|
22
|
+
return calls;
|
|
23
|
+
}
|
|
24
|
+
describe('ZveltioRealtime upgrade headers', () => {
|
|
25
|
+
// `/api/ws` accepts an API key in `X-API-Key`; a server-side client had no
|
|
26
|
+
// way to send one, so it could read a collection over REST and never
|
|
27
|
+
// subscribe to it.
|
|
28
|
+
it('passes headers to the socket when given', () => {
|
|
29
|
+
const calls = captureSockets();
|
|
30
|
+
const rt = new ZveltioRealtime('https://engine.test', { headers: { 'X-API-Key': 'zvk_x' } });
|
|
31
|
+
rt.connect();
|
|
32
|
+
expect(calls[0]).toEqual(['wss://engine.test/api/ws', { headers: { 'X-API-Key': 'zvk_x' } }]);
|
|
33
|
+
rt.disconnect();
|
|
34
|
+
});
|
|
35
|
+
it('uses the one-argument constructor without them', () => {
|
|
36
|
+
const calls = captureSockets();
|
|
37
|
+
const rt = new ZveltioRealtime('http://engine.test');
|
|
38
|
+
rt.connect();
|
|
39
|
+
expect(calls[0]).toEqual(['ws://engine.test/api/ws']);
|
|
40
|
+
rt.disconnect();
|
|
41
|
+
});
|
|
42
|
+
// A browser reads the second argument as subprotocols and throws a
|
|
43
|
+
// SyntaxError on an object. There the socket opens on the session cookie.
|
|
44
|
+
it('opens without headers where the constructor refuses them (a browser)', () => {
|
|
45
|
+
const calls = [];
|
|
46
|
+
globalThis.WebSocket = class {
|
|
47
|
+
static CONNECTING = 0;
|
|
48
|
+
static OPEN = 1;
|
|
49
|
+
readyState = 0;
|
|
50
|
+
constructor(...args) {
|
|
51
|
+
if (args.length > 1 && typeof args[1] === 'object' && !Array.isArray(args[1]))
|
|
52
|
+
throw new SyntaxError('An invalid or illegal string was specified');
|
|
53
|
+
calls.push(args);
|
|
54
|
+
}
|
|
55
|
+
close() { }
|
|
56
|
+
send() { }
|
|
57
|
+
};
|
|
58
|
+
const rt = new ZveltioRealtime('https://engine.test', { headers: { 'X-API-Key': 'zvk_x' } });
|
|
59
|
+
rt.connect();
|
|
60
|
+
expect(calls).toEqual([['wss://engine.test/api/ws']]);
|
|
61
|
+
rt.disconnect();
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
/** Fake sockets that record themselves, so a test can open or close one. */
|
|
65
|
+
function fakeSockets() {
|
|
66
|
+
const made = [];
|
|
67
|
+
globalThis.WebSocket = class {
|
|
68
|
+
static CONNECTING = 0;
|
|
69
|
+
static OPEN = 1;
|
|
70
|
+
readyState = 0;
|
|
71
|
+
sent = [];
|
|
72
|
+
args;
|
|
73
|
+
onopen;
|
|
74
|
+
onclose;
|
|
75
|
+
constructor(...args) {
|
|
76
|
+
this.args = args;
|
|
77
|
+
made.push(this);
|
|
78
|
+
}
|
|
79
|
+
close() { }
|
|
80
|
+
send(p) {
|
|
81
|
+
this.sent.push(p);
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
return made;
|
|
85
|
+
}
|
|
86
|
+
/** Close a fake socket as the runtime does: CLOSED first, then the event. */
|
|
87
|
+
function closeWith(ws, code) {
|
|
88
|
+
ws.readyState = 3;
|
|
89
|
+
ws.onclose?.({ code });
|
|
90
|
+
}
|
|
91
|
+
/** Drive a fake socket to OPEN, as the engine accepting the upgrade would. */
|
|
92
|
+
function accept(ws) {
|
|
93
|
+
ws.readyState = 1;
|
|
94
|
+
ws.onopen?.();
|
|
95
|
+
}
|
|
96
|
+
describe('a socket the engine closed for revoked credentials', () => {
|
|
97
|
+
// The engine closes with 4001 when the session or key is revoked, and every
|
|
98
|
+
// reconnect is then refused with 401 — retrying only hammered the engine.
|
|
99
|
+
afterEach(() => jest.useRealTimers());
|
|
100
|
+
it('ZveltioRealtime stops reconnecting on 4001 and says so', () => {
|
|
101
|
+
jest.useFakeTimers();
|
|
102
|
+
const made = fakeSockets();
|
|
103
|
+
const rt = new ZveltioRealtime('http://engine.test');
|
|
104
|
+
let told = 0;
|
|
105
|
+
rt.onUnauthorized(() => told++);
|
|
106
|
+
rt.connect();
|
|
107
|
+
closeWith(made[0], 4001);
|
|
108
|
+
jest.advanceTimersByTime(60_000);
|
|
109
|
+
expect(made).toHaveLength(1);
|
|
110
|
+
expect(told).toBe(1);
|
|
111
|
+
rt.disconnect();
|
|
112
|
+
});
|
|
113
|
+
it('ZveltioRealtime still reconnects on any other close', () => {
|
|
114
|
+
jest.useFakeTimers();
|
|
115
|
+
const made = fakeSockets();
|
|
116
|
+
const rt = new ZveltioRealtime('http://engine.test');
|
|
117
|
+
let told = 0;
|
|
118
|
+
rt.onUnauthorized(() => told++);
|
|
119
|
+
rt.connect();
|
|
120
|
+
closeWith(made[0], 1006);
|
|
121
|
+
jest.advanceTimersByTime(1_000);
|
|
122
|
+
expect(made).toHaveLength(2);
|
|
123
|
+
expect(told).toBe(0);
|
|
124
|
+
rt.disconnect();
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
describe('watchSchema', () => {
|
|
128
|
+
// It dialled the socket with no credentials, so the engine refused every
|
|
129
|
+
// upgrade (401) and the watcher reconnected every few seconds, forever.
|
|
130
|
+
it('sends its API key with the upgrade', async () => {
|
|
131
|
+
let upgradeKey;
|
|
132
|
+
const server = Bun.serve({
|
|
133
|
+
port: 0,
|
|
134
|
+
fetch(req, srv) {
|
|
135
|
+
const url = new URL(req.url);
|
|
136
|
+
if (url.pathname === '/api/collections')
|
|
137
|
+
return Response.json({ collections: [] });
|
|
138
|
+
if (url.pathname === '/api/ws') {
|
|
139
|
+
upgradeKey = req.headers.get('x-api-key');
|
|
140
|
+
if (upgradeKey !== 'zvk_watch')
|
|
141
|
+
return new Response('Unauthorized', { status: 401 });
|
|
142
|
+
return srv.upgrade(req) ? undefined : new Response('no upgrade', { status: 426 });
|
|
143
|
+
}
|
|
144
|
+
return new Response('not found', { status: 404 });
|
|
145
|
+
},
|
|
146
|
+
websocket: { message() { } },
|
|
147
|
+
});
|
|
148
|
+
const out = `${tmpdir()}/zveltio-watch-${Date.now()}.d.ts`;
|
|
149
|
+
const log = spyOn(console, 'log').mockImplementation(() => { });
|
|
150
|
+
const stop = await watchSchema(`http://127.0.0.1:${server.port}`, out, { apiKey: 'zvk_watch' });
|
|
151
|
+
try {
|
|
152
|
+
for (let i = 0; i < 100 && upgradeKey === undefined; i++)
|
|
153
|
+
await Bun.sleep(10);
|
|
154
|
+
expect(upgradeKey).toBe('zvk_watch');
|
|
155
|
+
for (let i = 0; i < 100 && !log.mock.calls.some((c) => String(c[0]).includes('connected')); i++) {
|
|
156
|
+
await Bun.sleep(10);
|
|
157
|
+
}
|
|
158
|
+
expect(log.mock.calls.some((c) => String(c[0]).includes('Schema watcher connected'))).toBe(true);
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
stop();
|
|
162
|
+
log.mockRestore();
|
|
163
|
+
server.stop(true);
|
|
164
|
+
await rm(out, { force: true });
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
// The engine publishes schema changes on `$schema` as `schema:changed`, to a
|
|
168
|
+
// schema admin's session only — so the watcher must be able to send one.
|
|
169
|
+
it('regenerates on a schema:changed event, and reports a refused subscribe', async () => {
|
|
170
|
+
let upgradeCookie = null;
|
|
171
|
+
const subscribed = [];
|
|
172
|
+
const server = Bun.serve({
|
|
173
|
+
port: 0,
|
|
174
|
+
fetch(req, srv) {
|
|
175
|
+
const url = new URL(req.url);
|
|
176
|
+
if (url.pathname === '/api/collections')
|
|
177
|
+
return Response.json({ collections: [] });
|
|
178
|
+
if (url.pathname === '/api/ws') {
|
|
179
|
+
upgradeCookie = req.headers.get('cookie');
|
|
180
|
+
return srv.upgrade(req) ? undefined : new Response('no upgrade', { status: 426 });
|
|
181
|
+
}
|
|
182
|
+
return new Response('not found', { status: 404 });
|
|
183
|
+
},
|
|
184
|
+
websocket: {
|
|
185
|
+
message(ws, raw) {
|
|
186
|
+
const msg = JSON.parse(String(raw));
|
|
187
|
+
subscribed.push(msg);
|
|
188
|
+
if (msg.channel !== '$schema')
|
|
189
|
+
return;
|
|
190
|
+
ws.send(JSON.stringify({ type: 'subscribed', channel: '$schema' }));
|
|
191
|
+
ws.send(JSON.stringify({ type: 'schema:changed', collection: 'orders', action: 'alter' }));
|
|
192
|
+
ws.send(JSON.stringify({ type: 'error', message: 'No read permission for "$schema"' }));
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
const out = `${tmpdir()}/zveltio-watch-evt-${Date.now()}.d.ts`;
|
|
197
|
+
const log = spyOn(console, 'log').mockImplementation(() => { });
|
|
198
|
+
let updates = 0;
|
|
199
|
+
const errors = [];
|
|
200
|
+
const stop = await watchSchema(`http://127.0.0.1:${server.port}`, out, {
|
|
201
|
+
headers: { cookie: 'session=abc' },
|
|
202
|
+
onUpdate: () => updates++,
|
|
203
|
+
onError: (e) => errors.push(e.message),
|
|
204
|
+
});
|
|
205
|
+
try {
|
|
206
|
+
for (let i = 0; i < 200 && (updates < 2 || errors.length === 0); i++)
|
|
207
|
+
await Bun.sleep(10);
|
|
208
|
+
expect(upgradeCookie).toBe('session=abc');
|
|
209
|
+
expect(subscribed).toEqual([{ type: 'subscribe', channel: '$schema' }]);
|
|
210
|
+
expect(updates).toBe(2); // the initial generation, then the event
|
|
211
|
+
expect(errors).toEqual(['Schema watcher: No read permission for "$schema"']);
|
|
212
|
+
}
|
|
213
|
+
finally {
|
|
214
|
+
stop();
|
|
215
|
+
log.mockRestore();
|
|
216
|
+
server.stop(true);
|
|
217
|
+
await rm(out, { force: true });
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reserved-paths.test.d.ts","sourceRoot":"","sources":["../../src/tests/reserved-paths.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { isReservedPath } from '../extension/index.js';
|
|
3
|
+
describe('isReservedPath', () => {
|
|
4
|
+
it('refuses a path whose first segment the engine or the App owns', () => {
|
|
5
|
+
for (const p of [
|
|
6
|
+
'admin',
|
|
7
|
+
'/admin',
|
|
8
|
+
'app/crm',
|
|
9
|
+
'/API/x',
|
|
10
|
+
'auth',
|
|
11
|
+
'.well-known/x',
|
|
12
|
+
'favicon.ico',
|
|
13
|
+
'robots.txt',
|
|
14
|
+
])
|
|
15
|
+
expect(isReservedPath(p)).toBe(true);
|
|
16
|
+
});
|
|
17
|
+
it('accepts a path that only starts with the same letters', () => {
|
|
18
|
+
for (const p of ['apps', 'about', 'administrator', 'blog/admin', '', '/'])
|
|
19
|
+
expect(isReservedPath(p)).toBe(false);
|
|
20
|
+
});
|
|
21
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sync-manager.test.d.ts","sourceRoot":"","sources":["../../src/tests/sync-manager.test.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,CAAC"}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import './setup';
|
|
2
|
+
import { describe, it, expect, afterEach } from 'bun:test';
|
|
3
|
+
import { SyncManager } from '../sync-manager.js';
|
|
4
|
+
import { LocalStore } from '../local-store.js';
|
|
5
|
+
/**
|
|
6
|
+
* A client whose `get` answers the server's copy of a record — the only call the
|
|
7
|
+
* realtime handler makes.
|
|
8
|
+
*/
|
|
9
|
+
function fakeClient() {
|
|
10
|
+
return {
|
|
11
|
+
collection: () => ({ get: async (id) => ({ id, title: 'from server' }) }),
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/** Stands in for `ZveltioRealtime`; `push` delivers a frame as the socket would. */
|
|
15
|
+
function fakeRealtime() {
|
|
16
|
+
let handler;
|
|
17
|
+
return {
|
|
18
|
+
subscribe: (_collection, cb) => {
|
|
19
|
+
handler = cb;
|
|
20
|
+
return () => { };
|
|
21
|
+
},
|
|
22
|
+
disconnect: () => { },
|
|
23
|
+
push: async (msg) => handler?.(msg),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
let sync;
|
|
27
|
+
afterEach(async () => {
|
|
28
|
+
await sync?.stop();
|
|
29
|
+
sync = undefined;
|
|
30
|
+
});
|
|
31
|
+
describe('SyncManager — realtime frames as the engine sends them', () => {
|
|
32
|
+
// The frame shape is `broadcastEvent` in packages/engine/src/routes/ws.ts.
|
|
33
|
+
// The handler used to wait for `record.created` / `record_id`, names the
|
|
34
|
+
// socket never sends, so no server push ever reached the local store.
|
|
35
|
+
it('applies an insert and drops a delete without queueing one back', async () => {
|
|
36
|
+
sync = new SyncManager(fakeClient(), { syncInterval: 60_000 });
|
|
37
|
+
await sync.start();
|
|
38
|
+
const store = sync.store;
|
|
39
|
+
await store.clear();
|
|
40
|
+
const rt = fakeRealtime();
|
|
41
|
+
sync.realtime = rt;
|
|
42
|
+
let latest = [];
|
|
43
|
+
sync.collection('posts').subscribe((records) => {
|
|
44
|
+
latest = records;
|
|
45
|
+
});
|
|
46
|
+
await rt.push({ type: 'event', collection: 'posts', event: 'insert', data: { id: 'p1' } });
|
|
47
|
+
expect((await store.get('posts', 'p1'))?.data).toMatchObject({ title: 'from server' });
|
|
48
|
+
expect(latest.map((r) => r.id)).toEqual(['p1']);
|
|
49
|
+
await rt.push({ type: 'event', collection: 'posts', event: 'delete', data: { id: 'p1' } });
|
|
50
|
+
expect(await store.get('posts', 'p1')).toBeUndefined();
|
|
51
|
+
// A queued delete here would send the server's own deletion back to it.
|
|
52
|
+
expect(await store.getPendingOps()).toEqual([]);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
describe('SyncManager — stop() before start() settles', () => {
|
|
56
|
+
// A React effect cleanup (and StrictMode, on every mount in development) calls
|
|
57
|
+
// `stop()` while `start()` is still awaiting the store. `start()` then armed
|
|
58
|
+
// the sync interval anyway, and nothing was left to clear it.
|
|
59
|
+
it('leaves no timer armed', async () => {
|
|
60
|
+
sync = new SyncManager(fakeClient(), { syncInterval: 60_000 });
|
|
61
|
+
const starting = sync.start();
|
|
62
|
+
await sync.stop();
|
|
63
|
+
await starting;
|
|
64
|
+
expect(sync.syncTimer).toBeNull();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
describe('SyncManager — clearLocalData', () => {
|
|
68
|
+
// The next user of the browser must neither see this user's records nor send
|
|
69
|
+
// this user's queued writes under their own session.
|
|
70
|
+
it('drops records and pending writes, open or not', async () => {
|
|
71
|
+
sync = new SyncManager(fakeClient(), { syncInterval: 60_000 });
|
|
72
|
+
await sync.start();
|
|
73
|
+
const store = sync.store;
|
|
74
|
+
await sync.collection('posts').create({ title: 'mine' });
|
|
75
|
+
expect(await store.getPendingOps()).not.toEqual([]);
|
|
76
|
+
await sync.clearLocalData();
|
|
77
|
+
expect(await store.list('posts')).toEqual([]);
|
|
78
|
+
expect(await store.getPendingOps()).toEqual([]);
|
|
79
|
+
});
|
|
80
|
+
it('clears a store this manager never opened', async () => {
|
|
81
|
+
const other = new LocalStore();
|
|
82
|
+
await other.open();
|
|
83
|
+
await other.put('posts', 'p9', { title: 'left behind' });
|
|
84
|
+
await other.close();
|
|
85
|
+
sync = new SyncManager(fakeClient(), { syncInterval: 60_000 });
|
|
86
|
+
await sync.clearLocalData();
|
|
87
|
+
await other.open();
|
|
88
|
+
expect(await other.list('posts')).toEqual([]);
|
|
89
|
+
expect(await other.getPendingOps()).toEqual([]);
|
|
90
|
+
await other.close();
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
describe('SyncManager — paged pull reads the list the engine sends', () => {
|
|
94
|
+
// A client the sync routes refuse (an API key, 403) pages `list()` instead.
|
|
95
|
+
// That path read `result.data`, which `GET /api/data/:collection` has never
|
|
96
|
+
// sent — it answers `{ records, pagination }` — so it applied nothing.
|
|
97
|
+
it('applies the records of each page', async () => {
|
|
98
|
+
const realFetch = globalThis.fetch;
|
|
99
|
+
globalThis.fetch = (async (input) => {
|
|
100
|
+
const url = String(input instanceof Request ? input.url : input);
|
|
101
|
+
if (url.endsWith('/api/sync/pull')) {
|
|
102
|
+
return Response.json({ status: 403, title: 'Forbidden' }, { status: 403 });
|
|
103
|
+
}
|
|
104
|
+
const page = Number(new URL(url).searchParams.get('page'));
|
|
105
|
+
const records = page === 1 ? [{ id: 'p1' }, { id: 'p2' }] : [{ id: 'p3' }];
|
|
106
|
+
return Response.json({ records, pagination: { total: 3, page, limit: 2, pages: 2 } });
|
|
107
|
+
});
|
|
108
|
+
try {
|
|
109
|
+
const { ZveltioClient } = await import('../client.js');
|
|
110
|
+
sync = new SyncManager(new ZveltioClient({ baseUrl: 'http://engine.test' }), {
|
|
111
|
+
syncInterval: 60_000,
|
|
112
|
+
});
|
|
113
|
+
await sync.start();
|
|
114
|
+
const store = sync.store;
|
|
115
|
+
await store.clear();
|
|
116
|
+
expect(await sync.pull(['posts'], 2)).toBe(3);
|
|
117
|
+
expect((await store.list('posts')).map((r) => r.id).sort()).toEqual(['p1', 'p2', 'p3']);
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
globalThis.fetch = realFetch;
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"today-in.test.d.ts","sourceRoot":"","sources":["../../src/tests/today-in.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { todayIn } from '../extension/dates.js';
|
|
3
|
+
describe('todayIn', () => {
|
|
4
|
+
// 22:30 UTC on the 18th is already the 19th in Bucharest (UTC+3 in October).
|
|
5
|
+
const lateUtc = new Date('2026-10-18T22:30:00Z');
|
|
6
|
+
it('is the tenant’s date, not the UTC one, across midnight', () => {
|
|
7
|
+
expect(todayIn('Europe/Bucharest', lateUtc)).toBe('2026-10-19');
|
|
8
|
+
expect(todayIn('UTC', lateUtc)).toBe('2026-10-18');
|
|
9
|
+
expect(todayIn('America/New_York', new Date('2026-10-19T02:00:00Z'))).toBe('2026-10-18');
|
|
10
|
+
});
|
|
11
|
+
it('formats as ISO YYYY-MM-DD', () => {
|
|
12
|
+
expect(todayIn('UTC', new Date('2026-01-05T12:00:00Z'))).toBe('2026-01-05');
|
|
13
|
+
});
|
|
14
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validate-manifest-actions.test.d.ts","sourceRoot":"","sources":["../../src/tests/validate-manifest-actions.test.ts"],"names":[],"mappings":""}
|