@syncular/client-react 0.0.1-60

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.
@@ -0,0 +1,550 @@
1
+ /**
2
+ * Integration test setup for @syncular/client-react
3
+ *
4
+ * Provides utilities for creating test clients and servers for integration testing.
5
+ * Based on the e2e test-utils pattern.
6
+ */
7
+
8
+ import type {
9
+ SyncClientDb,
10
+ SyncClientPlugin,
11
+ SyncTransport,
12
+ } from '@syncular/client';
13
+ import {
14
+ ClientTableRegistry,
15
+ ensureClientSyncSchema,
16
+ SyncEngine,
17
+ type SyncEngineConfig,
18
+ } from '@syncular/client';
19
+ import type { SyncOperation } from '@syncular/core';
20
+ import { createBunSqliteDb } from '@syncular/dialect-bun-sqlite';
21
+ import { createPgliteDb } from '@syncular/dialect-pglite';
22
+ import {
23
+ type ApplyOperationResult,
24
+ type EmittedChange,
25
+ ensureSyncSchema,
26
+ pull,
27
+ pushCommit,
28
+ recordClientCursor,
29
+ type ServerSyncDialect,
30
+ type ServerTableHandler,
31
+ type SyncCoreDb,
32
+ TableRegistry,
33
+ } from '@syncular/server';
34
+ import { createPostgresServerDialect } from '@syncular/server-dialect-postgres';
35
+ import { type Kysely, sql } from 'kysely';
36
+
37
+ function isRecord(value: unknown): value is Record<string, unknown> {
38
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
39
+ }
40
+
41
+ /**
42
+ * Server database schema for tests
43
+ */
44
+ interface ServerDb extends SyncCoreDb {
45
+ tasks: {
46
+ id: string;
47
+ title: string;
48
+ completed: number;
49
+ user_id: string;
50
+ server_version: number;
51
+ };
52
+ }
53
+
54
+ /**
55
+ * Client database schema for tests (extends SyncClientDb to include sync tables)
56
+ */
57
+ interface ClientDb extends SyncClientDb {
58
+ tasks: {
59
+ id: string;
60
+ title: string;
61
+ completed: number;
62
+ user_id: string;
63
+ server_version: number;
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Test server instance
69
+ */
70
+ export interface TestServer {
71
+ /** Full database instance with app tables (also includes sync tables) */
72
+ db: Kysely<ServerDb>;
73
+ dialect: ServerSyncDialect;
74
+ shapes: TableRegistry<ServerDb>;
75
+ }
76
+
77
+ /**
78
+ * Test client instance
79
+ */
80
+ export interface TestClient {
81
+ /** Full database instance with app tables (also includes sync tables) */
82
+ db: Kysely<ClientDb>;
83
+ engine: SyncEngine<ClientDb>;
84
+ transport: SyncTransport;
85
+ /** Client shapes registry */
86
+ shapes: ClientTableRegistry<ClientDb>;
87
+ }
88
+
89
+ /**
90
+ * Server-side tasks shape handler for tests
91
+ */
92
+ const tasksServerShape: ServerTableHandler<ServerDb> = {
93
+ table: 'tasks',
94
+ scopePatterns: ['user:{user_id}'],
95
+
96
+ async resolveScopes(ctx) {
97
+ return { user_id: ctx.actorId };
98
+ },
99
+
100
+ extractScopes(row: Record<string, unknown>) {
101
+ return { user_id: String(row.user_id ?? '') };
102
+ },
103
+
104
+ async snapshot(ctx): Promise<{ rows: unknown[]; nextCursor: string | null }> {
105
+ const userIdValue = ctx.scopeValues.user_id;
106
+ const userId = Array.isArray(userIdValue) ? userIdValue[0] : userIdValue;
107
+ if (!userId || userId !== ctx.actorId)
108
+ return { rows: [], nextCursor: null };
109
+
110
+ const pageSize = Math.max(1, Math.min(10_000, ctx.limit));
111
+ const cursor = ctx.cursor;
112
+
113
+ const cursorFilter =
114
+ cursor && cursor.length > 0
115
+ ? sql`and ${sql.ref('id')} > ${sql.val(cursor)}`
116
+ : sql``;
117
+
118
+ const result = await sql<{
119
+ id: string;
120
+ title: string;
121
+ completed: number;
122
+ user_id: string;
123
+ server_version: number;
124
+ }>`
125
+ select
126
+ ${sql.ref('id')},
127
+ ${sql.ref('title')},
128
+ ${sql.ref('completed')},
129
+ ${sql.ref('user_id')},
130
+ ${sql.ref('server_version')}
131
+ from ${sql.table('tasks')}
132
+ where ${sql.ref('user_id')} = ${sql.val(userId)}
133
+ ${cursorFilter}
134
+ order by ${sql.ref('id')} asc
135
+ limit ${sql.val(pageSize + 1)}
136
+ `.execute(ctx.db);
137
+
138
+ const rows = result.rows;
139
+
140
+ const hasMore = rows.length > pageSize;
141
+ const pageRows = hasMore ? rows.slice(0, pageSize) : rows;
142
+ const nextCursor = hasMore
143
+ ? (pageRows[pageRows.length - 1]?.id ?? null)
144
+ : null;
145
+
146
+ return {
147
+ rows: pageRows,
148
+ nextCursor:
149
+ typeof nextCursor === 'string' && nextCursor.length > 0
150
+ ? nextCursor
151
+ : null,
152
+ };
153
+ },
154
+
155
+ async applyOperation(
156
+ ctx,
157
+ op: SyncOperation,
158
+ opIndex: number
159
+ ): Promise<ApplyOperationResult> {
160
+ if (op.table !== 'tasks') {
161
+ return {
162
+ result: {
163
+ opIndex,
164
+ status: 'error',
165
+ error: `UNKNOWN_TABLE:${op.table}`,
166
+ code: 'UNKNOWN_TABLE',
167
+ retriable: false,
168
+ },
169
+ emittedChanges: [],
170
+ };
171
+ }
172
+
173
+ if (op.op === 'delete') {
174
+ const existingResult = await sql<{ id: string }>`
175
+ select ${sql.ref('id')}
176
+ from ${sql.table('tasks')}
177
+ where ${sql.ref('id')} = ${sql.val(op.row_id)}
178
+ and ${sql.ref('user_id')} = ${sql.val(ctx.actorId)}
179
+ limit ${sql.val(1)}
180
+ `.execute(ctx.trx);
181
+ const existing = existingResult.rows[0];
182
+
183
+ if (!existing) {
184
+ return { result: { opIndex, status: 'applied' }, emittedChanges: [] };
185
+ }
186
+
187
+ await sql`
188
+ delete from ${sql.table('tasks')}
189
+ where ${sql.ref('id')} = ${sql.val(op.row_id)}
190
+ and ${sql.ref('user_id')} = ${sql.val(ctx.actorId)}
191
+ `.execute(ctx.trx);
192
+
193
+ const emitted: EmittedChange = {
194
+ table: 'tasks',
195
+ row_id: op.row_id,
196
+ op: 'delete',
197
+ row_json: null,
198
+ row_version: null,
199
+ scopes: { user_id: ctx.actorId },
200
+ };
201
+
202
+ return {
203
+ result: { opIndex, status: 'applied' },
204
+ emittedChanges: [emitted],
205
+ };
206
+ }
207
+
208
+ const payload = isRecord(op.payload) ? op.payload : {};
209
+ const nextTitle =
210
+ typeof payload.title === 'string' ? payload.title : undefined;
211
+ const nextCompleted =
212
+ typeof payload.completed === 'number' ? payload.completed : undefined;
213
+
214
+ const existingResult = await sql<{
215
+ id: string;
216
+ title: string;
217
+ completed: number;
218
+ server_version: number;
219
+ }>`
220
+ select
221
+ ${sql.ref('id')},
222
+ ${sql.ref('title')},
223
+ ${sql.ref('completed')},
224
+ ${sql.ref('server_version')}
225
+ from ${sql.table('tasks')}
226
+ where ${sql.ref('id')} = ${sql.val(op.row_id)}
227
+ and ${sql.ref('user_id')} = ${sql.val(ctx.actorId)}
228
+ limit ${sql.val(1)}
229
+ `.execute(ctx.trx);
230
+ const existing = existingResult.rows[0];
231
+
232
+ if (
233
+ existing &&
234
+ op.base_version != null &&
235
+ existing.server_version !== op.base_version
236
+ ) {
237
+ return {
238
+ result: {
239
+ opIndex,
240
+ status: 'conflict',
241
+ message: `Version conflict: server=${existing.server_version}, base=${op.base_version}`,
242
+ server_version: existing.server_version,
243
+ server_row: {
244
+ id: existing.id,
245
+ title: existing.title,
246
+ completed: existing.completed,
247
+ user_id: ctx.actorId,
248
+ server_version: existing.server_version,
249
+ },
250
+ },
251
+ emittedChanges: [],
252
+ };
253
+ }
254
+
255
+ if (existing) {
256
+ const nextVersion = existing.server_version + 1;
257
+ await sql`
258
+ update ${sql.table('tasks')}
259
+ set
260
+ ${sql.ref('title')} = ${sql.val(nextTitle ?? existing.title)},
261
+ ${sql.ref('completed')} = ${sql.val(nextCompleted ?? existing.completed)},
262
+ ${sql.ref('server_version')} = ${sql.val(nextVersion)}
263
+ where ${sql.ref('id')} = ${sql.val(op.row_id)}
264
+ and ${sql.ref('user_id')} = ${sql.val(ctx.actorId)}
265
+ `.execute(ctx.trx);
266
+ } else {
267
+ await sql`
268
+ insert into ${sql.table('tasks')} (
269
+ ${sql.join([
270
+ sql.ref('id'),
271
+ sql.ref('title'),
272
+ sql.ref('completed'),
273
+ sql.ref('user_id'),
274
+ sql.ref('server_version'),
275
+ ])}
276
+ ) values (
277
+ ${sql.join([
278
+ sql.val(op.row_id),
279
+ sql.val(nextTitle ?? ''),
280
+ sql.val(nextCompleted ?? 0),
281
+ sql.val(ctx.actorId),
282
+ sql.val(1),
283
+ ])}
284
+ )
285
+ `.execute(ctx.trx);
286
+ }
287
+
288
+ const updatedResult = await sql<{
289
+ id: string;
290
+ title: string;
291
+ completed: number;
292
+ user_id: string;
293
+ server_version: number;
294
+ }>`
295
+ select
296
+ ${sql.ref('id')},
297
+ ${sql.ref('title')},
298
+ ${sql.ref('completed')},
299
+ ${sql.ref('user_id')},
300
+ ${sql.ref('server_version')}
301
+ from ${sql.table('tasks')}
302
+ where ${sql.ref('id')} = ${sql.val(op.row_id)}
303
+ and ${sql.ref('user_id')} = ${sql.val(ctx.actorId)}
304
+ limit ${sql.val(1)}
305
+ `.execute(ctx.trx);
306
+ const updated = updatedResult.rows[0];
307
+ if (!updated) {
308
+ throw new Error(`Failed to read updated task ${op.row_id}`);
309
+ }
310
+
311
+ const emitted: EmittedChange = {
312
+ table: 'tasks',
313
+ row_id: op.row_id,
314
+ op: 'upsert',
315
+ row_json: updated,
316
+ row_version: updated.server_version,
317
+ scopes: { user_id: ctx.actorId },
318
+ };
319
+
320
+ return {
321
+ result: { opIndex, status: 'applied' },
322
+ emittedChanges: [emitted],
323
+ };
324
+ },
325
+ };
326
+
327
+ /**
328
+ * Create an in-memory test server with PGlite
329
+ */
330
+ export async function createTestServer(): Promise<TestServer> {
331
+ const db = createPgliteDb<ServerDb>();
332
+ const dialect = createPostgresServerDialect();
333
+
334
+ await ensureSyncSchema(db, dialect);
335
+
336
+ // Create tasks table
337
+ await db.schema
338
+ .createTable('tasks')
339
+ .ifNotExists()
340
+ .addColumn('id', 'text', (col) => col.primaryKey())
341
+ .addColumn('title', 'text', (col) => col.notNull())
342
+ .addColumn('completed', 'integer', (col) => col.notNull().defaultTo(0))
343
+ .addColumn('user_id', 'text', (col) => col.notNull())
344
+ .addColumn('server_version', 'integer', (col) => col.notNull().defaultTo(1))
345
+ .execute();
346
+
347
+ // Register shapes
348
+ const shapes = new TableRegistry<ServerDb>();
349
+ shapes.register(tasksServerShape);
350
+
351
+ return {
352
+ db,
353
+ dialect,
354
+ shapes,
355
+ };
356
+ }
357
+
358
+ /**
359
+ * Create an in-process transport that calls server functions directly
360
+ */
361
+ function createInProcessTransport(
362
+ server: TestServer,
363
+ actorId: string
364
+ ): SyncTransport {
365
+ const syncDb = server.db;
366
+
367
+ return {
368
+ async sync(request) {
369
+ const result: { ok: true; push?: any; pull?: any } = { ok: true };
370
+
371
+ if (request.push) {
372
+ const pushed = await pushCommit({
373
+ db: syncDb,
374
+ dialect: server.dialect,
375
+ shapes: server.shapes,
376
+ actorId,
377
+ request: {
378
+ clientId: request.clientId,
379
+ clientCommitId: request.push.clientCommitId,
380
+ operations: request.push.operations,
381
+ schemaVersion: request.push.schemaVersion,
382
+ },
383
+ });
384
+ result.push = pushed.response;
385
+ }
386
+
387
+ if (request.pull) {
388
+ const pulled = await pull({
389
+ db: syncDb,
390
+ dialect: server.dialect,
391
+ shapes: server.shapes,
392
+ actorId,
393
+ request: {
394
+ clientId: request.clientId,
395
+ ...request.pull,
396
+ },
397
+ });
398
+
399
+ recordClientCursor(syncDb, server.dialect, {
400
+ clientId: request.clientId,
401
+ actorId,
402
+ cursor: pulled.clientCursor,
403
+ effectiveScopes: pulled.effectiveScopes,
404
+ }).catch(() => {});
405
+
406
+ result.pull = pulled.response;
407
+ }
408
+
409
+ return result;
410
+ },
411
+
412
+ async fetchSnapshotChunk() {
413
+ return new Uint8Array();
414
+ },
415
+ };
416
+ }
417
+
418
+ /**
419
+ * Create an in-memory test client with SQLite
420
+ */
421
+ export async function createTestClient(
422
+ server: TestServer,
423
+ options: {
424
+ actorId: string;
425
+ clientId: string;
426
+ plugins?: SyncClientPlugin[];
427
+ }
428
+ ): Promise<TestClient> {
429
+ const db = createBunSqliteDb<ClientDb>({ path: ':memory:' });
430
+
431
+ await ensureClientSyncSchema(db);
432
+
433
+ // Create tasks table
434
+ await db.schema
435
+ .createTable('tasks')
436
+ .ifNotExists()
437
+ .addColumn('id', 'text', (col) => col.primaryKey())
438
+ .addColumn('title', 'text', (col) => col.notNull())
439
+ .addColumn('completed', 'integer', (col) => col.notNull().defaultTo(0))
440
+ .addColumn('user_id', 'text', (col) => col.notNull())
441
+ .addColumn('server_version', 'integer', (col) => col.notNull().defaultTo(0))
442
+ .execute();
443
+
444
+ // Create client shapes registry
445
+ const shapes = new ClientTableRegistry<ClientDb>();
446
+ shapes.register({
447
+ table: 'tasks',
448
+
449
+ async applySnapshot(ctx, snapshot) {
450
+ if (snapshot.isFirstPage) {
451
+ await ctx.trx.deleteFrom('tasks').execute();
452
+ }
453
+
454
+ const rows = (snapshot.rows ?? []).filter(isRecord).map((row) => ({
455
+ id: typeof row.id === 'string' ? row.id : '',
456
+ title: typeof row.title === 'string' ? row.title : '',
457
+ completed: typeof row.completed === 'number' ? row.completed : 0,
458
+ user_id: typeof row.user_id === 'string' ? row.user_id : '',
459
+ server_version:
460
+ typeof row.server_version === 'number' ? row.server_version : 0,
461
+ }));
462
+ if (rows.length === 0) return;
463
+
464
+ await ctx.trx
465
+ .insertInto('tasks')
466
+ .values(rows)
467
+ .onConflict((oc) =>
468
+ oc.column('id').doUpdateSet({
469
+ title: (eb) => eb.ref('excluded.title'),
470
+ completed: (eb) => eb.ref('excluded.completed'),
471
+ user_id: (eb) => eb.ref('excluded.user_id'),
472
+ server_version: (eb) => eb.ref('excluded.server_version'),
473
+ })
474
+ )
475
+ .execute();
476
+ },
477
+
478
+ async clearAll(ctx) {
479
+ await ctx.trx.deleteFrom('tasks').execute();
480
+ },
481
+
482
+ async applyChange(ctx, change) {
483
+ if (change.op === 'delete') {
484
+ await ctx.trx
485
+ .deleteFrom('tasks')
486
+ .where('id', '=', change.row_id)
487
+ .execute();
488
+ return;
489
+ }
490
+
491
+ const row = isRecord(change.row_json) ? change.row_json : {};
492
+ const title = typeof row.title === 'string' ? row.title : '';
493
+ const completed = typeof row.completed === 'number' ? row.completed : 0;
494
+ const userId = typeof row.user_id === 'string' ? row.user_id : '';
495
+ const baseVersion =
496
+ typeof row.server_version === 'number' ? row.server_version : 0;
497
+
498
+ await ctx.trx
499
+ .insertInto('tasks')
500
+ .values({
501
+ id: change.row_id,
502
+ title,
503
+ completed,
504
+ user_id: userId,
505
+ server_version: change.row_version ?? baseVersion,
506
+ })
507
+ .onConflict((oc) =>
508
+ oc.column('id').doUpdateSet({
509
+ title: (eb) => eb.ref('excluded.title'),
510
+ completed: (eb) => eb.ref('excluded.completed'),
511
+ user_id: (eb) => eb.ref('excluded.user_id'),
512
+ server_version: (eb) => eb.ref('excluded.server_version'),
513
+ })
514
+ )
515
+ .execute();
516
+ },
517
+ });
518
+
519
+ const transport = createInProcessTransport(server, options.actorId);
520
+
521
+ const config: SyncEngineConfig<ClientDb> = {
522
+ db,
523
+ transport,
524
+ shapes,
525
+ actorId: options.actorId,
526
+ clientId: options.clientId,
527
+ subscriptions: [
528
+ { id: 'my-tasks', shape: 'tasks', scopes: { user_id: options.actorId } },
529
+ ],
530
+ pollIntervalMs: 999999, // Disable polling for tests
531
+ realtimeEnabled: false,
532
+ plugins: options.plugins,
533
+ };
534
+
535
+ const engine = new SyncEngine<ClientDb>(config);
536
+
537
+ return { db, engine, transport, shapes };
538
+ }
539
+
540
+ /**
541
+ * Destroy test resources
542
+ */
543
+ export async function destroyTestClient(client: TestClient): Promise<void> {
544
+ client.engine.destroy();
545
+ await client.db.destroy();
546
+ }
547
+
548
+ export async function destroyTestServer(server: TestServer): Promise<void> {
549
+ await server.db.destroy();
550
+ }