import request from 'supertest'; import type { TestContext } from './helpers'; import { closeTestApp, createTestApp } from './helpers'; // The sync log: opaque update payloads per doc, ordered by a per-doc cursor. describe('Sync log', () => { let ctx: TestContext; let http: ReturnType; beforeAll(async () => { ctx = await createTestApp(); http = request(ctx.app.getHttpServer()); }); afterAll(() => closeTestApp(ctx)); it('starts empty', async () => { const res = await http.get('/api/sync/manifest').expect(200); expect(res.body.docs).toEqual([]); }); it('appends updates and pulls them back by cursor', async () => { const push1 = await http .post('/api/sync/updates') .send({ doc_id: 'workspace', device_id: 'dev-a', updates: ['AAECAw==', 'BAUGBw=='] }) .expect(201); expect(push1.body.latest_seq).toBe(2); const all = await http.get('/api/sync/updates?doc_id=workspace&after_seq=0').expect(200); expect(all.body.updates.map((u: { seq: number }) => u.seq)).toEqual([1, 2]); expect(all.body.updates[0].payload).toBe('AAECAw=='); expect(all.body.latest_seq).toBe(2); const tail = await http.get('/api/sync/updates?doc_id=workspace&after_seq=1').expect(200); expect(tail.body.updates.map((u: { seq: number }) => u.seq)).toEqual([2]); const none = await http.get('/api/sync/updates?doc_id=workspace&after_seq=2').expect(200); expect(none.body.updates).toEqual([]); expect(none.body.latest_seq).toBe(2); }); it('keeps per-doc cursors independent and lists both in the manifest', async () => { const ann = 'ann:11111111-1111-4111-8111-111111111111'; await http .post('/api/sync/updates') .send({ doc_id: ann, updates: ['CAgI'] }) .expect(201); const manifest = await http.get('/api/sync/manifest').expect(200); const byDoc = Object.fromEntries( manifest.body.docs.map((d: { doc_id: string; latest_seq: number }) => [ d.doc_id, d.latest_seq, ]), ); expect(byDoc.workspace).toBe(2); expect(byDoc[ann]).toBe(1); }); it('seq keeps growing across pushes', async () => { const push = await http .post('/api/sync/updates') .send({ doc_id: 'workspace', updates: ['CQk='] }) .expect(201); expect(push.body.latest_seq).toBe(3); }); it('rejects unknown doc ids and malformed payloads', async () => { await http .post('/api/sync/updates') .send({ doc_id: '../etc', updates: ['AA=='] }) .expect(400); await http .post('/api/sync/updates') .send({ doc_id: 'workspace', updates: [''] }) .expect(400); await http.get('/api/sync/updates?doc_id=bogus').expect(400); }); });