import { createHash } from 'node:crypto'; import { describe, expect, it, vi } from 'vitest'; import { Doc0UploadClient } from '../../src/document-workbench/doc0-upload-client'; const bytes = new TextEncoder().encode('source bytes'); const input = { tenantId: 'tenant-a', projectId: 'project-a', actorId: 'user-a', requestId: 'req-a', idempotencyKey: 'idem-a', filename: 'test.txt', mimeType: 'text/plain', classification: 'confidential' as const, bytes, }; const receipt = { document: { documentId: 'doc-a', tenantId: 'tenant-a', projectId: 'project-a', currentVersionId: 'v1' }, currentVersion: { versionId: 'v1', tenantId: 'tenant-a', documentId: 'doc-a', checksumSha256: createHash('sha256').update(bytes).digest('hex'), sizeBytes: bytes.length, pipelineStage: 'parsed', }, }; describe('DOC0 upload client', () => { it('sends real bytes and validates a tenant-scoped checksum-bound receipt', async () => { const fetchImpl = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => { expect(new Headers(init?.headers).get('x-tenant-id')).toBe('tenant-a'); expect(new Headers(init?.headers).get('x-idempotency-key')).toBe('idem-a'); const form = init?.body as FormData; expect(await (form.get('file') as Blob).text()).toBe('source bytes'); return new Response(JSON.stringify(receipt), { status: 201 }); }); const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl: fetchImpl as typeof fetch, }); expect(await client.upload(input)).toMatchObject({ documentId: 'doc-a', versionId: 'v1', pipelineStage: 'parsed', }); }); it.each([ { document: { ...receipt.document, tenantId: 'tenant-b' } }, { document: { ...receipt.document, projectId: 'other' } }, { currentVersion: { ...receipt.currentVersion, checksumSha256: 'bad' } }, { currentVersion: { ...receipt.currentVersion, documentId: 'other' } }, ])('rejects an incorrect receipt', async (change) => { const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl: async () => new Response(JSON.stringify({ ...receipt, ...change }), { status: 201 }), }); await expect(client.upload(input)).rejects.toThrow(/receipt/); }); it('rejects empty or oversized inputs before calling DOC0', async () => { const fetchImpl = vi.fn(); const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 2, fetchImpl, }); await expect(client.upload(input)).rejects.toThrow(/Invalid/); await expect(client.upload({ ...input, bytes: new Uint8Array() })).rejects.toThrow(/Invalid/); expect(fetchImpl).not.toHaveBeenCalled(); }); });