import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { asBytes, asJson, asText, payloadFromWire, payloadToWire } from '../src/payload.js'; describe('payload conversion', () => { it('sends a string as text', () => { assert.deepEqual(payloadToWire('hello'), { text: 'hello' }); assert.equal(asText(payloadFromWire({ text: 'hello' })), 'hello'); }); it('carries a nested object through google.protobuf.Struct', () => { const input = { json: { owner: { name: 'Haus 12', built: 1974 }, rooms: [{ area: 24.5 }, { area: 18 }], heated: true, note: null, }, }; const wire = payloadToWire(input); const back = asJson(payloadFromWire(wire)); assert.deepEqual(back, input.json); }); it('treats a plain object as json, because that is what a caller means', () => { const wire = payloadToWire({ consumption: 120 }); assert.deepEqual(asJson(payloadFromWire(wire)), { consumption: 120 }); }); it('refuses a bare array, so the kind stays explicit', () => { assert.throws(() => payloadToWire([1, 2, 3]), /not a payload/); }); it('refuses a json payload that is not an object', () => { assert.throws(() => payloadToWire({ json: 'text' }), /Struct/); }); it('round-trips bytes with their media type', () => { const data = Buffer.from([1, 2, 3, 4]); const wire = payloadToWire({ bytes: data, mimeType: 'application/pdf' }); const out = payloadFromWire(wire); assert.equal(out.kind, 'bytes'); assert.deepEqual(asBytes(out), data); assert.equal(out.kind === 'bytes' ? out.mimeType : '', 'application/pdf'); }); it('round-trips a file reference with its hash', () => { const wire = payloadToWire({ file: { uri: 'file:///var/lib/portal/42.jpg', mimeType: 'image/jpeg', sizeBytes: 2048, sha256: 'ab'.repeat(32), }, }); const out = payloadFromWire(wire); assert.equal(out.kind, 'file'); if (out.kind === 'file') { assert.equal(out.sizeBytes, 2048); assert.equal(out.sha256, 'ab'.repeat(32)); } }); it('reads the kind the loader names, not the first key it finds', () => { const out = payloadFromWire({ kind: 'text', text: 'the answer', json: { fields: {} } }); assert.equal(out.kind, 'text'); }); it('answers empty for a payload that carries nothing', () => { assert.equal(payloadFromWire(undefined).kind, 'empty'); assert.equal(payloadFromWire({}).kind, 'empty'); }); });