Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
feat: render a Composition in the browser, with the timeline it lacks
rpone16d53adba618
diff --git a/package.json b/package.jsonindex aecb805e..0a91cace 100644--- a/package.json+++ b/package.json@@ -15,6 +15,7 @@"smoke:kie": "node --import tsx packages/provider-kie/test/live-smoke.ts","narratage": "node --import tsx packages/video-cli/src/cli.ts","svml": "node --import tsx packages/video-cli/src/cli.ts",+ "playground": "vite --config tools/playground/vite.config.ts","build:media-lambda": "pnpm --filter @narratage/media-lambda build","build:media-lambda-layer": "pnpm --filter @narratage/media-lambda build:layer"},@@ -38,6 +39,7 @@"@narratage/narrative": "workspace:*","@narratage/program-space": "workspace:*","@narratage/prompt-kit": "workspace:*",+ "@narratage/protocol": "workspace:*","@narratage/provider-google-vertex": "workspace:*","@narratage/provider-hyperframes-local": "workspace:*","@narratage/provider-image-opencv-local": "workspace:*",@@ -64,6 +66,7 @@"@types/node": "24.10.1","tsx": "4.21.0","typescript": "5.9.3",+ "vite": "5.4.21","vitepress": "^1.6.4"}}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8aa83864..16e8712d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -56,6 +56,9 @@ importers:'@narratage/prompt-kit':specifier: workspace:*version: link:packages/prompt-kit+ '@narratage/protocol':+ specifier: workspace:*+ version: link:packages/protocol'@narratage/provider-google-vertex':specifier: workspace:*version: link:packages/provider-google-vertex@@ -134,6 +137,9 @@ importers:typescript:specifier: 5.9.3version: 5.9.3+ vite:+ specifier: 5.4.21+ version: 5.4.21(@types/[email protected])vitepress:specifier: ^1.6.4version: 1.6.4(@algolia/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])diff --git a/test/playground-runtime-shim.test.ts b/test/playground-runtime-shim.test.tsnew file mode 100644index 00000000..3747f881--- /dev/null+++ b/test/playground-runtime-shim.test.ts@@ -0,0 +1,83 @@+import assert from "node:assert/strict";+import test from "node:test";++import { sealComposition, sealVisualTrack } from "@narratage/composition";+import { compileHyperframesDocument } from "@narratage/hyperframes";+import { sealProgramSpace } from "@narratage/program-space";++import { injectRuntimeShim } from "../tools/playground/src/preview/runtime-shim.js";++/**+ * The playground shows the compiled document directly in an iframe, so it must+ * supply the two things a real render gets from the HyperFrames producer: a+ * sized composition root, and a timeline. Both are absences in the document+ * rather than statements in it, which makes them easy to regress silently —+ * these tests pin the absences so the shim's reason for existing stays visible.+ */++const programSpace = sealProgramSpace({+ contract: "svml.program-space@1",+ durationSec: 2,+ frameRate: { numerator: 30, denominator: 1 },+});++function document_() {+ const track = sealVisualTrack({+ contract: "svml.visual-track@1",+ visualIr: "svml.visual-ir@1",+ id: "shot",+ presents: [{+ id: "one",+ span: { startFrame: 0, endFrameExclusive: 30 },+ stacking: { order: 10, tieBreak: "shot" },+ elements: [{+ id: "root",+ order: 0,+ kind: "box",+ style: [{ name: "position", value: "absolute" }, { name: "inset", value: 0 }],+ }],+ }],+ });+ return compileHyperframesDocument(sealComposition({+ contract: "svml.composition@1",+ id: "shim-fixture",+ canvas: { width: 1080, height: 1920, clearColor: "#09090b" },+ tracks: [track],+ }), programSpace);+}++test("the compiled document states its frame size only as data, never as layout", () => {+ const { html } = document_();+ // The size is present to read...+ assert.match(html, /data-width="1080"/u);+ assert.match(html, /data-height="1920"/u);+ // ...but the root's own rule carries no width or height, so the element+ // computes to zero height and clips every Present away. If this assertion+ // ever fails the upstream compiler started sizing the root and the shim can+ // stop doing it.+ const rootRule = /\[data-composition-id\]\{([^}]*)\}/u.exec(html);+ assert.notEqual(rootRule, null, "the compiled stylesheet must scope a rule to the composition root");+ assert.doesNotMatch(rootRule![1]!, /(^|;)\s*(width|height)\s*:/u);+});++test("the compiled document gates no Present and delays no animation", () => {+ const { html } = document_();+ assert.match(html, /class="clip svml-visual-present"/u);+ // data-start is metadata, not a rule: nothing hides a Present outside its span.+ assert.doesNotMatch(html, /visibility\s*:/u);+ assert.doesNotMatch(html, /animation-delay/u);+});++test("the shim supplies the size and the timeline, immediately before body close", () => {+ const shimmed = injectRuntimeShim(document_().html);+ assert.match(shimmed, /root\.style\.height/u);+ assert.match(shimmed, /__svmlSeekFrame/u);+ assert.match(shimmed, /visibility/u);+ const script = shimmed.lastIndexOf("<script>");+ assert.ok(script !== -1 && script < shimmed.lastIndexOf("</body>"),+ "the shim must run after the elements it seeks exist");+});++test("a document without a body close still receives the shim", () => {+ assert.match(injectRuntimeShim("<!doctype html><html></html>"), /__svmlSeek/u);+});diff --git a/tools/playground-sha256.test.mjs b/tools/playground-sha256.test.mjsnew file mode 100644index 00000000..365a4697--- /dev/null+++ b/tools/playground-sha256.test.mjs@@ -0,0 +1,40 @@+import assert from "node:assert/strict";+import { createHash } from "node:crypto";+import test from "node:test";++import { createHash as shimCreateHash } from "./playground/src/shims/node-crypto.ts";++/**+ * The playground runs the compiler's own `digestOf` in a browser, where+ * `node:crypto` does not exist. Content addressing is only meaningful if the+ * substitute agrees with the real thing on every byte, so pin them together.+ */+const cases = [+ "",+ "a",+ "abc",+ "svml.composition@1",+ // 55, 56 and 64 bytes straddle the SHA-256 padding boundary, where a wrong+ // implementation still passes short inputs.+ "x".repeat(55),+ "x".repeat(56),+ "x".repeat(64),+ "x".repeat(1000),+ "字幕轨道与画布",+ JSON.stringify({ contract: "svml.program-space@1", durationSec: 4 }),+];++test("the browser sha256 shim agrees with node:crypto", () => {+ for (const value of cases) {+ assert.equal(+ shimCreateHash("sha256").update(value).digest("hex"),+ createHash("sha256").update(value, "utf8").digest("hex"),+ `sha256 diverged for a ${value.length}-character input`,+ );+ }+});++test("the shim refuses algorithms and encodings it does not implement", () => {+ assert.throws(() => shimCreateHash("sha512"), /sha256/u);+ assert.throws(() => shimCreateHash("sha256").update("a").digest("base64"), /hex/u);+});diff --git a/tools/playground/index.html b/tools/playground/index.htmlnew file mode 100644index 00000000..5cee540a--- /dev/null+++ b/tools/playground/index.html@@ -0,0 +1,35 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <link rel="icon" href="data:," />+ <title>SVML Component Playground</title>+ <style>+ :root {+ color-scheme: dark;+ --bg: #09090b;+ --panel: #131316;+ --line: #26262b;+ --text: #e4e4e7;+ --muted: #8b8b94;+ --accent: #73fbd3;+ --danger: #ff6b6b;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; height: 100%; }+ body {+ background: var(--bg);+ color: var(--text);+ font: 13px/1.5 ui-sans-serif, -apple-system, "Segoe UI", sans-serif;+ display: flex;+ flex-direction: column;+ }+ #app { flex: 1; min-height: 0; display: flex; }+ </style>+ </head>+ <body>+ <div id="app"></div>+ <script type="module" src="/src/main.ts"></script>+ </body>+</html>diff --git a/tools/playground/src/main.ts b/tools/playground/src/main.tsnew file mode 100644index 00000000..38f3216e--- /dev/null+++ b/tools/playground/src/main.ts@@ -0,0 +1,114 @@+import { renderPreview } from "./preview/render.js";+import { sealProgramSpace, sealVisualTrack } from "./svml.js";+import type { ProgramSpace, Track, VisualElement } from "./svml.js";+import { createStage } from "./ui/stage.js";++/**+ * Slice 0 fixture.+ *+ * Two Presents that do not overlap, each with an animated child. The compiled+ * document gates neither — it marks every clip visible and starts every+ * animation at load — so this composition renders as one muddle without the+ * runtime shim and as a clean two-shot sequence with it. That difference is the+ * whole point of the fixture: it is what proves the shim before anything is+ * built on top of it.+ */++const programSpace: ProgramSpace = sealProgramSpace({+ contract: "svml.program-space@1",+ durationSec: 4,+ frameRate: { numerator: 30, denominator: 1 },+});++const CANVAS = { width: 1080, height: 1920, clearColor: "#09090b" };++function shot(+ id: string,+ startFrame: number,+ endFrameExclusive: number,+ order: number,+ fill: string,+ label: string,+): Track {+ const duration = endFrameExclusive - startFrame;+ const elements: VisualElement[] = [+ {+ id: "root",+ order: 0,+ kind: "box",+ style: [+ { name: "position", value: "absolute" },+ { name: "inset", value: 0 },+ { name: "display", value: "flex" },+ { name: "align-items", value: "center" },+ { name: "justify-content", value: "center" },+ ],+ },+ {+ id: "card",+ parent: "root",+ order: 1,+ kind: "box",+ style: [+ { name: "width", value: "760px" },+ { name: "height", value: "420px" },+ { name: "background", value: fill },+ { name: "border-radius", value: "36px" },+ { name: "display", value: "flex" },+ { name: "align-items", value: "center" },+ { name: "justify-content", value: "center" },+ ],+ // Fades up and settles. Seeking must land mid-fade, not at the end.+ animation: {+ keyframes: [+ { atFrame: 0, easing: "ease-out", style: [{ name: "opacity", value: 0 }, { name: "transform", value: "translateY(60px)" }] },+ { atFrame: Math.round(duration / 2), style: [{ name: "opacity", value: 1 }, { name: "transform", value: "translateY(0px)" }] },+ { atFrame: duration, style: [{ name: "opacity", value: 1 }, { name: "transform", value: "translateY(0px)" }] },+ ],+ },+ },+ {+ id: "label",+ parent: "card",+ order: 2,+ kind: "text",+ text: label,+ style: [+ { name: "color", value: "#09090b" },+ { name: "font-family", value: "ui-sans-serif, sans-serif" },+ { name: "font-size", value: "64px" },+ { name: "font-weight", value: 700 },+ { name: "text-align", value: "center" },+ ],+ },+ ];+ return sealVisualTrack({+ contract: "svml.visual-track@1",+ visualIr: "svml.visual-ir@1",+ id,+ presents: [{+ id: `${id}-present`,+ span: { startFrame, endFrameExclusive },+ stacking: { order, tieBreak: id },+ elements,+ }],+ });+}++const app = document.querySelector<HTMLElement>("#app")!;+const stage = createStage();+app.append(stage.element);++try {+ stage.show(renderPreview({+ id: "slice-0",+ canvas: CANVAS,+ programSpace,+ tracks: [+ shot("shot-a", 0, 60, 10, "#73fbd3", "frames 0–59"),+ shot("shot-b", 60, 120, 20, "#ffd166", "frames 60–119"),+ ],+ }));+} catch (error) {+ stage.showError(error instanceof Error ? error.message : String(error));+}diff --git a/tools/playground/src/preview/render.ts b/tools/playground/src/preview/render.tsnew file mode 100644index 00000000..d042f0de--- /dev/null+++ b/tools/playground/src/preview/render.ts@@ -0,0 +1,68 @@+import {+ compileHyperframesDocument,+ materializeHyperframesHtml,+ programSpaceFrameCount,+ sealComposition,+} from "../svml.js";+import type { Composition, ProgramSpace, Track } from "../svml.js";+import { injectRuntimeShim } from "./runtime-shim.js";++/** A grey card standing in for an Artifact the playground has not been given. */+const MISSING_MEDIA = `data:image/svg+xml;utf8,${encodeURIComponent(+ `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">`+ + `<rect width="320" height="180" fill="#26262b"/>`+ + `<text x="160" y="96" fill="#8b8b94" font-family="sans-serif" font-size="15"`+ + ` text-anchor="middle">media not set</text></svg>`,+)}`;++export type PreviewInput = {+ readonly id: string;+ readonly canvas: Composition["canvas"];+ readonly programSpace: ProgramSpace;+ readonly tracks: readonly Track[];+ /** Digest to object URL. A miss is a warning, never a failed preview. */+ readonly resolveArtifact?: (digest: string) => string | undefined;+};++export type PreviewOutput = {+ readonly srcdoc: string;+ readonly frameCount: number;+ readonly fps: number;+ /** The document's own frame size — what the stage must not let reflow. */+ readonly canvas: { readonly width: number; readonly height: number };+ readonly warnings: readonly string[];+};++/**+ * Composition to something an iframe can show.+ *+ * The seal and compile steps are the compiler's own, so anything the real Build+ * would reject is rejected here too — with the same message. Callers surface the+ * throw next to the form rather than clearing the stage.+ */+export function renderPreview(input: PreviewInput): PreviewOutput {+ const composition = sealComposition({+ contract: "svml.composition@1",+ id: input.id,+ canvas: input.canvas,+ tracks: input.tracks,+ });+ const document = compileHyperframesDocument(composition, input.programSpace);++ const warnings: string[] = [];+ const html = materializeHyperframesHtml(document, (artifact) => {+ const resolved = input.resolveArtifact?.(artifact.digest);+ if (resolved !== undefined) return resolved;+ warnings.push(`No media set for ${artifact.digest.slice(0, 19)}…`);+ return MISSING_MEDIA;+ });++ const { numerator, denominator } = input.programSpace.frameRate;+ return {+ srcdoc: injectRuntimeShim(html),+ frameCount: programSpaceFrameCount(input.programSpace),+ fps: numerator / denominator,+ canvas: document.canvas,+ warnings,+ };+}diff --git a/tools/playground/src/preview/runtime-shim.ts b/tools/playground/src/preview/runtime-shim.tsnew file mode 100644index 00000000..31d4e87f--- /dev/null+++ b/tools/playground/src/preview/runtime-shim.ts@@ -0,0 +1,93 @@+/**+ * The timeline the compiled document does not carry.+ *+ * `compileHyperframesDocument` emits every Present as an always-visible clip and+ * gives its animations a duration but no delay — a real render supplies the+ * runtime that gates and seeks them. This is that runtime, reduced to what a+ * preview needs, and it uses the same technique the production renderer does:+ * `getAnimations()` plus an explicit `currentTime`.+ *+ * Injected into the materialized HTML. `compileHyperframesDocument` is never+ * touched, so what renders here stays the document the compiler produced.+ */+export const RUNTIME_SHIM = String.raw`+<script>+(function () {+ var root = document.querySelector('[data-composition-id]');+ var fpsAttr = (root && root.getAttribute('data-fps')) || '30';+ var slash = fpsAttr.indexOf('/');+ var fps = slash === -1+ ? parseFloat(fpsAttr)+ : parseFloat(fpsAttr.slice(0, slash)) / parseFloat(fpsAttr.slice(slash + 1));+ var frameCount = parseInt((root && root.getAttribute('data-svml-frame-count')) || '0', 10);++ // The compiled stylesheet gives the composition root position and overflow but+ // no size — a real render sizes it from data-width/data-height. Left alone it+ // computes to zero height, and since every Present is absolutely positioned+ // inside it with overflow:hidden, the whole frame clips away to nothing.+ if (root) {+ root.style.width = (root.getAttribute('data-width') || '0') + 'px';+ root.style.height = (root.getAttribute('data-height') || '0') + 'px';+ }++ function clips() {+ return document.querySelectorAll('.svml-visual-present');+ }++ /** Seek to an absolute program time in seconds. */+ function seek(seconds) {+ var list = clips();+ for (var i = 0; i < list.length; i++) {+ var clip = list[i];+ var start = parseFloat(clip.getAttribute('data-start') || '0') || 0;+ var duration = parseFloat(clip.getAttribute('data-duration') || '0') || 0;+ var local = seconds - start;+ var inside = local >= 0 && local < duration;+ clip.style.visibility = inside ? 'visible' : 'hidden';++ var animations = clip.getAnimations({ subtree: true });+ for (var a = 0; a < animations.length; a++) {+ var animation = animations[a];+ try {+ animation.pause();+ // Clamp rather than skip: a Present's held first and last keyframes are+ // what the renderer shows at its edges, so the boundary frames match.+ var at = local < 0 ? 0 : (local > duration ? duration : local);+ animation.currentTime = at * 1000;+ } catch (error) {+ /* An animation that is not yet ready re-seeks on the next call. */+ }+ }++ var media = clip.querySelectorAll('video, audio');+ for (var m = 0; m < media.length; m++) {+ var element = media[m];+ element.pause();+ if (inside) {+ var offset = parseFloat(element.getAttribute('data-media-start') || '0') || 0;+ try { element.currentTime = offset + local; } catch (error) { /* not seekable yet */ }+ }+ }+ }+ }++ window.__svmlSeek = seek;+ window.__svmlFrameCount = frameCount;+ window.__svmlFps = fps;+ window.__svmlSeekFrame = function (frame) { seek(frame / fps); };++ // Paint the first frame correctly rather than whatever the CSS happened to be+ // mid-animation when the document loaded.+ seek(0);+ window.addEventListener('load', function () { seek(0); });+})();+</script>+`;++/** Places the shim last in the body so it observes the finished element tree. */+export function injectRuntimeShim(html: string): string {+ const marker = "</body>";+ const at = html.lastIndexOf(marker);+ if (at === -1) return html + RUNTIME_SHIM;+ return html.slice(0, at) + RUNTIME_SHIM + html.slice(at);+}diff --git a/tools/playground/src/shims/node-crypto.ts b/tools/playground/src/shims/node-crypto.tsnew file mode 100644index 00000000..4fd6daf5--- /dev/null+++ b/tools/playground/src/shims/node-crypto.ts@@ -0,0 +1,104 @@+/**+ * The one `node:crypto` surface the compiler packages touch, for the browser.+ *+ * `digestOf` (packages/protocol/src/canonical.ts) runs `createHash("sha256")`+ * synchronously at module load — several manifests compute their digest as a+ * top-level constant — so Web Crypto's async `subtle.digest` cannot stand in.+ * This is a plain synchronous SHA-256, aliased over `node:crypto` by+ * tools/playground/vite.config.ts.+ *+ * Verified byte-for-byte against Node's implementation by+ * tools/playground-sha256.test.mjs.+ */++const K = new Uint32Array([+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,+]);++function rotr(value: number, bits: number): number {+ return ((value >>> bits) | (value << (32 - bits))) >>> 0;+}++export function sha256Hex(bytes: Uint8Array): string {+ const h = new Uint32Array([+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,+ ]);+ const padded = new Uint8Array(((((bytes.length + 8) / 64) | 0) + 1) * 64);+ padded.set(bytes);+ padded[bytes.length] = 0x80;+ const view = new DataView(padded.buffer);+ const bits = bytes.length * 8;+ view.setUint32(padded.length - 8, Math.floor(bits / 0x1_0000_0000), false);+ view.setUint32(padded.length - 4, bits >>> 0, false);++ const w = new Uint32Array(64);+ for (let offset = 0; offset < padded.length; offset += 64) {+ for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(offset + i * 4, false);+ for (let i = 16; i < 64; i += 1) {+ const x = w[i - 15]!;+ const y = w[i - 2]!;+ const s0 = (rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3)) >>> 0;+ const s1 = (rotr(y, 17) ^ rotr(y, 19) ^ (y >>> 10)) >>> 0;+ w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) >>> 0;+ }+ let a = h[0]!, b = h[1]!, c = h[2]!, d = h[3]!;+ let e = h[4]!, f = h[5]!, g = h[6]!, s = h[7]!;+ for (let i = 0; i < 64; i += 1) {+ const S1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;+ const ch = ((e & f) ^ (~e & g)) >>> 0;+ const t1 = (s + S1 + ch + K[i]! + w[i]!) >>> 0;+ const S0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;+ const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0;+ const t2 = (S0 + maj) >>> 0;+ s = g; g = f; f = e; e = (d + t1) >>> 0;+ d = c; c = b; b = a; a = (t1 + t2) >>> 0;+ }+ h[0] = (h[0]! + a) >>> 0; h[1] = (h[1]! + b) >>> 0;+ h[2] = (h[2]! + c) >>> 0; h[3] = (h[3]! + d) >>> 0;+ h[4] = (h[4]! + e) >>> 0; h[5] = (h[5]! + f) >>> 0;+ h[6] = (h[6]! + g) >>> 0; h[7] = (h[7]! + s) >>> 0;+ }++ let hex = "";+ for (let i = 0; i < 8; i += 1) hex += h[i]!.toString(16).padStart(8, "0");+ return hex;+}++const encoder = new TextEncoder();++class Sha256Hash {+ #chunks: Uint8Array[] = [];++ update(chunk: string | Uint8Array): this {+ this.#chunks.push(typeof chunk === "string" ? encoder.encode(chunk) : chunk);+ return this;+ }++ digest(encoding?: string): string {+ if (encoding !== undefined && encoding !== "hex") {+ throw new Error(`node:crypto shim supports hex digests, not ${encoding}.`);+ }+ let length = 0;+ for (const chunk of this.#chunks) length += chunk.length;+ const joined = new Uint8Array(length);+ let at = 0;+ for (const chunk of this.#chunks) { joined.set(chunk, at); at += chunk.length; }+ return sha256Hex(joined);+ }+}++export function createHash(algorithm: string): Sha256Hash {+ if (algorithm !== "sha256") {+ throw new Error(`node:crypto shim supports sha256, not ${algorithm}.`);+ }+ return new Sha256Hash();+}++export default { createHash };diff --git a/tools/playground/src/svml.ts b/tools/playground/src/svml.tsnew file mode 100644index 00000000..c4fa5af2--- /dev/null+++ b/tools/playground/src/svml.ts@@ -0,0 +1,39 @@+/**+ * The browser-safe surface of the compiler, in one place.+ *+ * Almost every package the playground needs is pure, but+ * `@narratage/hyperframes`'s entry re-exports `stageHyperframesProject`, which+ * writes a project to disk through `node:fs/promises`. Importing the package+ * entry would therefore drag a filesystem into the browser for a function the+ * playground never calls, so the document module is imported by path instead.+ *+ * Everything else the playground uses goes through this module too, so the+ * boundary is one file to audit rather than an import convention to remember.+ */++export {+ assertHyperframesDocument,+ compileHyperframesDocument,+ materializeHyperframesHtml,+} from "../../../packages/hyperframes/src/document.js";+export type { HyperframesDocument } from "../../../packages/hyperframes/src/types.js";++export {+ sealComposition,+ sealVisualTrack,+ assertCompositionIdentity,+} from "@narratage/composition";+export type {+ Composition,+ FrameSpan,+ Track,+ VisualElement,+ VisualPresent,+ VisualStyleDeclaration,+ VisualTrack,+} from "@narratage/composition";++export { programSpaceFrameCount, sealProgramSpace } from "@narratage/program-space";+export type { ProgramSpace } from "@narratage/program-space";++export type { CanonicalValue, ValueSchema } from "@narratage/protocol";diff --git a/tools/playground/src/ui/stage.ts b/tools/playground/src/ui/stage.tsnew file mode 100644index 00000000..a9d87c7f--- /dev/null+++ b/tools/playground/src/ui/stage.ts@@ -0,0 +1,157 @@+import type { PreviewOutput } from "../preview/render.js";++type SeekWindow = Window & {+ __svmlSeekFrame?: (frame: number) => void;+};++const CSS = `+.stage { flex: 1; min-width: 0; display: flex; flex-direction: column; background: #0d0d10; }+.stage-viewport {+ flex: 1; min-height: 0; position: relative; overflow: hidden;+ display: flex; align-items: center; justify-content: center; padding: 20px;+}+.stage-scaler { position: relative; transform-origin: center center; }+.stage-scaler iframe {+ display: block; border: 0; background: #000;+ box-shadow: 0 0 0 1px #26262b, 0 18px 50px rgba(0, 0, 0, .55);+}+.stage-bar {+ display: flex; align-items: center; gap: 12px;+ padding: 10px 14px; border-top: 1px solid var(--line); background: var(--panel);+}+.stage-bar button {+ width: 30px; height: 26px; border: 1px solid var(--line); border-radius: 5px;+ background: #1c1c21; color: var(--text); cursor: pointer; font-size: 12px;+}+.stage-bar button:hover { border-color: #3a3a42; }+.stage-bar input[type=range] { flex: 1; accent-color: var(--accent); }+.stage-frame { font-variant-numeric: tabular-nums; color: var(--muted); min-width: 92px; }+.stage-size { color: var(--muted); font-variant-numeric: tabular-nums; }+.stage-note { padding: 9px 14px; font-size: 12px; border-top: 1px solid var(--line); white-space: pre-wrap; }+.stage-note.error { background: #2a1416; color: var(--danger); font-family: ui-monospace, monospace; }+.stage-note.warn { background: #241f12; color: #e3b341; }+.stage-note:empty { display: none; }+`;++export type Stage = {+ readonly element: HTMLElement;+ show(output: PreviewOutput): void;+ showError(message: string): void;+};++export function createStage(): Stage {+ const style = document.createElement("style");+ style.textContent = CSS;+ document.head.append(style);++ const element = document.createElement("div");+ element.className = "stage";+ element.innerHTML = `+ <div class="stage-viewport"><div class="stage-scaler"><iframe title="preview"></iframe></div></div>+ <div class="stage-bar">+ <button type="button" data-play>▶</button>+ <input type="range" min="0" max="0" step="1" value="0" data-scrub />+ <span class="stage-frame" data-frame>0 / 0</span>+ <span class="stage-size" data-size></span>+ </div>+ <div class="stage-note error" data-error></div>+ <div class="stage-note warn" data-warn></div>+ `;++ const viewport = element.querySelector<HTMLElement>(".stage-viewport")!;+ const scaler = element.querySelector<HTMLElement>(".stage-scaler")!;+ const frame = element.querySelector<HTMLIFrameElement>("iframe")!;+ const play = element.querySelector<HTMLButtonElement>("[data-play]")!;+ const scrub = element.querySelector<HTMLInputElement>("[data-scrub]")!;+ const readout = element.querySelector<HTMLElement>("[data-frame]")!;+ const size = element.querySelector<HTMLElement>("[data-size]")!;+ const error = element.querySelector<HTMLElement>("[data-error]")!;+ const warn = element.querySelector<HTMLElement>("[data-warn]")!;++ let canvas = { width: 1080, height: 1920 };+ let frameCount = 1;+ let fps = 30;+ let ready = false;+ let playing = false;+ let raf = 0;++ /**+ * The iframe keeps its composition pixel size and is scaled by transform.+ * Letting it reflow at the viewport size would silently change every length+ * in the document, so a font-size read here would not be the rendered one.+ */+ function fit(): void {+ const room = viewport.getBoundingClientRect();+ const scale = Math.min(+ (room.width - 40) / canvas.width,+ (room.height - 40) / canvas.height,+ );+ const k = Number.isFinite(scale) && scale > 0 ? Math.min(scale, 1) : 1;+ scaler.style.transform = `scale(${k})`;+ scaler.style.width = `${canvas.width * k}px`;+ scaler.style.height = `${canvas.height * k}px`;+ scaler.style.transformOrigin = "top left";+ frame.style.width = `${canvas.width}px`;+ frame.style.height = `${canvas.height}px`;+ }++ function seek(at: number): void {+ readout.textContent = `${at} / ${frameCount - 1}`;+ if (!ready) return;+ (frame.contentWindow as SeekWindow | null)?.__svmlSeekFrame?.(at);+ }++ function stop(): void {+ playing = false;+ play.textContent = "▶";+ if (raf !== 0) cancelAnimationFrame(raf);+ raf = 0;+ }++ play.addEventListener("click", () => {+ if (playing) { stop(); return; }+ playing = true;+ play.textContent = "❚❚";+ const startedAt = performance.now();+ const from = Number(scrub.value);+ const step = (now: number): void => {+ if (!playing) return;+ const at = from + Math.round((now - startedAt) / 1000 * fps);+ if (at >= frameCount) { scrub.value = String(frameCount - 1); seek(frameCount - 1); stop(); return; }+ scrub.value = String(at);+ seek(at);+ raf = requestAnimationFrame(step);+ };+ raf = requestAnimationFrame(step);+ });++ scrub.addEventListener("input", () => { stop(); seek(Number(scrub.value)); });+ frame.addEventListener("load", () => { ready = true; seek(Number(scrub.value)); });+ new ResizeObserver(fit).observe(viewport);++ return {+ element,+ show(output) {+ error.textContent = "";+ warn.textContent = [...new Set(output.warnings)].join("\n");+ canvas = output.canvas;+ frameCount = Math.max(1, output.frameCount);+ fps = output.fps;+ stop();+ // Keep the playhead across edits so tweaking a value does not lose the+ // frame you were judging.+ const at = Math.min(Number(scrub.value), frameCount - 1);+ scrub.max = String(frameCount - 1);+ scrub.value = String(at);+ readout.textContent = `${at} / ${frameCount - 1}`;+ size.textContent = `${canvas.width}×${canvas.height}`;+ ready = false;+ frame.srcdoc = output.srcdoc;+ fit();+ },+ showError(message) {+ stop();+ error.textContent = message;+ },+ };+}diff --git a/tools/playground/vite.config.ts b/tools/playground/vite.config.tsnew file mode 100644index 00000000..47611345--- /dev/null+++ b/tools/playground/vite.config.ts@@ -0,0 +1,52 @@+import { readdirSync, readFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import { defineConfig } from "vite";++const here = dirname(fileURLToPath(import.meta.url));+const repoRoot = resolve(here, "../..");++/**+ * Workspace packages publish raw TypeScript (`exports: { ".": "./src/index.ts" }`),+ * so they must reach Vite as project source rather than as prebundled+ * dependencies. Aliasing every package by its declared entry does that and picks+ * up transitive dependencies for free — enumerating them by hand would drift the+ * moment a package gains one.+ */+function workspaceAliases(): Array<{ find: string; replacement: string }> {+ const packages = join(repoRoot, "packages");+ return readdirSync(packages, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .flatMap((entry) => {+ const manifestPath = join(packages, entry.name, "package.json");+ let manifest: { name?: unknown; exports?: unknown };+ try {+ manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as typeof manifest;+ } catch {+ return [];+ }+ const entryPoint = (manifest.exports as Record<string, unknown> | undefined)?.["."];+ if (typeof manifest.name !== "string" || typeof entryPoint !== "string") return [];+ // Exact-or-followed-by-slash matching keeps "@narratage/speech" from+ // swallowing "@narratage/speech-basis".+ return [{ find: manifest.name, replacement: join(packages, entry.name, entryPoint) }];+ });+}++export default defineConfig({+ root: here,+ resolve: {+ alias: [+ // `digestOf` hashes synchronously at module load, so Web Crypto cannot+ // stand in. See src/shims/node-crypto.ts.+ { find: "node:crypto", replacement: join(here, "src/shims/node-crypto.ts") },+ ...workspaceAliases(),+ ],+ },+ server: {+ port: 5178,+ // The playground reads sources and media from anywhere in the repository.+ fs: { allow: [repoRoot] },+ },+});diff --git a/tsconfig.json b/tsconfig.jsonindex b0dbc6a2..ab120867 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -223,7 +223,9 @@},"include": ["packages/**/*.ts",- "services/media-lambda/src/**/*.ts"+ "services/media-lambda/src/**/*.ts",+ "tools/playground/**/*.ts",+ "test/playground-*.test.ts"],"exclude": ["dist",