// What the playground keeps of the work on it, with no server storage: a // link holding it whole (`#v=`, its JSON deflated, as `CompressionStream` // does it, and base64url), and the browser's own copy (`localStorage`), so // a reload loses nothing. import { isTool, type Tool } from './examples'; /** What a link holds: the call, and the view it draws. */ export type Shared = { tool: Tool; arguments: Record; view: unknown }; /** What the browser keeps: the texts as typed, valid or not, and the bundled view they began as. */ export type Kept = { tool: Tool; args: string; view: string; template: string | null; baseline: string | null }; const KEPT = 'hud-playground'; const isObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); async function through(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): Promise> { const out = new Blob([bytes]).stream().pipeThrough(stream); return new Uint8Array(await new Response(out).arrayBuffer()); } /** `shared` as a link's hash, `#v=…`. */ export async function linkOf(shared: Shared): Promise { const packed = await through(new TextEncoder().encode(JSON.stringify(shared)), new CompressionStream('deflate-raw')); const base64 = btoa(Array.from(packed, (byte) => String.fromCharCode(byte)).join('')); return `#v=${base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`; } /** What a hash (`#v=…`) holds, or null for none, or one that holds no call and view. */ export async function fromLink(hash: string): Promise { const encoded = new URLSearchParams(hash.replace(/^#/, '')).get('v'); if (!encoded) return null; try { const binary = atob(encoded.replace(/-/g, '+').replace(/_/g, '/')); const bytes = await through(Uint8Array.from(binary, (c) => c.charCodeAt(0)), new DecompressionStream('deflate-raw')); const found: unknown = JSON.parse(new TextDecoder().decode(bytes)); if (!isObject(found) || !isTool(found.tool) || !isObject(found.arguments) || !('view' in found)) return null; return { tool: found.tool, arguments: found.arguments, view: found.view }; } catch { return null; } } /** The work the browser kept, or null. */ export function kept(): Kept | null { try { const found: unknown = JSON.parse(localStorage.getItem(KEPT) ?? 'null'); if (!isObject(found) || !isTool(found.tool) || typeof found.args !== 'string' || typeof found.view !== 'string') return null; const text = (value: unknown) => (typeof value === 'string' ? value : null); return { tool: found.tool, args: found.args, view: found.view, template: text(found.template), baseline: text(found.baseline) }; } catch { return null; } } /** Keep the work for the next load. */ export function keep(work: Kept) { try { localStorage.setItem(KEPT, JSON.stringify(work)); } catch { // Not kept: the work stays on the page, and a link still holds it. } }