/** * Whether a push button takes an image over the cloud engine, on the wire: * a real @cloudpdf/server with the native runtime behind the * `@cloudpdf/engine` client. What a create, an update and a change carry; * that a server older than the fact is never sent it, nor a bundle with an * image field; and that its push buttons still read whole. */ import { afterAll, beforeAll, describe, expect, test } from 'vitest'; import { IMAGE_FIELD_PDF } from '@embedpdf/engine-core/conformance'; import { EngineError, EngineErrorCode, toPageRef, type DocumentHandle, type FormField, type FormFieldRef, } from '@embedpdf/engine-core/runtime'; import { BUTTON_IMAGE_AND_LAYOUT_SINCE } from '@embedpdf/engine-core/wire'; import { cloudEngine } from '../src/index'; import { bundleTakesImageTheServerLacks, fieldFactsTheServerLacks, } from '../src/document/fieldFacts'; import { buildDbSeededFixture, docScopedToken, seedDocument, teardownDbSeededFixture, type DbSeededFixture, } from './_helpers/db-seeded-app'; const TENANT_ID = 'cloud-image-field-wire-tenant'; const PAGE = toPageRef(3); const named = (name: string): FormFieldRef => ({ kind: 'fqn', name }); const factOf = (field: FormField) => (field.kind === 'pushbutton' ? field.takesImage : undefined); /** Older than this build (3.4) and than `takesImage` (3.5). */ const OLDER = '3.3'; let fx: DbSeededFixture | undefined; let docs = 0; beforeAll(async () => { fx = await buildDbSeededFixture({ secret: 'cloud-image-field-wire-secret' }); }); afterAll(async () => { await teardownDbSeededFixture(fx); }); /** One write as it went out: its method, the end of its route, and its JSON. */ interface SentWrite { method: string; route: string; body: unknown; } /** * `value` with every form field in it, at any depth, as an older server * answers it: without `takesImage`. A field is the object with a * `valueEntry`. */ function withoutTheFact(value: unknown): unknown { if (Array.isArray(value)) return value.map(withoutTheFact); if (typeof value !== 'object' || value === null) return value; const isField = 'valueEntry' in value; return Object.fromEntries( Object.entries(value) .filter(([key]) => !isField || key !== 'takesImage') .map(([key, member]) => [key, withoutTheFact(member)]), ); } /** * A fetch that records the writes of fields (a create, an update, an import, * a request of changes). With `version`, the server says it is that * version, and its JSON answers come without `takesImage`, as an older * server sends them. */ function recordingFetch(version?: string) { const sent: SentWrite[] = []; const fetchFn: typeof fetch = async (input, init) => { const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; const path = new URL(url).pathname; const method = init?.method ?? 'GET'; const route = ['/form/fields', '/form/import', '/changes'].find((part) => path.includes(part)); if (route && (method === 'POST' || method === 'PATCH')) { // An import's body is multipart: only that it went out is recorded. const body = typeof init?.body === 'string' ? JSON.parse(init.body) : null; sent.push({ method, route, body }); } const response = await fetch(input, init); if (version === undefined) return response; const headers = new Headers(response.headers); headers.set('EmbedPDF-Server-Version', version); const type = headers.get('content-type') ?? ''; if (type.includes('multipart/form-data')) { // An exported bundle: its `body` part holds the fields. const older = new FormData(); for (const [name, value] of (await response.formData()).entries()) { const stripped = name === 'body' && typeof value === 'string'; older.append(name, stripped ? JSON.stringify(withoutTheFact(JSON.parse(value))) : value); } headers.delete('content-type'); headers.delete('content-length'); return new Response(older, { status: response.status, headers }); } if (!type.includes('application/json')) { return new Response(response.body, { status: response.status, headers }); } headers.delete('content-length'); const body = JSON.stringify(withoutTheFact(await response.json())); return new Response(body, { status: response.status, headers }); }; return { fetchFn, sent }; } async function open(fetchFn: typeof fetch): Promise { const docId = `cloud-image-field-${++docs}`; await seedDocument(fx!, TENANT_ID, docId, IMAGE_FIELD_PDF); const engine = cloudEngine({ baseUrl: fx!.baseUrl, fetch: fetchFn }); return engine.open({ kind: 'token', token: docScopedToken(fx!, TENANT_ID, docId) }); } const refusal = (attempt: Promise): Promise => attempt.then( () => null, (error: unknown) => error, ); describe('whether a push button takes an image, on the wire', () => { test('a create, an update and a change carry the fact as it is given, and no script', async () => { const { fetchFn, sent } = recordingFetch(); const doc = await open(fetchFn); try { const widgets = [ { page: PAGE, box: { x: 300, y: 40, width: 90, height: 30 }, layout: 'image' as const }, ]; const { field } = await doc.forms.create({ kind: 'pushbutton', name: 'made', takesImage: true, widgets, }); expect(sent.at(-1)).toMatchObject({ method: 'POST', route: '/form/fields', body: { kind: 'pushbutton', name: 'made', takesImage: true }, }); // The engine writes the script: the request names none. expect(JSON.stringify(sent.at(-1)!.body).includes('buttonImportIcon')).toBe(false); expect(factOf(field)).toBe(true); await doc.forms.update(field.ref, { takesImage: false }); expect(sent.at(-1)).toMatchObject({ method: 'PATCH', route: '/form/fields', body: { takesImage: false }, }); await doc.apply({ ops: [ { type: 'forms.update', field: field.ref, patch: { takesImage: true }, expect: { takesImage: false }, }, ], }); expect(sent.at(-1)).toMatchObject({ method: 'POST', route: '/changes', body: { changes: [ { ops: [ { type: 'forms.update', patch: { takesImage: true }, expect: { takesImage: false }, }, ], }, ], }, }); expect(factOf(await doc.forms.get(field.ref))).toBe(true); } finally { await doc.close(); } }); test('a server older than the fact is never sent it, and the refusal names both versions', async () => { // The packages still carry the version before the one it arrives in, and // a side of this build's own version is never read as lacking: an older one is. const { fetchFn, sent } = recordingFetch(OLDER); const doc = await open(fetchFn); try { const field = named('plain_button'); const made = { kind: 'pushbutton', name: 'made' } as const; const writes: (() => Promise)[] = [ () => doc.forms.create({ ...made, takesImage: true }), // `false` is a member such a server doesn't know either. () => doc.forms.create({ ...made, takesImage: false }), () => doc.forms.update(field, { takesImage: true }), () => doc.forms.update(field, { takesImage: false }), () => doc.apply({ ops: [{ type: 'forms.create', draft: { ...made, takesImage: true } }] }), () => doc.apply({ ops: [{ type: 'forms.update', field, patch: { takesImage: true } }] }), () => doc.apply({ ops: [ { type: 'forms.update', field, patch: { required: true }, expect: { takesImage: false }, }, ], }), () => doc.apply({ ops: [{ type: 'forms.delete', field, expect: { takesImage: false } }] }), ]; for (const [at, write] of writes.entries()) { const error = await refusal(write()); expect(EngineError.is(error) && error.code, `write ${at}`).toBe( EngineErrorCode.NotImplemented, ); expect((error as EngineError).details).toMatchObject({ field: 'takesImage', needs: BUTTON_IMAGE_AND_LAYOUT_SINCE, serverVersion: OLDER, }); expect((error as EngineError).message).toBe( `a field's takesImage needs a server of version ${BUTTON_IMAGE_AND_LAYOUT_SINCE}, ` + `and this server is ${OLDER}`, ); } expect(sent).toEqual([]); // A write that names none goes out as it always did. const { field: plain } = await doc.forms.create(made); await doc.forms.update(plain.ref, { required: true }); await doc.apply({ ops: [{ type: 'forms.update', field, patch: { required: true } }] }); expect(sent.map((write) => [write.method, write.route])).toEqual([ ['POST', '/form/fields'], ['PATCH', '/form/fields'], ['POST', '/changes'], ]); expect((await doc.forms.get(plain.ref)).required).toBe(true); // An import makes an image field too: such a server knows it only by its // scripts, so the bundle never goes out. const exported = await doc.forms.export({ fields: [named('plain_button')] }); const image = { ...exported, fields: exported.fields.map((row) => ({ ...row, data: { ...row.data, takesImage: true }, })), }; const before = sent.length; const refused = await refusal(doc.forms.import(image, { attribution: 'stamp' })); expect(EngineError.is(refused) && refused.code).toBe(EngineErrorCode.NotImplemented); expect((refused as EngineError).details).toMatchObject({ field: 'takesImage', needs: BUTTON_IMAGE_AND_LAYOUT_SINCE, serverVersion: OLDER, }); expect(sent).toHaveLength(before); // A bundle whose buttons take none goes out. await doc.forms.import(exported, { attribution: 'stamp' }); expect(sent.at(-1)).toMatchObject({ method: 'POST', route: '/form/import' }); } finally { await doc.close(); } }); test("an older server's push buttons read whole, and take no image", async () => { const { fetchFn } = recordingFetch(OLDER); const doc = await open(fetchFn); try { const { fields } = await doc.forms.list(); const buttons = fields.filter((field) => field.kind === 'pushbutton'); expect(buttons.length).toBeGreaterThan(10); // The script in the file is one such a server doesn't read as the fact. expect(buttons.map(factOf).every((fact) => fact === false)).toBe(true); expect('takesImage' in fields.find((field) => field.kind === 'text')!).toBe(false); expect(factOf(await doc.forms.get(named('Image10_af_image')))).toBe(false); // An answer to a write reads the same way. const { field } = await doc.forms.update(named('Image10_af_image'), { required: true }); expect([factOf(field), field.required]).toEqual([false, true]); // And so do the fields of a bundle it exports. const bundle = await doc.forms.export({ fields: [named('Image10_af_image')] }); expect(bundle.fields.map(({ data }) => [data.name, factOf(data)])).toEqual([ ['Image10_af_image', false], ]); } finally { await doc.close(); } }); }); describe('what a server lacks, asked before anything is sent', () => { const bundleOf = (...facts: unknown[]) => ({ fields: facts.map((takesImage) => ({ data: takesImage === undefined ? {} : { takesImage }, })), }); test('a write that names the fact needs a server of its version', () => { for (const write of [{ takesImage: true }, { takesImage: false }]) { // An older server lacks it; this build's own version, a newer one and one not yet known don't. expect(fieldFactsTheServerLacks(OLDER, write)?.details).toMatchObject({ field: 'takesImage', needs: BUTTON_IMAGE_AND_LAYOUT_SINCE, serverVersion: OLDER, }); for (const version of ['3.4', BUTTON_IMAGE_AND_LAYOUT_SINCE, '4.0', null]) { expect(fieldFactsTheServerLacks(version, write)).toBe(null); } } expect(fieldFactsTheServerLacks(OLDER, { required: true } as never, undefined)).toBe(null); // Any of the writes of a change counts. expect( fieldFactsTheServerLacks(OLDER, undefined, {}, { takesImage: true })?.details, ).toMatchObject({ field: 'takesImage' }); }); test('a bundle with an image field needs it too; one whose buttons take none goes out', () => { expect(bundleTakesImageTheServerLacks(OLDER, bundleOf(false, true))?.details).toMatchObject({ field: 'takesImage', needs: BUTTON_IMAGE_AND_LAYOUT_SINCE, serverVersion: OLDER, }); expect(bundleTakesImageTheServerLacks(OLDER, bundleOf(false, undefined))).toBe(null); expect(bundleTakesImageTheServerLacks(OLDER, bundleOf())).toBe(null); for (const version of ['3.4', BUTTON_IMAGE_AND_LAYOUT_SINCE, null]) { expect(bundleTakesImageTheServerLacks(version, bundleOf(true))).toBe(null); } }); });