import { iconRect } from './creatables'; import type { ConformanceTestRunner, ConformanceOptions } from './runMetadataConformance'; import type { FileAttachmentAnnotation, TextAnnotation } from '../annotation/kinds'; import type { DocumentHandle } from '../engine/DocumentHandle'; import type { Engine } from '../engine/Engine'; import { toAttachmentRef } from '../dto/Attachment'; import { EngineError } from '../errors/EngineError'; import { EngineErrorCode } from '../errors/EngineErrorCode'; import { deletedAttachmentOf } from '../mutation/AttachmentMutationResults'; import { AttachmentCreateResultSchema, AttachmentListSchema } from '../wire/schemas'; import type { PageObjectNumber } from '../identity/PageObjectNumber'; import { toPageRef } from '../identity/PageRef'; import { EVERY_PERMISSION } from './fixtureScope'; /** * Attachment conformance suite. Fixture requirement: a document whose * `/EmbeddedFiles` name tree contains at least one embedded file. * * Both homes of a file: `doc.attachments` (the `/EmbeddedFiles` name tree) * and a file-attachment annotation's `file` resource * (`page.annotations.downloadResource(ref, 'file')`). Both downloads answer * the bytes; the name and type are what the listing says. * * Invariants: * 1. `list()` reflects the name tree: positional indices, non-empty * names, and repeated calls agree (a read). * 2. `download(ref)` returns exactly `size` decoded bytes when the * fixture declares one. * 3. Unknown keys reject with an `EngineError`. * 4. A created file-attachment annotation round-trips its file: * metadata inline on the DTO (never bytes), bytes byte-identical * as its `file` resource. * 5. A created text (sticky-note) annotation round-trips icon + color. */ export function runAttachmentConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void { const { describe, test, beforeAll, afterAll, expect } = runner; describe(`attachment conformance: ${options.label}`, () => { let engine: Engine; let firstPageObjectNumber: PageObjectNumber; beforeAll(async () => { engine = await options.makeEngine(); const probe = await openFixture(engine, options); const pages = await probe.pages.list(); firstPageObjectNumber = pages.pages[0].ref.objectNumber; await probe.close(); }); afterAll(async () => { if (engine) await engine.destroy(); }); test('attachments.list() reflects the /EmbeddedFiles name tree and is a stable read', async () => { const doc = await openFixture(engine, options); try { const list = await doc.attachments.list(); expect(AttachmentListSchema.safeParse(list).success).toBe(true); const items = list.attachments; expect(items.length > 0).toBe(true); items.forEach((item, position) => { expect(item.index).toBe(position); expect(item.ref.key.length > 0).toBe(true); expect(item.name.length > 0).toBe(true); }); // Keys are unique by construction — they are the durable refs. expect(new Set(items.map((i) => i.ref.key)).size).toBe(items.length); // A read: calling again observes the identical snapshot. expect(await doc.attachments.list()).toEqual(list); } finally { await doc.close(); } }); test('attachments.download() returns the listed decoded size', async () => { const doc = await openFixture(engine, options); try { const { attachments } = await doc.attachments.list(); for (const item of attachments) { const bytes = await doc.attachments.download(item.ref); expect(bytes).toBeInstanceOf(Uint8Array); if (item.sizeBytes !== null) { expect(bytes.length).toBe(item.sizeBytes); } } } finally { await doc.close(); } }); test('attachments.download() rejects an unknown key', async () => { const doc = await openFixture(engine, options); try { await expect( doc.attachments.download(toAttachmentRef('conformance-no-such-key.bin')), ).rejects.toBeInstanceOf(EngineError); } finally { await doc.close(); } }); test('a File brings its name and type, and a file without a type has none', async () => { const doc = await openFixture(engine, options); try { const picked = new File([new Uint8Array([1, 2, 3])], '0-picked.csv', { type: 'text/csv' }); const { attachment: fromFile } = await doc.attachments.create({ data: picked }); expect(fromFile.name).toBe('0-picked.csv'); expect(fromFile.mimeType).toBe('text/csv'); // Bytes with no type: the engine doesn't guess one. const { attachment: untyped } = await doc.attachments.create({ data: new Uint8Array([4, 5, 6]), name: '0-untyped.bin', }); expect(untyped.mimeType).toBe(null); const listed = (await doc.attachments.list()).attachments; expect(listed.find((item) => item.ref.key === '0-untyped.bin')?.mimeType).toBe(null); expect(listed.find((item) => item.ref.key === '0-picked.csv')?.mimeType).toBe('text/csv'); // Bare bytes need a name. await expect(doc.attachments.create({ data: new Uint8Array([7]) })).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, }); } finally { await doc.close(); } }); test('create() and delete() round-trip the name tree; keys survive index shifts', async () => { const doc = await openFixture(engine, options); try { const { attachments: before } = await doc.attachments.list(); const data = new Uint8Array(512); for (let i = 0; i < data.length; i++) data[i] = (i * 7 + 3) & 0xff; // "0-…" sorts before the fixture's entries, shifting their indices — // the sharpest difference from append-only annotation creates. const createdResult = await doc.attachments.create({ data: data.buffer, name: '0-conformance.bin', mimeType: 'application/octet-stream', description: 'added by conformance', }); expect(AttachmentCreateResultSchema.safeParse(createdResult).success).toBe(true); const created = createdResult.attachment; expect(created.ref).toEqual(toAttachmentRef('0-conformance.bin')); expect(createdResult.meta.changedRefs).toEqual([created.ref]); expect(created.name).toBe('0-conformance.bin'); expect(created.mimeType).toBe('application/octet-stream'); expect(created.description).toBe('added by conformance'); expect(created.sizeBytes).toBe(data.length); const { attachments: after } = await doc.attachments.list(); expect(after.length).toBe(before.length + 1); // Pre-existing keys still resolve even though their indices shifted. for (const item of before) { const match = after.find((i) => i.ref.key === item.ref.key); expect(match !== undefined).toBe(true); } // Duplicate keys reject — keys are the identity. await expect( doc.attachments.create({ data, name: '0-conformance.bin' }), ).rejects.toBeInstanceOf(EngineError); // The created file round-trips byte-identically. const bytes = await doc.attachments.download(created.ref); expect(bytes.length).toBe(data.length); expect(bytes.every((byte, i) => byte === data[i])).toBe(true); // Delete by ref; the ref stops resolving and the rest are intact. const removed = await doc.attachments.delete(created.ref); expect(Object.keys(removed)).toEqual(['meta']); expect(deletedAttachmentOf(removed)).toEqual(created.ref); const { attachments: final } = await doc.attachments.list(); expect(final.map((i) => i.ref)).toEqual(before.map((i) => i.ref)); await expect(doc.attachments.delete(created.ref)).rejects.toBeInstanceOf(EngineError); } finally { await doc.close(); } }); test('a file-attachment annotation takes a File as it is, and never guesses a type', async () => { const doc = await openFixture(engine, options); try { const annotations = doc.page(toPageRef(firstPageObjectNumber)).annotations; const rect = { x: 80, y: 40, width: 20, height: 20 }; const picked = new File([new Uint8Array([1, 2, 3])], 'figures.csv', { type: 'text/csv' }); const { annotation: fromFile } = await annotations.create( { subtype: 'file-attachment', rect: iconRect(rect.x, rect.y) }, { resources: { file: picked } }, ); const file = (fromFile as FileAttachmentAnnotation).file!; expect(file.name).toBe('figures.csv'); expect(file.mimeType).toBe('text/csv'); const { annotation: untyped } = await annotations.create( { subtype: 'file-attachment', rect: iconRect(rect.x, rect.y), file: { name: 'raw.bin' }, }, { resources: { file: new Uint8Array([4, 5]) } }, ); expect((untyped as FileAttachmentAnnotation).file!.mimeType).toBe(null); // Bare bytes need a name. await expect( annotations.create( { subtype: 'file-attachment', rect: iconRect(rect.x, rect.y) }, { resources: { file: new Uint8Array([6]) } }, ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details: { field: 'file.name' }, }); } finally { await doc.close(); } }); test('a created file-attachment annotation round-trips its file as its file resource', async () => { const doc = await openFixture(engine, options); try { const annotations = doc.page(toPageRef(firstPageObjectNumber)).annotations; const data = new Uint8Array(2048); for (let i = 0; i < data.length; i++) data[i] = (i * 31 + 7) & 0xff; const { annotation: created } = await annotations.create( { subtype: 'file-attachment', rect: iconRect(40, 60), file: { name: 'conformance.bin', mimeType: 'application/octet-stream', description: 'attachment conformance payload', }, icon: 'paperclip', color: '#dc2626', contents: 'conformance attachment', }, { resources: { file: data } }, ); // Metadata rides the DTO; bytes never do. const dto = created as FileAttachmentAnnotation; expect(dto.subtype).toBe('file-attachment'); expect(dto.icon).toBe('paperclip'); expect(dto.color).toEqual('#dc2626'); const file = dto.file!; expect(file.name).toBe('conformance.bin'); expect(file.mimeType).toBe('application/octet-stream'); expect(file.description).toBe('attachment conformance payload'); expect(file.sizeBytes).toBe(data.length); // Bytes come back byte-identical as the `file` resource. const bytes = await annotations.downloadResource(dto.ref, 'file'); expect(bytes.length).toBe(data.length); expect(Array.from(bytes.slice(0, 16))).toEqual(Array.from(data.slice(0, 16))); expect(bytes.every((byte, i) => byte === data[i])).toBe(true); // A read goes back in: into a create (its name left out, so the copy // on the same page gets a fresh one), with the bytes it downloaded, // and into an update that sends its file back unchanged. const { nm: _name, ...unnamed } = dto; const { annotation: copy } = await annotations.create(unnamed, { resources: { file: bytes }, }); expect((copy as FileAttachmentAnnotation).file).toMatchObject({ name: 'conformance.bin', mimeType: 'application/octet-stream', description: 'attachment conformance payload', sizeBytes: data.length, }); const { annotation: updated } = await annotations.update(dto.ref, { ...dto, contents: 'changed', }); expect((updated as FileAttachmentAnnotation).file?.name).toBe('conformance.bin'); expect(updated.contents).toBe('changed'); } finally { await doc.close(); } }); test('a created text annotation round-trips icon, color, and contents', async () => { const doc = await openFixture(engine, options); try { const annotations = doc.page(toPageRef(firstPageObjectNumber)).annotations; const { annotation: created } = await annotations.create({ subtype: 'text', rect: iconRect(100, 120), icon: 'comment', color: '#facc15', contents: 'conformance note', }); const dto = created as TextAnnotation; expect(dto.subtype).toBe('text'); expect(dto.icon).toBe('comment'); expect(dto.color).toEqual('#facc15'); expect(dto.contents).toBe('conformance note'); // Icon is patchable; the file half of an attachment is not, and // the same presentation-only patch path applies to notes. const { annotation: updated } = await annotations.update(dto.ref, { subtype: 'text', icon: 'help', }); expect((updated as TextAnnotation).icon).toBe('help'); } finally { await doc.close(); } }); }); async function openFixture(engine: Engine, options: ConformanceOptions): Promise { if (options.openKind === 'bytes') { return engine.open( { kind: 'bytes', id: options.fixture.id, bytes: await options.fixture.bytes(), }, EVERY_PERMISSION, ); } return engine.open({ kind: 'id', id: options.fixture.cloudId ?? options.fixture.id }); } }