/** * The framing a pushed frame arrives in, and what a malformed one must do. * * Run: `bun src/lib/media.check.ts` (there is no unit runner; the suite in * `tests/` drives a running stack). */ import assert from "node:assert/strict" import { describeArtifact, isRef, parseMediaFrame } from "./media" function frame(header: object, payload: Uint8Array): ArrayBuffer { const encoded = new TextEncoder().encode(JSON.stringify(header)) const out = new Uint8Array(4 + encoded.length + payload.length) new DataView(out.buffer).setUint32(0, encoded.length) out.set(encoded, 4) out.set(payload, 4 + encoded.length) return out.buffer } const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]) const parsed = parseMediaFrame( frame( { type: "media", name: "cam.frame", digest: `sha256:${"a".repeat(64)}`, media_type: "image/png", ts: 1, }, bytes, ), ) assert.ok(parsed) assert.equal(parsed.header.name, "cam.frame") assert.equal(parsed.header.media_type, "image/png") assert.equal(parsed.bytes.size, 4) assert.equal(parsed.bytes.type, "image/png") // A frame the client cannot read is dropped, never thrown on: this runs on // every socket message. assert.equal(parseMediaFrame(new ArrayBuffer(0)), null) assert.equal(parseMediaFrame(new ArrayBuffer(2)), null) assert.equal(parseMediaFrame(frame({ name: "n" }, bytes)), null) // A length longer than the frame is truncation, not a payload. const short = new Uint8Array(8) new DataView(short.buffer).setUint32(0, 999) assert.equal(parseMediaFrame(short.buffer), null) assert.ok(isRef({ digest: `sha256:${"b".repeat(64)}` })) assert.equal(isRef({ digest: "nope" }), false) assert.equal(isRef(null), false) assert.equal( describeArtifact({ media_type: "image/png", name: "f.png", size: 48000 }), "image/png · f.png · 48kB", ) // No media type is still worth summarising as something. assert.equal( describeArtifact({ media_type: "application/octet-stream", size: 12 }), "artifact · 12B", ) console.log("media.check.ts ok")