// Wire format between a canvas and its viewers. // Config is JSON text; snapshots and diffs are binary, tagged by their first byte. export interface CanvasConfig { uri: string; name: string; width: number; height: number; palette: string[]; cooldownSeconds: number; startsAt?: string; endsAt?: string; } export interface Pixel { x: number; y: number; color: number; } export type PlaceResult = | { ok: true; nextPlaceAt: number } | { ok: false; error: string; nextPlaceAt?: number }; export type ServerMessage = | { type: "config"; config: CanvasConfig } | { type: "snapshot"; pixels: Uint8Array } | { type: "diff"; pixels: Pixel[] }; const SNAPSHOT = 1; const DIFF = 2; const DIFF_ENTRY_BYTES = 5; // u16 x, u16 y, u8 color export function encodeConfig(config: CanvasConfig): string { return JSON.stringify({ type: "config", config }); } // Snapshot: tag byte + gzipped palette indices, row-major. export async function encodeSnapshot(pixels: Uint8Array): Promise { const compressed = await pipe(pixels, new CompressionStream("gzip")); const out = new Uint8Array(1 + compressed.length); out[0] = SNAPSHOT; out.set(compressed, 1); return out; } export function encodeDiff(pixels: Pixel[]): Uint8Array { const out = new Uint8Array(1 + pixels.length * DIFF_ENTRY_BYTES); const view = new DataView(out.buffer); out[0] = DIFF; pixels.forEach((p, i) => { const at = 1 + i * DIFF_ENTRY_BYTES; view.setUint16(at, p.x); view.setUint16(at + 2, p.y); view.setUint8(at + 4, p.color); }); return out; } export async function decodeMessage(data: string | ArrayBuffer): Promise { if (typeof data === "string") return JSON.parse(data) as ServerMessage; const bytes = new Uint8Array(data); switch (bytes[0]) { case SNAPSHOT: return { type: "snapshot", pixels: await pipe(bytes.subarray(1), new DecompressionStream("gzip")) }; case DIFF: { const view = new DataView(data); const pixels: Pixel[] = []; for (let at = 1; at + DIFF_ENTRY_BYTES <= bytes.length; at += DIFF_ENTRY_BYTES) { pixels.push({ x: view.getUint16(at), y: view.getUint16(at + 2), color: view.getUint8(at + 4) }); } return { type: "diff", pixels }; } default: throw new Error(`unknown message tag ${bytes[0]}`); } } async function pipe(bytes: Uint8Array, transform: CompressionStream | DecompressionStream): Promise { const stream = new Blob([bytes as Uint8Array]).stream().pipeThrough(transform); return new Uint8Array(await new Response(stream).arrayBuffer()); }